content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import sympy def render(expr, lhs=""): """ Puts $ at the beginning and end of a latex expression. lhs : if we want to render something like: $x = 3 + 5$, set the left hand side here """ left = "$$" if lhs: left = "$$%s =" % lhs return ''.join([left, sympy.latex(expr), "$$...
64190fe4358b212f15972d29873504317899c685
688,785
import os import sys import configparser def read(): """Return the application configurations.""" file_location = os.path.abspath(os.path.dirname(sys.argv[0])) inifile = file_location + '/config.cfg' config = configparser.ConfigParser() config.read(inifile, encoding='utf-8') return config
c214163401b2f5b95fa5af81376113eabf6fc9a7
688,786
def compress_name(champion_name): """To ensure champion names can be searched for and compared, the names need to be reduced. The process is to remove any characters not in the alphabet (apostrophe, space, etc) and then convert everything to lowercase. Note that reversing this is non-trivial, ther...
de76dfd48436ae1ec66dc7e42357e6c52f15719a
688,787
import os def get_sorted_list_of_svg_in_dir(svg_dir): """ Calculated an alphabetically-sorted list of svg files in a given directory :param svg_dir: the directory in which to look for svg files :return: a sorted list of svg files """ if not os.path.isdir(svg_dir): quit('Py: %s is not a...
ae9fff27f0bd813720c5ad69adc48b63ae981e2d
688,788
def createDatas(*models): """Call createData() on each Model or GeometryModel in input and return the results in a tuple. If one of the models is None, the corresponding data object in the result is also None. """ return tuple([None if model is None else model.createData() for model in models])
c4dd5231ac8e7a3efd16e33bd793cb8d60ea9292
688,789
def _create_source_file(source, tmp_path): """Create a file with the source code.""" directory = tmp_path / "models" directory.mkdir() source_file = directory / "models.py" source_file.write_text(source) return source_file
872bc917f8cae340ae8c098a7fdf96ebd5725ba2
688,790
def __top_frond_left(dfs_data): """Returns the frond at the top of the LF stack.""" return dfs_data['LF'][-1]
6a7870bf1dd2d165410a2e187240cf548a4e3cdb
688,791
import argparse def parser(): """ Flags parser """ parser = argparse.ArgumentParser( description="Python project that uses OpenAI Gym with the environment \ (provided) Marvin. The goal is to train Marvin to walk, \ having the training and walking process.", epi...
1c9236f2991096c2804f8558a247f634043d5c35
688,792
def parse_team_comp(match_info): """ Gets champion IDs for players on each team, arranged top-jng-mid-adc-sup """ blue_champs = [x['championId'] for x in match_info['participants'][:5]] red_champs = [x['championId'] for x in match_info['participants'][5:]] return blue_champs, red_champs
303591292b6b9dcdec866f9b5a43eb1197a6b074
688,793
def link_cmd(path, link): """Returns link creation command.""" return ['ln', '-sfn', path, link]
a7c0477fd643b6eebc028fdfbd890922ac4ceb09
688,794
import re def is_indel_impact(exonicFuncRefGene): """ @summary: Predict stop codon effect of the variant @param exonicFuncRefGene: [str] The exonic function predicted by RefGene @return: [int/bool] Rank (2) if is frameshift impact; Rank (8) if non-frameshift; False in other cases """ match_fra...
e8e0d82dd8ebc49f65c357f36eb93479e20919a7
688,795
def _full_report(project, project_source, date, command, graph_components, raw_files_components): """Returns the full HTML of a complete report, from the graph components. """ return """ <html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/...
8f72ad70aed1819eccebbbb617d308d8933a90f1
688,796
import os def version_location(): """ Where to save different versions of the same library, which will be loaded as appropriate """ return os.path.join(os.path.dirname(os.path.abspath(__file__)), '_versions')
d00906b40ed41cb4db4447cbdd9680107b658d5d
688,797
import ntpath import posixpath def as_posixpath(location): """ Return a posix-like path using posix path separators (slash or "/") for a `location` path. This converts Windows paths to look like posix paths that Python accepts gracefully on Windows for path handling. """ return location.replac...
0a0e4f9c4dbff17781cbe980820ebf3f545fda21
688,799
def flag_greens_on_set(func): """Decorator to signal Green's functions are now out of date.""" def setter_wrapper(obj, value): retval = func(obj, value) obj._uptodate = False return retval return setter_wrapper
030808f24f1a1b978e55e2f318849d8d029d1e75
688,800
def _auth_header(module): """Generate an authentication header from a token.""" token = module.params.get('auth')['access_token'] auth_header = { 'Authorization': 'Bearer {}'.format(token) } return auth_header
187b232c36c2ec453821e0a07c2976322e5f8dc2
688,802
import re import os def discover_python_files(paths, ignore): """Discover Python files.""" def _ignore(path): """Return True if `path` should be ignored, False otherwise.""" return any(re.match(pattern, path) for pattern in ignore) for path in sorted(set(paths)): for root, _, fil...
e5b57f2ec135b8b33a757a9ae5b8acbdafc24160
688,803
def is_true(obj, true_props=['inner stream', 'oriented', 'consecutive', 'exited', 'centered']): """Returns True if true object and False if not.""" for prop in true_props: # if lacks one of the key props for a true object, not a true object try: props = obj.get_props(prop) ...
47053b025b258a8ea071c49e796c7a7462436ac2
688,804
import uuid def _replace_substrings(code, first_char, last_char): """Replace the substrings between first_char and last_char with a unique id. Return the replaced string and a list of replacement tuples: (unique_id, original_substring) """ substrings = [] level = 0 start = -1 for i...
4a4b877df5aa6ce889a62f6e3ed9b784e37ad41c
688,805
def s3boto_dlurl(self, name, response_headers=None): """Just like s3boto.url(), but it supports response_headers setting. This method is monkeypatched onto the class class2go/main/monkeypatch.py """ name = self._normalize_name(self._clean_name(name)) if self.custom_domain: return "%s://...
2436109393594a1f38f6f6a81e923cd99deed479
688,806
import re def get_set(srr_rar_block): """ An SRR file can contain re-creation data of different RAR sets. This function tries to pick the basename of such a set. """ n = srr_rar_block.file_name[:-4] match = re.match("(.*)\.part\d*$", n, re.I) if match: return match.group(1) else: return n
2dc166e40d410beaf31d450ca4d932ab79e50292
688,807
import re import argparse import pathlib import logging def check_params(args: argparse.Namespace) -> bool: """ check cli parameters for patterns and check for existing directories/files :param args: passed args :return: true if all correct or false """ path = pathlib.Path(args.path) if no...
ca9548bec628cb97d17c497da48bfb92d72937b0
688,808
def intersect2D(segment, point): """ Calculates if a ray of x->inf from "point" intersects with the segment segment = [(x1, y1), (x2, y2)] """ x, y = point #print(segment) x1, y1 = segment[0] x2, y2 = segment[1] if (y1<=y and y<y2) or (y2<=y and y<y1): x3 = x2*(y1-y)/(y1...
403bf09794036572d4eb198951e89379634825c8
688,809
def max_profit_naive(prices): """ :type prices: List[int] :rtype: int """ max_so_far = 0 for i in range(0, len(prices) - 1): for j in range(i + 1, len(prices)): max_so_far = max(max_so_far, prices[j] - prices[i]) return max_so_far
5ff9b3324258cfaacdda31da6bab10542f37aaa4
688,815
def units_pluralise(unit: str, quantity: str): """ Pluralise goods measurements units """ if unit.endswith("(s)"): unit = unit[:-3] if not quantity == "1": unit = unit + "s" return unit
631f25fa5a1143008893e08e419d2358f1ea8f4c
688,816
def _get_reserved_field(field_id, reserved_fields): """Returns the desired reserved field. Args: field_id: str. The id of the field to retrieve. reserved_fields: list(fields). The reserved fields to search. Returns: The reserved field with the given `field_id`. Raises: ValueError: `field_id` ...
b32e4b183682c2bd482cb244956cc23865c85921
688,817
import math def sigmoid(x): """Sigmoid function f(x)=1/(1+e^(-x)) Args: x: float, input of sigmoid function Returns: y: float, function value """ # for x which is to large, the sigmoid returns 1 if x > 100: return 1.0 # for x which is very small, the sigmoid r...
c65624784c34422ca41f14d118e3690990a05b47
688,818
def _make_skew_pcols(grid): """ 0 1 6 7 4 5 2 3, "left_init" """ Ncore, Nrow, Ncol = grid out = [] out.append(tuple(range(Ncore))) to_flip = [] for i in range(1, Nrow * Ncol): chip = list(range(i * Ncore, (i + 1) * Ncore)) to_flip.append(tuple(chip)) out += to_flip[::-1] to_return = [] for...
e6fb03afe26ae72d69249bed7dd110db1c0ad56d
688,819
def connect_the_dots(pts): """given a list of tag pts, convert the point observations to poly-lines. If there is only one pt, return None, otherwise connect the dots by copying the points and offseting by 1, producing N-1 line segments. Arguments: - `pts`: a list of point observations of the f...
9d678a1033acc75631c2391884df6d3ea46f013b
688,820
from typing import List def dict_to_generic_object_format(args: dict) -> List[dict]: """ Converts args dict into a list, please see GenericObjectGenerator Class in Pymisp. Args: args: dictionary describes MISP object Returns: list: list containing dicts that GenericObjectGenerator can...
42118e4ffc053ef2758a9ebe69c0f7a212ea8091
688,822
import base64 def encode_photo(filepath): """ encode photo to text :param filepath: file encoded :return: encoded text """ with open(filepath, mode="rb") as f: return base64.encodebytes(f.read()).decode("utf-8")
7cfe4b8f3ba32b6a7fa1dbfe9277e6ae15ab21dc
688,823
import numpy def mask_lines(shape, limits, start=0, step=1): """ Accepts a list of tuples with (start, end) horizontal ranges. Start from specified x coordinate. """ a = numpy.zeros(shape, dtype=bool) mx, my = shape x = start for line in limits: if x < 0 or x >= mx: ...
fe5bb0b81fd08037a34042eba435688bc650dc34
688,824
import requests def get_api_json(major: int = 1, minor: int = 0, patch: int = 0) -> dict: """Download html content from https://libgit2.org/libgit2/#v{x}.{y}.{z}""" url = f"https://libgit2.org/libgit2/v{major}.{minor}.{patch}.json" return requests.get(url).json()
d9640430e00da2c71b78c3da2ba8f7a10aac8081
688,825
def k_step(n_steps, rewards, gamma): """ paper : ... + low variance - high bias """ reward = lambda data, i: sum([r * (gamma ** i) for i, r in enumerate(data)]) return [ reward(rewards[i:i+n], i) for i, n in enumerate(n_steps) ]
6a11bde7af3fb710b10026f97190fef784523396
688,826
import time def test(x: int, y: int, *args: int, z: int, w: int = 30, **kwargs: int) -> int: """ 被装饰函数 :param x: :param y: :param args: :param z: :param w: :param kwargs: :return: """ print('wrapped function begin') result = x + y for i in args: result += i ...
f2fd238da5366a17a196a49dd00dec7011172df2
688,827
def rotate_list(l): """ Rotate a list of lists :param l: list of lists to rotate :return: """ return list(map(list, zip(*l)))
b4ae24f2f0dcadaf7b33ec6c0b231cbf01c71c5d
688,828
import os def setup(protocol_path, save_dir=None): """ Establish save directory for simulations and data. """ if save_dir is None: path=os.getcwd() else: if os.path.isabs(save_dir)==True: path=save_dir else: path=os.path.join(os.getcwd(), save_dir) ...
ab4927eb6e1f87782a0048a0d2908eab9f0bc883
688,829
def compress(data, compresslevel=9): # real signature unknown; restored from __doc__ """ compress(data [, compresslevel=9]) -> string Compress data in one shot. If you want to compress data sequentially, use an instance of BZ2Compressor instead. The compresslevel parameter, if given, must be a ...
05b0b51143898aec630cf4edd5d6c536a00a4c9a
688,830
from typing import Any def optparseFormat(values: dict[str, Any]) -> dict[str, Any]: """Format args for optparse.""" args = {} for key in values: args[key] = values[key] if values[key] else None return args
e79ca049dab83d1c4bb84a04a7a536bbdfb558af
688,832
def segwit_scriptpubkey(witver, witprog): """Create a segwit locking script for a given witness program (P2WPKH and P2WSH).""" return bytes([witver + 0x50 if witver else 0, len(witprog)] + witprog)
64969e52d2f665c511f9f24855a474dbad7d61da
688,833
from typing import Union from typing import List def parse_setup(options: Union[List, str]) -> str: """Convert potentially a list of commands into a single string. This creates a single string with newlines between each element of the list so that they will all run after each other in a bash script. ...
24ed9ddde7933c19d3196775229f214f82eff3e0
688,835
import re def clean_tweet(tweet): """[clean a paragraph to keep only words and numbers] Args: tweet ([string]): [the text paragraph to be cleaned] """ return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
5437f380db7c634d2e9e0f9beef3412044cd238f
688,836
from typing import List from typing import Dict from typing import Tuple from typing import Union def span_list_to_dict(span_list: List[list]) -> Dict[Tuple[int, int], Union[str, tuple]]: """ convert entity label span list to span dictionaries Parameters ---------- span_list Returns ----...
fe22eb64f06c27ab1b668bbe2d986f62a5ec378d
688,837
import sys import ctypes def zero(s): """ Tries to securely erase a secret string from memory (overwrite it with zeros.) Only works on CPython. Returns True if successful, False otherwise. """ try: bufsize = len(s) + 1 offset = sys.getsizeof(s) - bufsize location ...
8a60b07b18145183505484124dd20d675d9b5d85
688,838
def compare_exact(main, baseline): """ Compares the results of a main file with those of a baseline using exact predicate match. Returns a list of predicate tuples with (predicate definition, measure difference). """ diff = dict() for key, value in main.iteritems(): if key in baseline: ...
1c83fd3ffb3ae846dd4308562e5e5b1ed961a51e
688,840
def _get_unique(layout, *args, **kwargs): """Helper function to get a unique result instead of a list when calling BIDSLayout.get Lets you choose from a list if ambiguous and raises an error if no match is found. Parameters ---------- layout : BIDSLayout So this can beused as an instance me...
4d9390bea4f4cd2da9c8c86b86d439ccaf378a30
688,841
import unicodedata def is_printable(char: str) -> bool: """ Determines if a chode point is printable/visible when printed. Args: char (str): Input code point. Returns: True if printable, False otherwise. """ letters = ('LC', 'Ll', 'Lm', 'Lo', 'Lt', 'Lu') numbers =...
7cd5b07b2d1400dd93633ec26a1ca80acb67231a
688,842
def convert_secret_hex_to_bytes(secret): """ Convert a string secret to bytes. """ return int(secret, 16).to_bytes(32, byteorder="big")
93b7b1973d32cb2dc1c48ae53fbd5ef8231737d3
688,843
from typing import Counter def count_items(column_list): """ Function count the users. Args: column_list: The data list that is doing to be iterable. Returns: A list with the item types and another list with the count values. """ item_types = [] count_items = [] ...
5800a93d2747348705b8b3e96b594f49e160e5ef
688,844
def get_brief_description(description): """Get brief description from paragraphs of command description.""" if description: return description[0] else: return 'No description available.'
eb41a9dc6dd6145defb81f73f63b604312020f6d
688,845
import numpy def my_average_error(y_true: numpy.ndarray, y_pred: numpy.ndarray): """ average error :param y_true: :param y_pred: :return: """ gap = y_pred - y_true ret = sum(gap) * 1.0 / len(y_true) return ret
4363646b26ccc142248d90b7fc3a2b99e8a84b4d
688,846
def needs_reversal(chain): """ Determine if the chain needs to be reversed. This is to set the chains such that they are in a canonical ordering Parameters ---------- chain : tuple A tuple of elements to treat as a chain Returns ------- needs_flip : bool Whether or...
b5ef8841fe01b9608b16b6823f103de56e654fa6
688,847
import logging def get_logger(): """Returns the common logger object. Don't use for standard output""" return logging.getLogger()
bdf74c89f4ea66d226313a50c8c7e05d7e1f8fcc
688,848
from typing import Dict from typing import Optional import shlex def format_args(args: Dict[str, Optional[str]]) -> str: """Quotes and joins arguments. :param args: Arguments to process. """ argument_list = [] for key, value in sorted(args.items()): argument_list.append(key) ...
af9c22c6bb85d641c8927aeab1fcaa51f3925484
688,849
def bulleted_list(items, max_count=None, indent=2): """Format a bulleted list of values.""" if max_count is not None and len(items) > max_count: item_list = list(items) items = item_list[: max_count - 1] items.append("...") items.append(item_list[-1]) line_template = (" " * ...
f62ec763348488dcc96880c02843baa509cf873f
688,850
def make_divisible(value, divisor, min_value=None, min_ratio=0.9): """Make divisible function. This function rounds the channel number to the nearest value that can be divisible by the divisor. It is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by ...
8da026b333fab308d3152cf088bf34f142eccd0c
688,851
def get_max_stack(ant_list): """Get size of largest possible ant stack.""" stacks = [0,] # 0/1 Knapsack Problem for ant in ant_list: temp_stacks = stacks[:] for i in range(len(stacks)): if stacks[i] <= 6 * ant: if i == len(stacks) - 1: te...
d1cebafc4fa6f56551c4ce2cd563c58e0f98b6b0
688,852
import json def read_experiment_infofile(fn): """ now the experiments are all writing out basic information. read this in here, to know the range of blocks. """ with open(fn, "r") as f: info = json.load(f) return info
47de660866660145e17827b4493ab848ec28aed3
688,853
import sys def jupyter_notebook_skeleton(): """Returns a dictionary with the elements of a Jupyter notebook""" py_version = sys.version_info notebook_skeleton = { "cells": [], "metadata": { "kernelspec": { "display_name": "Python " + str(py_version[0]), ...
e055b0082bafd44adbb3ca060b066447286c753f
688,854
import os def get_file_name(url_or_path): """Get standard file path by file_name and DATADIR.""" return os.path.basename(url_or_path)
9de25d6b9fc37dd8a94a63ddad1ab5fda98bc593
688,855
def _maybe_list_replace(lst, sublist, replacement): """Replace first occurrence of sublist in lst with replacement.""" new_list = [] idx = 0 replaced = False while idx < len(lst): if not replaced and lst[idx:idx + len(sublist)] == sublist: new_list.append(replacement) replaced = True idx...
3f75099928108190999d88bd79d488e735ce74bb
688,856
def PrintHtml(log): """Prints a log as HTML. Args: log: a Log namedtuple. """ def Tag(tag, cls, value): return '<%s class="%s">%s</%s>' % (tag, cls, value, tag) classes = ['filename', 'date', 'log'] line = ' '.join([Tag('span', cls, value) for cls, value in zip(classes, log)]) print(Tag('div', 'l...
df0836e13c090e058c49d73a2b6ee86b720588c9
688,858
def get_string_index(strings, substrings, exact=False): """ Search for the first index in list of strings that contains substr string anywhere or, if exact=True, contains an exact match. Args: ----- strings : List of strings to be searched substrings : List of strings to be...
bb904e925e6f2602af6d336b2ca458f4ff3eb220
688,859
def camel_case_to_lower_case_underscore(string): """ Split string by upper case letters. F.e. useful to convert camel case strings to underscore separated ones. @return words (list) """ words = [] from_char_position = 0 for current_char_position, char in enumerate(string): if c...
9faf739f5fe782ff0b87204afa3c292f82278a65
688,860
def get_max_offset_supported(atten): """Get maximum supported offset for given attenuation""" if atten >= 0.1: return (-8, +8) else: return (-2, +2)
9c246203e62823132ba68d56b7a6ab4e4da942cc
688,861
def log_likelihood_from(*, chi_squared: float, noise_normalization: float) -> float: """ Returns the log likelihood of each model data point's fit to the dataset, where: Log Likelihood = -0.5*[Chi_Squared_Term + Noise_Term] (see functions above for these definitions) Parameters ---------- chi_...
87dc243546ca17eedaed0534a3a1d2dd8171e435
688,862
def rename_fields(columns, data): """Replace any column names using a dict of 'old column name': 'new column name' """ return data.rename(columns=columns)
59d569faaf51759b96824fe869fdacb5d5240c94
688,863
def local_infection(file: dict) -> int: """Function that takes a dictionary of the local covid cases and return the 7 day infection rate""" data = file['data'] total_cases = [] # From the Covid API add the cases by day into a list for items in data: total_cases.append(items['cases']) ...
352fecb16ec227aa2bbaf46302dc578386184a46
688,864
def _user_is_admin_for(user, org): """ Whether this user is an administrator for the given org """ return org.administrators.filter(pk=user.pk).exists()
32c4f74a6d1ca8afdd783ea9197ee86100d0366b
688,865
import math def moss_lab_cs_to_cms(cms_theta, lab_cs_value): """Return cross section in CM frame by the given CM theta angle (for direct kinematics case) and lab CS value.""" m1, m2 = 1., 4. num = 1. + m1/m2*math.cos(cms_theta); den = (1. + m1**2/m2**2 + 2 * m1/m2*math.cos(cms_theta))**(3./2.) ...
e123c9c051ae60493ec289ed13b4fef3bc268d0c
688,866
import sys def get_samples(patient, names, samples): """ checks samples from arg.samples to insure indicated sample names are present in query request if all samples are requested, samples is returned with all sample names in a list """ if samples != 'All': for sample in samples: ...
ea931800e750126653a3c19b12158c1c6ef8c3cb
688,867
def drive_list(service, parent_id): """ List resources in parent_id """ query = "trashed=false and '%s' in parents" % parent_id response = service.files().list(q=query).execute() if response and 'items' in response and response['items']: return response['items'] return []
d901b69b39908c9b68dc05576c981e834d07a8b7
688,868
def _new_or_old_field_property(prop, new_field, old_field, old_priority): """ Get the given property on the old field or the new field, with priority given to a field of the user's choosing. Arguments: prop -- a string of the requested property name old_field -- the old field as a Field instance new_fiel...
4deef6347ae6077552fa5784f347ff0e07fa1c5e
688,869
import re def sanitize( word: str, chars=['.', ",", "-", "/", "#"], check_mongoengine=True) -> str: """Sanitize a word by removing unwanted characters and lowercase it. Args: word (str): the word to sanitize chars (list): a list of characters to remove check_mo...
28554008cd124fd4503c68153e97ccee0ad906f7
688,870
def add_space_to_parentheses(string: str): """ :param string: Must be a string :return: string with space before '(' and after ')' """ return string.replace('(', ' (').replace(')', ') ')
cc0bea2f82a2328bdf3a907f77a3ea992e729939
688,871
import os def _get_chat_file_path(instance, filename): """Save chat files in `MEDIA_ROOT/chats/UUID4.ext`.""" _, extension = os.path.splitext(filename) return f'chats/{instance.id}{extension}'
a07331e332465b9d2f484780c72198c9c8327a24
688,872
def chained(iterable): """flattens a single embed iterable""" return list(elm for sublist in iterable for elm in sublist)
bd26c164852cda3de8b282ccd4c8b9ddb3c249ef
688,873
def rest_list(): """Returns list of supported hyperglass API types""" rest = ["frr", "bird"] return rest
2cbca47b9b148a7cf199e04e3c6aaa162fbe4e15
688,874
def cast_type(cls, val, default): """Convert val to cls or return default.""" try: val = cls(val) except Exception: val = default return val
131ceceb42d053125d1a4fc19e9dea8eaf231d4a
688,875
def example1(name, value=42): """ example function :param name: name string :param value: something value """ print("Hello {}!".format(name)) return value
0d35d8098669801f99f8d937876029ede17cad62
688,876
def dict_fields(obj, parent=[]): """ reads a dictionary and returns a list of fields cojoined with a dot notation args: obj: the dictionary to parse parent: name for a parent key. used with a recursive call """ rtn_obj = {} for key, value in obj.items(): new_key = pa...
b86d268662f080cbbe019c96c2cdbf57353765af
688,877
import re def split_orb_name(name): """ split name to : n, l, label """ m = re.findall(r"(\d[a-z\d\-]*)(.*)", name) m = m[0] return m[0], m[1]
b460a697bc3a1d27e53ea472b65d9c271ff746b9
688,878
def is_insertion(row): """Encodes if the indel is an insertion or deletion. Args: row (pandas.Series): reference seq (str) at index 'ref' Returns: is_insertion (int): 0 if insertion, 1 if deletion """ is_insertion = 0 if row["ref"] == "-": is_insertion = 1 ret...
a358233643b4a4cf7ffe2a96828a3355e7d5ae3d
688,879
import os def knack_credentials(): """ Read Knack credentials from the local environment and construct headers object. Returns the headers with the the api key and api id. """ api_key = os.environ['KNACK_API_KEY'] api_id = os.environ['KNACK_API_ID'] headers = { 'Content-Type': "a...
81fd00ca7a31889dceb8a464584c54025c86f1d7
688,880
import textwrap def unindent(text: str) -> str: """Remove indentation from text""" return textwrap.dedent(text).strip()
035c46a9921a328902f84d71316707f854bf5201
688,881
from datetime import datetime def strftime_format(format): """Check if string satisfy the require format. Code modified from reference: `https://datatest.readthedocs.io/en/stable/how-to/date-time-str.html` Args: format: A format code. Returns: """ def func(value): try: ...
f00849f6ef6e28ae26acf2789288166c3da29984
688,882
def get_error_res(eval_id): """Creates a default error response based on the policy_evaluation_result structure Parameters: eval_id (String): Unique identifier for evaluation policy Returns: PolicyEvalResultStructure object: with the error state with the given id """ return { ...
ebb80435b6f0c590dc30a9095559cbbbd1da5662
688,883
import re import os def load_projects(configs): """Scans the project directories for GCP projects to check.""" filter_re = re.compile(r'^.+\.(env|sh)$') project_re = re.compile('^PROJECT="?([^"\r\n]+)"?$', re.MULTILINE) projects = set() for dirname, _, files in os.walk(configs): for path...
5fdd10b4a9d0e24a2c8fd27d4b059471a4fa6714
688,884
def index(): """Create the home page of the web app. Link to the second page. """ return """ <html> <head> <title>Hello world</title> </head> <body> Hello world! <br> <a href='/second_page.html'>LINK</a> to second page. ...
18b9e07d6914b868442f6ca5010f1896a2a1f5a5
688,885
def replaceSpaceByGuion(string): """ Funcion que reemplaza los espacios por guiones """ return string.replace(" ","-")
7a93ab99e76c7ad5be11d024d6061d3d0e8b4e8a
688,887
def torch_complement(tensor1, tensor2, boolean_out=False): """ Return the complement of tensors 1 and 2. """ boolean = [] for i in range(len(tensor1)): boolean_i = True if boolean.count(False) < len(tensor2): for j in range(len(tensor2)): if tens...
0d0cc386a7fbdb1414aa789fdb2e9bad9fcc561f
688,888
import string import random def gen_random_string(n=24): """Returns a random n-length string, suitable for a password or random secret""" # RFC 3986 section 2.3. unreserved characters (no special escapes required) char_set = string.ascii_letters + string.digits + "-._~" return "".join(random.choices(...
b3bd49ed5b89d886aefa7431b62d85b6f5ff1c60
688,889
def Percentile2(scores, percentile_rank): """Computes the value that corresponds to a given percentile rank. Slightly more efficient. """ scores.sort() index = percentile_rank * (len(scores)-1) / 100 return scores[index]
676eacd38e541eda917534c387659d34206cfa27
688,890
def query_adapter(interface, request, context=None, view=None, name=''): """Registry adapter lookup helper If view is provided, this function is trying to find a multi-adapter to given interface for request, context and view; if not found, the lookup is done for request and context, and finally only fo...
81c164ab122717cb31d001f3cf632da49183da87
688,891
def read_questionnaire_file(file_location): """Read file with boarding passes informations """ return open(file_location, 'r').read().split('\n\n')
55c388f4bb49edef74ffedc7bc18ae848fa81d87
688,892
from typing import Dict async def check_collector(collector: Dict, logger) -> bool: """ simple check of connection to http Logcollector :param collector: :param logger: :return: """ trace_request_ctx = {'logger': logger, 'name': collecto...
468b0dd51ea98ae0cece222dd7bd75bf6a9fae46
688,893
from typing import Optional def _rename_list( list1: list[str], method: str, list2: Optional[list[str]] = None ) -> list[str]: """Renames multiple list items following different methods. Method can be "consecutive" to rename identical consecutive items with increasing number or "fuse" to fuse with th...
df3385abef1c19a3a9056397c7f2549d615f9d8e
688,894
def base_contribute_score(): """ item cf base sim contribution score by user """ return 1
ca3ec888bf47645e7dc2833c187d47c117aa402f
688,897
def zotero_parser(zt): """ Treats the Cts object as a Zotero cts object. """ #print("zotero_parser") #print(zt) if zt.m.group(4) != '': zt.mode = zt.m.group(4) zt.number = zt.m.group(6) #print(f"Zotero extras: mode = {zt.mode}, number = {zt.number}") return zt
fc1885c6b0c5850f6f33088abdc20e5edd270a98
688,898
def ping(request): """ Simple resource to check that server is up. """ return 'pong'
957c7f4a0733a99292d8a04562e179317da63fb6
688,900