content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from datetime import datetime def get_telapsed(last_draw_timestamp): """ Takes in a dictionary that shows last-draw timestamp for each card and uses that to compute Returns: Time elapsed dictionary that shows seconds elapsed since last time each card was drawn (Key is the cue and value i...
50b6cc12bcbbb9f80de6d59080329a6816f3a7a8
633,393
def combined_maintenance(*args): """ Takes any number of maintenance functions and returns one function that calls all of the given ones in the order they are given. """ def combined(net, task, result): nonlocal args for mf in args: mf(net, task, result) return combined
5d1044a33caddfe9d7b979f51683dce7414f40f4
633,394
def SUM(src_column): """ Builtin sum aggregator for groupby. Example: Get the sum of the rating column for each user. If src_column is of array type, if array's do not match in length a NoneType is returned in the destination column. >>> sf.groupby("user", ... {'rating_sum':tc.aggregate.SUM('...
18adf3b81e7cd15f603ebc60878598dcfd56144f
633,395
def df_to_joints(df): """ Return joint names from list of degrees of freedom. List of joint names is sorted alphabetically. :param df: List of degrees of freedom like ["joint.x",]. :type df: list :return: Joint names. :rtype: list """ joints = sorted(set((x.split('.')[0] for x in df if ...
6061b29001944f976c0657a8d14c3da12cba8205
633,397
from typing import List def permute_list(x: List, permutation_indices: List[int]) -> List: """Permute `x` according to the indices in `permutation_indices`""" return [x[i] for i in permutation_indices]
80c7007683b3cc69922a0e8fa2fa30e541fd70de
633,398
def text_(s, encoding='latin-1', errors='strict'): """ If ``s`` is an instance of ``bytes``, return ``s.decode(encoding, errors)``, otherwise return ``s``""" if isinstance(s, bytes): return s.decode(encoding, errors) return s
3aca002da7af1641909eebf489e33e37e0850c65
633,402
def plane_distance(p, plane): """Return signed distance to plane of point.""" x, y, z = p A, B, C, D = plane return A*x + B*y + C*z + D
e8c0570e794399eeca0ec647ad058da4c5d6a7aa
633,407
def read_fai_file(fai_file_name): """ Get a dictionary of an FAI file (reference index). :param fai_file_name: Name of the file to read. :return: A dictionary keyed on the sequence names with one tuple of the record values per record (all integers). """ fai_record_dict = {} with open(fai...
297689a2c0e2ad68838d265932e1a70904067db6
633,413
import ast def check_deletevar(node): """ Check if there is a delete statement for a variable. Deletes for attributes and subscripts don't count. """ class Visitor(ast.NodeVisitor): def __init__(self): self.found = False def visit_Delete(self, node): ...
23ecface62374a9cd7ec3d53543dc385f91a1903
633,415
def _permissions(annotation): """ Return a permissions dict for the given annotation. Converts our simple internal annotation storage format into the legacy complex permissions dict format that is still used in some places. """ read = annotation.userid if annotation.shared: read = ...
5fb4b0a28023a1ec5b74cc8edaf680a27432a43f
633,416
from datetime import datetime def translate_date(str, in_format, out_format): """Convert a date to ISO8601 date format without time""" try: return datetime.strptime(str.strip(), in_format).date().strftime(out_format) except Exception: pass return ''
9b347a2b503aaafb05a56be93506d3decd4f7838
633,417
import colorsys def increase_saturation(r, g, b): """ Increase the saturation from rgb and return the new value as rgb tuple """ h, s, v = colorsys.rgb_to_hsv(r, g, b) s = min(s+0.3, 1.0) return colorsys.hsv_to_rgb(h, s, v)
7f61cf27c95546238d83dc55b5282ce0611e30f8
633,419
import contextlib import socket def is_port_open(host: str, port: int) -> bool: """Determines whether a port on a given host is open.""" with contextlib.closing( socket.socket(socket.AF_INET, socket.SOCK_STREAM) ) as s: return s.connect_ex((host, port)) == 0
d64233e3e2a55f024ea05f4fd8ca829913bacecb
633,423
import six def get_num_evts_per_merged_dataset(merged_datasets,num_evts_per_dataset): """ Return number of events per merged dataset Returns a dict `<merged_dataset>:<num_evts>'; see comments to function `merge_datasets' for an explanation of <merged_dataset>. """ num_evts_per_merged_dataset = {}...
e4533c1156359ffa87974dd13135e4d2fdccbbc4
633,424
import hashlib def _sha1_py3(msg): """Compute sha1 hash of a message. :param msg: string to hash :type msg: str :return: upper case hexdigest representation of a hash :type: str """ sha1hash = hashlib.sha1() sha1hash.update(msg.encode('utf-8')) return sha1hash.hexdigest().upper()
adb8e216b6075132d7a816fcabc013d994604006
633,425
import typing def extract_entity_types(line: dict) -> typing.List[str]: """Extracts the entity type(s) for an entity. Arguments: line: ``dict`` A line in the Wikidata dump. Returns: entity_types: ``list`` A list of entity types for the entity. Entity types are also QIDs in Wik...
fd8ead9c03bf63d0a0c8655a39ccd8d0bc105992
633,428
def MSEloss(y_actual, y_pred): """ Mean squared error: squared of actual target minus predicted target y_actual = expected output y_pred = predicted output """ return (y_actual - y_pred) ** 2
62c00fbd51aa12e49d5058f7e661290f93b8566c
633,429
from contextlib import suppress def flatten(lst): """ Flatten list. :param lst: A list to be flattened :type lst: ``list`` :return: Flattened list :rtype: ``list`` """ flattened = [] for element in lst: if isinstance(element, str): flattened.append(element) ...
135eec0779175734129c086e7434584ff60be4c2
633,432
def _limit(lower, upper): """Returns a regular expression quantifier with an upper and lower limit.""" if ((lower < 0) or (upper <= 0) or (upper < lower)): raise Exception("Illegal argument to _limit") return u"{%d,%d}" % (lower, upper)
f6f638518a0b89d1dd25083b98f7b17107164258
633,437
def get_file_len(f): """Get file length of file""" i = -1 for i, l in enumerate(f): pass return i + 1
1e43c71bd44ca0e18907806ffca603f78dc989f5
633,438
import json def read_json(filename): """ Read data from JSON file. Args: filename (str): Name of JSON file to be read. Returns: dict: Data stored in JSON file. """ with open(filename, 'r') as in_file: return json.load(in_file)
5c6ccfd56d476ed54b3ec176d0b338fd8309a5ab
633,439
def _parse_options_from_cmd_args(args): """ Parse out build options from the command line. Args: args (Argparse obj): The output of 'ArgumentParser.parse_args()' Returns: dict of options. """ opts = {} if args.name is not None: opts['app_name'] = args.name ...
d421066945a2eee174f9a18e80a0697d33175d41
633,442
from typing import Dict from typing import Any def update_buffer(production: Dict[str, Any], buffer: str) -> Dict[str, str]: """Returns a pattern to update the given buffer with. Args: production: The production dict that specifies the buffer update. buffer: The name of the buffer to update. ...
264dc05b0a41bdea2d3ceb3f580ea24780d3d9d7
633,443
from pathlib import Path def getDir(*args): """ Returns a Path from $HOME/rl_results/ and the extra folders given as args. """ dr = Path.home() adds = ["rl_results", *args] for s in adds: dr /= s return dr
4383589d18f37fe4aa7c75d401fd4afc237a6dbd
633,445
def tau_sobol(dim_num): """ tau_sobol defines favorable starting seeds for Sobol sequences. Discussion: For spatial dimensions 1 through 13, this routine returns a "favorable" value TAU by which an appropriate starting point in the Sobol sequence can be determined. These starting p...
ecaf5151402998e192734e07d78e0873e80d2cc2
633,447
def intfs_only(s1code): """Given s1code, keep only interfaces (.h); ignore implementations (.f90).""" return [(l, f, c) for l, f, c in s1code if f.endswith(".h")]
2e43d16d87aa7b427f58622d973229c082e9a67d
633,449
def process_img_paths(input): """Processes image paths If one path is entered, return list of length 1 containing location. If multiple (comma-separated) paths are entered, return list containing all paths. Args: input (str): string containing image path(s) Returns: paths (list...
53f693885d10c7631257583bb465c9147dc2dca7
633,454
def fst(x): """ Returns the first item of a collection. Examples -------- >>> fst([0, 1, 2]) 0 """ return x[0]
3287201eb82859a4dd275f2516f82c94f50ca816
633,455
import re def paste_urls_from_details(details): """Return list of URLs to objects from details page source.""" return re.findall( r'<a href="(http://localhost:\d+/html/[^"]+)"', details, )
53d034ae8625741968d3fb17757ef0d7b65a9bf9
633,456
def parse_state_setup(setup): """Parse state setup to name, and tuples with parameters for step.""" split = [part.split() for part in setup.split('\n')] name = split[0][-1][0] if_zero = ( [param[-1][:-1] if param[-1][:-1].isalpha() else int(param[-1][0]) for param in split[2:5]]) if...
05ed73c52097c07ce9dc671bbbf0e5e7b18a1635
633,461
def secant(f,x0,x1, TOL=0.001, NMAX=100): """ Takes a function f, start values [x0,x1], tolerance value(optional) TOL and max number of iterations(optional) NMAX and returns the root of the equation using the secant method. """ n=1 while n<=NMAX: x2 = x1 - f(x1)*((x1-x0)/(f(x1)-f(x0))) if x2-x1 < TOL: ret...
4d1bda112d6348b9a23c92eda39d99d16f3e4005
633,462
def read_evid_db(dat_content, BN): """ Returns a list of dictionaries. For each dictionary: Key: var_name Val: var_state """ # remove \n dat_content= [i[:-1] for i in dat_content] dat_db= [] # List of dictionaries. Each dictionary is a map of var_name to var_state var_lst= dat_con...
f324b890ab2b6016e6b1764876961465664e2b5f
633,463
def indent_text(indent, text): """Prepend the specified number of spaces to the specified text. Args: indent (int): the number of spaces to use as an indentation text (object): text to indent. lists will be converted into a newline-separated str with spaces prepended to each line ...
8ef7dd1f58ceb44f888b007274b27c48fd329861
633,467
from typing import List def calc_acc(pred_data: List[List[str]], gold_data: List[List[str]]): """Calculates the accuracy, precision and recall Args: pred_data (List[List[str]]): The output data from the model gold_data (List[List[str]]): The labeled data to compare with Returns: ...
df4622ce701a0427eb24ef0ce4a5b06f68641ca2
633,469
def is_prime_number(number): """ 判断数值是否为素数 :param number: :return: boolean """ if number <= 1: return False for i in range(2, number): if number % i == 0: return False return True
2f621a2851234b3ed20fefbcb7c02d1a79fb7a16
633,475
def tick_direction(*, x="inout", y="inout"): """Adjust the tick direction.""" return { "xtick.direction": x, "ytick.direction": y, }
a77c175d6898cccdf62286e131b9506e9cda5e30
633,476
def parse_bnd_pos(alt): """ Parses standard VCF BND ALT (e.g. N]1:1000]) into chrom, pos Parameters ---------- alt : str VCF-formatted BND ALT Returns ------- chrom : str pos : int """ alt = alt.strip('ATCGNRYSWKMBDHV') # Strip brackets separately, otherwise GL ...
00c3a4f680eaea91385244fec509c6ef0ab5eaf8
633,477
import re def is_book(url): """Check if *url* hints a book. """ return url is None or re.match('https?://[^/]*books.google.com', url) is not None
69ae8ac85dc6edebdd92e3e06af2ab353b995394
633,480
import re def no_yaml_char(s): """Check for characters which prevent the yaml syntax highlighter from being applied. For example [] and ? and ' """ return bool(re.match(r"^[a-zA-Z0-9()%|#\"/._,+\-=: {}<>]*$", s))
31b700e7c42d0944c8e787a0e0d129bf0a20c0b9
633,483
def yaml_diff_config(yaml_diff_sample_path): """Return a list containing the key and the sample path for a different yaml config.""" return ["--config", yaml_diff_sample_path]
9c1aa2871b596e60ad77242e9f33adc455aedccc
633,486
import json import logging def dict_to_json(metrics, input_filepath): """ Outputs metrics dictionary as a JSON file with the same name (and directory) as the original csv file from the beginning of the pipeline. :param metrics: Dictionary of metrics :param input_filepath: The filepath of the inputted...
af786e04d94950c8f479bbd2c0a91d4b57441a29
633,490
def step(env, action, state): """ Implementation of "step" which uses the given action as an offset of the existing state. This function overloads the environment step method and should be used when actions-as-offsets are required for this particular environment. """ # if action == (0.0, 0.0...
71e8eb8b2e2f352869b0a9d7cf0c5be0574c5f2f
633,491
def det_ltri(ltri): """Lower triangular determinant""" det = ltri[0] * ltri[2] return det
3a0fdfa4cc05ea13f504b122462a7c83c94a36fb
633,498
def get_crowd_selection(selection_counts, delimiter='|', error=None): """ Figure out what the crowd actually selected :param selection_counts: output from get_crowd_selection_counts() :type selection_counts: dict :param delimiter: character to place between tied responses - response1|response2 ...
bff6498b53d7b464609d539e73c91a88e365e0ee
633,499
def format_symbolic_duration(symbolic_dur): """Create a string representation of the symbolic duration encoded in the dictionary `symbolic_dur`. Parameters ---------- symbolic_dur : dict Dictionary with keys 'type' and 'dots' Returns ------- str A string representation ...
4c3beb9fbe2e4ea1bf30d6b76f6b25d99530a2e6
633,502
def vector(p1, p2): """ p1->p2ベクトルを返す Args: p1 (list[float, float, float]): ベクトルの起点座標 p2 (list[float, float, float]): ベクトルの終点座標 """ return (p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2])
e4e0b5fb09fb8889091d6be74ee6ce3a028e8f68
633,504
from typing import Callable from typing import Tuple def find_upper_and_lower_integral_upper_bound( get_integral_value: Callable[[float], Tuple[float, float]], target_value: float, min_upper_bound: float, max_upper_bound: float, ) -> Tuple[float, float]: """ This function finds approximate low...
b17d21e85e689fa5cbf1d8b301c3b83f6bbdda58
633,511
def select_element(c, i): """Given a collection and an integer "i", return the ith element of this collection """ print("Received collection value is %s" % str(c)) return c[i]
2ed1e3d906ff49df6bb0fec5a368e0c9562f73c1
633,512
def get_from_params(request, key): """Try to read a value named ``key`` from the GET parameters. """ return request.query.get(key)
22d6ad4ed7b26309fb21d240878d4a74ce882952
633,513
def pixelwise_norm(x, eps: float=1e-8): """ Pixelwise feature vector normalization. :param x: input activations volume :param eps: small number for numerical stability :return: y => pixel normalized activations """ return x * x.pow(2).mean(dim=1, keepdim=True).add(eps).rsqrt()
de7447dee50467cc9a854470b94ddafaa2c92e0b
633,516
import typing def spring_splitter_by_chunks(number_of_chunks: int, string_to_split: str) -> typing.List[str]: """ Splits string into a number of chunks specified :param number_of_chunks: number of chunks :param string_to_split: string_to_split :return: list of strings """ pieces = string_t...
6126c39f8fce2fd55fdcb313e546d81b386e9e51
633,521
def citation_metrics(publications): """ Return the h_index and total number of citations calculated from a list of publications. """ cite_counts = sorted([v['citations'] for v in publications], reverse=True) for j, k in enumerate(cite_counts): if j + 1 > k: return j, sum(cite...
240ecc9f8910d394de8b35ce0ad866348aff39d0
633,522
def filhos(indice, dependency_filhos): """ Devolve os indices dos filhos do nó dado como input (indice) :param indice: indice de um nó :param dependency_filhos: lista com sublistas que contêm os indices dos filhos, ex: [[], [0, 4], [], [], [2, 3], [1, 6, 7], [], []] :return: Lista com os indices filhos do nó dado ...
910676b560bea23165c17e543c199105655b3067
633,524
import pathlib def get_file_path(file: str) -> pathlib.Path: """ Get path to passed in file. Example get_file_path(__file__) """ return pathlib.Path(file).parent.absolute()
1fd66872b5209de43f8e8896d88206ccbb574951
633,525
def respond_list(**kwargs): """Returns a response to `list`.""" bot = kwargs['bot'] message = kwargs['message'] game_ids = [str(g) for g, c, _ in bot.pollers if c == message.channel.id] msg = "I'm following: " + ', '.join(game_ids) return msg
b2131fb5b26c25b77f9474b0f34845eec999c476
633,526
def addContent(old_html, raw_html): """Add html content together""" old_html += raw_html return old_html
cd5a1677ac4f4216d4cbeb7b7565b44429872bcc
633,528
def build_variant_display_title(chrom, pos, ref, alt, sep='>'): """ Builds the variant display title. """ return 'chr%s:%s%s%s%s' % ( chrom, pos, ref, sep, alt )
3461166b459e9a5715353080f271ec9ee014bb34
633,530
import torch def safe_to_device(X, device): """Move the tensor or model to the device if it doesn't already live there. This function will avoid copying if the object already lives in the correct context. Works on PyTorch tensors and PyTorch models that inherit from the torch.nn.Module class. Pa...
6d5ccffc2bab4e6447447a90080fe08468966880
633,532
def quote_literal(s): """Quote a literal string constant.""" return "'" + s.replace("\\", "\\\\").replace("'", "\\'") + "'"
4be3944b286872597fe73e97f714f12c0c4204be
633,533
import requests def validate_actions(repo): """Validate if a repo has workflows/githubci.yml""" repo_has_actions = requests.get( "https://raw.githubusercontent.com/adafruit/" + repo["name"] + "/master/.github/workflows/githubci.yml" ) return repo_has_actions.ok
0f57e1a7efbea9009c6ea9127b9ecddbbcdd2888
633,534
import torch def cos_difference_mem(a, b, adjacency_matrix): """ The difference of coupled states in an oscillator model. Vectorized, faster but costs more memory. :param a: the vector a :param b: the vector b :param adjacency_matrix: The adjacency matrix :return: The vector y with element...
cecf7c00a3efe5bf76b37bf5c88565e4f11e9be2
633,536
def square_frobenius_distance(m1, m2): """ Square frobenius distance between two probability matrices/vectors :param m1: :param m2: :return: """ c = m1 - m2 c = c * c return c.sum()
4e3ae1cb1f5ffdec196a94252e4f95fee589d093
633,541
import math def city_cost(city: int) -> float: """ Calculate the cost to purchase a specified city. :param city: The city to be purchased. :return: The cost to purchase the specified city. """ city -= 1 return 50000 * math.pow((city - 1), 3) + 150000 * city + 75000
4440d9a27b3c1b7ee1994ef1d1a12042f9335074
633,543
def is_digit(arg: str): """ isdigit() method """ return arg.isdigit()
a64fa899ed8f7ef7665e2de32769ec34f372ce4d
633,545
def macd(dataframe_name, signal_lag = 9): """Creates MACD Signals Args: dataframe_name (df): Single security dataframe containing at least a 'macd' column signal_lag (int): Desired lag time used for macd rolling average Returns: A dataframe of: original data passed to fun...
43b86619cd215d95b4d52d0dbf0641f39defa190
633,547
from typing import List from functools import reduce def sum(l:List[int],n:bool)->int: """ Sum a list of integer. :param l: List of integer. :param n: if present, multiply the result by -1 :return: The sum of the list """ o = reduce(lambda prev,act:prev+act,l) if(n):o*=-1 return o
e5555a6f0d111a638d233e3d6d45bba1cebba03d
633,548
def get_intervals(l): """For list of lists, gets the cumulative products of the lengths""" intervals = len(l) * [0] # Initalize with 1 intervals[0] = 1 for k in range(1, len(l)): intervals[k] = (len(l[k]) + 1) * intervals[k - 1] return intervals
9cc189c288d758541617337455337a16e9046c94
633,552
def pointwise_dict_multiply(dict1, dict2): """ Inputs: - dict1, dict2: dicts with {key: float} Returns: - dict_mult: dict with {key: dict1[key]*dict2[key]} for all keys dict1 and dict2 have in common """ common_keys = set(dict1.keys()) & set(dict2.keys()) return {k: dict1[k]*dict...
27c4923da2408d4785121bd07afb7ca335bfa862
633,553
def is_version_newer(version_1, version_2): """ Indicates whether one vManage version is newer than another. Compares only the first 2 digits from version because maintenance (i.e. 3rd digit) differences are not likely to create any incompatibility between REST API JSON payloads, thus not relevant in th...
f324489d37b559783322baf6ac73574d003317dd
633,554
from typing import Optional from typing import Dict def cb_str_loss_wrapper(name: str, **params: Optional[Dict]) -> str: """CatBoost loss name wrapper, if it has keyword args. # noqa D403 Args: name: One of CatBoost loss names. **params: Additional parameters. Returns: Wrapped C...
bec35df2e8c511d8731554271311d7f27da4d527
633,558
def demo_extension_3(**kwargs): """test that kwargs style functions are acceptable""" return "p3"
ede2181cd948877ced8eb1badee174edc58ae840
633,563
def is_dict_obj(obj): """Return True if obj is a dict.""" return isinstance(obj, dict)
4b30a91258a8388155eb69888deccbe46a4dc1e2
633,564
def get_array_of_field_values_matching(field_names, matchop, collection_obj): """Returns an array with all values the given field takes in all documents matched by the given Matchop in the given collection.""" push_dict = {field_name : "$" + field_name for field_name in field_names} agg_pipe = [ ...
4c02826b2dc598c1ba3f12df467fcbb6283a1a2b
633,566
import re def to_valid_key(name): """ convert name into a valid key name which contain only alphanumeric and underscores """ valid_name = re.sub(r'[^\w\s]', '_', name) return valid_name
458683acbad2fcd72cc39a586ae4c1d1fbf8cf73
633,568
import math def myround(x, base, choice=None): """ Round values to the nearest base :type x: float :param x: value to round :type base: int :param base: nearest number to round to :type choice: str :param choice: 'up' to round up, 'down' to round down, or None for nearest """ ...
82b75a0c3883a481645b590e5253e07c25086c93
633,570
def fix_sqltype(sqltype): """Fix `sqltype` string. Force uppercase string and change 'FLOAT' -> 'REAL'. Parameters ---------- sqltype : str Returns ------- st : string """ st = sqltype.upper() if st == 'FLOAT': st = 'REAL' return st
ffdb226a4fbed30f48344e2c1d6328be52e8bf70
633,576
def add_text_generate_args(parser): """Text generation arguments.""" group = parser.add_argument_group(title='text generation') group.add_argument("--temperature", type=float, default=1.0, help='Sampling temperature.') group.add_argument("--greedy", action='store_true', default=F...
0c1838ca868eb2685ce3a9dd5284b0892c889edc
633,577
from typing import Callable from typing import Iterable def zip_with(func: Callable, *iters) -> Iterable: """`zip` all the iters and apply function `func` to each of them """ return map(func, zip(*iters))
9e0c1635d9f11b133fa54c47310125fa480b91b6
633,578
def decode_variable_integer(bytes_input: bytes): """ If the length is fitting in 7 bits it can be encoded in 1 bytes. If it is larger then 7 bybitstes the last bit of the first byte indicates that the length of the lenght is encoded in the first byte and the length is encoded in the following bytes....
ba770a3a1035d8b3e8df4f85c428b6729a20ab09
633,579
def control_char_symbol(c: str) -> str: """Returns one of the Unicode Control Picture characters (e.g. '␛') for the given single-character string with an ord() less than 32. Raises ValueError for invalid strings. """ if len(c) != 1 or ord(c) >= 32: raise ValueError('Argument must be a singl...
55e95d6b1db5d1e65ea5011711f026684f1f58b5
633,584
def tf(tokens): """ Compute TF Args: tokens (list of str): input list of tokens from tokenize Returns: dictionary: a dictionary of tokens to its TF values """ d = {} for token in tokens: if token in d: d[token] += 1 else: d[token] = 1 t...
aac14c2f771638467a151ec18b4d5366386b4a71
633,587
def extract_by_index(a_list, indices): """ Creates a list that consists of the elements at the given indices of the given list. :param a_list: The list to get elements from. :param indices: The indices to use to source elements. :return: The selected list. """ retur...
76d6594645985066df31a53059b5308c2338b494
633,594
def is_prime(integer): """Determines weather integer is prime, returns a boolean value""" # add logic here to make sure number < 2 are not prime for i in range(2, integer): if integer % i == 0: return False return True
d4e8d54cb25006217bc47687e47ba72a0fefc23b
633,598
def batch_get_similarity_matrix(ref, target): """ Get pixel-level similarity matrix. :param ref: (batchSize, num_ref, feature_dim, H, W) :param target: (batchSize, feature_dim, H, W) :return: (batchSize, num_ref*H*W, H*W) """ (batchSize, num_ref, feature_dim, H, W) = ref.shape ref = ref....
edc516b0aba8990eb37839bf578a75be5f479f65
633,600
def fallbackSeries(requestContext, seriesList, fallback): """ Takes a wildcard seriesList, and a second fallback metric. If the wildcard does not match any series, draws the fallback metric. Example: .. code-block:: none &target=fallbackSeries(server*.requests_per_second, constantLine(0)) ...
ff50bc21530e1ca7ce079132437dbdcd88f13886
633,601
import inspect def get_class_property_names(obj: object): """Returns the names of all properties of a class.""" return [ p[0] for p in inspect.getmembers(type(obj), inspect.isdatadescriptor) if not p[0].startswith("_") ]
b96413d4b17aef2f0b53b68528c394cd50c3cdaf
633,602
def get_most_popular_drugs(nonzero_df): """ Get the top 3 drugs that are used by patients. Input ----- df: pandas.DataFrame The dataframe containing patients with positive response to treatments Returns ------- popular_df: pandas.DataFrame The dataframe containing t...
f77a8753e2ec3515a601fb67240ca2e9daeeb0ca
633,603
def c_to_f(temp): """ Convert celcius temperature to fahrenheit. """ return temp * 1.8 + 32
101135ffd13f4d2d636305ea33968734cb1ebb07
633,604
import string import secrets def generate_password(length=12): """Generates a random password Args: length (int, optional): Length of the generated password. Defaults to 12. Returns: str: The output generated password """ req_str = string.ascii_letters + string.digits secure...
5ddf9c957a2ed994617f8650b51b49ee489d8d70
633,605
def max_run(_b, _x): """Determine the length of the maximum run of b's in vector x. Parameters ---------- b: int Integer for counting. x: array Vector of integers. Returns ------- max: int Length of maximum run of b's. """ # Initialize counter _max ...
3d0afdfd13bfe6f4c4b5009b115a33c7714f34c6
633,609
def ssh_cmd_container_instance(detail) -> str: """SSH command to access a ecs2 instance by id.""" return f"TERM=xterm ssh {detail['ec2InstanceId']}"
003255798f038fe9ac676549049e5c89792fa6fd
633,615
def get_tmin_tmax(ct_idx, chop_times, sfreq): """ Get tmin and tmax for the chop interval based on the time points given by chop_times. Parameters: ----------- ct_idx : int Index corresponding to chop_times. chop_times : list of float List with the time points of when to cho...
0e5446f121c5c5bce7d59697790b907bf1d1500f
633,616
import time def datetime2ts(dt): """ Convert a `datetime` object to unix timestamp (seconds since epoch). """ return int(time.mktime(dt.timetuple()))
289c11c47d4cb0e9a6ea620fa5b40f81e4c5644d
633,618
def sreprlow(s): """Squash unicode and return the repr() of string `s` as lower case.""" return repr(str(s)).lower()
5fb91c45d05b075e488fa0b2f1084ed811538548
633,619
def FormatThousands(value): """Format a numerical value, inserting commas as thousands separators. Args: value: An integer, float, or string representation thereof. If the argument is a float, it is converted to a string using '%.2f'. Returns: A string with groups of 3 digits before the decimal po...
df453e379924644c7a7822dff3d5a54e4a9f3276
633,621
def get_ligand_filetype(ligand_filename): """Returns the filetype of ligand.""" if ".mol2" in ligand_filename: return "mol2" elif ".sdf" in ligand_filename: return "sdf" elif ".pdbqt" in ligand_filename: return "pdbqt" elif ".pdb" in ligand_filename: return "pdb" else: raise ValueError("...
0c56e63a314cb0994989c14180c7fd542181969d
633,623
def _check_value(value): """Convert the provided value into a boolean, an int or leave it as it.""" if str(value).lower() in ["true"]: value = True elif str(value).lower() in ["false"]: value = False elif str(value).isdigit(): value = int(value) return value
b5dbc8925de7ea383529a7131d5d65bb1f7e88fc
633,628
def getdiffmeta(diff): """get commit metadata (date, node, user, p1) from a diff object The metadata could be "hg:meta", sent by phabsend, like: "properties": { "hg:meta": { "date": "1499571514 25200", "node": "98c08acae292b2faf60a279b4189beb6cff1414d", "u...
8bd27fc7cbf62d20b08e4f8aa65d4f0cef2d3e0b
633,629
import re from datetime import datetime def clean_title_input(title, draft=False): """Convert a string into a valide Jekyll filename. Remove non-word characters, replace spaces and underscores with dashes, and add a date stamp if the file is marked as a Post, not a Draft. Args: title (string...
80958f893641bd420f487077d009be4c3efec1dc
633,633
def _find_node(state, node_id_or_label): """ Finds a node according to its ID (if integer is provided) or label (if string is provided). :param node_id_or_label Node ID (if int) or label (if str) :return A nodes.Node object """ if isinstance(node_id_or_label, str): for n i...
32a73b9e486994110e5ff812702cd4a6294fd7fb
633,634