content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import cmath def op_phase(x): """Returns the phase of a complex number.""" if isinstance(x, list): return [op_phase(a) for a in x] else: return cmath.phase(x)
e1a3b37c91bd4726ce0f14c9b9eb0fd007a4e0d2
45,990
def compute_brightness(brightness): """Return the hex code for the specified brightness""" value = hex(int(brightness))[2:] value = value.zfill(4) value = value[2:] + value[:2] # how to swap endianness return "57" + value
dab3ec94d9b39342491130074966fc6b7a988aca
45,991
def ln_like(theta, event, parameters_to_fit): """ likelihood function """ KCT01 = 0 Spitzer = 9 for (key, val) in enumerate(parameters_to_fit): # *** NEW *** # Some fluxes are MCMC parameters if val[0:] == 'f': if val == 'fsKCT01': event.datasets[KCT01...
83f2a0f161c150aa166bcf02a75be96bd3ce305e
45,992
import ast def prep_function_def_from_node_for_return(function_node: ast.FunctionDef) -> str: """ Returns a string representation of the function definition with an empty return type """ return "def " + function_node.name + "(" + ast.unparse(function_node.args) + ") ->"
7b1bfe4e4597b76333a7a2262be0e74c735a8bb2
45,993
from typing import get_origin from typing import Union from typing import get_args def is_optional_type(type_annotation) -> bool: """ Determines if a type is Optional[XXX] :param type_annotation: A type annotation, e.g Optional[float] or float :return: Whether the type annotation is an optional """ ...
2ef9fb8a536dbe489c2039a95ae1f8f185515d61
45,994
def splitList(initialList, chunkSize, only=None): """This function chunks a list into sub lists that have a length equals to chunkSize. Example: lst = [3, 4, 9, 7, 1, 1, 2, 3] print(chunkList(lst, 3)) returns [[3, 4, 9], [7, 1, 1], [2, 3]] taken from http://stackoverflow.com/questions...
d620405933749ab4eab54d6ff7d5202ef56aa2d1
45,995
def leiaint(msg): """ --> Função que faz a validação da entrada de dados do tipo inteiro (int) :param msg: Mensagem para entrada de dados do usuário :return: retorna o valor digitado, caso este tenha sido um número inteiro :print: Escreve uma mensagem de erro na tela, caso o valor digitado não seja ...
29b96b26055d965e987bf1e39a96b1924751f56c
45,996
def convert_format(ori_list: list) -> dict: """ 设输入列表长度为n 时间复杂度 O(n) 遍历两次list, 1. 构建辅助字典, 实现通过子节点查找父节点时间复杂度为O(1); 初始化子节点 2. 不断将子节点追加到父节点 空间复杂度: 需要构建辅助节点dict, 和返回结果dict, 空间复杂度是 O(n) """ tree = {"root": {}} revert_dict = dict() for n in ori_list: # 构造反向键值字典 ...
02deadf4c1e6ceaabfabf93fd09d49e1e4e87ddd
45,997
import inspect def get_fn_parameters(fn): """ return the number of input parameters of the fn , None on error""" param_len = len(inspect.getfullargspec(fn).args) if inspect.ismethod(fn): param_len -= 1 return param_len
cf90737655367422a96929d1f935aea4db620a41
45,998
def box_it(X, L): """X is a vector of x and y coordinates of a hard disk""" """L is a vector of Lx and Ly, such that the box has size Lx X Ly""" return [X[0]%L[0], X[1]%L[1]]
b377f7b75562490ca5048ca5ea8692c616a5327a
46,000
import math def correlation (cf): """Returns the correlation metric given a confusion matrix.""" p = cf[0][0] n = cf[0][1] P = p + cf[0][1] N = n + cf[1][1] return (p*N - P*n) / math.sqrt(P*N*(p+n)*(P-p+N-n))
1ab13a83c8451eb0e7a9f4e5621657d13f21e21f
46,001
import os def frame_id(fname): """ fname: x.jpg returns: int(x) """ return int(os.path.basename(fname).split('.')[0])
66a9a5853da60fca54bc9abdb9b45e9c691e1c19
46,002
def non_colinearity(read_start_cigar,read_end_cigar,aln_start,mate_interval_start,mate_interval_end): """Input a read and the mate interval in the graph. The function checks whether the alignment would be linear (splicing) or colinear. Will return false, in order to not attemp realignment. This is mainly though...
90a206867e0561b54a3c663395cf8ea6a1062997
46,005
def parse_accept(headers): #------------------------- """ Parse an Accept header and return a dictionary with mime-type as an item key and 'q' parameter as the value. """ return { k[0].strip(): float(k[1].strip()[2:]) if (len(k) > 1 and k[1].strip().startswith('q=')) else 1 ...
43e2698695f3484d47284cb8e0d1e278b33b322d
46,006
import six import os def fill_remote(cur, find_fn, is_remote_fn): """Add references in data dictionary to remote files if present and not local. """ if isinstance(cur, (list, tuple)): return [fill_remote(x, find_fn, is_remote_fn) for x in cur] elif isinstance(cur, dict): out = {} ...
50fe45d32cd1974b3fe3e9a3850cd92cd088d19a
46,007
def get_x_y_set(mt, type="test"): """Gets data set from ModelTuning object Parameters ---------- mt : ModelTuning object ModelTuning object used type : str, default="test" specifies which set to return ('train'/'test'/'val') Returns ---------- X_data, y_data : ndarray ...
6a423e93d85e4f18057550b6d3de3d3fe3c80766
46,008
def mbToBytes(byte_data: int) -> int: """Convert byte number data and this convert to mb""" return byte_data * 1048576
ff165f89c3c3067dd30532b5f0043a4e36fd141e
46,009
from itertools import tee def nwise(iterable, n=2): """ Adapted from more_itertools s, 2 -> (s0,s1), (s1,s2), (s2, s3), ..." s, 3 -> (s0,s1,2), (s1,s2,s3), (s2,s3,s4), ..." """ parts = tee(iterable, n) to_zip = [] while(parts): to_zip.append(parts[0]) parts = parts[1:] for p in parts: ...
1b73f4a565243b5aeeea4ac85ba5e6f0f83864ee
46,010
import sys def get_file_size(file): """ Returns a string with the file size and highest rating. """ byte_size = sys.getsizeof(file) kb_size = byte_size / 1024 if kb_size == 0: byte_size = "%s Bytes" % (byte_size) return byte_size mb_size = kb_size / 1024 if mb_size == 0...
9a90c4fa480423d82bc3790a4a8b3c8a39d5235e
46,011
def read_mesh_off(path, scale=1.0): """ Reads a *.off mesh file :param path: path to the *.off mesh file :return: tuple of list of vertices and list of faces """ with open(path) as f: assert (f.readline().split()[0] == 'OFF'), 'Not OFF file' nv, nf, ne = [int(x) for x in f.readli...
e65a78cc457dd251c8e604b24096776b54cae33c
46,012
def mean(li): """ Calculate mean of a list. >>> mean([0.5,2.0,3.5]) 2.0 >>> mean([]) """ if li: return sum(li) / len(li) return None
249d71615f0b671e6ad0e9be127d5eedacee0a64
46,014
import os from pathlib import Path def make_directory(directory_name): """Create a directory if it does not exist. Returns: A string of the created path name. """ path_name = os.path.join(os.getcwd(), 'audio_data', directory_name) Path(path_name).mkdir(parents=True, exist_ok=True) return path...
fa70c303f1ba420d2ef07a2e1386c271102cf4f4
46,015
import re def fixup_generated_snippets(content): """ Adjust the expanded code snippets that were generated by mdsnippets, to improve rendering by Sphinx """ # Remove lines like: <!-- snippet: verify_exception_message_example --> content = re.sub( r"<!-- snippet: .* -->\n", r""...
81c58f83058c1eb91d6846e026b9e2c7a757189b
46,016
def vnfd_update(vnfd): """ Implement VNFD updater here """ vnfd['vnfd:vnfd-catalog']['vnfd'][0]['version'] = '2.5' return vnfd
925d1e4eb89e339dda8cc746eb26ba2158eefe30
46,017
def order_cols_by_nunique(df, cols): """ Reorder columns in cols according to number of unique values in the df. This can be used to have a cleaner grouped (multi-level) x-axis where the level with the least unique values is at the bottom. Note: alternatively you could remove cols that have only 1 u...
ccc6b4208182add8f43ea7cfdeb5bad048ddf26e
46,018
def southOf(x, y, xy0, xy1): """ Returns 1 for point south/east of the line that passes through xy0-xy1, 0 otherwise. """ x0 = xy0[0]; y0 = xy0[1]; x1 = xy1[0]; y1 = xy1[1] dx = x1 - x0; dy = y1 - y0 Y = (x-x0)*dy - (y-y0)*dx Y[Y>=0] = 1; Y[Y<=0] = 0 return Y
cd7d903b60eec70f580bccc6f8dcd9a05734f161
46,019
def get_info_for_country(data, country): """Получает информацию о пользователе из результатов запроса. Parameters: data (list): список словарей, содержащий все записи, полученные из запроса country (str): значение country, запрошенной страны Returns: country_c...
60b5b68cda918a54b3f2edc310bb987fc4a6e1af
46,020
def sanitize_document(document, fields=[]): """ Removes sensitive fields from a MongoDB document. Args: document: The MongoDB document to sanitize. fields: An array of fields to check against. Each field is treated as a substring of keys within the MongoDB document. Returns: A sanitize...
a9040f12e1b5dea601c7f6266663097338ce33da
46,021
import json def to_json(wad_data): """ Output statistics as raw data. """ return json.dumps(wad_data, indent=2)
1747208e30c2d23183f79b905a0583cd44b9d95e
46,022
def scrubber_criteria(bit_counts): """Bit criteria for CO2 scrubber rating.""" return '0' if bit_counts['0'] <= bit_counts['1'] else '1'
3851bf60b239110fb2676996d4af14243bbfac68
46,023
def ignore_topics_list(): """ A list of headings or topics to be ignored by the plagiarism checker """ return [ 'references', 'citations', 'references and citations', 'citations and references' ]
77d65dc57c820fbab3c97399f38b20d2acd37e53
46,024
def get_action_value(mdp, state_values, state, action, gamma): """ Computes Q(s,a) as in formula above """ return sum( prob * (mdp.get_reward(state, action, state_dash) + gamma * state_values[state_dash]) for state_dash, prob in mdp.get_next_states(state, action).items() )
082fe8b979e6ceaca218db5de5084c9040fbe34c
46,028
import argparse def parse_args(): """ parse input args """ parser = argparse.ArgumentParser() parser.add_argument("--model_path", type=str, help="model .pb input path") parser.add_argument( "--output_path", type=str, help="tf saved model output path") parser.add_argument( "...
0b868b21021ccf461da803576aaaeddc7b753169
46,030
def ParseSubversionPropertyValues(props): """Parse the given property value which comes from [auto-props] section and returns a list whose element is a (svn_prop_key, svn_prop_value) pair. See the following doctest for example. >>> ParseSubversionPropertyValues('svn:eol-style=LF') [('svn:eol-style', 'LF')] ...
9874d2a308f66ec4dc4aa14292370977685c6e5e
46,033
import math def distance(coordinate_tuple): """Intake a coordinate tuple, return the distance between points""" x1 = coordinate_tuple[0] y1 = coordinate_tuple[1] x2 = coordinate_tuple[2] y2 = coordinate_tuple[3] dist = math.sqrt((x2-x1)**2 + (y2-y1)**2) return dist
f93e505aa267c0d4011f7e94e8a0996478c75058
46,035
def is_trunk_revision(rev): """Return True iff REV is a trunk revision. REV is a CVS revision number (e.g., '1.6' or '1.6.4.5'). Return True iff the revision is on trunk.""" return rev.count('.') == 1
96da375c93b166502bd3f30171dd127815f10a5f
46,037
def find_duplicates(l: list) -> set: """ Return the duplicates in a list. The function relies on https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list . Parameters ---------- l : list Name Returns ------- set Duplicated values >>> f...
f5c3ce0949996865935182028b7782c13eb0998a
46,038
def gw_get(object_dict, name=None, plugin=None): """ Getter function to retrieve objects from a given object dictionary. Used mainly to provide get() inside patterns. :param object_dict: objects, which must have 'name' and 'plugin' as attribute :type object_dict: dictionary :param name: name o...
ee441ec56e55bd962e35079e8e87cf281b6f6948
46,040
def shuf_key(shuf): """ return an index to sort shuffles in this order. """ return ["none", "edge", "be04", "be08", "be16", "smsh", "dist", "agno", ].index(shuf)
d3379daddb499fa9a1132782d4d65ce817ded8b9
46,041
import html def unescape(text): """Replace HTML entities and character references.""" return html.unescape(text)
075821e15ee6a8bd9a924c5db20f0596de64ad1b
46,042
def dump_flags(flag_bits, flags_dict): """Dump the bits in flag_bits using the flags_dict""" flags = [] for name, mask in flags_dict: if (flag_bits & mask) != 0: flags.append(name) if not flags: flags = ["0"] return "|".join(flags)
a8d28c023c3f33823cf2bcce47a9414e80164164
46,043
def save_dataframe(df): """Save dataframe to file object, with streamlit cache.""" return df.to_csv().encode('utf-8')
342732712cf0707726e5215e7400cba1cf737c89
46,045
def get_mu_input_fixed_indegree(K, gamma, g, w, mu): """returns mean input for given connection statistics and presynaptic activity """ return (gamma - (1. - gamma) * g) * K * w * mu
d4594085031e840648f587ad0c04399452d35870
46,047
import json def amplify_by_instrument(sounds, amplification_factors): """ Amplify the signals with different gain based on the instrument """ print("Amplifying sounds by instruments...") print(json.dumps(amplification_factors, indent=2)) for sound in sounds: if sound['instrument'] in a...
9fd5fdcf6923bb38099084f56cb9c2615b9ee4d0
46,048
import os def _preprocess_path(path): """The path can either be a path to a specific optimizer or to a whole testproblem. In the latter case the path should become a list of all optimizers for that testproblem Args: path(str): Path to the optimizer or to a whole testproblem Returns: A ...
99dd33fb3c1cf652cfcb330ad4b9ba9734590e34
46,049
import re def extract_mc_url(re_pattern: str, msg: str) -> str: """ return extracted mixed content url as string if found else empty string """ if "Mixed Content:" in msg: results = re.search(re_pattern, msg) if results and (len(results.group()) > 1): return results.group(...
3cfc8238431942facd65983ccfa34304a50a068c
46,051
def _parse_line(line): """Parse poolq Quality file lines.""" if not line == "\n": parsed_line = line.strip("\n").split("\t") if not parsed_line[0].startswith("Read counts"): return parsed_line
56cf059dd75e329303054f683bc6b360641ae6e5
46,052
def hub_balance(m, i, j, co, t): """Calculate commodity balance in an edge {i,j} from/to hubs. """ balance = 0 for h in m.hub: if (h, co) in m.r_in_dict: balance -= m.Epsilon_hub[i,j,h,t] * m.r_in_dict[(h, co)] # m.r_in = 1 by definition if (h, co) in m.r_out_dict: ba...
239ba38223661a3dcbb3b9fa8bf793b6e32156c1
46,053
import sys import os def current_path(*names): """Return the path to names relative to the current module.""" depth = 0 if __name__ == '__main__' else 1 frame = sys._getframe(depth) try: path = os.path.dirname(frame.f_code.co_filename) finally: del frame if names: pa...
bf118459258a041137a373bf0fd18dee897b7672
46,055
def _new_object(cls): """Helper function for pickle""" return cls.__new__(cls)
f9a0cef73d0f53932ea7955f1aa85234faf6a1eb
46,058
def get_form_prepro(vocab, id_unk): """Given a vocab, returns a lambda function word -> id Args: vocab: dict[token] = id Returns: lambda function(formula) -> list of ids """ def get_token_id(token): return vocab[token] if token in vocab else id_unk def f(formula): ...
a5c7a375b894550fbb978cff7bc6262d7338fc99
46,060
def isCSERelative(uri : str) -> bool: """ Check whether a URI is CSE-Relative. """ return uri is not None and uri[0] != '/'
98cfc2e74e7cb5e1561dec2e40e8076f6eb966e4
46,062
import json import requests def containerMyFolder(apikey,state=None,groupid=None): """ returns a short list of your own folders filtered by state (if passed as parameter). Please note every Object child of the container-Node starts with a trailing _. apikey: Your ApiKey from FileCrypt state(optional): filter by ...
074f2f55335a4084f5f509b754cb17ffe036d451
46,063
from typing import Dict from typing import Any def build_validation(validator) -> Dict[str, Any]: """Builds and returns a fake validator response object.""" if validator == "sql": metadata = {"sql": "SELECT user_id FROM users"} elif validator == "content": metadata = { "field_n...
a344d97b2f80486a0c826099bc47fe4bdd60989a
46,064
def combine_channel_number(major: int, minor: int) -> str: """Create a combined channel number from its major and minor.""" if minor == 65535: return str(major) return "%d-%d" % (major, minor)
7eee6911546e62b25db05a3c099de75c382e7081
46,065
import torch def batch_log_matvecmul(A, b): """For each 'matrix' and 'vector' pair in the batch, do matrix-vector multiplication in the log domain, i.e., logsumexp instead of add, add instead of multiply. Arguments --------- A : torch.Tensor (batch, dim1, dim2) Tensor b : torch.Te...
116d6f5713c2bc7dc6b39fb784ee4f6f6c5ba852
46,066
def constant_check(array): """ Checks to see numpy array includes a constant. Parameters ---------- array : array an array of variables to be inspected Returns ------- constant : boolean true signifies the presence of a cons...
aadbc430b0843d6ca63c643adcad1090aca05400
46,067
def _do_overlap(rect_1, rect_2): """ Determines whether the two rectangles have overlap. Args: rect_1: Tuple :code:`(lat_min, lon_min, lat_max, lon_max) describing a rectangular tile. rect_2: Tuple :code:`(lat_min, lon_min, lat_max, lon_max) describing ...
74379617ceca1bce4237acdbd9800ba1583e781e
46,068
import os def model_state_exists(weight_file_path): """ Check for model version weights based on file name :param weight_file_path: Name of the file :return: bool True if the file exists """ return os.path.isfile(weight_file_path)
cb98e28231df1fa486cb7f23f48b5f03045a7a8f
46,070
def symbol(data): """ Get the feature symbol. """ return data["marker_symbol"]
2efca500e061818e62405e58107d6d6883950761
46,071
import hashlib def uuid_hash(uuid): """Return SHA1 hash as hex digest of an uuid. Requirement from VAC team : You should apply SHA1 hashing over the data as a text. More specifically you should have the text data as a UTF8 encoded string then convert the string to byte array and digest it into a SHA1...
eb26bfa75cf2d694218adc9782181532c50fb13f
46,072
import pytz from datetime import datetime def determine_current_datetime(**args) -> tuple: """ Return args['today_date'] as a timezone aware python datetime object """ tz = pytz.timezone('America/Vancouver') args['today_date'] = datetime.now(tz) return True, args
cd31a44133955da015f9fce2794d89dc4351ca6e
46,073
def get_node_flow(flow_net, node): """ Returns the sum of the flow into minus the sum of the flow out from the node. In a maximum flow network, this function returns 0 for all nodes except for the source (wich returns -max_flow) and drain (wich returns max_flow). """ flow = 0 n = len(fl...
c58518dff13658b15c4b2adebe2f4c4efe2a914e
46,075
def gene_tsne_list(tsne_df): """ return data dic """ tSNE_1 = list(tsne_df.tSNE_1) tSNE_2 = list(tsne_df.tSNE_2) Gene_Counts = list(tsne_df.Gene_Counts) res = {"tSNE_1": tSNE_1, "tSNE_2": tSNE_2, "Gene_Counts": Gene_Counts} return res
4dc3832e8bf78476630585d70afe692bb5526563
46,076
def num_to_text(num): # Make sure we have an integer """ Given a number, write out the English representation of it. :param num: :return: >>> num_to_text(3) 'three' >>> num_to_text(14) 'fourteen' >>> num_to_text(24) 'twenty four' >>> num_to_text(31) 'thirty one' ...
aedc20c49dc8bca3996e834944998a6cb338f3a5
46,081
import random def normalRandomInt(max_val, spread, skew=0): """Returns a random integer from a normal distribution whose parameters may be tweaked by setting max_val, spread and skew. The value is clipped to the range [0, max_val]. Args: max_val {number} A positive number. All returned values will be les...
4bbe790dc86a0308700d10a65179288f0d3c2674
46,082
def get_dot(dic, key, default=None): """ Similar to dict.get(), but key is given with dot (eg. foo.bar) and result is evaluated in generous way. That is, get_dot(dic, 'foo.bar.vaz') will return dic['foo']['bar'] if both dic['foo'] and dic['foo']['baz'] exists, but return default if any of them does not ...
cc764debf77b6982733226ec5547e26e2394cd89
46,083
import json def load_json(json_path = "folder_tree.json"): """ Loads in memory a structured dictionary saved with `create_json` :param json_path: Path of JSON file with the dictionary :type json_path: str :return: Loaded JSON file :rtype: dict """ with open(json_path, "r") as json_fi...
c8c6f683c1622e340a479904b625b14f37ab5525
46,084
import glob import os def get_file_paths(mtrack_list, data_path): """Get the absolute paths to input/output pairs for a list of multitracks given a data path """ file_paths = [] for track_id in mtrack_list: input_path = glob.glob( os.path.join(data_path, 'inputs', "{}*_input...
df3c6757bf3059168f06a484fcd677bf40cfda02
46,085
import numpy def convert_to_array(pmap, nsites, imtls): """ Convert the probability map into a composite array with header of the form PGA-0.1, PGA-0.2 ... :param pmap: probability map :param nsites: total number of sites :param imtls: a DictArray with IMT and levels :returns: a composite...
93d0dced847f9ebe796aa6695b0b62e587f130c3
46,087
def mark_cards(cards, number): """Go through cards list marking off number whenever it appears.""" for card in cards: for row_index, row in enumerate(card): card[row_index] = [x if x != number else None for x in row] return cards
048314b6aa2416770ceb1942136fc187c726527b
46,088
def band_sample(sample): """ Fixture which returns a bands sample file. """ return sample('silicon_bands.hdf5')
fa9ebb5e180ef1e2c67adb7d2ead4a8c21d1f815
46,090
def predict_model(grid, input_train_fs, target_train, input_test_fs): """ Validate the best grid model based on training and crossvalidation. Parameters ---------- grid: Object GridSearchCV object input_train_fs: 2D-list target_train: 2D-list input_test_fs: 2D-list """ ...
63b7715309fdcc2ac8d69995d65ad587bd438cd0
46,091
def _refine_index_filename(filename): """ get the current file name for CSV index """ return f"{filename}.index"
819b2587a2a823d57a604dfd981ea4bcc65e1a0d
46,094
import re def convert_to_abgeno(geno_df, lookup_table): """Use lookup table to convert genotypes to AB genotype representation. This function assumes lookup table has alleles corresponding to A and B alleles in columns 2 and 3.""" abgeno_df = geno_df for snp_col in abgeno_df.columns: if sn...
5ea37adb48a374f940217a8eddde041a73e51be9
46,095
def skip_django_trace(func): """disable tracing on a django view function""" func.__skip_trace__ = True return func
8583f9ab8338c597f02ac074b75157c70aef8baa
46,096
def expandDims(samweb, dimensions): """ Expand the given dimensions """ result = samweb._callDimensions('/files/expand_query', dimensions) return result.json()
0cd6f5f67d00b2edc375ecc6370061a62ec37d9f
46,097
def fmtf(format): """ Returns a function that formats strings. >>> f = fmtf("%.2f") >>> f(0.5) '0.50' """ return lambda x: format % x
9e8d1960aca7bbe69b72cd61c6374f88e0ff5e7b
46,098
def distance_to_greater_value(arr: list, allow_equal: bool) -> list: """Creates array where each value indicates distance from arr[i] to a value in arr greater than arr[i]. In order to avoid counting multiple maximums in a given subarray we count the distance to a strictly greater value in one direction an...
bd08e7f34783c8ea221b03184e3533778be354ea
46,101
from typing import List from pathlib import Path def glob_file_from_dirs(dirs: List[str], pattern: str) -> List[str]: """Return a list of all items matching `pattern` in multiple `dirs`.""" return [next(Path(d).glob(pattern)).as_posix() for d in dirs]
c8815e2a39e2722d45fcab4b81d6c81b53566b18
46,102
def _get_default_route(version, subnet): """Get a default route for a network :param version: IP version as an int, either '4' or '6' :param subnet: Neutron subnet """ if subnet.get('gateway') and subnet['gateway'].get('address'): gateway = subnet['gateway']['address'] else: ret...
f039b70bf24ffcac1f31a6ffb9de570606fb55dd
46,103
def contents(filename): """The contents of FILENAME, or the empty string if the file does not exist or is unreadable.""" try: with open(filename) as inp: return inp.read() except: return ''
043d154ed2ef01536b9c9bc0ad88a6de596a39d1
46,105
from sys import platform def font_name(): """ 苹果系统和微软系统需要不同的字体文件 """ if platform == "darwin": return 'Arial Unicode' elif platform == "win32": return 'SimHei' else: print('not support')
32dcaeb945f2d45b52281d94747bf9acb33dcaad
46,106
import json def hello(event, _): """ Simple helloworld endpoint which gives back the event to check things """ body = { "message": "Go Serverless v1.0! Your function executed successfully!", "input": event } return { "statusCode": 200, "body": json.dumps(body) ...
1f55e8e389cce72427f0c658e4d698b01216d9ec
46,107
import socket def end_processes(msg_socket, run_event): """ Shuts down socket connection, end threads """ print("shutting down..") run_event.set() msg_socket.shutdown(socket.SHUT_RDWR) print("socket shutted down") return []
dc411466590ffadd44c82134a66e9dab3dac8871
46,109
def getMenuLabel(menuPar): """ Return menuPar's currently selected menu item's label """ try: return menuPar.menuLabels[menuPar.menuIndex] except IndexError: raise except: raise TypeError("getMenuLabel: invalid menu par " + repr(menuPar))
162c2e6158696c9f306012fa1cba16e5d3af62ea
46,110
def email_event_event(event_d): """Event part of a new/deleted event email""" output = "Event:\n" output += "* eventId: %i\n" % event_d['eventId'] output += "* Rule name: %s\n" % event_d['rulename'] output += "* Severity: %s\n" % event_d['severity'] output += "* attackerAddress: %s\n" % event_d[...
73b32c12a89d4115205a97caf25c8588db4cc0ba
46,115
def get_user(keystone, name): """ Retrieve a user by name""" users = [x for x in keystone.users.list() if x.name == name] count = len(users) if count == 0: raise KeyError("No keystone users with name %s" % name) elif count > 1: raise ValueError("%d users with name %s" % (count, name)...
de66d6397ff4a40716acd67cea432eaaeedc76e9
46,116
import re def filter_invalid_urls(files_and_urls_dict, regex_pattern): """ Filters out the URLs that need to be removed based on a regular expression pattern. :param files_and_urls_dict: files' path and their respective URLs. :type files_and_urls_dict: dict :param regex_pattern: regular expr...
d8cf7626571b3f9cc54961b2584731e248a87174
46,117
import decimal import random def get_random_decimal() -> str: """ Returns random decimal number """ number = str(decimal.Decimal(random.randrange(155, 389)) / 100) return number
4f34c4fcaec3612f2fa0572962b1fc6e554b516e
46,118
def test_summary(root, printerror=False): """Verifies if there are problems with the Lattes CV summary parsed in the argument root. Args: root: the Lattes CV that has been parsed with the ElementTree language. flag: if 0, there is a summary. If 1, the summary is absent. print...
746b577862e83208598b4fbabb1b78fa0a7435af
46,119
def space_out_camel_case(stringAsCamelCase): """ Note to self: There has to be a better way. """ part = [] parts = [part] for this, next in zip(stringAsCamelCase, stringAsCamelCase[1:] + "#"): part.append(this) if this.islower() != next.islower(): part = [] ...
362b51ef774c09dfe9d0ec5106a3771f80ef7f19
46,120
def valid_attribute(view, pos): """attribute in valid scope""" if view.match_selector(pos, "source.python comment"): return False # match f-string if view.match_selector(pos, "source.python meta.interpolation.python"): return True # match common string if view.match_selector(p...
cbac18bb63e2a0304f91ef45d394778b4f9fab0d
46,122
def find(arr, fkt): """find a specific element in the given array""" for el in arr: if fkt(el): return el
ee949a92267d1fcf8717586abad0664a1010b708
46,123
def mask_peptides(peptides, max_len, pad_aa='Z', pre_pad=True): """ Mask and pad for an LSTM (can be used without calling from instance of Dataset) """ num_skipped = 0 num_total = 0 padded_peptides = [] original_peptides = [] #for residues that we are not sure ab...
d0ebf8650e3d5575a6081a59a209a35dfb55bf70
46,124
import os import re def get_files(directory, regex, files_to_exclude): """Finds files matching the regex in the specified directory except for those in the exclusion list. Returns a list of file paths.""" files = [] for dirpath, dirnames, filenames in os.walk(directory): for f in filenames: ...
88a4045298a770edcc28425486bda9140e59fe9a
46,125
import os import sys def get_binary_path(testname, build_dir): """ Returns full path to test executable.""" base_path = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) binary_name = testname if sys.platform == 'win32': binary_name += '.exe' build_path = os.path...
1c0387f2972eb206ba86a0f4b7fbdd03cbad30e9
46,127
import requests import time def get_with_retry(uri, max_retry=5): """Wrapper for requests.get() to retry Args: uri (str): URI to request max_retry (int): number of retries to make Returns: the requests response """ r = requests.get(uri) k = 0 while r.status_code !...
1351e138b02e409434c5058f033a53a742ba0204
46,128
def _check_solve_output(out, err): """ Verify from shell output that the Radia solve completed satisfactorily. Will print any output from the shell. :param out: (bytes) STDOUT piped from shell :param err: (bytes) STDERR piped from shell :return: (bool) True if STDERR is empty. False if STDERR is...
56fc1d5ffd5d361a4f4090703393dbb19ce11c23
46,130
def get_pix_offsets_for_point(ds, lng, lat): """ Given a raster datasource (from osgeo.gdal) and lng/lat coordinates, return the x and y pixel offsets required to get the pixel that point is in. Note - this assumes that the point is within the datasource bounds """ top_left_x, pix_w...
ebfe9bfd92baa71ef1e5aa931b893ad822ce7e06
46,131