content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def deserialize_user(user): """JSON으로 인스턴스 deserialize""" return { 'id': user.id, 'username': user.username, 'email': user.email, 'first_name': user.first_name, 'last_name': user.last_name }
31ff9e7ee35780da0c410728e77ae2b4aebe702d
664,332
def cli_parse(parser): """Add method specific options to CLI parser. Parameters ---------- parser : argparse object Returns ---------- Updated argparse object """ parser.add_argument('-M', '--m-coef', type=int, required=False, default=4, help='M coefficient,...
d5c87c98b7641767a5dafa41219b1e30f1a88f9e
664,333
def _getSubtitleNumber(entry): """ Helper function that returns the subtitle number of a TTI block. Used to sort a list of TTI blocks by subtitle number. """ return entry['SN']
c72d4ee7df0007a316c33de5e35a14da62d77899
664,334
def qualitative_from_scheme(scheme, num_bins): """ Similar to sequential_from_scheme above, generates brew colors from full scheme. See http://www.albany.edu/faculty/fboscoe/papers/harrower2003.pdf, table 2. """ return tuple(scheme[:num_bins])
87443feeb2b9bfa4f6c673d11f046b0a4fc68b0b
664,335
def extract_amount(accident, base_key): """ Get the amound of wounded/dead people from the accident data. """ if not base_key in accident.keys(): return 0 else: if len(accident[base_key].keys()) == 2: return int(accident[base_key][f"{base_key}_min"]) else: ...
96dcef363243e116115b58be70adfbca3d46d101
664,336
def set_route_go_back(doctor_time,pi,sudden_id,sudden_time): """ 一度診療から戻ってきた人が見る """ backed_doctor = False backed_time = 0 for i in range(len(doctor_time)): if(doctor_time[i][-1]< sudden_time): print(doctor_time[i][-1]) print(sudden_time) backed_time =...
2af524b40db674e5a30be3bfe4fc46dfdc4b9738
664,337
def remove_outliers(target_df, low, high, exclude_cols): """ Remove outliers smaller than than the lower percentile value or those larger than the higher percentile value. For those features in exclude_cols, not remove outliers. param: target_df: num_df param: low: lower percentile param: h...
5ba34e2e6e30b9993c6c47f78f1b50d57b96c4f3
664,338
def write_bytes(fp, data): """ Write bytes to the file object and returns bytes written. :return: written byte size """ pos = fp.tell() fp.write(data) written = fp.tell() - pos assert written == len(data ), 'written=%d, expected=%d' % (written, len(data)) r...
4ffcfaa7005ce86d54382f273e2f801ba291dcba
664,339
def request_path(context): """Return request.path""" return context['request'].path
feebe8bb926632759ce98aeeebd7f1678005153d
664,340
def illegal(x): """Save the passengers if the pedestrians are crossing illegally.""" # if passenger vs passenger (shouldn't be possible) if x["Passenger_int"] == 1 and x["Passenger_noint"] == 1: return -1 # if ped v ped elif x["Passenger_int"] == 0 and x["Passenger_noint"] == 0: # ab...
fec47295e5e0ce3e41f0a0eaa92056e89cbc0e78
664,342
def ab(a, b, c): """Flip the result around to compare (a, b) with (b, a)""" return (a, c, b)
80e30f1913d29bd439521be5ee9e47f1415ec3db
664,343
import inspect def keyword(name=None, tags=(), types=()): """Decorator to set custom name, tags and argument types to keywords. This decorator creates ``robot_name``, ``robot_tags`` and ``robot_types`` attributes on the decorated keyword function or method based on the provided arguments. Robot Frame...
90bd90f4de9adafd657dba60c56cf4ffe74de097
664,344
def determine_position( beacon_from_scanner_with_unknown_position, beacon_from_scanner_with_known_position, known_position, ): """ :param beacon_from_scanner_with_known_position: beacon from Scanner with no position, rotated to be as if in XYZ :param beacon_from_scanner_with_known_position: same...
00eb49895854c1242b59382c400a3b68c45593d7
664,345
def cache_in_state(*depends_on): """Decorator to memoize / cache output of a function of state variable(s). Used to wrap functions of a chain state vaiable(s) to allow caching of the values computed to prevent recomputation when possible. Args: *depends_on: One or more strings defining which st...
96808e11ca04f71ba40f91df0877066f54b7d783
664,346
import math def truncate_middle(content, max_length, middle="..."): """ Truncates the middle part of the string if the total length if too long. For example: truncate_middle('testabcdecho', 8) == 'tes...ho' :param content: The string that must be truncated. :type: str :param max_length: ...
16f9ec8e6210ab2820a78328e2f21ec6d636b787
664,347
import os def file_exists(filename): """ Utility function to check if a specified file exists (or not) :param filename: the file name to validate exists :returns: True if the file exists and is a file (e.g. not a directory), : otherwise False. """ return os.path.isfile(filename)
ec5328dcea10775bf24ed40e026be3dd9d6a97ea
664,348
def BF_shortest_path(g, source): """Returns the shortest path between a source and all the other verices of a graph using the Bellman-Ford algorithm. Args: g (graph): a graph object. source (node val data type): the data of the source node. Returns: (list) the shortest path from the...
b3626a14f7b769ac4e180bcb3c252fe8303fad97
664,349
from typing import Dict from typing import Set def definition_map() -> Dict[str, Set[str]]: """Used to represent the result of `parse_definition_nodes_from_codebase`""" return { "reverse_string": {"my_package/strings/strings.py"}, "concatenate_strings": {"my_package/strings/strings.py"}, ...
0e4cda0e497dd2bc5ad84cf894fc45d9fc0cdadd
664,350
def support(ctx) -> str: """Truck Simulator support server""" return "https://discord.gg/FzAxtGTUhN"
ceb902a959cea0759e5259477b1e5c9cad8fbbac
664,351
def merge_jsons(jsons): """Merge JSONS returned from api.API.retrieve_pages. Args: jsons (list[dict]): Having the form: {"query": { "normalized": [ { "from": "", "to": "", }, ], "redirects": [ { "from": "", "to": "...
3fcf62b4c94b71972037727e7adbb39cc158186b
664,352
import string import unicodedata def clean_filename(filename, whitelist=None, replace=" "): """ https://gist.github.com/wassname/1393c4a57cfcbf03641dbc31886123b8 """ if whitelist is None: whitelist = "-_.() %s%s" % (string.ascii_letters, string.digits) char_limit = 255 # replace space...
d3c31e7abc24a902d5d0deed7f9714112169fbed
664,353
def sub(proto, *args): """ This really should be a built-in function. """ try: text = proto.format(*args) except: text = "--" #print sub("WARNING: Couldn't sub {} with {}", proto, args) return text
830c80e1ddbb2243695e50235c183205c38f6225
664,354
def truncate_description(desc: str) -> str: """Take the first line of a multiline description, truncated to 40 chars""" first_line = desc.strip().split("\n")[0] return first_line[:40]
387eebfcdbe1bbe1917226dd2a98763c8c8bad6e
664,355
import re def _check_separator(line, read_order): """Identify data separators, tabs or blanks """ temp = line.strip() lread = len(read_order) terms1 = re.split('\t', temp) # terms2 = re.split(' ', temp) if len(terms1) == lread: use_tabs = True print('Information: Reading ta...
62a5bf90d77a2a48cedce90ab9d7f4c8e421f0ba
664,356
import os def split_env_flag(name): """Converts a comma-delimited env var into a list. Args: name: (str) the name of the environment variable Returns: (list<str>) the elements of the comma-delimited list, or an empty list if the env variable is empty or unset """ if name not ...
4e5f7b5da00cea8d8e4b6d18c4be505b4933865c
664,357
def get_multi_cum_impact(graph, max_levels=100): """Add cumulative impact ``cum_impact`` to each ``technosphere`` level of a multi method tagged graph. This function recurses until all levels in the graph have been checked, or the ``max_levels`` cutoff is reached Input arguments: * ``graph``: A t...
1a6c218227ed59f94f23296b06c3c73ae175d5f1
664,358
def clean_string(string:str)->str: """ Clean a string removing symbols, capitalize each word and join. string -- string to be cleaned. return -- cleaned string. """ string_cleaned = string.translate(str.maketrans(' ', ' ', '!"“”#$%&\'()*+/:;<=>?@[\\]^_`{|}~')) return ''.join([i.capitalize() ...
5c43f3cbe752d9915e923d62b1a1bad406950172
664,359
def base_test_dir(tmp_path_factory): """Creates a temporary directory for the tests.""" return tmp_path_factory.mktemp("test_files")
ec8e1f123378f6d0fa4c938f664ccc665d3c4c3f
664,360
import threading def or_events(*events): """Or multiple events together. Does not clear the underlying events""" or_event = threading.Event() def changed(): if any(e.is_set() for e in events): or_event.set() else: or_event.clear() def orify(e, changed_callback...
a0a468a23e445ef360a73c31d33dee774cf72d5d
664,361
def find_by_href(browser, link): """ - Encontrar o Elemento 'a' com o link `link` """ elementos = browser.find_elements_by_tag_name('a') for elemento in elementos: if link in elemento.get_attribute('href'): return elemento
cdc9e54a72d6cbdeac842d2ba2f0e694463c38e3
664,362
def fmt_identify_name(v): """ v: ('rs1045288|11:237087:A:G', 'rs1128320|11:244167:C:T',) """ return ','.join(v)
b4e73864889ea00aeb3964b039eefb67facfc134
664,363
def elife_journal_volume(pub_date): """ volume value is based on the pub date year pub_date is a python time object """ try: volume = str(pub_date.tm_year - 2011) except: volume = None return volume
2f020bd4cec1eb21b9df0db435f7264375faa153
664,364
def _user_can_administer(user, org): """ Whether this user can administer the given org """ return user.is_superuser or org.administrators.filter(pk=user.pk).exists()
4664011e1cd28a149fedb5981f7d1f4595f0699b
664,365
def _get_element_type(tag): """This function extracts the type of tag specified in tag Args: tag (str or bytes): Full valid html tag from < to > Returns: str: type of HTML tag, e.g. div, p, meta, span, td, etc """ # decode tag parameter if its a bytes object tag = tag.decode() ...
42548a9f33ceeaa1126eafdc128b496b435eb2fb
664,366
def prevent_sentence_boundary_detection(doc): """ Parameters ---------- doc: spacy.Doc Returns ------- spacy.Doc """ for token in doc: # This will entirely disable spaCy's sentence detection token.is_sent_start = False return doc
5e9658dfebee2df06ecef9136d05c2c0c5bbe9e3
664,367
import os def getname_fromdirname(): """ Sets stoichiometry as the directory name if no -s is specified """ cwd = os.getcwd() return cwd.split('/')[-1]
41bbdd72f720895b4772f9ae272a2cd55eb8fdde
664,368
def convert_to_normal_tensor(tensor, orig_device): """ For some backends, such as NCCL, communication only works if the tensor is on the GPU. This converts the tensor back to original device. """ if tensor.is_cuda and orig_device == "cpu": tensor = tensor.cpu() return tensor
b04fa35768f08c2046c46006695a66884508286b
664,369
def internal_metabase_url(): """The URL under which the Metabase instance can be reached by from mara (usually circumventing SSOs etc.)""" return 'http://127.0.0.1:3000'
c15bb7590e44b0ade895908ce748b5161d8047a0
664,370
import torch def safe_sqrt(A: torch.Tensor, eps: float = float(1e-4)) -> torch.Tensor: """ performs safe differentiable sqrt """ return (torch.clamp(A, float(0)) + eps).sqrt()
e5430b3d3cd01329a7ac0506ec09a48e3bebd3b5
664,371
import requests import json def query_vep(variants, search_distance): """Query VEP and return results in JSON format. Upstream/downstream genes are searched up to a given distance.""" ensembl_request_url = 'https://rest.ensembl.org/vep/human/region' headers = {'Content-Type': 'application/json', 'Accept':...
05558f329bf1f7deef3479937c1c54831492ee8a
664,372
def to_none(field): """ Returns the value of None for input empty strings and empty lists. """ if field == '' or field == []: return None else: return field
585e67f79ad779f0905828f4ea837f7e2e03f1d6
664,374
def ReadFile(file_path): """Returns the content of |file_path|.""" with open(file_path) as f: content = f.read() return content
4092e80a67c8495c0f71e0d4da358a9d1b98391d
664,375
from typing import Dict from typing import Hashable from typing import List def _switch_keys_and_values( key_value: Dict[Hashable, int] ) -> Dict[int, List[Hashable]]: """ Returns dictionary with switched key-value arguments where new values (old keys) stored in the list. """ value_key = {} ...
7c76cd2caea4f0a8215b026725d5896512517083
664,376
from pathlib import Path import subprocess def is_git_repo(path: Path) -> bool: """Check whether directory is already a git repository.""" if Path(path / ".git").exists(): return True try: subprocess.run( ["git", "rev-parse", "--git-dir"], check=True, capture_output=True ...
5d2638e39d837dd7c70c94a876d77dae78de4ade
664,377
def should_assume_role(role_arn): """ Handles the case when AWS_IAM_ROLE_ARN Codefresh input parameter is omitted, which will cause the role ARN to contain the literal string "${{AWS_IAM_ROLE_ARN}}". In this case, we do not want to assume role. """ if role_arn == '${{AWS_IAM_ROLE_ARN}}': ...
3cc012977839a9edcf4bc533c29d0628ccd13d99
664,378
import torch def up_sample_points_torch_memory_efficient(points, times=1): """ Upsamples points based on nearest neighbors. Takes two neareast neighbors and finds the centroid and that becomes the new point. :param points: N x 3 """ for t in range(times): # dist = torch.unsqueeze(p...
61f2c418bdc841cbc64ef38aec83b9caf6207e02
664,379
def numberOfWaysToMakeChange(n, denoms): """ ways[amount] += ways[amount - denomination] ways[amount] = ways[amount - denomination] + ways[amount] for amount - denomination >= 0 base case: ways[amount=0] = number of ways for smallest demomination """ ways = [0] * (n + 1) # Base case: the...
5b9f28abf014048b121670e7ce04c7d0d96d36b9
664,381
def zipped(): """ Zipped strings """ return [ ('120(0,3,5,8,9)', [120, 123, 125, 128, 129]), ('12(1,4),140(0,2,5)', [13, 16, 140, 142, 145]) ]
cc6086bf2e406922250332983dfef72ba9e5457c
664,382
def pad(*dicts): """ Pad dicts according to the head dict of input """ if not dicts: return dicts dict_base = dicts[0] for d in dicts[1:]: for k in dict_base.keys(): if k not in d: d[k] = dict_base[k] return dicts
d202457ebf0f27097b4ff523c26e442bd7091418
664,383
def converged(losses, window=10, threshold=0.0001): """"Detect loss convergence in a window.""" try: if len(losses) < window: return False losses = losses[-window:] return max(losses) - min(losses) < threshold except: return False
560f2aacc66300e097c7c353cad7ae1f0d0578a2
664,384
from typing import Union from pathlib import Path from typing import Any import pickle def read_pickle(path: Union[str, Path]) -> Any: """ Read a pickle file from path. Args: path: File path Returns: Unpickled object """ with open(path, "rb") as fp: return pickle.load...
53511f4b00bac4af6c2ed4150efc4b3dc575f59c
664,385
def dump_vcd(request): """Dump VCD for each test.""" if request.config.option.dump_vcd: test_module = request.module.__name__ test_name = request.node.name return '{}.{}.vcd'.format( test_module, test_name ) else: return ''
7a8d21cebeed768c06776a4e9ab0ca6691e6fef1
664,386
def first_sub_method(): """First sub-sibling package method.""" return 1
7a15b139ee03b351426be4c78de8f5d07949f15e
664,387
def get_agent_config(node_properties): """cloudify_agent is deprecated, but still might be used in older systems, so we try to gather the agent config from both sources """ agent_config = node_properties.get('cloudify_agent', {}) agent_config.update(node_properties.get('agent_config', {})) retur...
3db985e001fa10e6dd5b9329501e47f9003932c7
664,389
import torch from typing import OrderedDict def load_model(fname,model): """ Load saved model's parameter dictionary to initialized model. The function will remove any ``.module`` string from parameter's name. Parameters ---------- fname : :py:class:`str` Path to saved model model :...
561a0d2557aa92321cd8a3603cfc9d0f3cbb4b29
664,391
def range_from_eigth(): """ Return the list [8, 6, 4, 2, 0, -2, -4, -6, -8] :return: the list [8, 6, 4, 2, 0, -2, -4, -6, -8] >>> range_from_eigth() [8, 6, 4, 2, 0, -2, -4, -6, -8] """ return range(8, -9, -2)
e87d1d6f9da0e571d37ceeb631ee5ea80f754ca0
664,392
def task_test(): """ Run tests and display basic coverage """ return {'actions': ['go test -cover ./...'], 'verbosity': 2}
570ad998ad275e80681aebb7ba32eb01118778b6
664,393
def get_monitor_table_constraints(data_dict, table_name): """Add any necessary table constrains to the given table via the ``data_dict``. Parameters ---------- data_dict : dict A dictionary whose keys are column names and whose values are column definitions. table_name : str ...
e529c4c7f4dbef484fbc7ad65828a39740faeb58
664,394
import socket def unused_port(hostname): """Return a port that is unused on the current host.""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((hostname, 0)) port = s.getsockname()[1] s.close() return port
c33be922d2663355b7df03c2a135535079186bac
664,395
def echo(request): """For testing purposes only.""" return request.POST
776f301cab18fc7215dabce30e27a2d147b245bd
664,396
import sys def root_tree(t, spe2age=None, midpoint=False): """Root a Phylogenetic tree. Parameters ---------- t : Tree Tree to root. spe2age : dict Species2age dictionary if available. midpoint : bool Use midpoint rooting. Returns ------- tree Root...
fdfdf03359144a845ce0df117ebb3cc66f8c5632
664,397
def get_tree(data, parent_id): """根据list返回多级树形分类 Args: data: 原始list数据 parent_id: 从哪级菜单开始生成 """ result = [] for d in data: if d['parent_id'] == parent_id: _id = d['id'] d.update(dict(children=get_tree(data, _id))) if not d['children']: d.po...
7625f4fb61c7c9767c5e89df485e5eef923ba08e
664,398
from typing import Callable from typing import Any def compose(*funcs: Callable[..., Any]) -> Callable[..., Any]: """ Composes two or more functions. :funcs: The functions to be composed. :return: The composition of the two functions. """ if not funcs: raise ValueError("No functions t...
809e9e9e34f567410c895e98bb0f659c6832b69d
664,399
def addSolverOptions(arg_parser, skip_velpart=False): """ Adds common arguments for all input formats to the argument parser handle. """ arg_parser.add_argument('-s', '--solver', metavar='SOLVER', help="""Trajectory solver to use. \n - 'original' - Monte Carlo solver - 'gural0' - Gural constant...
2682aa65ab50acf82cd23c0203b260d1d4c914da
664,400
def get_values_as_int(history, key): """Retrieve values from sequence of dictionaries, convert all values to int.""" return [int(i[key]) for i in history]
9c762fc25f33b41b1d24b54f0f27f1e1359a7aca
664,401
from pathlib import Path def empty_ref_tree(tmpdir): """Empty reference directory.""" tree = Path(tmpdir) / "ref" tree.mkdir() return tree
cc2adfd099f1adf3f95aa4ce7dd604db4a6364d9
664,402
def load_table(handle): """ Loads Data Table """ data = {} for line in handle: if line.startswith('#'): continue line = line.strip().split(',') values = line[:-1] gene = line[-1] if '#' in gene: continue if gene.count(';') < 4: continu...
9e2cb06a147e5f21c04f00e71f417a74e78b8a31
664,403
def format_typename(object): """format the typename and return only the last part""" return str(type(object)).split("'")[1].split(".")[-1]
7f6c69ba5e32bad6fe9ddf73482fc0227f1bb39d
664,404
import argparse def parse_args(): """Parse the arguments given with program call""" parser = argparse.ArgumentParser() parser.add_argument( "-t", "--train", required=True, action="store", dest="f_train", help="name of train file", ) parser.add_argument( "-d", "--dev", required=T...
ccc96df30f06231ffb738cb3ec00813fb14960d9
664,405
import random def split_cases(cases, part=0.5): """Randomly split a list into two parts. part is a float between 0 and 1, indicating the relative size of the first part. """ cases = cases.copy() random.shuffle(cases) idx = int(len(cases) * part) return cases[:idx], cases[idx:]
34c726abc106e15f41edcaa84896b9e41d6decee
664,406
def _make_signal_unique(signal_name: str, db: dict) -> str: """ Preserve duplicated signal in WaveDrom format by adding extra space that will be removed later on. Add as many spaces it is required to make the identifier unique. """ new_name = signal_name while new_name in db: new_nam...
eab7a8ffe018799f4150aa8d13d34fdbd04464e3
664,407
def clean_results_for_printing(results): """ creates a column for final output file """ output = [] for k, v in results.items(): if k != 'Field': output.append(v) return output
e4ceb3d755808b498ffd8a1285c2a68e723b33ea
664,408
def get_annot_reviewed_matching_aids(ibs, aid_list, eager=True, nInput=None): """ Returns a list of the aids that were reviewed as candidate matches to the input aid """ ANNOT_ROWID1 = 'annot_rowid1' ANNOT_ROWID2 = 'annot_rowid2' params_iter = [(aid,) for aid in aid_list] colnames = (ANNOT_R...
6181772fae00a13a25df9d3bea6513c394382e42
664,409
def never_swap(doors, past_selections): """ Strategy that never swaps when given a chance. """ return past_selections[-1]
77c318afdc6aea3d5d35a1ce97fe57878efc7383
664,411
def get_threshold(ctx, param, value): """ Obtains a threshold from the given parameter. """ if value is not None: try: return int(value) except ValueError: if value not in ['cohort', 'cluster']: raise ValueError('must be a number, "cohort", o...
cd1ee974ebe9de6a3be1f1d36512c01a87ae54ed
664,412
from typing import List from typing import Dict from typing import Set def get_unique_affected_entity_ids(security_problems: List[Dict]) -> Set[str]: """Extract all unique affected entity IDs from a list of security problems. :param security_problems: the security problems, parsed from JSON to Dicts of Dicts ...
ffcfd9189e83ac7f0aa4c252216f47e2361713d7
664,413
import re def get_anchor_format(a): """Extract the resource file-type format from the anchor""" # (. or format=) then (file_extension) then (? or $) # e.g. "...format=txt" or "...download.mp4?..." file_format = re.search("(?:\.|format=)(\w+)(?:\?.*)?$", a) return file_format.group(1) if file_forma...
59ce6a76f82b84e8d20b2a10bd3c4130b1960656
664,415
def list_(detail=False, **kwargs): """Return list of flavors.""" url = '/flavors' if detail: url = '%s/detail' % url return url, {}
dfeb82e6a7c84650aebed391fcc471c71b8d4503
664,416
import copy def convert_to_binary_cols(df, col, vals, targ_vals): """ convert_to_binary_cols(df, col, vals, targ_vals) Returns the input dataframe with the column values converted to categorical binary columns. The original column is dropped. Required args: - df (pd DataFrame): dataframe...
c70d46a41de933977538e1d10092fdd4380be8b6
664,417
def _invoke_account_delete_aws(self, cloud_account_uuid): """Invokes initiation of Delete AWS Account in Polaris Arguments: polaris_account_id {str} -- Account ID to initiate delete in Polaris """ try: query_name = "accounts_aws_delete_initiate" variables = { "cloud_...
2b5367a718a4e4d2f0e8039674821f85e780deb5
664,419
def compute_avg_cosine(similarity_result, topn): """ Compute and return the average cosine similarities. Args ---- similarity_result (list): List of word:cosine similarity dict pairs. Return: avg_cosine (float): Computed average cosine similarity """ if len(similarity_result) >=...
fa107c66559342c7a66f5fee947cd3caeda40e9c
664,420
def default_preprocessing(df): """Replace Attrition Yes/No with 1/0""" status_map = {'No': 1, 'Yes': 0} df['Attrition'] = df['Attrition'].replace(status_map) return df
5bf0e0a87141cc4381d28edb4e40a343649083e0
664,421
def slash_tokenize(message): """Carefully discover tokens.""" tokens = [] accum = "" i = 0 size = len(message) # In-line comments are already gone at this point while i < size: char = message[i] if char == "/": tokens.append(accum) accum = "" e...
9385a412efeadb873a42e264b5f699089600e6ce
664,422
from datetime import datetime import os def insert_before_extension(filename: str, s: str = '') -> str: """ Insert string [s] before the extension in [filename], separated with '.'. If [s] is empty, generates a date/timestamp. If [filename] has no extension, appends [s]. Examples >>> insert_...
db8485499774a60086c06139e04f53d9287dce94
664,423
def valid(board, val, pos): """Checks if value is valid to be entered in the cell or not params : val : int pos : tuple (cell cordinates) returns : boolean """ # Check row for i in range(len(board[0])): if board[pos[0]][i] == val and pos[1] != i: return False # C...
91b5aacc35f5ffe44388f678530cfc7f0e41a7d8
664,424
import numpy def xyy2xyz(vector): """Convert from xyY to XYZ. Note: xyY is sometimes called xyL.""" #x = vector[0], y = vector[1], Y = vector[2] assert(isinstance(vector, numpy.ndarray)) assert(len(vector) == 3) return numpy.array([vector[0]*vector[2] / vector[1], vect...
20d1ca73dd0bc61795b4eacecd280f7eb26cedb9
664,425
async def check_credentials(config): """Confirms bot owner set credentials""" client_id = await config.client_id() secret = await config.client_secret() return client_id and secret
a645f753ebb1db8536768040cb67f57ac32a98fe
664,426
from typing import List def convert_records_to_dict(records: List[tuple]) -> dict: """Converts pyscopg2 records list to a dict.""" dict = {} for record in records: # Add record tuple data to dict. dict[record[0]] = record[1] return dict
523efb6c040779c3b885acdbf304177556e04c67
664,427
from typing import Union def is_number(value: Union[int, float, str]) -> bool: """ Checks if a value is a numeric type or if all characters in the string are digits. Parameters ---------- value: int, float, str """ is_numeric_type = isinstance(value, (int, float)) is_all_digit = is_numeric_type or (isinsta...
e3f6f7f4abb6d381833e40f5702fcc1024a7259a
664,428
def parse_status(data: dict) -> bool: """ Health Parser for endpoints that report status: pass warn or fail are both considered unhealthy See also: https://tools.ietf.org/html/draft-inadarei-api-health-check-04 """ return str(data.get('status', '')).lower() in ("pass", "ok", "up")
66b552f8d991bb41eef17212aff906e1c18eb518
664,429
import numpy def allclose( a, b, tol=0.00001 ): """ Like numpy.allclose but treat Nan == Nan """ d = numpy.absolute( a - b ) return numpy.all( numpy.isnan( d ) | ( d < tol ) )
d3a915c0b956c653a38083c6614614d209bf1897
664,430
from operator import xor def repeating_xor(key, bytes_): """Repeating-key XOR.""" quotient = len(bytes_) // len(key) remainder = len(bytes_) % len(key) pad = key * quotient + key[:remainder] return xor(pad, bytes_)
072e0932998e38ba475e8e87f1b67683ca113889
664,431
def is_key(obj): """Return True if object is most likely a key.""" if obj is not None and isinstance(obj, str): return "'" in obj
6eddb53f055dceac81db5056ec4b2dc8a246cc2b
664,432
import numpy def GetDistance(tan1, tan2, cos3): """Calculate Distance D.""" temp = tan1 * tan1 + tan2 * tan2 - 2. * tan1 * tan2 * cos3 res = numpy.sqrt(numpy.maximum(0., temp)) return res
be44b944ceaf84d19c92663d9e2ba1d2138a7b7b
664,433
import os def get_file_extension(fname): """Get the file extension.""" return os.path.splitext(fname)[1]
b5c8ea71ce570387d79e491b6d77cc2f140c67dc
664,434
def is_channel(string): """Check if a string is a channel name. Returns true if the argument is a channel name, otherwise false. """ return string and string[0] in "#&+!"
bbc3ece0ec5beaa8442e5c3e25866362b5e76eef
664,435
def find_gpu_ready_for_task(gpu_status, task): """ Returns the index of thegpu in gpu_status with memfree >= memory_req with the fewest running tasks Args: gpu_status (list of GpuStatus) task (list of Task) Returns: gpu.index (int) """ # of the set of GPUs with su...
79a0bcfd5a8eafeaa7f14473adac42a20ee43578
664,436
def update_user(username, event) -> str: """ Placeholder to handle updating the given user based on the event type """ event_type = event["event"]["type"] if event_type == "escalate": message = f"Escalating user: {username}" elif event_type == "deescalate": message = f"Deescalati...
1df36c0b58cc1d470f3b330c5f0d6d2c1280c656
664,437
from typing import OrderedDict from typing import Counter def get_token_count(tokenlist): """ function to read training data token token list args: tokenlist: list of documents as sequence of tokens returns: vocab: counter of document token occurances as ordered dict """ vocab ...
990edb2ec998a5a12fcf7d12c8e7b43d5c6c7005
664,438
def cmd( admin_only=False, acl="*", aliases=None, while_ignored=False, reply_in_thread=False, reply_broadcast=False, parse=None, strip_formatting=False, *args, **kwargs ): """ Decorator to mark plugin functions as commands in the form of !<cmd_name> * admin_only - in...
53d55b9246b0e2d0df01744ed82fe7843e896364
664,440