content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def tag_in_tags(entity, attribute, value): """ Return true if the provided entity has a tag of value in its tag list. """ return value in entity.tags
ad88be5f8848b387f2a261ce5506dffde285a1d8
1,296
import torch def to_device(x, device): """Cast a hierarchical object to pytorch device""" if isinstance(x, torch.Tensor): return x.to(device) elif isinstance(x, dict): for k in list(x.keys()): x[k] = to_device(x[k], device) return x elif isinstance(x, list) or isinstance(x, tuple): return type(x)(to_device(t, device) for t in x) else: raise ValueError('Wrong type !')
a315905fb0cf6d6720103c0d22440418ebd41bf1
1,299
def f(x): """Cubic function.""" return x**3
13832221de3490dbd92f4f1a26854baec7010023
1,300
import textwrap def dedent(ind, text): """ Dedent text to the specific indentation level. :param ind: common indentation level for the resulting text (number of spaces to append to every line) :param text: text that should be transformed. :return: ``text`` with all common indentation removed, and then the specified amount of indentation added. """ text2 = textwrap.dedent(text) if ind == 0: return text2 indent_str = " " * ind return "\n".join(indent_str + line for line in text2.split("\n"))
271b9fd270d78c4bc952af31d3d9be0ff6bdab73
1,301
def get_polarimeter_index(pol_name): """Return the progressive number of the polarimeter within the board (0…7) Args: pol_name (str): Name of the polarimeter, like ``R0`` or ``W3``. Returns: An integer from 0 to 7. """ if pol_name[0] == "W": return 7 else: return int(pol_name[1])
0068931868e214896f6263e58fc09215352d502c
1,305
import io import base64 def get_image_html_tag(fig, format="svg"): """ Returns an HTML tag with embedded image data in the given format. :param fig: a matplotlib figure instance :param format: output image format (passed to fig.savefig) """ stream = io.BytesIO() # bbox_inches: expand the canvas to include the legend that was put outside the plot # see https://stackoverflow.com/a/43439132 fig.savefig(stream, format=format, bbox_inches="tight") data = stream.getvalue() if format == "svg": return data.decode("utf-8") data = base64.b64encode(data).decode("utf-8") return f"<img src=\"data:image/{format};base64,{data}\">"
f5c59a6f4f70fb6616cec4619d8cbf9ca2e28529
1,308
def reformat_language_tuple(langval): """Produce standardly-formatted language specification string using given language tuple. :param langval: `tuple` in form ('<language>', '<language variant>'). Example: ('en', 'US') :return: `string` formatted in form '<language>-<language-variant>' """ if langval: langval_base, langval_variant = langval if langval_variant: langval_base = '{0}-{1}'.format(langval_base, langval_variant) return langval_base else: return None
63c479d7dd273f31b9bdcc6c0ce81d4267a43714
1,309
def memdiff_search(bytes1, bytes2): """ Use binary searching to find the offset of the first difference between two strings. :param bytes1: The original sequence of bytes :param bytes2: A sequence of bytes to compare with bytes1 :type bytes1: str :type bytes2: str :rtype: int offset of the first location a and b differ, None if strings match """ # Prevent infinite recursion on inputs with length of one half = (len(bytes1) // 2) or 1 # Compare first half of the string if bytes1[:half] != bytes2[:half]: # Have we found the first diff? if bytes1[0] != bytes2[0]: return 0 return memdiff_search(bytes1[:half], bytes2[:half]) # Compare second half of the string if bytes1[half:] != bytes2[half:]: return memdiff_search(bytes1[half:], bytes2[half:]) + half
fbcb221c77730c45be4c81a6ae7515e602468af5
1,310
def stringify(li,delimiter): """ Converts list entries to strings and joins with delimiter.""" string_list = map(str,li) return delimiter.join(string_list)
a4c35a19d8ea654a802cd3f92ababcbdfdf0ecfb
1,313
def load_module(module, app): """Load an object from a Python module In: - ``module`` -- name of the module - ``app`` -- name of the object to load Return: - (the object, None) """ r = __import__(module, fromlist=('',)) if app is not None: r = getattr(r, app) return r, None
858d9d0bf91ff7d83ad391218b8ff1b37007b43b
1,315
from unittest.mock import Mock def make_subprocess_hook_mock(exit_code: int, output: str) -> Mock: """Mock a SubprocessHook factory object for use in testing. This mock allows us to validate that the RenvOperator is executing subprocess commands as expected without running them for real. """ result_mock = Mock() result_mock.exit_code = exit_code result_mock.output = output hook_instance_mock = Mock() hook_instance_mock.run_command = Mock(return_value=result_mock) hook_factory_mock = Mock(return_value=hook_instance_mock) return hook_factory_mock
a047608503be8bc7fc4b782139e7d12145efb3cd
1,316
def binstr2int(bin_str: str) -> int: """转换二进制形式的字符串为10进制数字, 和int2binstr相反 Args: bin_str: 二进制字符串, 比如: '0b0011'或'0011' Returns: 转换后的10进制整数 """ return int(bin_str, 2)
87c6ac16c2215e533cb407407bef926ed8668e3e
1,317
def _scale(tensor): """Scale a tensor based on min and max of each example and channel Resulting tensor has range (-1, 1). Parameters ---------- tensor : torch.Tensor or torch.autograd.Variable Tensor to scale of shape BxCxHxW Returns ------- Tuple (scaled_tensor, min, max), where min and max are tensors containing the values used for normalizing the tensor """ b, c, h, w = tensor.shape out = tensor.view(b, c, h * w) minimum, _ = out.min(dim=2, keepdim=True) out = out - minimum maximum, _ = out.max(dim=2, keepdim=True) out = out / maximum # out has range (0, 1) out = out * 2 - 1 # out has range (-1, 1) return out.view(b, c, h, w), minimum, maximum
64eed9bd70c543def6456f3af89fa588ec35bca8
1,318
def url(endpoint, path): """append the provided path to the endpoint to build an url""" return f"{endpoint.rstrip('/')}/{path}"
dee733845984bfc4cf5728e9614cce08d19a2936
1,319
def is_collision(line_seg1, line_seg2): """ Checks for a collision between line segments p1(x1, y1) -> q1(x2, y2) and p2(x3, y3) -> q2(x4, y4) """ def on_segment(p1, p2, p3): if (p2[0] <= max(p1[0], p3[0])) & (p2[0] >= min(p1[0], p3[0])) & (p2[1] <= max(p1[1], p3[1])) & (p2[1] >= min(p1[1], p3[1])): return True return False def orientation(p1, p2, p3): val = ((p2[1] - p1[1]) * (p3[0] - p2[0])) - ((p2[0] - p1[0]) * (p3[1] - p2[1])) if val == 0: return 0 elif val > 0: return 1 elif val < 0: return 2 p1, q1 = line_seg1[0], line_seg1[1] p2, q2 = line_seg2[0], line_seg2[1] o1 = orientation(p1, q1, p2) o2 = orientation(p1, q1, q2) o3 = orientation(p2, q2, p1) o4 = orientation(p2, q2, q1) if (o1 != o2) & (o3 != o4): return True if (o1 == 0 & on_segment(p1, p2, q1)): return True if (o2 == 0 & on_segment(p1, q2, q1)): return True if (o3 == 0 & on_segment(p2, p1, q2)): return True if (o4 == 0 & on_segment(p2, q1, q2)): return True return False
17dba61faebe50336cbc2cd2cc56c49474db5431
1,320
def fibonacci(position): """ Based on a position returns the number in the Fibonacci sequence on that position """ if position == 0: return 0 elif position == 1: return 1 return fibonacci(position-1)+fibonacci(position-2)
cc4fe0860fa97234ead2179e18d208a8567e0cb3
1,322
import asyncio import functools def bound_concurrency(size): """Decorator to limit concurrency on coroutine calls""" sem = asyncio.Semaphore(size) def decorator(func): """Actual decorator""" @functools.wraps(func) async def wrapper(*args, **kwargs): """Wrapper""" async with sem: return await func(*args, **kwargs) return wrapper return decorator
030e4dea0efccf9d5f2cbe4a40f3e6f32dfef846
1,323
def pg_index_exists(conn, schema_name: str, table_name: str, index_name: str) -> bool: """ Does a postgres index exist? Unlike pg_exists(), we don't need heightened permissions on the table. So, for example, Explorer's limited-permission user can check agdc/ODC tables that it doesn't own. """ return ( conn.execute( """ select indexname from pg_indexes where schemaname=%(schema_name)s and tablename=%(table_name)s and indexname=%(index_name)s """, schema_name=schema_name, table_name=table_name, index_name=index_name, ).scalar() is not None )
98ebdc0db7f3e42050e61205fd17309d015352a0
1,326
def time_rep_song_to_16th_note_grid(time_rep_song): """ Transform the time_rep_song into an array of 16th note with pitches in the onsets [[60,4],[62,2],[60,2]] -> [60,0,0,0,62,0,60,0] """ grid_16th = [] for pair_p_t in time_rep_song: grid_16th.extend([pair_p_t[0]] + [0 for _ in range(pair_p_t[1]-1)]) return grid_16th
8986819bd39ae4830d04bf40ab158d310bb45485
1,329
def require(*modules): """Check if the given modules are already available; if not add them to the dependency list.""" deplist = [] for module in modules: try: __import__(module) except ImportError: deplist.append(module) return deplist
88df83cd33d8bddea63e4d2fbfb4d8351a3c23b1
1,331
def fixture_base_context( env_name: str, ) -> dict: """Return a basic context""" ctx = dict( current_user="a_user", current_host="a_host", ) return ctx
fbfed439f784bdd64e93910bbb581955200af2bb
1,332
def evaluation(evaluators, dataset, runners, execution_results, result_data): """Evaluate the model outputs. Args: evaluators: List of tuples of series and evaluation functions. dataset: Dataset against which the evaluation is done. runners: List of runners (contains series ids and loss names). execution_results: Execution results that include the loss values. result_data: Dictionary from series names to list of outputs. Returns: Dictionary of evaluation names and their values which includes the metrics applied on respective series loss and loss values from the run. """ eval_result = {} # losses for runner, result in zip(runners, execution_results): for name, value in zip(runner.loss_names, result.losses): eval_result["{}/{}".format(runner.output_series, name)] = value # evaluation metrics for generated_id, dataset_id, function in evaluators: if (not dataset.has_series(dataset_id) or generated_id not in result_data): continue desired_output = dataset.get_series(dataset_id) model_output = result_data[generated_id] eval_result["{}/{}".format(generated_id, function.name)] = function( model_output, desired_output) return eval_result
ef3470edb8b2336bdc54507a5df8023f8095b995
1,333
import base64 def base64_decode(string): """ Decodes data encoded with MIME base64 """ return base64.b64decode(string)
38870882fca9e6595e3f5b5f8943d0bf781f006c
1,335
import re def convert_operand_kind(operand_tuple): """Returns the corresponding operand type used in spirv-tools for the given operand kind and quantifier used in the JSON grammar. Arguments: - operand_tuple: a tuple of two elements: - operand kind: used in the JSON grammar - quantifier: '', '?', or '*' Returns: a string of the enumerant name in spv_operand_type_t """ kind, quantifier = operand_tuple # The following cases are where we differ between the JSON grammar and # spirv-tools. if kind == 'IdResultType': kind = 'TypeId' elif kind == 'IdResult': kind = 'ResultId' elif kind == 'IdMemorySemantics' or kind == 'MemorySemantics': kind = 'MemorySemanticsId' elif kind == 'IdScope' or kind == 'Scope': kind = 'ScopeId' elif kind == 'IdRef': kind = 'Id' elif kind == 'ImageOperands': kind = 'Image' elif kind == 'Dim': kind = 'Dimensionality' elif kind == 'ImageFormat': kind = 'SamplerImageFormat' elif kind == 'KernelEnqueueFlags': kind = 'KernelEnqFlags' elif kind == 'LiteralExtInstInteger': kind = 'ExtensionInstructionNumber' elif kind == 'LiteralSpecConstantOpInteger': kind = 'SpecConstantOpNumber' elif kind == 'LiteralContextDependentNumber': kind = 'TypedLiteralNumber' elif kind == 'PairLiteralIntegerIdRef': kind = 'LiteralIntegerId' elif kind == 'PairIdRefLiteralInteger': kind = 'IdLiteralInteger' elif kind == 'PairIdRefIdRef': # Used by OpPhi in the grammar kind = 'Id' if kind == 'FPRoundingMode': kind = 'FpRoundingMode' elif kind == 'FPFastMathMode': kind = 'FpFastMathMode' if quantifier == '?': kind = 'Optional{}'.format(kind) elif quantifier == '*': kind = 'Variable{}'.format(kind) return 'SPV_OPERAND_TYPE_{}'.format( re.sub(r'([a-z])([A-Z])', r'\1_\2', kind).upper())
3d26a0b330ae64209655b24dfe86578cb4b8724c
1,336
def _ensure_package(base, *parts): """Ensure that all the components of a module directory path exist, and contain a file __init__.py.""" bits = [] for bit in parts[:-1]: bits.append(bit) base.ensure(*(bits + ['__init__.py'])) return base.ensure(*parts)
fc9bb95445cc1b0e8ec819dfafdaff7d5afbf372
1,338
import math def sigmoid(z): """Sigmoid function""" if z > 100: return 0 return 1.0 / (1.0 + math.exp(z))
097e1a85fc46264cb1c7cd74498d6cfab97e5b88
1,339
def format_str_for_write(input_str: str) -> bytes: """Format a string for writing to SteamVR's stream.""" if len(input_str) < 1: return "".encode("utf-8") if input_str[-1] != "\n": return (input_str + "\n").encode("utf-8") return input_str.encode("utf-8")
1b83a2c75118b03b7af06350e069775c0b877816
1,344
def _as_nested_lists(vertices): """ Convert a nested structure such as an ndarray into a list of lists. """ out = [] for part in vertices: if hasattr(part[0], "__iter__"): verts = _as_nested_lists(part) out.append(verts) else: out.append(list(part)) return out
c69bd2084aa8e76a53adf3e25286a8dd7ae23176
1,347
def A070939(i: int = 0) -> int: """Length of binary representation of n.""" return len(f"{i:b}")
31b12e493645c3bdf7e636a48ceccff5d9ecc492
1,350
def char_to_num(x: str) -> int: """Converts a character to a number :param x: Character :type x: str :return: Corresponding number :rtype: int """ total = 0 for i in range(len(x)): total += (ord(x[::-1][i]) - 64) * (26 ** i) return total
f66ee13d696ec1872fbc2a9960362456a5c4cbe9
1,353
import json def get_rate_limit(client): """ Get the Github API rate limit current state for the used token """ query = '''query { rateLimit { limit remaining resetAt } }''' response = client.execute(query) json_response = json.loads(response) return json_response['data']['rateLimit']
ec5f853014f25c841e71047da62ca41907b02e13
1,356
from typing import List def unique_chars(texts: List[str]) -> List[str]: """ Get a list of unique characters from list of text. Args: texts: List of sentences Returns: A sorted list of unique characters """ return sorted(set("".join(texts)))
02bc9ce28498bd129fdb68c2f797d138ca584490
1,361
def count_str(text, sub, start=None, end=None): """ Computes the number of non-overlapping occurrences of substring ``sub`` in ``text[start:end]``. Optional arguments start and end are interpreted as in slice notation. :param text: The string to search :type text: ``str`` :param sub: The substring to count :type sub: ``str`` :param start: The start of the search range :type start: ``int`` :param end: The end of the search range :type end: ``int`` :return: The number of non-overlapping occurrences of substring ``sub`` in ``text[start:end]``. :rtype: ``int`` """ assert isinstance(text,str), '%s is not a string' % text return text.count(sub,start,end)
1578f868a4f1a193ec9907494e4af613ca2a6d4d
1,366
def _gnurl( clientID ): """ Helper function to form URL to Gracenote_ API service. :param str clientID: the Gracenote_ client ID. :returns: the lower level URL to the Gracenote_ API. :rtype: str """ clientIDprefix = clientID.split('-')[0] return 'https://c%s.web.cddbp.net/webapi/xml/1.0/' % clientIDprefix
6d1935c8b634459892e4ec03d129c791b1d8a06a
1,367
def utf8_bytes(string): """ Convert 'string' to bytes using UTF-8. """ return bytes(string, 'UTF-8')
8e5423d2b53e8d5fbeb07017ccd328236ef8bea5
1,368
def gram_matrix(x): """Create the gram matrix of x.""" b, c, h, w = x.shape phi = x.view(b, c, h * w) return phi.bmm(phi.transpose(1, 2)) / (c * h * w)
11de97b67f3f8ecb7d7d009de16c1a5d153ab8ff
1,375
def matchesType(value, expected): """ Returns boolean for whether the given value matches the given type. Supports all basic JSON supported value types: primitive, integer/int, float, number/num, string/str, boolean/bool, dict/map, array/list, ... """ result = type(value) expected = expected.lower() if result is int: return expected in ("integer", "number", "int", "num", "primitive") elif result is float: return expected in ("float", "number", "num", "primitive") elif result is str: return expected in ("string", "str", "primitive") elif result is bool: return expected in ("boolean", "bool", "primitive") elif result is dict: return expected in ("dict", "map") elif result is list: return expected in ("array", "list") return False
24949f01a1bc3ae63a120d91549ae06ba52298a8
1,382
def get_attr(item, name, default=None): """ similar to getattr and get but will test for class or dict :param item: :param name: :param default: :return: """ try: val = item[name] except (KeyError, TypeError): try: val = getattr(item, name) except AttributeError: val = default return val
0c68c7e54ef901e18a49d327188f29f72f54da01
1,390
def float2(val, min_repeat=6): """Increase number of decimal places of a repeating decimal. e.g. 34.111111 -> 34.1111111111111111""" repeat = 0 lc = "" for i in range(len(val)): c = val[i] if c == lc: repeat += 1 if repeat == min_repeat: return float(val[:i+1] + c * 10) else: lc = c repeat = 1 return float(val)
07fc521e877387242a1e6cf951a6d5cbdc925aaf
1,391
def format_sec_to_hms(sec): """Format seconds to hours, minutes, seconds. Args: sec: float or int Number of seconds in a period of time Returns: str Period of time represented as a string on the form ``0d\:00h\:00m``. """ rem_int, s_int = divmod(int(sec), 60) h_int, m_int, = divmod(rem_int, 60) return "{}h {:02d}m {:02d}s".format(h_int, m_int, s_int)
aa2cc5d6584cdebf4d37292435ecd46bb6adc4a4
1,395
def which_db_version(cursor): """ Return version of DB schema as string. Return '5', if iOS 5. Return '6', if iOS 6 or iOS 7. """ query = "select count(*) from sqlite_master where name = 'handle'" cursor.execute(query) count = cursor.fetchone()[0] if count == 1: db_version = '6' else: db_version = '5' return db_version
07b1dbcea3fb4bf65bba5c578257440d39b6784c
1,400
import re def repeating_chars(text: str, *, chars: str, maxn: int = 1) -> str: """Normalize repeating characters in `text`. Truncating their number of consecutive repetitions to `maxn`. Duplicates Textacy's `utils.normalize_repeating_chars`. Args: text (str): The text to normalize. chars: One or more characters whose consecutive repetitions are to be normalized, e.g. "." or "?!". maxn: Maximum number of consecutive repetitions of `chars` to which longer repetitions will be truncated. Returns: str """ return re.sub(r"({}){{{},}}".format(re.escape(chars), maxn + 1), chars * maxn, text)
9dc326947a900d3531dcd59bf51d5c3396a42fea
1,401
import json def create_response(key, value): """Return generic AWS Lamba proxy response object format.""" return { "statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": json.dumps({key: value}) }
9236a9e4504e6fbebe841b8cc6b6ad4602dae463
1,404
import re def format_query(str_sql): """Strips all newlines, excess whitespace, and spaces around commas""" stage1 = str_sql.replace("\n", " ") stage2 = re.sub(r"\s+", " ", stage1).strip() stage3 = re.sub(r"(\s*,\s*)", ",", stage2) return stage3
5adb0f9c3314ba04bbf92c88e3ef17802b2afeb0
1,410
import re def check_token(token): """ Returns `True` if *token* is a valid XML token, as defined by XML Schema Part 2. """ return (token == '' or re.match( "[^\r\n\t ]?([^\r\n\t ]| [^\r\n\t ])*[^\r\n\t ]?$", token) is not None)
b4e1d313fb64aad4c1c244cb18d3629e13b1c3af
1,412
def get_phoible_feature_list(var_to_index): """ Function that takes a var_to_index object and return a list of Phoible segment features :param var_to_index: a dictionary mapping variable name to index(column) number in Phoible data :return : """ return list(var_to_index.keys())[11:]
a53995cd927d1cdc66fadb2a8e6af3f5e2effff0
1,413
def n_states_of_vec(l, nval): """ Returns the amount of different states a vector of length 'l' can be in, given that each index can be in 'nval' different configurations. """ if type(l) != int or type(nval) != int or l < 1 or nval < 1: raise ValueError("Both arguments must be positive integers.") return nval ** l
98770fa5a5e62501bf365a4a5a40a932b2ba2450
1,415
def remove_items_from_dict(a_dict, bad_keys): """ Remove every item from a_dict whose key is in bad_keys. :param a_dict: The dict to have keys removed from. :param bad_keys: The keys to remove from a_dict. :return: A copy of a_dict with the bad_keys items removed. """ new_dict = {} for k in a_dict.keys(): if k not in bad_keys: new_dict[k] = a_dict[k] return new_dict
7c665e372c2099441f8a661f1194a76a21edf01c
1,416
import re def filter_strace_output(lines): """ a function to filter QEMU logs returning only the strace entries Parameters ---------- lines : list a list of strings representing the lines from a QEMU log/trace. Returns ------- list a list of strings representing only the strace log entries the entries will also be cleaned up if a page dump occurs in the middle of them """ #we only want the strace lines, so remove/ignore lines that start with the following: line_starts= ['^[\d,a-f]{16}-', # pylint: disable=anomalous-backslash-in-string '^page', '^start', '^host', '^Locating', '^guest_base', '^end_', '^brk', '^entry', '^argv_', '^env_', '^auxv_', '^Trace', '^--- SIGSEGV', '^qemu' ] filter_string = '|'.join(line_starts) filtered = [] prev_line = "" for line in lines: if re.match(filter_string,line): continue # workaround for https://gitlab.com/qemu-project/qemu/-/issues/654 if re.search("page layout changed following target_mmap",line): prev_line = line.replace("page layout changed following target_mmap","") continue if re.match('^ = |^= ', line): line = prev_line+line filtered.append(line) return filtered
01b6c048ebdf890e9124c387fc744e56cc6b7f4d
1,419
def magerr2Ivar(flux, magErr): """ Estimate the inverse variance given flux and magnitude error. The reason for this is that we need to correct the magnitude or flux for Galactic extinction. Parameters ---------- flux : scalar or array of float Flux of the obejct. magErr : scalar or array of float Error of magnitude measurements. """ fluxErr = flux * ((10.0 ** (magErr/2.5)) - 1.0) return 1.0 / (fluxErr ** 2.0)
37c48c26f1b876ca4d77dc141b1728daaea24944
1,422
def save_file_in_path(file_path, content): """Write the content in a file """ try: with open(file_path, 'w', encoding="utf-8") as f: f.write(content) except Exception as err: print(err) return None return file_path
7b1e453a9b2a8c1211e111a6e8db432811d84a7a
1,426
def uncapitalize(string: str): """De-capitalize first character of string E.g. 'How is Michael doing?' -> 'how is Michael doing?' """ if len(string): return string[0].lower() + string[1:] return ""
1a294f171d16d7a4c41fb0546feca3c03b7ae37a
1,430
def ensure_dict(value): """Convert None to empty dict.""" if value is None: return {} return value
191b1a469e66750171648e715501690b2814b8b2
1,432
def merge_dicts(dicts, handle_duplicate=None): """Merge a list of dictionaries. Invoke handle_duplicate(key, val1, val2) when two dicts maps the same key to different values val1 and val2, maybe logging the duplication. """ if not dicts: return {} if len(dicts) == 1: return dicts[0] if handle_duplicate is None: return {key: val for dict_ in dicts for key, val in dict_.items()} result = {} for dict_ in dicts: for key, val in dict_.items(): if key in result and val != result[key]: handle_duplicate(key, result[key], val) continue result[key] = val return result
44c06ab30bb76920ff08b5978a6aa271abd3e449
1,434
def escape(s): """ Returns the given string with ampersands, quotes and carets encoded. >>> escape('<b>oh hai</b>') '&lt;b&gt;oh hai&lt;/b&gt;' >>> escape("Quote's Test") 'Quote&#39;s Test' """ mapping = ( ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ('"', '&quot;'), ("'", '&#39;'), ) for tup in mapping: s = s.replace(tup[0], tup[1]) return s
2b4971c4e87e613cad457dde6d62806d299cdbcd
1,438
def _get_db_columns_for_model(model): """ Return list of columns names for passed model. """ return [field.column for field in model._meta._fields()]
181999f28ca659bf296bcb4dda7ac29ddfe61071
1,439
def issym(b3): """test if a list has equal number of positive and negative values; zeros belong to both. """ npos = 0; nneg = 0 for item in b3: if (item >= 0): npos +=1 if (item <= 0): nneg +=1 if (npos==nneg): return True else: return False
e8cc57eec5bc9ef7f552ad32bd6518daa2882a3e
1,442
def get_parents(tech_id, model_config): """ Returns the full inheritance tree from which ``tech`` descends, ending with its base technology group. To get the base technology group, use ``get_parents(...)[-1]``. Parameters ---------- tech : str model_config : AttrDict """ tech = model_config.techs[tech_id].essentials.parent parents = [tech] while True: tech = model_config.tech_groups[tech].essentials.parent if tech is None: break # We have reached the top of the chain parents.append(tech) return parents
7220a57b770232e335001a0dab74ca2d8197ddfa
1,443
def get_month_n_days_from_cumulative(monthly_cumulative_days): """ Transform consecutive number of days in monthly data to actual number of days. EnergyPlus monthly results report a total consecutive number of days for each day. Raw data reports table as 31, 59..., this function calculates and returns actual number of days for each month 31, 28... """ old_num = monthly_cumulative_days.pop(0) m_actual_days = [old_num] for num in monthly_cumulative_days: new_num = num - old_num m_actual_days.append(new_num) old_num += new_num return m_actual_days
5ede033023d357a60ba5eb7e9926325d24b986e8
1,444
def harvest(post): """ Filter the post data for just the funding allocation formset data. """ data = {k: post[k] for k in post if k.startswith("fundingallocation")} return data
67f400caf87f2accab30cb3c519e7014792c84d7
1,447
def clut8_rgb888(i): """Reference CLUT for wasp-os. Technically speaking this is not a CLUT because the we lookup the colours algorithmically to avoid the cost of a genuine CLUT. The palette is designed to be fairly easy to generate algorithmically. The palette includes all 216 web-safe colours together 4 grays and 36 additional colours that target "gaps" at the brighter end of the web safe set. There are 11 greys (plus black and white) although two are fairly close together. :param int i: Index (from 0..255 inclusive) into the CLUT :return: 24-bit colour in RGB888 format """ if i < 216: rgb888 = ( i % 6) * 0x33 rg = i // 6 rgb888 += (rg % 6) * 0x3300 rgb888 += (rg // 6) * 0x330000 elif i < 252: i -= 216 rgb888 = 0x7f + (( i % 3) * 0x33) rg = i // 3 rgb888 += 0x4c00 + ((rg % 4) * 0x3300) rgb888 += 0x7f0000 + ((rg // 4) * 0x330000) else: i -= 252 rgb888 = 0x2c2c2c + (0x101010 * i) return rgb888
ca95c95306f7f4762add01f2ffc113f348e29d3b
1,450
import json from typing import OrderedDict def to_json_dict(json_data): """Given a dictionary or JSON string; return a dictionary. :param json_data: json_data(dict, str): Input JSON object. :return: A Python dictionary/OrderedDict with the contents of the JSON object. :raises TypeError: If the input object is not a dictionary or string. """ if isinstance(json_data, dict): return json_data elif isinstance(json_data, str): return json.loads(json_data, object_hook=OrderedDict) else: raise TypeError(f"'json_data' must be a dict or valid JSON string; received: {json_data!r}")
e1264d88a4424630f7348cbe7794ca072c057bdf
1,451
def _collect_scalars(values): """Given a list containing scalars (float or int) collect scalars into a single prefactor. Input list is modified.""" prefactor = 1.0 for i in range(len(values)-1, -1, -1): if isinstance(values[i], (int, float)): prefactor *= values.pop(i) return prefactor
bea7e54eec16a9b29552439cd12ce29b9e82d40b
1,455
import itertools def all_inputs(n): """ returns an iterator for all {-1,1}-vectors of length `n`. """ return itertools.product((-1, +1), repeat=n)
526dff9332cf606f56dcb0c31b5c16a0124478ed
1,456
def init_time(p, **kwargs): """Initialize time data.""" time_data = { 'times': [p['parse']], 'slots': p['slots'], } time_data.update(**kwargs) return time_data
2aff3819d561f0dc9e0c9b49702b8f3fbb6e9252
1,458
import socket def get_socket_with_reuseaddr() -> socket.socket: """Returns a new socket with `SO_REUSEADDR` option on, so an address can be reused immediately, without waiting for TIME_WAIT socket state to finish. On Windows, `SO_EXCLUSIVEADDRUSE` is used instead. This is because `SO_REUSEADDR` on this platform allows the socket to be bound to an address that is already bound by another socket, without requiring the other socket to have this option on as well. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if 'SO_EXCLUSIVEADDRUSE' in dir(socket): sock.setsockopt(socket.SOL_SOCKET, getattr(socket, 'SO_EXCLUSIVEADDRUSE'), 1) else: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return sock
6edbc0f0aaaeaebd9c6d0f31257de0b4dfe7df1c
1,460
import functools def skippable(*prompts, argument=None): """ Decorator to allow a method on the :obj:`CustomCommand` to be skipped. Parameters: ---------- prompts: :obj:iter A series of prompts to display to the user when the method is being skipped. argument: :obj:`str` By default, the management command argument to indicate that the method should be skipped will be `skip_<func_name>`. If the argument should be different, it can be explicitly provided here. """ def decorator(func): @functools.wraps(func) def inner(instance, *args, **kwargs): parameter = argument or "skip_%s" % func.__name__ if parameter in kwargs and kwargs[parameter] is True: instance.prompt(*prompts, style_func=instance.style.HTTP_NOT_MODIFIED) return False else: return func(instance, *args, **kwargs) return inner return decorator
879106f4cc0524660fb6639e56d688d40b115ac4
1,464
import hashlib def _cache_name(address): """Generates the key name of an object's cache entry""" addr_hash = hashlib.md5(address).hexdigest() return "unsub-{hash}".format(hash=addr_hash)
6933b1170933df5e3e57af03c81322d68a46d91f
1,465
def fizzbuzz(end=100): """Generate a FizzBuzz game sequence. FizzBuzz is a childrens game where players take turns counting. The rules are as follows:: 1. Whenever the count is divisible by 3, the number is replaced with "Fizz" 2. Whenever the count is divisible by 5, the number is replaced with "Buzz" 3. Whenever the count is divisible by both 3 and 5, the number is replaced with "FizzBuzz" Parameters ---------- end : int The FizzBuzz sequence is generated up and including this number. Returns ------- sequence : list of str The FizzBuzz sequence. Examples -------- >>> fizzbuzz(3) ['1', '2', 'Fizz'] >>> fizzbuzz(5) ['1', '2', 'Fizz', '4', 'Buzz'] References ---------- https://blog.codinghorror.com/why-cant-programmers-program/ """ sequence = [] for i in range(1, end + 1): if i % (3 * 5) == 0: sequence.append('FizzBuzz') elif i % 3 == 0: sequence.append('Fizz') elif i % 5 == 0: sequence.append('Buzz') else: sequence.append(str(i)) return sequence
b68b1c39674fb47d0bd12d387f347af0ef0d26ca
1,469
import six import base64 import zlib def deflate_and_base64_encode(string_val): """ Deflates and the base64 encodes a string :param string_val: The string to deflate and encode :return: The deflated and encoded string """ if not isinstance(string_val, six.binary_type): string_val = string_val.encode('utf-8') return base64.b64encode(zlib.compress(string_val)[2:-4])
31fc19cf134bc22b3fc45b4158c65aef666716cc
1,472
import pickle def load_pickle(file_path): """ load the pickle object from the given path :param file_path: path of the pickle file :return: obj => loaded obj """ with open(file_path, "rb") as obj_des: obj = pickle.load(obj_des) # return the loaded object return obj
4770a152dad9c7d123f95a53642aff990f3590f7
1,473
import json import re def create_summary_text(summary): """ format a dictionary so it can be printed to screen or written to a plain text file Args: summary(dict): the data to format Returns: textsummary(str): the summary dict formatted as a string """ summaryjson = json.dumps(summary, indent=3) textsummary = re.sub('[{},"]', '', summaryjson) return textsummary
3a8dd508b760a0b9bfe925fa2dc07d53dee432af
1,476
def maximo_basico(a: float, b: float) -> float: """Toma dos números y devuelve el mayor. Restricción: No utilizar la función max""" if a > b: return a return b
f98db565243587015c3b174cf4130cbc32a00e22
1,477
def is_pattern_error(exception: TypeError) -> bool: """Detect whether the input exception was caused by invalid type passed to `re.search`.""" # This is intentionally simplistic and do not involve any traceback analysis return str(exception) == "expected string or bytes-like object"
623246404bbd54bc82ff5759bc73be815d613731
1,479
def _format_author(url, full_name): """ Helper function to make author link """ return u"<a class='more-info' href='%s'>%s</a>" % (url, full_name)
50f001c2358b44bb95da628cc630a2ed3ea8ddfd
1,483
def validinput(x0, xf, n): """Checks that the user input is valid. Args: x0 (float): Start value xf (float): End values n (int): Number of sample points Returns: False if x0 > xf or if True otherwise """ valid = True if x0 > xf: valid = False if int(n) != n: valid = False if not valid: print("Please recheck your input") return valid
096e0702eb8fe47486d4f03e5b3c55c0835807cd
1,484
import glob def find_paths(initial_path, extension): """ From a path, return all the files of a given extension inside. :param initial_path: the initial directory of search :param extension: the extension of the files to be searched :return: list of paths inside the initial path """ paths = glob.glob(initial_path+r'/**/*.' + extension, recursive=True) return paths
0220127050b765feaf423c195d020d65ece8d22e
1,487
import requests import io import tarfile def sources_from_arxiv(eprint): """ Download sources on arXiv for a given preprint. :param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``). :returns: A ``TarFile`` object of the sources of the arXiv preprint. """ r = requests.get("http://arxiv.org/e-print/%s" % (eprint,)) file_object = io.BytesIO(r.content) return tarfile.open(fileobj=file_object)
b26c46009b23c5a107d6303b567ab97492f91ad9
1,496
import csv def read_manifest(instream): """Read manifest file into a dictionary Parameters ---------- instream : readable file like object """ reader = csv.reader(instream, delimiter="\t") header = None metadata = {} for row in reader: if header is None: header = row else: metadata[row[0]] = row[1] return metadata
afa6c2bb0a9d81267b1d930026a229be924a1994
1,498
import webbrowser def open_in_browser(path): """ Open directory in web browser. """ return webbrowser.open(path)
41328b2b478f0bd69695da1868c412188e494d08
1,503
def encode_letter(letter): """ This will encode a tetromino letter as a small integer """ value = None if letter == 'i': value = 0 elif letter == 'j': value = 1 elif letter == 'l': value = 2 elif letter == 'o': value = 3 elif letter == 's': value = 4 elif letter == 't': value = 5 elif letter == 'z': value = 6 return value
6c72c4c9e44c93d045296ab1f49c7783f2b4fc59
1,504
import hashlib import json def get_config_tag(config): """Get configuration tag. Whenever configuration changes making the intermediate representation incompatible the tag value will change as well. """ # Configuration attributes that affect representation value config_attributes = dict(frame_sampling=config.proc.frame_sampling) sha256 = hashlib.sha256() sha256.update(json.dumps(config_attributes).encode("utf-8")) return sha256.hexdigest()[:40]
2cab6e9473822d0176e878114ceb3fda94d1e0f7
1,510
import requests import re def api_wowlight_version_check(version: str) -> bool: """ Checks incoming wow-lite wallet version, returns False when the version is too old and needs to be upgraded. :param version: :return: bool """ url = "https://raw.githubusercontent.com/wownero/wow-lite-wallet/master/src/renderer/components/Landing/LandingPage.vue" try: resp = requests.get(url, headers={"User-Agent": "Mozilla 5.0"}) resp.raise_for_status() content = resp.content.decode() except: return True # default to true # parse latest version current = next(re.finditer(r"wowlite\?version=(\d+.\d+.\d+)", content), None) if not current: return False return version == current.group(1)
470f8580df357c206b595c1145e04e33fd897058
1,515
def construct_SN_default_rows(timestamps, ants, nif, gain=1.0): """ Construct list of ants dicts for each timestamp with REAL, IMAG, WEIGHT = gains """ default_nif = [gain] * nif rows = [] for ts in timestamps: rows += [{'TIME': [ts], 'TIME INTERVAL': [0.1], 'ANTENNA NO.': [antn], 'REAL1': default_nif, 'REAL2': default_nif, 'IMAG1': default_nif, 'IMAG2': default_nif, 'WEIGHT 1': default_nif, 'WEIGHT 2': default_nif} for antn in ants] return rows
b81e45d2d5299042b3332a2386a0fd4d2d6d59d7
1,517
def isUniqueSeq(objlist): """Check that list contains items only once""" return len(set(objlist)) == len(objlist)
4522c43967615dd54e261a229b05c742676c7f99
1,528
def tag_to_dict(node): """Assume tag has one layer of children, each of which is text, e.g. <medalline> <rank>1</rank> <organization>USA</organization> <gold>13</gold> <silver>10</silver> <bronze>9</bronze> <total>32</total> </medalline> """ d = {} for child in node: d[child.tag] = child.text return d
e2131e070dce8620630e994cc25578a9a8438c64
1,531
from typing import Dict from typing import Any import yaml def yaml_dump(dict_to_dump: Dict[str, Any]) -> str: """Dump the dictionary as a YAML document.""" return yaml.safe_dump(dict_to_dump, default_flow_style=False)
4635514ba8ff901656b8a4b5869a6ae101528fa8
1,533
import hashlib def cache_key(path): """Return cache key for `path`.""" return 'folder-{}'.format(hashlib.md5(path.encode('utf-8')).hexdigest())
6b9afe1267e0cc0c7168bf3b0d5c7536e2b3c768
1,537
import torch def quaternion2rotationPT( q ): """ Convert unit quaternion to rotation matrix Args: q(torch.tensor): unit quaternion (N,4) Returns: torch.tensor: rotation matrix (N,3,3) """ r11 = (q[:,0]**2+q[:,1]**2-q[:,2]**2-q[:,3]**2).unsqueeze(0).T r12 = (2.0*(q[:,1]*q[:,2]-q[:,0]*q[:,3])).unsqueeze(0).T r13 = (2.0*(q[:,1]*q[:,3]+q[:,0]*q[:,2])).unsqueeze(0).T r21 = (2.0*(q[:,1]*q[:,2]+q[:,0]*q[:,3])).unsqueeze(0).T r22 = (q[:,0]**2+q[:,2]**2-q[:,1]**2-q[:,3]**2).unsqueeze(0).T r23 = (2.0*(q[:,2]*q[:,3]-q[:,0]*q[:,1])).unsqueeze(0).T r31 = (2.0*(q[:,1]*q[:,3]-q[:,0]*q[:,2])).unsqueeze(0).T r32 = (2.0*(q[:,2]*q[:,3]+q[:,0]*q[:,1])).unsqueeze(0).T r33 = (q[:,0]**2+q[:,3]**2-q[:,1]**2-q[:,2]**2).unsqueeze(0).T r = torch.cat( (r11,r12,r13, r21,r22,r23, r31,r32,r33), 1 ) r = torch.reshape( r, (q.shape[0],3,3)) return r
feeed764ee179b31674790f9d2afc7b606a02aef
1,538
def calculate_reliability(data): """ Calculates the reliability rating of the smartcab during testing. """ success_ratio = data['success'].sum() * 1.0 / len(data) if success_ratio == 1: # Always meets deadline return ("A+", "green") else: if success_ratio >= 0.90: return ("A", "green") elif success_ratio >= 0.80: return ("B", "green") elif success_ratio >= 0.70: return ("C", "#EEC700") elif success_ratio >= 0.60: return ("D", "#EEC700") else: return ("F", "red")
d1c9ad7bba220beeae06c568cfd269aaaebfb994
1,545
def explode(screen): """Convert a string representing a screen display into a list of lists.""" return [list(row) for row in screen.split('\n')]
a43a9d8c830c4a784bb9c3505c62aaf2077bb732
1,548
def fpath_to_pgn(fpath): """Slices the pgn string from file path. """ return fpath.split('/')[-1].split('.jpeg')[0]
1cc6cad60c5356b6c731947a59998117bf15035a
1,552
def data_zip(data): """ 输入数据,返回一个拼接了子项的列表,如([1,2,3], [4,5,6]) -> [[1,4], [2,5], [3,6]] {"a":[1,2],"b":[3,4]} -> [{"a":1,"b":3}, {"a":2,"b":4}] :param data: 数组 data 元组 (x, y,...) 字典 {"a":data1, "b":data2,...} :return: 列表或数组 """ if isinstance(data, tuple): return [list(d) for d in zip(*data)] if isinstance(data, dict): data_list = [] keys = data.keys() for i in range(len(data[list(keys)[0]])): # 迭代字典值中的数据 data_dict = {} for key in keys: data_dict[key] = data[key][i] data_list.append(data_dict) return data_list return data
31dcaa3905a7d062cfe994543df31f293fdc962a
1,553
from pathlib import Path from typing import List import re def tags_in_file(path: Path) -> List[str]: """Return all tags in a file.""" matches = re.findall(r'@([a-zA-Z1-9\-]+)', path.read_text()) return matches
1071c22ac79f51697b2ed18896aa1d17568ecb2c
1,554
def check_ip_in_lists(ip, db_connection, penalties): """ Does an optimized ip lookup with the db_connection. Applies only the maximum penalty. Args: ip (str): ip string db_connection (DBconnector obj) penalties (dict): Contains tor_penalty, vpn_penalty, blacklist_penalty keys with integer values Returns: :int: penalty_added """ penalties = {'tor': int(penalties['tor_penalty']), 'vpn': int(penalties['vpn_penalty']), 'blacklist': int(penalties['ip_blacklist_penalty'])} penalties = sorted(penalties.items(), key=lambda x: x[1]) # sort by penalty value to check in that order and perform early stopping penalty_added = 0 for penalty_type, penalty_value in penalties: if penalty_value == 0: continue if penalty_type == 'tor': if db_connection.set_exists('tor_ips', ip): penalty_added = penalty_value elif penalty_type == 'blacklist': if db_connection.set_exists('blacklist_ips', ip): penalty_added = penalty_value elif db_connection.set_exists('blacklist_ips', '.'.join(ip.split('.')[:3])): penalty_added = penalty_value elif db_connection.set_exists('blacklist_ips', '.'.join(ip.split('.')[:2])): penalty_added = penalty_value elif penalty_type == 'vpn': if db_connection.set_exists('vpn_ips', ip): penalty_added = penalty_value elif db_connection.set_exists('vpn_ips', '.'.join(ip.split('.')[:3])): penalty_added = penalty_value elif db_connection.set_exists('vpn_ips', '.'.join(ip.split('.')[:2])): penalty_added = penalty_value if penalty_added > 0: break return penalty_added
2d6e3615d4b0d9b0fb05e7a0d03708856ffcbfef
1,555
def is_validated(user): """Is this user record validated?""" # An account is "validated" if it has the `validated` field set to True, or # no `validated` field at all (for accounts created before the "account # validation option" was enabled). return user.get("validated", True)
c1ddfc52a62e71a68798dc07e7576a4ae42aa17f
1,562
import pickle def load_config(path): """Loads the config dict from a file at path; returns dict.""" with open(path, "rb") as f: config = pickle.load(f) return config
eb12aed2ebdeebacf3041f3e4880c714f99c052c
1,563
def lower_strings(string_list): """ Helper function to return lowercase version of a list of strings. """ return [str(x).lower() for x in string_list]
58dcaccbc0f4ce8f22d80922a3ac5da26d7f42b1
1,564
import hashlib import hmac def _HMAC(K, C, Mode=hashlib.sha1): """ Generate an HMAC value. The default mode is to generate an HMAC-SHA-1 value w/ the SHA-1 algorithm. :param K: shared secret between client and server. Each HOTP generator has a different and unique secret K. :type K: bytes :param C: 8-byte counter value, the moving factor. This counter MUST be synchronized between the HOTP generator (client) and the HOTP validator (server). :type C: bytes :param Mode: The algorithm to use when generating the HMAC value :type Mode: hashlib.sha1, hashlib.sha256, hashlib.sha512, or hashlib.md5 :return: HMAC result. If HMAC-SHA-1, result is 160-bits (20-bytes) long. :rtype: bytes """ return hmac.new(K, C, Mode).digest()
db9bf26c52427acc259f3cb1590c7c13b0d0dd9e
1,569
def nth_even(n): """Function I wrote that returns the nth even number.""" return (n * 2) - 2
26e1465a039352917647ae650d653ed9842db7f6
1,571