content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def identity(df): """Verb: No-op.""" return df
633835e460b3945fb8c3b634081a65045fc223d9
636,626
import pipes import logging import subprocess def runShellCommand(*args): """ Run a shell command (e.g. bcf tools), and return output """ qargs = [] for a in args: if a.strip() != "|": qargs.append(pipes.quote(a)) else: qargs.append("|") cmd_line = " ".join...
a509967fb8396703e439a79ab6edc40ee872f43d
636,627
import platform import subprocess def copyToClipboard(text): """ Copies the given text to the clipboard Args: text (string): Text to copy to clipboard. """ operating_system = platform.system() command = 'echo ' + text.strip() if operating_system == 'Darwin': # macOS comm...
712e0b4a8305c35c7856016118e101fbdf9726ea
636,628
import requests import logging def _raise_for_status(response: requests.Response, logger: logging.Logger) -> requests.Response: """ Check the status code of the response. If the status code suggests an error, log the response as JSON and then raise an exception. Otherwise, return the response for further ...
787e514f128978d834df14ab7bda25b8e7acad35
636,629
def time_to_ms(time1: float, time2: float): """Substracts times and rounds and adds a ms""" return f"{round((time1-time2)*1000,2)}ms"
b4d195f0ec73d7769ee2b340455d2ce19c4592f9
636,630
def get_platform_bools(user_agent): """Return if we're on a pc, mobile or tablet platform.""" is_pc_mac = False is_pc_windows = False is_mobile_ios = False is_mobile_android = False is_tablet_ios = False is_tablet_android = False if user_agent.is_mobile: if user_agent.os.family...
9c1161bf01932f60e537c6e9e0861f349382b122
636,631
import requests import os def download_frames(sdate, edate, headers, prop, datafolder): """Download files This function downloads all the frames for a given range of dates, querying 50 frames at a time (i.e., if 150 frames have to be downloaded, the process is repeated 3 times, each time downlo...
fb61784b5413481784f00b1c18445446b999cdc2
636,633
from typing import List def valid_hops(A: List[int]) -> bool: """We can solve this in O(n) time and O(1) space by simply traversing the array and accumulating hops as we see them. We also have to remove a hop for every traversal we do. We keep moving until we run out of hops or we reach the end. ...
9627e33829d9e98ae324f56b6f276fae0f8e4a5d
636,634
def lazy_filter(filter_type, filter_func): """ Lazy typed filter on top of the built-in function. It's meant to be used when the values to be filtered for are only defined later on dynamically at runtime. """ def filter_closure(value, items): if not isinstance(value, filter_type): ...
705222e60f834f2d74ceda4e7172dcb944c85276
636,635
def ftp_useradd(device): """Add ftp user to client list to grant access :param device: Linux device(lan/wan) :type device: Object :return: None if client already exists, True if "failed" is present in device.before else False :rtype: Boolean or None """ device.sendline("useradd...
1f14d48d1c2ca292b7be7d44358ab4f2103273a7
636,636
import hashlib def HashPassword(plaintext): """Generate a MySQL password hash from a string.""" hashobj = hashlib.sha1(hashlib.sha1(plaintext).digest()) return '*%s' % hashobj.hexdigest().upper()
c3be9e07ae88ad1735363a18f6585fa894e5483d
636,637
def public_nodes(): """ Static list of bitshares nodes """ return [ "wss://bitshares.openledger.info/ws", "wss://openledger.hk/ws", "wss://na.openledger.info/ws", "wss://ws.gdex.top", "wss://api.bts.ai", "wss://api-ru.bts.blckchnd.com", "wss://bts-...
d1c51ea1198e750b7f67542ae6df48f7b135e3a4
636,638
def createContextSingle(obj, id=None, keyTransform=None, removeNull=False): """ Recieves a dict with flattened key values, and converts them into nested dicts :type data: ``dict`` or ``list`` :param data: The data to be added to the context (required) :type id: ``str`` :key...
88ce400d5d4afa5966409abcf89537a9f30991aa
636,640
import platform import os def determine_db_dir(): """return the default location of the moorecoin data directory""" if platform.system() == "darwin": return os.path.expanduser("~/library/application support/moorecoin/") elif platform.system() == "windows": return os.path.join(os.environ['a...
63e0a4938f1be8a902aa38948dcd4b27e18d8c43
636,641
import struct def float_to_bin(value): """ Convert float to 64-bit binary string. """ [d] = struct.unpack(">Q", struct.pack(">d", value)) return "{:064b}".format(d)
88768bee60164774a3cd1d0a1fdcc958884f8984
636,642
def duration(first, last): """Evaluate duration Parameters ---------- first : int First timestamp last : int Last timestamp Returns ------- str Formatted string """ ret = '' diff = last - first if diff <= 0: return '' mm = divmod(di...
d368f18cb574dadab3794e3816410c9d8dcb07ee
636,643
def idfobjectkeys(idf): """returns the object keys in the order they were in the IDD file it is an ordered list of idf.idfobjects.keys() keys of a dict are unordered, so idf.idfobjects.keys() will not work for this purpose""" return idf.model.dtls
884ae6c0b920d08415942aad409dafc1f5eb3ef0
636,644
def build_obj_trailer(): """Add closing elements to object""" ret = '' ret += f'</div>\n' ret += f'</pre>\n</div>\n' return ret
b16c6e468a7b99b3287e2fe0ad37f4c579b0a019
636,645
def replace_ellipsis(n, index): """Replace ... with slices, :, : ,: >>> replace_ellipsis(4, (3, Ellipsis, 2)) (3, slice(None, None, None), slice(None, None, None), 2) >>> replace_ellipsis(2, (Ellipsis, None)) (slice(None, None, None), slice(None, None, None), None) """ # Careful about usin...
774acac046947261af4e42920823015699d9e8f8
636,646
import functools import numpy def _mul(*args): """An internal method to multiply matrices.""" return functools.reduce(numpy.dot, args)
a6ee9dfc46a684ad378d78acd8334d1f14f881c1
636,648
def retorno(): """Regresa un valor usando la palabra reservada return-> x*y""" x = 10 y = 10 return x*y
25bccaf3285f5097957615ea62e708694d7c1f7a
636,650
def format_input(inp, index): """ Parameters ---------- inp input expression index Index of the pi number Returns The full expression ------- """ return f"Pi{index} = {inp}"
8c1c5d015c29b92c2c69b42c2d1da5d401e189f1
636,651
def get_number_internal_layers(n, output_size): """ E.g.: get_number_internal_layers(20, 3) --> [16, 8, 4] get_number_internal_layers(192, 16) # --> [128, 64, 32] """ i = 1 d = 2 s = [] while (n - 1) / d > 1: s.append(d) i += 1 d = 2 ** i s = [e f...
2b2b121db8206046d92c6c2bb4ca14ae2725d664
636,652
def mmult(a, b): """Matrix multiplication: mmult([[11, 12], [21, 22]], [[-1, 0], [0, 1]]) returns [[-11, 12], [-21, 22]]""" return [[sum([i*j for i, j in zip(row, col)]) for col in zip(*b)] for row in a]
c440168ea0cbfe653b40b0486c14f7e3acc6771a
636,653
def scale_ticks_params(tick_scale='linear'): """ Helper function for learning cureve plots. Args: tick_scale : available values are [linear, log2, log10] """ if tick_scale == 'linear': base = None label_scale = 'Linear scale' else: if tick_scale == 'log2': ...
16b56ac81ef36abe63a30a159f25259d5a1e21e7
636,654
from typing import Callable def max_length(length: int) -> Callable[[str], bool]: """ Create an MAX length validator (inclusive) Args: length (int): MAX length Returns: Callable[[str], bool]: a function with the name exact_length_{length} """ def v(_field): return le...
6093d934637ee0fe24e1ebf5a57ea59281f4644c
636,656
def parse_field(field): """ Parse a non-meta key from the response attributes dict. The non-meta keys correspond to (sub-)question titles ((s)qid). If the field name contains no brackets ('[', ']'), a qid without subquestions is meant. Otherwise one or two sqids are within the brackets: two if ...
8c06354f2a2982b8a507d0c1965602e22fa2c03c
636,657
from typing import Any import json async def parse_response(json_: Any) -> Any: """Convert JSON object to a python data type. Args: response (Any): The JSON object to deserialize. Returns: Any: The deserialized JSON object. """ try: return json.loads(json_.read()) exc...
9426c651bddec8ee2dcba741fb7c1c601241b26b
636,658
import os def retrieve_token(token_file_name='DIGITALOCEAN_TOKEN'): """ check if have a saved Digital Ocean API token, or retreive one. """ if os.path.isfile(token_file_name): print('token found.') with open(token_file_name, 'r') as token_f: digitalocean_token = token_f.r...
11de32f92dc694230d08211873a539493dffa151
636,659
def replace_with_phrases(tokens, phrases): """Replace applicable tokens in semantically-ordered tokens with their corresponding phrase. Args: tokens (list of str): A list of semantically-ordered tokens. phrases (list of str): A list of phrases. Returns: list of str: A list o...
b0f3a3652870784c2fab74ac3d229434a58d01f3
636,660
def get_fasta_size_from_faifile(infile): """ Get chromosome size from .fai file .fai format: 1 249250621 52 60 61 2 243199373 253404903 60 61 3 198022430 500657651 60 61 4 191154276 701980507 ...
5c33a2eda39108b847fc3add99f45a84dc6b091e
636,661
def read_line2(path): """Read file auxiliary function.""" f = open(path, 'r', encoding='utf-8') lines = f.readlines() data = {} for idx, i in enumerate(lines): data[idx] = i.strip() return data
096afcc0ee36f65d0bfeea1df8594aa043d3f6f7
636,662
import os def scripts(): """ Return the list of scripts in the scripts directory :return: """ if os.path.isdir('scripts'): return [ os.path.join('scripts', f) for f in os.listdir('scripts') ]
1ba0f54db2d69b37820bd7e87735892a7d176844
636,663
def add_vecs_to_vocab(vocab, vectors): """Add list of vector tuples to given vocab. All vectors need to have the same length. Format: [("text", [1, 2, 3])]""" length = len(vectors[0][1]) vocab.reset_vectors(width=length) for word, vec in vectors: vocab.set_vector(word, vector=vec) return...
72926407518161b5babb637006f190fdf9c5140e
636,665
def int2str(value): """ int 转换为 str """ return str(value)
64bf9bcf960263703aa1c3b98bf2cf9ed453c1cb
636,667
def _update_function(oldfunc, newfunc): """Update a function object.""" oldfunc.__doc__ = newfunc.__doc__ oldfunc.__dict__.update(newfunc.__dict__) try: oldfunc.__code__ = newfunc.__code__ except AttributeError: oldfunc.func_code = newfunc.func_code try: oldfunc.__de...
5a2075d0f1c2537e538344640ee2d944c955edd3
636,668
def _gamut(component): """keeps color components in the proper range""" return min(max(int(component), 0), 254)
2f30c49243aa19f8fb314fed65cc1805cbf1fd00
636,669
def extract_page_id(full_file_name: str) -> str: """ Extract page id from file_name Example: Data-loss-94d44921-0a4c-4319-8f78-60ef45267d97.md -> 94d449210a4c43198f7860ef45267d97 """ file_name, _ = full_file_name.rsplit('.', maxsplit=1) parts = file_name.rsplit('-', maxsplit=5) id_...
d66f338bb61845af949d94fb6f497c64f26af2c5
636,670
import random import os def get_a_random_filepath_from_folder(folder_path: str) -> str: """get a random filepath from folder :param folder_path: [root folder path] :type folder_path: str :return: [file pull path] :rtype: str """ file_name = random.choice(os.listdir(folder_path)) file_...
5666d87b9935ba308b6f1fcee4613514758b345b
636,673
def _check_key_types(remote_values, local_values): """ Validates that the key types match regardless of the casing. E.g. 'RSA' == 'rsa' :param list[str] remote_values: :param list[str] local_values: :rtype: bool """ copy = [] for val in local_values: copy.append(val.upper()) ...
6e32ab9914bdce38a511afd00ff1f56d7c68434b
636,675
def read_data(node_number, state_file, cut_file): """ Read in the IQ-TREE state file that contains information about ancestral nodes as well as the file that defines positions to be cut. """ with open(state_file, "r") as infile: input_data = [] for line in infile: if line...
5cc132ca33ad0860d0430f163510ff5bd1ae7078
636,676
def rook_attack_id(x, y, board, king_x, king_y): """ Function for determining fields that can be blockaded to stop the check of the king for a rook """ indices = [] if king_x == x and king_y < y: dx = 0 dy = -1 elif king_x == x and king_y > y: dx = 0 dy = 1 el...
05439ae7716bbfcac736ae9e58bd3624d9a9db29
636,677
import torch def group1_forward_branch(layer, in_tensor, resized_feat): """Defines group 1 connections. Args: layer (torch.nn.Module): Network layer. in_tensor (torch.Tensor): Input tensor. resized_feat (torch.Tensor): Resized input. Returns: ...
19ab11bea4f24404377f472841465e251ad73db1
636,678
def decrypt_cnc_msg(ct): """ Decrypt strings ct: bytearray of the ciphertext returns bytearray of the plaintext """ # seed k = 0xff for i in reversed(range(len(ct))): # XOR with previous k = ct[i] = ct[i] ^ k return ct
014784851b0c8a514688c9c3353ee4d301aad3a7
636,680
def _get_invalid_circle_definitions(): """Create a list of invalid 2D circle parameters. Create and return a list of tuples each containing invalid parameters of a 2D circle along with the expected type of exception that should be thrown. An invalid parameter is a parameter with either an unexpected d...
d9abb99f9d8c30a12baaf44c7bee4769e013cbf1
636,681
def sorted_components(layout_area, row_height, comps): """ Sort the components by row :param layout_area: a list [x, y] that stores the area of the layout :param comps: a list of components that need to be sorted :return: a list of rows, each containing a list of components in that row. """ ...
bf320e9414405192752ccfcced360d8eb06ec0de
636,682
import json def is_sword_purchase(event_as_json): """udf for filtering events """ event = json.loads(event_as_json) if event['event_type'] == 'purchase_sword': return True return False
2916c0193b706fd7aaf405e1f7ca14c638a050ca
636,683
def _sorted_facet_counts(solr_counts, field): """ Convert the raw solr facet data (counts, ranges, etc.) from a flat array into a two-dimensional list sorted by the number of hits. The result will look something like this: (('field1', count1), ('field2', count2), ...) """ raw = solr_counts.get(...
01d093fd71e80c7651ec4ca9ceb7f66f414fad9e
636,685
from typing import Dict def canberra(a: Dict, b: Dict) -> float: """Return the canberra distance beetween the given dictionaries. Parameters ---------------------------- a: Dict, First dictionary to consider. b: Dict, Second dictionary to consider. Returns ---------------...
ce08ba8b79b87230a92b732209439b9810f6a544
636,687
def licensekey(pytestconfig): """License key which should be applied to the remote server(s).""" return pytestconfig.getoption('license')
7c22cc5be2bacf26c05f47bbd8f79629e2467ce0
636,688
import re def get_percent(line): """ Args: line: A progress string containing percent complete Return: integer of current percent value if found, otherwise None """ m = re.search(r'\d+', line) if m: try: return int(m.group()) except ValueE...
0bcf59cdf833b9c29a510169061c1c58df6b7a9b
636,689
def fakesh(): """Spawns a fake shell. Prints a 'sh-4.1$ ' prompt and ignores input.""" return """ ;; Clear eax, ebx, edx xor ebx, ebx imul ebx ;; Push 'sh-4.1$ ' push `.1$ ` push `sh-4` start: ;; Print string mov al, 0x4 mov ecx, esp ...
ea0331db093888a4b5eaec3b021e352f9d730319
636,690
def esc(string): """ Escape strings for SQLite queries """ return string.replace("'", "''")
54b2faffaba7b5b9cdccc4b6ca31d289e542105f
636,691
def verificalista(arquivo): """ -> funcao que vai verificar se tem um arquivo .txt caso não ele mesmo informa no valor de retorno False, :param arquivo: :return: """ try: a = open(arquivo, 'rt') a.close() except FileNotFoundError: return False else: return...
f633213bcbcec586c19b19e9445a85a136016315
636,692
def limb_prec_match(mp_prec, prec): """ predicate verified when all limbs of @p mp_prec matches @p prec """ return all(mp_prec.get_limb_precision(i) == prec for i in range(mp_prec.limb_num))
7ecc7592ce0a0753474ee9f60b8817c764e8a226
636,693
def min_length(minimum): """ Return a function that tests if values are the specified minimum length """ def callback(value): """Accept a value to validate, return validation results""" if len(value) >= minimum: return True, None return False, ('"' + str(value) + '" is not a ...
be01b938355c1c4e7bd0fc7c0f025419b8f1986d
636,694
def get_tf_idf(doc_tf, idf_map): """ calculate the product of the term frequency and the idf :param doc_tf: term frequency map of the string :param idf_map: idf map of all the strings :return: vector map of a document """ vector = {} for word in doc_tf: if word in idf_map: ...
28122958d9464427bb984b3b4a37219b26d05ad8
636,695
def _nbw_ids(tests): """Return IDs for widget attribute tests.""" return [test[0].__name__ for test in tests]
5aecdb56fc2aaeef12a65d0b0e3578b41cb0fef5
636,696
def escape_list(list, escape_func): """Escape a list of arguments by running the specified escape_func on every object in the list that has an escape() method.""" def escape(obj, escape_func=escape_func): try: e = obj.escape except AttributeError: return obj e...
80c64dcacfd37e755a4ae0488f261f6c328ddae3
636,697
def pick(cont, arg, fallback=''): """Iterate through arg and return first choice which is not None""" choices = arg.split(',') for choice in choices: if choice in cont and cont[choice] is not None: return cont[choice] return fallback
a3d0e2c778ea427103d2299896d50164406923ff
636,700
def first_changes(dict_1, dict_2, dict_3, node): """ Technical changes need to be done after adding the node to the projection :param dict_1: dict_node_enode OR dict_enode_node :param dict_2: dict_enode_enode_out OR dict_enode_enode_in :param dict_3: dict_enode_enode_in OR dict_enode_enode_out :...
a7c2b32247c22f98cb09513bf9d6d1ed4acdf031
636,701
import torch def shape_list(x: torch.Tensor) -> list: """Return a list of dims""" return list(x.shape)
557ac275a76c104a7074776f4078d34202c6865e
636,702
def extract_server_arguments(namespace): """Given the output of .parse() on a ArgumentParser that had add_server_arguments called with it, remove the resulting option in-place from namespace and return them in a separate namespace.""" server_arguments = type(namespace)() server_arguments.bind = nam...
c1aeb21fdd0f61b7a6b845cd5d3c815686747fff
636,703
def _IsOutsideTimeRange(timestamp, time_range = None): """Returns a boolean indicating whether a timestamp is in a given range.""" return time_range is not None and (timestamp < time_range[0] or timestamp > time_range[1])
05b72d28607b74f0b71517381583ca88dde0efc5
636,704
def iloc(df, loc): """Get the specified dataframe row as a dict""" return dict(sorted(df.iloc[loc].items()))
db3c12e0125713b09f005c05d0327f8f779d450a
636,705
import re def AuthorStart(s): """ To check if there is an author for the input text by performing a regex check to match the format of first name, first name and last name, first name and middle name and last name, or mobile number Parameters: s (string): The string for which we need to perform r...
65042e0ec21fe2d8d6ca48bd9634736e3eb5d386
636,707
import math def calculate_p_active(weight, cohesion, adhesion, wedge_angle, wall_angle, int_friction, wall_friction): """ Analytical solution to Columb's Force Polygon :param weight: weight of wedge :param cohesion: cohesion force on soil slip plane :param adhesion: adhesion force on interface ...
c8904cb4d8794f4a911bc00364a46e82bdec873a
636,708
def output_tensor(interpreter, i): """Gets a model's ith output tensor. Args: interpreter: The ``tf.lite.Interpreter`` holding the model. i (int): The index position of an output tensor. Returns: The output tensor at the specified position. """ return interpreter.tensor(interpreter.get_output_det...
4c4915ac4ee9337daa45eabbbc38e58d1b9fdec9
636,709
def IsFlag(token_name): """Returns whether the passed string is a flag. Args: token_name: the string to check. Returns: True if it's a flag, False otherwise. """ return token_name.startswith('-')
35731409ac7fffe1917c29e0f4f9735b384d3a4c
636,710
import torch def L1_loss(pred, target): """ Calculate L1 loss """ return torch.mean(torch.abs(pred - target))
dd34fe06502676cba62813e156da5246b5933cc5
636,711
def get_server_name(prefix, xid, wid): """Gets unique server name for each work unit in the experiment. Args: prefix: String, the prefix of the server. xid: Integer, the experiment id. wid: Integer, the work unit id. Returns: String. """ return f'{prefix}-{xid}-{wid}'
6fdaa7c998ccf0f3fa38534b233a25e9fc1eb04a
636,713
import math def Trunc_val(input, intwidth=7, fracwidth=8, rounding="round"): """ Trunc_val is an operation to convert one single value to format (1, intwidth, fracwidth). """ scale = 2**fracwidth max_val = (2**(intwidth + fracwidth) - 1) min_val = 0 - (2**(intwidth + fracwidth)) if roundin...
42e2912e2acbf1bcf3efef240d98907fe79437c0
636,714
def filter_poses(sphere_poses, object_pose, filter_behind=False, filter_under=True): """Given the generated poses and the object pose filter out the poses that are behind or under (if set to True) :type sphere_poses: [] list of Pose :type object_pose: PoseStampe...
bcfe8733a55fd703bbaf1ee4e0a188a73450aa37
636,715
import re def prompt_header(): """ Prompt user for relevant sample sheet variables. Input: ------ None Output: ------- header :: str The header section of Illumina's sample sheet rc :: bool Do we need to reverse compliment Depends: -------- re """...
8f812879c110c83bf55b0dc1b9ceb4d6665cac43
636,716
def extract_topn_from_vector(feature_names, sorted_items, topn=10): """return n-gram counts in asc order of counts""" # use only topn items from vector sorted_items = sorted_items[-topn:] results = [] for idx, count in sorted_items: # get the ngram name n_gram = feature_names[idx]...
7a6f52fb89950aa24bb75c7c2054b796efd1438a
636,718
def add_res(acc, elem): """ Adds results to the accumulator :param acc: :param elem: :return: """ if not isinstance(elem, list): elem = [elem] if acc is None: acc = [] for x in elem: acc.append(x) return acc
e0d32fcc4ad19948dca5e88c7b5fe651952083df
636,719
def get_build_list(json_data: dict) -> list: """Return a list of build IDs for a device""" builds = [] for firmware in json_data["firmwares"]: builds.append(firmware["buildid"]) return builds
a92d49cca68cc91a9a3c33aa224583ffcf65a36c
636,720
import argparse def create_argument_parser() -> argparse.ArgumentParser: """Create a command-line parser.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("name", nargs="?", help="builtin, module, or module member") return parser
4d51ec0b632c84cefa17ec0777e6ed2030c771ad
636,721
def iou_socre(pred, target): """ :param pred: :param target: :return: """ ious = [] n_class = target.max() + 1 # IOU for background class ("0") for c in range(1, n_class): pred_idx = pred == c target_idx = target == c intersection = (pred_idx & target_idx...
0a3ec6ec5b2216fb49ba5670a292f72584f31e2b
636,722
def _get_fake_dataset_contents() -> str: """ Build a fake dataset file and write it to a temporary folder. The dataset has "measurements" for 3 different channels 0, 8, and 12, with columns for two numerical features NUM1, NUM2 and two categorical features CAT1, CAT". Labels are attached to channel ...
4f3677380fec74f56170ceace42dee1deae22727
636,723
import binascii def crc32text(text): """ crc32text - Returns the crc2 """ return binascii.crc32(text) & 0xffffffff
5f937b50e719dc8bb354ef1f8896111af7873af5
636,724
def getbetas(df, market, window = 45): """ given an unstacked pandas dataframe (columns instruments, rows dates), compute the rolling betas vs the market. """ nmarket = market/market.rolling(window).var() thebetas = df.rolling(window).cov(other=nmarket) return thebetas
70916da86739909a7db765358b44e24c30c8a1ea
636,725
def genimage(core, args): """Generate the manifest for the source directory.""" for aggregator in core.get_ordered_aggregators(): if aggregator.matches(core): image = aggregator.generate_image(core) return image else: core.get_output().error('Unknown directory type')
521f2a7235993eddb1a45ef5a07b08f86ac1329c
636,726
import typing def clamp(source: typing.Tuple[int, int, int]) -> typing.Tuple[int, ...]: """Helper for clamping rgb values Args: source (Tuple[int, int, int]): values to be clamped Returns: value (Tuple[int, int, int]): clamped values """ return tuple(max(0, min(value, 255)) for v...
5daedc938cfe1d9930c537db1d46ee0fa676499d
636,727
def token_network( register_token_network, custom_token, ): """Register a new token network for a custom token""" return register_token_network(custom_token.address)
32889711e55bf05cbd6a30763cd51ee046184b86
636,728
def _find_cells_with_tags(nb, tags): """ Find the first cell with any of the given tags, returns a dictionary with 'cell' (cell object) and 'index', the cell index. """ tags_to_find = list(tags) tags_found = {} for index, cell in enumerate(nb['cells']): for tag in cell['metadata'].g...
7ff62fc853f5b196a1cd2f0e022867f8f8a8bf65
636,729
def f_flag(opt, test_not=False): """ convert a test parameter into t if true for the Fortran build system """ if test_not: if opt: return " " else: return "t" else: if opt: return "t" else: return " "
0913f4acd8e0d3447b75af2edeb7c3dab001ac7c
636,730
from typing import Optional from datetime import datetime import requests def weekly_mean( start: Optional[datetime] = None, end: Optional[datetime] = None ) -> dict: """ NOTE: DATA FOR THE LAST SEVERAL MONTHS ARE PRELIMINARY, ARE STILL SUBJECT TO QUALITY CONTROL PROCEDURES. NOTE: The week "1 ...
901de5d34b9d78269d883e0f055519b1f900930a
636,731
import itertools def nwise(iterable, n=2): """ Iterates over iterable n items at a time list(nwise('ABCDE', 3)) >>> ['ABC', 'BCD', 'CDE'] """ iterables = itertools.tee(iterable, n) [next(iterables[i]) for i in range(n) for j in range(i)] return zip(*iterables)
9556614f388747cee62ebf2501a281a0bcf4551b
636,732
def serialize_device(device): """ Standard representation for a device as returned by various tasks:: { 'id': 'device_id' 'hostname': 'device_hostname', 'tags': [], 'locked': false, 'state': 'provisioning', 'ip_addresses': [ ...
4d74f43c7cdffed0f605756530aaa46a8796f952
636,733
from datetime import datetime def validate_date(date_text): """Validates that the date is in ISO 8601 format: YYYY-MM-DD""" try: if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'): return False return True except ValueError: return False
2d7592edc150b9270403d01c849fd57097111107
636,734
def get_script_url_from_initiator(initiator): """Remove the scheme and query section of a URL.""" if initiator: return initiator.rsplit(":", 2)[0].split("@")[-1].split(" line")[0] else: return ""
4c32f1639ab8c03404cd621e368210bb43c7eaf8
636,735
def lpmerge(L, R): """Left precedent dictionary merge. Keeps values from `l`, if the value in `r` is :const:`None`.""" return dict(L, **dict((k, v) for k, v in R.iteritems() if v is not None))
47b35d189a8f263c4548e410fce5a6b4de412f45
636,736
def asset_description(): """return a test asset name""" return "test_travis"
41fc2dd0ecceca8fbcb0226aebd1daa7e3882cb2
636,737
import types def _get_synthesizer_name(synthesizer): """Get the name of the synthesizer function or class. If the given synthesizer is a function, return its name. If it is a method, return the name of the class to which the method belongs. Args: synthesizer (function or method): ...
2a42e7d43b91b58cd8f8782c3f40950c60a93fbf
636,738
def in_browser() -> bool: """Test if this code is running in the browser. Checks for existence of package "pyodide" used in pyodide. If present it is assumed the code is running in the browser.""" try: return True except ImportError: return False
8f71a3886cf21c8644440247172ab00fc632c3f6
636,739
def test_function(x): """Some DocString""" return x*x
4034b99fb81def781b99acaec486a1e403db43a0
636,740
def solution(n): """ Determines the maximal 'binary gap' in an integer :param n: a positive integer (between 1 and 2147483647) :return: a count of the longest sequence of zeros in the binary representation of the integer """ bin_limit = 2147483647 if not isinstance(n, int): ...
a62d7822cbd480f650c0f804e543c0b8f17dee15
636,741
def red_sequence_ri_zevol_sigmoid_params(r): """ """ c0_ymin, c1_ymin = 0.2646, -0.0063 ymin = c0_ymin + c1_ymin*r c0_ymax, c1_ymax = 0.0419, -0.00695 ymax = c0_ymax + c1_ymax*r return ymin, ymax
ec2e427a94214d51a83db69eb0882cd6f16de135
636,742
import struct def _parseMCCDHeader(header): """ Parse experimental metadata from MCCD header. Byte-offsets of experimental parameters are based on this `reference <http://www.sb.fsu.edu/~xray/Manuals/marCCD165header.html>`_ Parameters ---------- header : bytes MCCD header ""...
0ffd483a412ed79726c687fb4c8dd75e94a21410
636,743