content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def yang(x, epsilon): """ x and epsilon are R^5 vectors, x[i] <= 5 (?) """ return sum([epsilon[i] * abs(x[i]) ** (i + 1) for i in range(len(x))])
a6c36d03a15504bda499c83979921f2e16ad52df
657,132
def argument(*args, **kwargs): """ Decorator to create arguments for argparse commands. The arguments to this decorator are used as arguments for the argparse argument. Does only work if the decorated function was decorated with the command-decorator before. """ def decorator(func): ...
5b95cd60908bed592d4ce3bd6894ae05590a15bc
657,133
def count_even(lst: list) -> int: """ return a number of the even numbers in list lst -- list """ return len(list(filter(lambda x: x%2==0, lst)))
51aa4961f303774fdc06b308055151459f048774
657,134
import pytz from datetime import datetime def float_to_datetime(timestamp, tzinfo=None): """ Convert a timestamp to a datetime instance. If tzinfo is passed, interpret the timestamp in the given timezone. If tzinfo isn't passed, interpret the timestamp as UTC. For example, epoch starts at 1am CET...
f74dadce58664115e7f29c92723540be4e5f71e9
657,135
def euler114(l=50, size_min=3): """Solution for problem 114.""" no_block, block = 1, 0 nb_comb = [] for i in range(l): # Dynamic programming # Combinations of length n ending with no block are generated taking all combinations of length n-1. # Combinations of length n ending wi...
3ee4c691c1e016968c47588be8e58e1631a62874
657,136
from typing import Any import time def measure_time(func: Any) -> Any: """ Measures and prints execution time for function. Args: func: Function to monitor. Returns: inner function. """ def inner(*args, **kwargs): start = time.time() try: return fun...
bc1096ad33752b16f6f2042dead503250dc2dd40
657,137
import hashlib def md5_for_file(f, block_size=2**20): """ Reads in a file, f, using a configurable block size, block_size. Returns an md5 hash of the content of the file """ m = hashlib.md5() with open(f , "rb" ) as f: while True: buf = f.read(block_size) if no...
755bf925b2d1d7d5a474b567f2ae2d9798e2eb65
657,138
from typing import List def calculateVoltageDifference(adapters: List[int]) -> int: """ Given a list of adapters, calculate product of 1-volt and 3-volt diffs """ oneDiff: int = 0 threeDiff: int = 1 # your phone adapter's diff prev: int = 0 for i in range(len(adapters)): diff: int = abs(pr...
83facdd5579c23e817cb04d92e3ce675504812a6
657,139
import sys def ff(fstring): """Emulates Python 3.6+ f-strings""" fr = sys._getframe(1) kw = fr.f_globals.copy() kw.update(fr.f_locals) return fstring.format(**kw)
1c5fdf188ffe8d91adcfb02318d811a9031669ca
657,140
def search(misp, **kwargs): """ Search the MISP server and return records that match misp: The MISP server connection object kwargs: The specification of the search (e.g. controller="attributes", org="CIRCL") """ res = {} try: r = misp.search(**kwargs) if r.get('errors'): ...
1328139502f4968b922e16a080f487c07f34bb4f
657,141
def str_timedelta(dt, max_num_fields=3, short=False, negative_to_zero = False): """ Given a dt in seconds, return it in a HH:MM:SS format. :param dt: a TimeDelta object :param max_num_fields: maximum number of non-zero fields to show (for instance if the number of days is non-zero, shows only ...
c083ea4bdb6cc15f15034afd909c373d3af583aa
657,142
import math def areaToDiameter(area): """Returns the diameter of a circle based on a given area Args: area (int): The area in pixels. Returns: diameter (int): The diameter of the corresponding circle. """ return (2 * math.sqrt((area / math.pi)))
95b9df916d0351148e5a016714ab7aca2d298d80
657,143
def upstream_authority(valid_authority): """ Authority of the upstream API used to validate certificates sent from APIcast. May be overwritten to configure different test cases. """ return valid_authority
9fc14040a926393a46611b7b3971b205de1ee27a
657,144
def escape(s): """Escape characters forbidden by Telegram API""" # to_escape = '_*~[]()`#+-|{}.!' # for c in to_escape: # s = s.replace(c, '\\' + c) return s
3dce0d2ac3dcfb207b9956f803b8bfa9539ff35b
657,145
import sys def equal_float(a, b, decimals=None): """Returns True if a and b are equal to the limits of the machine's accuracy or to the specified number of decimal places if specified >>> equal_float(.1, .1), equal_float(.000000000001, .000000000001) (True, True) >>> equal_float(.00000000000101, ...
3cefcb0d2f2a6c8f2000f8bb81d119d087512339
657,146
def proxify(scraped_urls,prefix): """ This method takes a list of scraped urls and turns them into urls that go through the UW Library proxy so that all of them are full access. """ proxy_urls = [] for url in scraped_urls: sd_id = url[32:] newlink = prefix + sd_id proxy_...
a9e66c33b1ee0fd9c7b754cf8c443acbb98232f4
657,147
def render_js(url, defer=False): """Render tag to include Javascript resource""" return '<script type="text/javascript" src="%s"%s></script>' % \ (url, ' defer' if defer else '')
cb0a4292c9d261c4896dcb7db5828de1af4b16dc
657,149
def get_intent_by_name(intent_list: list, intent_name: str): """Get an intent by name from an intent list.""" for intent in intent_list: if intent.display_name == intent_name: return intent return None
4b1137a788d891baef29bd4b4df26172c773f943
657,150
def makeEntry(filename, lineNumber, sig): """Returns the string that is inserted into the header.""" text = sig + "; \t// \"" + filename + "\"(" + str(lineNumber) + ")" return text
4c183463d051d30657442dcbef6a980310674cf6
657,151
import re def parse_all_args(parser): """ Parse known and unknown args """ common_options, other_args = parser.parse_known_args() other_options = dict() index = 0 n = len(other_args) float_pattern = re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$') while index < n: # only str, int and...
d12a39ad52c9e03ac5f5a13458d7b60bbc98d772
657,152
import os def save_page(body, fn, folder="../results/runs/"): """ saves text to file """ target = os.path.join(folder, fn) with open(target, "w") as f: f.write(body) return target
de723f5771c9a2b7b7094292b7d3a436c620230f
657,153
import ast from typing import Callable def unary_op(op: ast.unaryop) -> Callable[[ast.expr], ast.UnaryOp]: """Generate an ast unary operation""" def _unary_op(operand: ast.expr) -> ast.UnaryOp: return ast.UnaryOp(op=op, operand=operand) return _unary_op
d5217b16e11221b71a755c47f335331ab60c96fc
657,154
import torch def accuracy(output, target): """Computes the precision@k for the specified values of k""" with torch.no_grad(): pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability correct = pred.eq(target.view_as(pred)).sum().item() batch_size = target.s...
d77a65d376de8ed5c0dcb40c61fdf5c514e53d0c
657,156
def has_unittest_attr(item, attr): """ Check if a test item has a specific attribute set. This is basically a compatability layer while Salt migrates to PyTest """ if hasattr(item.obj, attr): return True if item.cls and hasattr(item.cls, attr): return True if item.parent and...
bdea04fc837fac552671c7bd3b926c477f439f94
657,157
import numpy def _estimate_from_fit(xhat, slope, intercept, xlog=False, ylog=False): """Estimate the dependent variables of a linear fit given x-data and linear parameters. Parameters ---------- xhat : numpy array or pandas Series/DataFrame The input independent variable of the fit sl...
8cb6a84e3230805d49d22209a116aaeda047fcbb
657,158
def assemble(*funs): """Helper function to assemble a preprocessing pipeline. Example: `pre = assemple(lower, replace_numbers)`. :param functions that will compose the pipeline :return a sequential pipeline function to be used by Minuet .""" def closure(x): for f in funs: x...
01a92e1c7a52cafcfd3f932f90fbdf4c66ae5d77
657,159
def read_file(fname): """ Get a file into a list of strings (one entry=one line) """ with open(fname) as f: lines = f.readlines() return lines
d0322839e510c46209b6716739a6f371292e17a5
657,160
def sort_dict_desc(dictionary): """Sorts dictionary in descending order by values.""" return sorted(dictionary.items(), key=lambda item: item[1], reverse=True)
da218da1f4fea7f7bd9ba9d310e86f37a9ee28e1
657,163
import numpy def prepare_points(*,GEOM_PARAMS_OPTIMAL : dict, name : str, SENSITIVITY_RANGE : float, NUM_PTS : int) -> numpy.ndarray: """ Prepare sensitivity points. SENSITIVITY_RANGE : sensitivity range around nominal value in percent, e.g. 5. """ start_value = (1.0-SENSITIVITY_RANGE/100.0) * GEO...
4c0ef9c35d4d8c664532993e5324979e098b3be5
657,164
import os def get_binary(tool): """Convert tool command to its environment variable, if it is set.""" if tool.split(".")[0].upper() in os.environ: tool = os.environ[tool.split(".")[0].upper()] return tool
4673c798d07448ba7ccaaed08ff5932475cef6f9
657,165
def LCSWithValues(S1,S2): """returns the longest common string""" if S1 == "" or S2 == "": return (0, "") if S1[0] == S2[0]: result = LCSWithValues(S1[1:], S2[1:]) return (1 + result[0], S1[0] + result[1]) useS1 = LCSWithValues(S1, S2[1:]) useS2 = LCSWithValues(S1[1:], S2) ...
7419bab54c4c96589b7a8b0b767b726c76579af2
657,166
import subprocess import textwrap import sys def install_egg(modules_tmpdir, monkeypatch): """Generate egg from package name inside base and put the egg into sys.path.""" def inner(name, base=modules_tmpdir): if not isinstance(name, str): raise ValueError(name) base.join(name)...
26e3540dce0c2f86ad7ab69fefeb263cf138ef2d
657,167
def _caps_to_mask(caps): """Convert list of bit offsets to bitmask""" mask = 0 for cap in caps: mask |= 1 << cap return mask
e06bc35e58f1e7ed7a5c07c025bd16c5e00421e2
657,168
def format_repr(obj, max_len=50, ellipsis="..."): """Wrapper around `repr()` to print shortened and formatted string version. obj: The object to represent. max_len (int): Maximum string length. Longer strings will be cut in the middle so only the beginning and end is displayed, separated by ellipsi...
f8458125ee85e4bb986e6caeacd141b9d14cd644
657,170
import sqlite3 def getConfig(guild_id: int, module: str) -> bool: """Gets the server configuration""" with sqlite3.connect('serverconfig/servermodules.db') as connection: cursor = connection.cursor() check = cursor.execute( f"""SELECT {module} FROM server_modules ...
17cca9761d4dee58f2ceb01587550e11e08853f4
657,171
def zendesk_help_page(): """ Zendesk Help page """ return """ Read more on using ZD search here https://developer.zendesk.com/rest_api/docs/help_center/search """
802414d50f54e6684aedd1d1a811bebd1ebd072e
657,172
def reverse_pct(df, start_num, pct_col, num_col): """Convert % change back to number""" nums_out = [] for i in range(df.shape[0]): start_num = df[pct_col].iloc[i] * start_num + start_num nums_out.append(start_num) return df \ .assign(**{num_col: nums_out})
7b872bf638176ce55a0cbd56ead9b62f35b77594
657,173
def filter_arc(w, h, aspect): """Aspect ratio convertor. you must specify output size and source aspect ratio (as float)""" taspect = float(w)/h if abs(taspect - aspect) < 0.01: return "scale=%s:%s"%(w,h) if taspect > aspect: # pillarbox pt = 0 ph = h pw = int (h*aspect) ...
0368fe9ffae7a9e75092a0733c722b19f1c195ff
657,174
def modular_geometric_sum(x, n, mod): """ Compute a_n = (1 + a^1 + ... + a^{n-1}) % mod using that a_{2n} = ((x_n + 1) * a_n) % mod a_{2n+1} = (x^{2n} + a_{2n}) % mod """ if n == 1: return 1 % mod elif n % 2 == 0: return ((pow(x, n // 2, mod) + 1) * modular_geometri...
5ec1af73ec6229679c1075a49c21bdb0eccc53f8
657,175
def data_format(df, n_back): """ 将时间序列数据转换为可训练的类型 基本假设为后一期数据受到前几期数据影响 :param df: 时间序列 :param n_back: :return new_df: """ length = len(df) data = [] target = [] for i in range(0, length-n_back): data.append(df[i:i+n_back].values.T.tolist()[0]) target.append(df[...
c9f792b11811b5bdd2c6702289c870f78c3d0b3a
657,176
from typing import Union def join(value: Union[tuple, list, str], separator: str = ':') -> str: """Uses ``.join`` to squash a list or tuple using a separator. Args: value: Value to be squashed. separator: Separator to be used to squash. Returns: str: A squashed string. ...
51e0ecd03582e1bf4428c212a65a0c82396f76d4
657,177
def FlattenDiseases(kind, dataSet): """ Some categories appear in groups of 2 or more. FlattenDiseases will separate the individual diseases that appear in the Pathology.Categories_... column into single, unique values Param: kind (str): either "pancreas" or "liver" dataSet (DataFrame): eit...
5046ea2d3403276c34f981444cee8dc57b8f70dd
657,178
def show_procs(procs, mem_limit): """Pretty print host procs in ps-like fashion""" mem_limit_kb = mem_limit / 1024 result = "" fmt_line = "%(user)5d %(pid)5d %(cpu)5.1f %(mem)5.1f %(vsz)8d \ %(rss)8d %(state)6s %(command)s\n" if procs: result = "\n%5s %5s %5s %5s %8s %8s %6s ...
153bb1e52587489a1ad52c20aefcea91d6223cc9
657,179
def getCategoryLengths(category_table, category, seq_lengths): """Return a table mapping categories to the total bps in that category. base pairs are in the same units as getSeqLens. """ if category == 'gene': return seq_lengths ind = {'classus': 1, 'mech': 2, 'group': 3}[category] cat_...
704aa760657d887fce6e63b5dc773259aba870ad
657,180
def from_sdss_albd_to_megacam_albd(sdss): """Return A(lbd) for the 6 Megecam filters: u, g, r, i_old, i_new, z.""" megacam = {} megacam['u'] = sdss['u'] - 0.241 * (sdss['u'] - sdss['g']) megacam['g'] = sdss['g'] - 0.153 * (sdss['g'] - sdss['r']) megacam['r'] = sdss['r'] - 0.024 * (sdss['g'] - sdss['...
e3e40d9a303a2b64632fe24fe3f6192691585ae0
657,181
def find_occurences_in_list_of_dicts(list_dict, in_val): """ return number of occurences of value in dict """ n = 0 for item in list_dict: for k in item.keys(): if item[k] == in_val: n += 1 return n
2464d1234e6106a246467993f2fe075de898de0e
657,182
def omp_get_num_devices(): """ The omp_get_num_devices routine returns the number of target devices. """ return 1
7aa3b382e90975d8c042074c9883b4bd0a34adf3
657,184
def hex_cdid(disc) : """ returns the musicBrainz CD is as an hexadecimal string. The original code is taken by two letters and the ascii code of each letters is converted to hexadecimal. the original code : QMSaDuuKtKVWKD_cimSlvt2on5o- is converted into : 514d-5361-4475-754b-744b-5657-...
afe0c900f58f90021f97361f5ae56677e6353127
657,185
def get_cameras_with_filter(cameras, filter_name): """ Get a dict of cameras wit the required filter. Args: cameras (dict): Dict of cam_name: camera pairs. filter_name (str): The filter name. """ cameras_with_filter = {} for cam_name, cam in cameras.items(): if cam.filterwhe...
877b6d7459a562e42140cc7315538f9887920b8f
657,186
def get_higher_value(grille): """return the maximum value of the grid""" max=0 for i in range(len(grille)): for j in range(len(grille[0])): if grille[i][j]==None: continue if grille[i][j]>max: max = grille[i][j] return max
7dcd0b539da2befd7a9d5b6fe766834a1111bf43
657,187
import operator def eval_RPN(tokens: list[str]) -> int: """Returns the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is gua...
6e19a2959c9350115fe054673be68091c085a59d
657,188
def is_palindromic(s, i=0, j=None): """ Return True if the sequence is the same from left to right as it is from right to left in the whole sequence (default) or in the Python slice ``s[i: j]``; else False. Examples ======== >>> from sympy.utilities.iterables import is_palindromic >>> ...
2dd7e31df3235ca61b2bfcc8d6eb97228a33ddb7
657,189
def _replace_characters(s: str) -> str: """Replace characters that are not suitable to present in Labber. Returns: Labber compatible string. """ if not s: return "" chars = [ ("\n", " "), ("\r", ""), ('"', "`"), ("'", "`"), (";", ":"), ...
e64b7501870179fcc9f18d2fcd0a99a8738b4c68
657,191
def to_classname(filename: str) -> str: """ maps divided mock class file name to class names inverse function of headersplit.to_filename e.g. map "test/mocks/server/admin_stream.h" to "MockAdminStream" Args: filename: string, mock class header file name (might be the whole path instead of t...
afebaa59d2155134c43e16302240ee773c46b0cd
657,192
from io import StringIO def render_pil(image, fmt="jpg"): """ Render PIL Image to base64. :param image: given image. :param fmt: image format. :return: rendered image. """ if not callable(getattr(image, "save", None)): return None output = StringIO() image.save...
9f24fe4e74691c252a06d4da2caf8974f59f8fb1
657,193
def sort_numbers(numbers_list): """ >>> sort_numbers(['07895462130', '919875641230', '9195969878']) ['07895462130', '9195969878', '919875641230'] >>> sort_numbers(['5'*10, '1'*10, '9'*10]) ['1111111111', '5555555555', '9999999999'] >>> sort_numbers(['+91 78954 62130', '+91 98756 41230', '+91 919...
db384bf510c5ed20d3a8950b1b2839f8f92baf0e
657,194
def tuplefy(value): """Returns the value in or as a tuple if not already a tuple.""" return value if isinstance(value, tuple) \ else tuple(value) if isinstance(value, list) else (value, )
5007719d88f62002425f293af37a6bbc37f8dfcd
657,195
def _sh_cmd(system, *args): """ Helper function to build a local shell command """ if len(args) == 0: return None return args
232653f8f1170fb5715860206678e560a40000e3
657,196
import torch def DTW(batch_pred, batch_target, scale_factor: int, range_: int): """ Calcuates ideal time-warp for each frame to minimize L1 Error from target. Params: scale_factor: Scale factor for linear interpolation. Values greater than 1 allows blends neighbouring frames ...
cc54798beb80f22e6fcd28874694201672934872
657,197
def split_alpha_mask(RGBA_mask): """Splits alpha mask and RGB image. # Arguments RGBA_mask: Tensor [batch, H, W, 4] # Returns Color tensor [batch, H, W, 3] and alpha tensor [batch, H, W, 1] """ color_mask = RGBA_mask[:, :, :, 0:3] alpha_mask = RGBA_mask[:, :, :, 3:4] return...
bebd13559ccd67e4b37ac88449db17d388f2ce23
657,198
def _update_reducer(store_dict, data): """ :type store_dict: dict :type data: dict :rtype: dict """ if data.get('switch_on_time', None) is not None: store_dict['switch_on_time'] = int(data['switch_on_time']) % 24 * 3600 if data.get('switch_off_time', None) is not None: store...
df76bafafea1487357254f695072db73a257d65e
657,199
import json def test_fetch_photos(client, auth): """ Try to fetch some photos. Check user access as well. """ def entries(offset=0, total=6): return json.loads( client.post("/photos", data=dict(offset=offset, total=total)).data ) # from the visitor's eyes: json_data = ent...
36a4bd49907990e45cdd137f1fe532b4a0edda71
657,200
def levenstein(s, t): """ Calculates the Levenstein distance between two strings. Below is the types returned by the algorithm if we wanted to return the list of operations: type operations = [operation] type operation = | Nothing existing_char | Insert new_char | De...
141281fd01b5d05c2ab334f74149957a958ebe12
657,201
def change_elements(items, old_index, new_index): """Switch places of two elements in list collection.""" new_items = items[:] new_items[old_index], new_items[new_index] = new_items[new_index], new_items[old_index] return new_items
0fefd4e6b79b0583b483f5cb0d303de77d0e1c92
657,202
import itertools def getallgroups(arr, k=-1): """ returns all the subset of @arr of size less than equalto @k the return array will be of size \sum_{i=1}^k nCi, n = len(arr) """ if k<0: k = len(arr) return itertools.chain.from_iterable(itertools.combinations(set(arr), j) ...
c9f9130eb64d8fff1bb449c027f2f47b2b3e60bc
657,203
import optparse def option_parser(): """ Return an :mod:`optparse` parser for parsing command line options. """ usage_msg = "usage: %prog [options] (start|stop|restart|run|update_config)" parser = optparse.OptionParser(usage=usage_msg) parser.add_option("--config_file", ...
71112ab55723de1bb48288a4d5e035fd5b0d62e5
657,205
def event_wrapper(function): """ Useful to wrap callbacks for calling in a different context. """ def f(event): function() return f
a922d7179edb42bac9b0ce08f918e0e72ecc36cc
657,206
import random def _apply_randomness(value, random_factor): """ Applies a random factor to the value :param value: Input value :param random_factor: Random factor, must be between 0 (no random) and 1 (output is between 0 and 2* value) :return: Value with random factor applied """ if random_...
f9efa3839e5ac513bf3b5f8dc4dc021d1ad0d03f
657,207
def has_solution(cell): """Return True if cell is marked as containing an exercise solution.""" cell_text = cell["source"].replace(" ", "").lower() first_line = cell_text.split("\n")[0] return ( cell_text.startswith("#@titlesolution") or "to_remove" in first_line and "explanation...
a41780ea85c4dd4c4013f5b562d2a6e7127cee71
657,208
def af_subtraction(ch1, ch2, m, c): """ Subtract ch2 from ch1 ch2 is first adjusted to m * ch2 + c :param ch1: :param ch2: :param m: :param c: :return: """ af = m * ch2 + c signal = ch1 - af return signal
ebf11ffdc9d64860179407a48d7351bacf35492d
657,209
def notears_constr(adj_m, max_pow=None): """No Tears for binary adjacency matrixes. If adj_m is non binary: give adj_m * adj_m as input (Hadamard product).""" m_exp = [adj_m] if max_pow is None: max_pow = adj_m.shape[1] while(m_exp[-1].sum() > 0 and len(m_exp) < max_pow): m_exp.appe...
f787f80ac31401a8c0131154b35f35b429d5a20d
657,211
def title2list(news_title): """ 将一个新闻标题分字并转换成列表 :param news_title: 一个新闻标题字符串 E.g.:'2019年校领导寒假会商会召开' :return: 一个新闻标题按字切分的列表 ['2','0','1','9','年','校','领','导','寒','假','会','商','会','召','开'] """ title = [] for i in news_title: title.append(i) # print("================title============\...
2239c1c3a46ae859adb88cad1a68b1e2cc66f781
657,213
import signal def ftimeout(func, args=(), kwargs={}, timeout_duration=1, default=None): """http://stackoverflow.com/a/13821695""" class TimeoutError(Exception): pass def handler(signum, frame): raise TimeoutError() # set the timeout handler signal.signal(signal.SIGALRM, handler)...
1fcc67f52fc3a0fe8c2fc7115f39fe15627d8cef
657,214
import re def _replace_ad(html): """Remove symbols 'a0:' and 'a2:'. 'a0:' stands for 'nobreak'""" # opening tag html = re.sub('\<\s*a\d\:', '<', html) # closing tag html = re.sub('\</\s*a\d\:', '</', html) return html
e32b146e59895cb2dcf32ecc0221334890b2e032
657,215
def group_by_days(df): """ """ return df.groupby(['CA', 'UNIT', 'SCP', 'STATION', 'DATE']).agg({'INS': 'sum', 'OUTS': 'sum'})
0f4af765d65a875417c492bfbe9d1e7100dddcc9
657,216
import os import base64 def encode_image(img): """ Base 64 encoding of an image field that may be missing. """ # The image is not filled in. if not img: return '' # The path is incorrect. if not os.path.isfile(img.path): return '' # The binary representation of the d...
d62f5a45c5c896893a3f61efe8e8a1ec3e78beec
657,217
def iter_method(): """iter, for: Create an iterator for an iterable.""" class _Iterable: def __iter__(self): return iter(["guitare"]) return next(iter(_Iterable()))
942f33ca442c33e8f83cc9f8d6fb66934225ca63
657,218
def is_informational(status): """ 检查状态码是否信息提示 :param: * status: http 状态码 :return: * result: True or False """ return 100 <= status <= 199
04a4077bbe7d69c1107db4404c78faf93fba0f49
657,219
def historical_process_flag(flags): """ This function updates flag to make it backward compatible with old versions :param flags: dictionary of configurations, this is from the config.json file """ if 'imagenet' not in flags: flags['imagenet'] = 'True' if 'name' not in flags['optimizer']...
c28cad0d613904552a09aeb1e2b42b9b5dc25a98
657,220
def solve(values: list[int], n: int) -> int: """Compute the solution to day 1. The interesting insight is that for an arbitrary window size only the values at the beginning/end of the window that don't overlap matter. For example, for `n = 3` checking that `a + b + c < b + c + d` is equivalent...
1bff213de163d10d44a537542cfd9741657078cb
657,221
import subprocess def execute_command(command): """ Execute the provided command :param command: A list of arguments :return: A tuple containing the output and return code """ # Execute command process = subprocess.Popen(command, stdout=subprocess.PIPE, std...
a18974faf7749a72bf3ca3bd7c4b6a072c1634da
657,222
def escape_characters(data: bytes) -> bytes: """ Characters that are used for telegram control are replaced with others so that it easier to parse the message over the wire. Final character is never replaced. '\x0d' -> '\x1b\x0e' '\x1b' -> '\x1b\x1b' '\x8d' -> '\x1b\x0f' """ if not ...
fd98297114b8c106b43324c75f630372eedbda08
657,223
def count_false_negatives(self, clusters, emb_id_to_name_dict): """ Number of face pairs incorrectly clustered to different clusters :return: Number of """ def does_match(emb_id_pair): # Count iff result of check (yes/no) is same as wanted type (true/false positives) return self.ar...
590b89261c81315018b83729263230a2d6171b93
657,224
def _xy_locs(mask): """Mask should be a set of bools from comparison with a feature layer.""" y, x = mask.nonzero() return list(zip(x, y))
e5b1d168f8f99adaf3186c1169e4b75f51a3fe8d
657,225
def from_pairs(pairs): """Creates a new object from a list key-value pairs. If a key appears in multiple pairs, the rightmost pair is included in the object""" out = {} for (k, v) in pairs: out[k] = v return out
3b6bc42aa3aa5f5a34373e5a7c25bd130b1c2c49
657,226
def memory_information() -> int: """ Goal: get total amount of ram on system """ formatting = lambda quantity, power: quantity/(1000**power) path = "/proc/meminfo" with open(path, "r") as fp: total = int(fp.readline().split()[1]) return int(formatting(total, 2))
89782e81a2dd2475a861fb0fcfbcb085a8b6ff3c
657,227
def spmwrite(self, method="", nmode="", inputs="", inputlabels="", outputs="", outputlabels="", nic="", velacckey="", fileformat="", **kwargs): """Calculates the state-space matrices and writes them to the SPM file. APDL Command: SPMWRITE Parameters ---------- method ...
fea18d3ed9edb1d1f16ec0f268fedbae05ed95ab
657,228
from typing import List def _match_not_found(all_inputs: list, res: list) -> List[str]: """ Args: all_inputs: all indicator values received from the user res: list of all indicator values that returned from api request Returns: Which indicator has no match on AccentureCTI database "...
6d586357b8fa7cbdf6e9b197225ce7d93c10d359
657,229
def relocate_h2id(soup): """Moves the anchor ID to the H2 tag, from the wrapper DIV.""" for h2 in soup.find_all('h2'): div = h2.find_parent('div') if div.has_attr('id') and not h2.has_attr('id'): # print('Move ID: ' + div['id']) h2['id'] = div['id'] del div['id'] # Also delete embedded...
536978abb6b1583085b6ea098efac019b2f591c5
657,230
import ast def parse_string_value(str_value): """ parse string to number if possible e.g. "123" => 123 "12.2" => 12.3 "abc" => "abc" "$var" => "$var" """ try: return ast.literal_eval(str_value) except ValueError: return str_value except SyntaxError: ...
9e982a045cc2ee5005b5f14c3d8db8f02efb4feb
657,231
def SmiNetDateTime(python_date): """ Datetime as a string in the format `YYYY-MM-DD HH:MM:SS` Original xsd documentation: SmiNetLabExporters datum- och tidformat (ÅÅÅÅ-MM-DD TT:MM:SS). """ return python_date.strftime("%Y-%m-%d %H:%M:%S")
3f736e4bd0972419815196420f5b4a9edd96d660
657,232
def dict_filter_keys_start_with(start, row): """ Given a dict, returns a new dict with key-value pairs where the key of each pair starts with start. """ return {k[len(start)+1:]: v for k, v in row.items() if k.startswith(start)}
2187d7fe3af5821633eebf3ac914dbfb3bbeac05
657,233
def get_velocities(ust): """USTを読み取って子音速度のリストを返す。 """ return tuple(note.velocity for note in ust.notes)
4368f4b58b794e730419b2dc9cdf3a1027de4316
657,234
def trailing_ws(flag): """ - flag: bool, if True, return two newlines RETURN: string """ return "\n\n" if flag else ""
efd4be5719b9df978ea81bbf41b87c791b7ade9d
657,235
def make_image_black_and_white(img, threshold=127): """Convert an image to a black and white image.""" #convert('1') converts to black and white; # use a custom threshold via: # https://stackoverflow.com/a/50090612/454773 fn = lambda x : 255 if x > threshold else 0 img = img.convert('L').p...
fbe3aa0c344e34075870160476ea9743a7fce97f
657,236
def fcc_round(x): """Round as in FCC 19-126 Table 1, p. 23.""" if x < 10: return round(x, 1) else: return int(round(x))
f1c9e038c20057350c9ea043cdc6f40f444b525c
657,237
import os def get_file_info(filename, frame_num, rand_changes): """ Returns the base filename and frame_num for the inital fram in the loaded frame sequence Input: filename: name of the file where the sequence is loaded from frame_num: frame number of the first frame in the sequence ...
9af4c1c2745aa3a45715634bf5b0a312c549a717
657,238
import os def get_output_as_bids_command(args, config): """ Get the command to convert the output of oxford_asl to a BIDS data set :param args: Command line arguments :param config: oxford_asl session config """ options = config["options"] cmdline = f"oxasl_bids bidsout --bidsdir {os.path...
bbc6ce1ae26c51db27d14336802195efc2448661
657,239
def rgb(r, g, b): """generate rbg in hex Args: r g b Returns: rgb in hex """ return "#%s%s%s" % tuple([hex(int(c * 255))[2:].rjust(2, "0") for c in (r, g, b)])
b9fd901d72350a14e0f3d184382b09e6757363c1
657,240
def split_by_connection(ifc_connection): """ write below two in write template ifc_file = ifcopenshell.open(path) ifc_connection = ifc_file.by_type('IFCRELCONNECTSWITHREALIZINGELEMENTS') """ relate_elements = [] realizing_elements = [] for _ in ifc_connection: relate_elements.app...
bc82ad45c4896e0c3373c04f631a575bf10da49f
657,241