content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import codecs async def putStorBytes(app, key, data, filter_ops=None, bucket=None): """ Store byte string as S3 object with given key """ client = _getStorageClient(app) if not bucket: bucket = app['bucket_name'] if key[0] == '/': key = key[1:] # no leading slash shuffle = -1...
f58ff0c9073e2ce7dce19b2c586abc14af792590
22,600
import glob import os def fetch_block(folder, ind, full_output=False): """ A more generic function to fetch block number "ind" from a trajectory in a folder This function is useful both if you want to load both "old style" trajectories (block1.dat), and "new style" trajectories ("blocks_1-5...
0bbbfa1c2d86b6c71b8700c8dba43656173c797b
22,601
def unique_boxes(boxes, scale=1.0): """Return indices of unique boxes.""" assert boxes.shape[1] == 4, 'Func doesnot support tubes yet' v = np.array([1, 1e3, 1e6, 1e9]) hashes = np.round(boxes * scale).dot(v) _, index = np.unique(hashes, return_index=True) return np.sort(index)
951f0b6f0d51212ad63e787a32c78d14f7e11bd1
22,602
def dataloader(loader, mode): """Sets batchsize and repeat for the train, valid, and test iterators. Args: loader: tfds.load instance, a train, valid, or test iterator. mode: string, set to 'train' for use during training; set to anything else for use during validation/test Returns: An itera...
b15b736919c21df142e2d4815f33b24dc0f01e5f
22,603
def sub_inplace(X, varX, Y, varY): """In-place subtraction with error propagation""" # Z = X - Y # varZ = varX + varY X -= Y varX += varY return X, varX
646578886c37003eb860134b93db95e6b4d73ed7
22,604
def inv_logtransform(plog): """ Transform the power spectrum for the log field to the power spectrum of delta. Inputs ------ plog - power spectrum of log field computed at points on a Fourier grid Outputs ------- p - power spectrum of the delta field """ xi_log = np.fft.ifftn(plo...
aaf414796e5dfd5ede71dd8e18017f46b7761a39
22,605
import builtins def ipv6_b85decode(encoded, _base85_ords=RFC1924_ORDS): """Decodes an RFC1924 Base-85 encoded string to its 128-bit unsigned integral representation. Used to base85-decode IPv6 addresses or 128-bit chunks. Whitespace is ignored. Raises an ``OverflowError`` if stray characters...
324ec9835c7228bf406a8b33450c530b7191c4a0
22,606
def relabel_sig(sig:BaseSignature, arg_map:TDict[str, str]=None, new_vararg:str=None, kwarg_map:TDict[str, str]=None, new_varkwarg:str=None, output_map:TDict[str, str]=None) -> BaseSigMap: """ Given maps along which to rename signature elements, generate a new ...
a6b7ab1f8e8d3104938a6b1cecc609fb8a3aa1a0
22,607
import functools def inferred_batch_shape_tensor(batch_object, bijector_x_event_ndims=None, **parameter_kwargs): """Infers an object's batch shape from its parameters. Each parameter contributes a batch shape of `base_shape(parameter)[:-event_ndi...
d3c3a40f36c66ef28f6aeaddbdaa7dff5729f1ed
22,608
from datetime import datetime def fsevent_log(self, event_id_status_message): """Amend filesystem event history with a logging message """ event_id = event_id_status_message[0] status = event_id_status_message[1] message = event_id_status_message[2] dbc = db_collection() history_entry = { ...
64cd88762e2775172bcf4c894c5187c373db3ee8
22,609
def fetch_synthetic_2d(lags=0): """ Build synthetic 2d data. Parameters ---------- lags : int, optional If greater than 0 it's added time dependence. The default is 0. Returns ------- data : numpy.ndarray, shape=(3000, 2) Synthetic data. """ seed = 98 ...
006f1dc900d88c45d16eb518403bb576167bcae1
22,610
from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import train_test_split def prepare_data() -> tuple: """Do the whole data preparation - incl. data conversion and test/train split. Returns: tuple: (X_train, y_train, X_test, y_test) """ (data, labels) = get_da...
a2a31f09858393d5fbcd5be80fd61b2e69df3cdf
22,611
def current_url_name(request): """ Adds the name for the matched url pattern for the current request to the request context. """ try: match = resolve(request.path) url_name = match.url_name except Http404: url_name = None return { 'current_url_name':...
9ec6ea26a503e0969400a85a0df7491f6aefc064
22,612
import click def get_crypto_key(): """Shows your crypto key""" key = load_key() if key: click.secho("your actual crypto key:", fg = "blue") return click.echo(load_key())
7078f5fd0fe099ef49a3d702111aae9ee5e23387
22,613
def get_entropies(data: pd.DataFrame): """ Compute entropies for words in wide-format df """ counts = pd.DataFrame(apply_count_values( data.to_numpy(copy=True)), columns=data.columns) probs = (counts / counts.sum(axis=0)).replace(0, np.nan) nplogp = -probs * np.log2(probs) return npl...
49a0a52194472a4285e60a05dab8a83dfaa7eec0
22,614
import os def create_dataset(dataset_path, do_train, image_size=224, interpolation='BILINEAR', crop_min=0.05, repeat_num=1, batch_size=32, num_workers=12, autoaugment...
130457530b30cb917091c3613a5d247140a8bfd9
22,615
def _numeric_adjust_widgets(caption: str, min: float, max: float) -> HBox: """Return a HBox with a label, a text box and a linked slider.""" label = Label(value=caption) text = BoundedFloatText(min=min, max=max, layout=wealth.plot.text_layout) slider = FloatSlider(readout=False, min=min, max=max) wi...
b45aaa069f425a888bf54281c6324509eac783c6
22,616
import os def evaluate(benchmark, solution): """Evaluate the solution against the benchmark.""" # Get test data root = os.path.dirname(__file__) path = os.path.join(root, "../../task/regression/data/{}_test.csv".format(benchmark)) df_test = pd.read_csv(path, header=None) X = df_test.values[:,...
038f2e24c985619b319a24263d236ec77ded4b02
22,617
def where_handle(tokens): """Process where statements.""" internal_assert(len(tokens) == 2, "invalid where statement tokens", tokens) final_stmt, init_stmts = tokens return "".join(init_stmts) + final_stmt + "\n"
8377a1b62ffbca31a6b6fa42a125e3b16387a665
22,618
def nltk_ngram_pos_tagger(input_dict): """ A tagger that chooses a token's tag based on its word string and on the preceding n word's tags. In particular, a tuple (tags[i-n:i-1], words[i]) is looked up in a table, and the corresponding tag is returned. N-gram taggers are typically trained on a...
ab6d1f48590042b1efe0a9c7e741e7a5ccbcdb34
22,619
import subprocess import sys def pkg(root, version, output, identifier=CONFIG['pkgid'], install_location='/', sign=CONFIG['sign_cert_cn'], ownership='recommended' ): """ Create a package. Most of the input parameters should be recognizable for most ...
dc51b990d2e585f8c239ec459bcb9024764f5c27
22,620
def remove_app(INSTALLED_APPS, app): """ remove app from installed_apps """ if app in INSTALLED_APPS: apps = list(INSTALLED_APPS) apps.remove(app) return tuple(apps) return INSTALLED_APPS
7386b6f38b73abf25e94d9c8368aaac6255d2cee
22,621
from typing import OrderedDict def get_feature(cluster, sample, i): """Turn a cluster into a biopython SeqFeature.""" qualifiers = OrderedDict(ID="%s_%d" % (sample, i)) for attr in cluster.exportable: qualifiers[attr] = getattr(cluster, attr.lower()) feature = SeqFeature(FeatureLocation(cluste...
4ec3cb0757db9b884d3bce3d4406f1824a6c62dd
22,622
def loss(Y, spectra, beta, Yval, val_spec): """ Description ----------- Calculate the loss for a specfic set of beta values Parameters ---------- Y: labels (0 or 1) spectra: flux values beta: beta values Yval: validation set labels (0 or 1) val_spec: validation flux values Returns ------- ...
5be2675d14062834bc0f8c9cd83551a60b528668
22,623
def video_detail_except(): """取得channelPlayListItem/videoDetail兩表video_id的差集 Returns: [list]: [目前尚未儲存詳細資料的影片ID] """ playlist_id = get_db_ChannelPlayListItem_video_id() video_detail_id = get_db_VideoDetail_video_id() if video_detail_id and playlist_id: filter_video = list(set(pla...
efe9f151c6689cf6a71584cf988d0af8bb1c0c2a
22,624
def nodes(xmrs): """Return the list of Nodes for *xmrs*.""" nodes = [] _props = xmrs.properties varsplit = sort_vid_split for p in xmrs.eps(): sortinfo = None iv = p.intrinsic_variable if iv is not None: sort, _ = varsplit(iv) sortinfo = _props(iv) ...
0e081648e6b30ec6cc230218c346384624d2ade6
22,625
import matplotlib.pyplot as plt import matplotlib as mpl def get_figure(a=None, e=None, scale=10): """ Creates the desired figure setup: 1) Maximize Figure 2) Create 3D Plotting Environment 3) Rotate Z axis label so it is upright 4) Let labels 5) Increase label font size 6) Rotate camer...
595f91b9e62fd85db68ec0d06d117d36d76e1ab2
22,626
import torch def get_data_loader(transformed_data, is_training_data=True): """ Creates and returns a data loader from transformed_data """ return torch.utils.data.DataLoader(transformed_data, batch_size=50, shuffle=True) if is_training_data else torch.utils.data.DataLoader(transformed_data, batch_size...
7f7dfdc83abc0ab261fde7be2216b4e130761f7e
22,627
import six def resolve_authconfig(authconfig, registry=None): """ Returns the authentication data from the given auth configuration for a specific registry. As with the Docker client, legacy entries in the config with full URLs are stripped down to hostnames before checking for a match. Returns No...
a21ee92f3477c4270f708c5577b3d1adcf1b03a9
22,628
def structured_rand_arr(size, sample_func=np.random.random, ltfac=None, utfac=None, fill_diag=None): """Make a structured random 2-d array of shape (size,size). If no optional arguments are given, a symmetric array is returned. Parameters ---------- size : int Determi...
4463f62bef1feff23019cc35439545b52461ee40
22,629
def append_empty_args(func): """To use to transform an ingress function that only returns kwargs to one that returns the normal form of ingress functions: ((), kwargs)""" @wraps(func) def _func(*args, **kwargs): return (), func(*args, **kwargs) return _func
ec2bf4c30eddb418ade57e50ce8a4a233a8f0f9d
22,630
def gateway(job, app, tool, user, user_email): """ Function to specify the destination for a job. At present this is exactly the same as using dynamic_dtd with tool_destinations.yml but can be extended to more complex mapping such as limiting resources based on user group or selecting destinations ...
b51cd288b638469d054191be0c1423d0c637ce9a
22,631
import argparse def process_command_line(): """ Return a 1-tuple: (args list). `argv` is a list of arguments, or `None` for ``sys.argv[1:]``. """ parser = argparse.ArgumentParser(description='usage') # add description # positional arguments parser.add_argument('d1s', metavar='domain1-source', type=str,...
7ab4e61850bf1f4fd84198ffd93d577864a9b873
22,632
def pprint(matrix: list) -> str: """ Preety print matrix string Parameters ---------- matrix : list Square matrix. Returns ------- str Preety string form of matrix. """ matrix_string = str(matrix) matrix_string = matrix_string.replace('],', '],\n') retu...
5c0ffa2b0a9c237b65b5ad7c4e17c2456195c088
22,633
def sigmoid(x : np.ndarray, a : float, b : float, c : float) -> np.ndarray : """ A parameterized sigmoid curve Args: x (np.ndarray or float): x values to evaluate the sigmoid a (float): vertical stretch parameter b (float): horizontal shift parameter c (float): horizontal st...
dacb80ca958bf9f0a007fe6d50970f444fd9b4e7
22,634
def merge_testcase_data(leaf, statsname, x_axis): """ statsname might be a function. It will be given the folder path of the test case and should return one line. """ res = get_leaf_tests_stats(leaf, statsname) return merge_testcase_data_set_x(res, x_axis)
5b8829377d9249630a9261e7ee27533cce72542c
22,635
import os def get_account_ids(status=None, table_name=None): """return an array of account_ids from the Accounts table. Optionally, filter by status""" dynamodb = boto3.resource('dynamodb') if table_name: account_table = dynamodb.Table(table_name) else: account_table = dynamodb.Table(o...
ea893a9001856ce6424eb3c6c340fd1a2c7ab99c
22,636
def dashed_word(answer): """ :param answer: str, from random_word :return: str, the number of '-' as per the length of answer """ ans = "" for i in answer: ans += '-' return ans
358be047bfad956afef27c0665b02a2a233fefbf
22,637
def merge_overpass_jsons(jsons): """Merge a list of overpass JSONs into a single JSON. Parameters ---------- jsons : :obj:`list` List of dictionaries representing Overpass JSONs. Returns ------- :obj:`dict` Dictionary containing all elements from input JSONS. """ el...
c68fde0ddbdf22a34377e1e865be36aaabaa47be
22,638
from admin.get_session_info import run as _get_session_info from admin.login import run as _login from admin.logout import run as _logout from admin.recover_otp import run as _recover_otp from admin.register import run as _register from admin.request_login import run as _request_login from admin.handler import MissingF...
1885705099ce67e806a6cc9a461f92c659bbf0bb
22,639
def load_template(tmpl): """ Loads the default template file. """ with open(tmpl, "r") as stream: return Template(stream.read())
a37a74cf37a05142bcddac870a81ee44531004f3
22,640
import hashlib def calculate_id_name(message): """ Calculates hash value based on message. Useful for unique id - six hex characters. 6 digits - 16777216 permutations. TODO: check for hash collisions. """ hash_object = hashlib.md5(b'%s'% message) return hash_object.hexdigest()[0:5]
37e6e53a75bd2397a37125c4205b6a1cf24057ee
22,641
def get_total_cases(): """全国の現在の感染者数""" return col_ref.document(n).get().to_dict()["total"]["total_cases"]
1e933fd86cde49edbb5d78591fb513cb9633c080
22,642
from typing import Optional def _find_db_team(team_id: OrgaTeamID) -> Optional[DbOrgaTeam]: """Return the team with that id, or `None` if not found.""" return db.session.query(DbOrgaTeam).get(team_id)
9c0709c8b601a1910ed1e6b08f16970c976b7310
22,643
from typing import Optional from contextlib import suppress def make_number( num: Optional[str], repr: str = None, speak: str = None, literal: bool = False, special: dict = None, ) -> Optional[Number]: """Returns a Number or Fraction dataclass for a number string If literal, spoken string...
0fdbd9610355cfceb2ee5ab0fd04b694ca8da9af
22,644
import os def _readmapfile(fp, mapfile): """Load template elements from the given map file""" base = os.path.dirname(mapfile) conf = config.config() def include(rel, remap, sections): subresource = None if base: abs = os.path.normpath(os.path.join(base, rel)) i...
8faf0782230cce63b99295d6142c3ee713539d5e
22,645
import plotly.graph_objs as go def gif_jtfs_3d(Scx, jtfs=None, preset='spinned', savedir='', base_name='jtfs3d', images_ext='.png', cmap='turbo', cmap_norm=.5, axes_labels=('xi2', 'xi1_fr', 'xi1'), overwrite=False, save_images=False, width=800, height=800, surface_count...
0d34878378e463a55655be29bd6b3d665adc05c6
22,646
def get_arguments(): """ Parse command line arguments :return Namespace: parsed arguments """ parser = ArgumentParser(description='') subparsers = parser.add_subparsers(help='sub-command help', dest='subparser_name') parser.add_argument( '-v', '--verbose', type=int, ...
083f4e0c38ea3a4d1e7734136b08827aa26af32c
22,647
def _serialize_account(project): """Generate several useful fields related to a project's account""" account = project.account return {'goal': account.goal, 'community_contribution': account.community_contribution, 'total_donated': account.total_donated(), 'total_raised':...
dea20df5db1ae37f61d6c661f957432b7cb72158
22,648
import socket def _NodeThread(node_ip): """Check if this IP is a node""" log = GetLogger() SetThreadLogPrefix(node_ip) known_auth = [ ("admin", "admin"), ("admin", "solidfire") ] SFCONFIG_PORT = 442 sock = socket.socket() sock.settimeout(0.5) try: sock.co...
ffbd1058e105c4ddc7ddea11da1aa20862a8fb9f
22,649
def neighbor_smoothing_binary(data_3d, neighbors): """ takes a 3d binary (0/1) input, returns a "neighbor" smoothed 3d matrix Input: ------ data_3d: a 3d np.array (with 0s and 1s) -> 1s are "on", 0s are "off" neighbors: the value that indicates the number of neighbors around voxel to check Returns: -------...
22f503e9843a1a0864e3a66c4ed05070712defa3
22,650
def view( name = None, description = None, parameters = (), devel = False ): """ Decorator function to be used to "annotate" the provided function as an view that is able to return a set of configurations for the proper display of associated information. Proper usage of the view def...
988750523fa0f2d471ec3d54e834411d565ff22f
22,651
import io import gzip def _decode_response(resp_bytes: bytes) -> str: """Even though we request identity, rvm.io sends us gzip.""" try: # Try UTF-8 first, in case they ever fix their bug return resp_bytes.decode('UTF-8') except UnicodeDecodeError: with io.BytesIO(resp_bytes) as byt...
3197cbdf3cc9d7b0337d6748cf5c1467759645ca
22,652
def registrymixin_models(): """Fixtures for RegistryMixin tests.""" # We have two sample models and two registered items to test that # the registry is unique to each model and is not a global registry # in the base RegistryMixin class. # Sample model 1 class RegistryTest1(BaseMixin, db.Model):...
420ecaea78780524ac0a889af1d584d0bbced8f3
22,653
def is_test_input_output_file(file_name: str) -> bool: """ Return whether a file is used as input or output in a unit test. """ ret = is_under_test_dir(file_name) ret &= file_name.endswith(".txt") return ret
961c2dcda2cb848a1880b36ca06c01a8bf091704
22,654
import csv def generate_csv_from_queryset(queryset, csv_name = "query_csv"): """ Genera un file csv a partire da un oggetto di tipo QuerySet :param queryset: oggetto di tipo QuerySet :param csv_name: campo opzionale per indicare il nome di output del csv :return: oggetto response """ try: ...
ba4fab63e40cf791d7ac148ca804f0f60173d395
22,655
def get(isamAppliance, id, check_mode=False, force=False, ignore_error=False): """ Retrieving the current runtime template files directory contents """ return isamAppliance.invoke_get("Retrieving the current runtime template files directory contents", "/mga/template_f...
252bf635445af134772e8e762508ec9eb32d974e
22,656
def update(contxt, vsmapp_id, attach_status=None, is_terminate=False): """update storage pool usage""" if contxt is None: contxt = context.get_admin_context() if not vsmapp_id: raise exception.StoragePoolUsageInvalid() is_terminate = utils.bool_from_str(is_terminate) kargs = { ...
1015a7387cb264e9f8ce611d1b2de531aabb249e
22,657
import tqdm def adsgan(orig_data, params): """Generate synthetic data for ADSGAN framework. Args: orig_data: original data params: Network parameters mb_size: mini-batch size z_dim: random state dimension h_dim: hidden state dimension lamda: identifiability parameter itera...
f0e4f85f93d116c75c82a1aba524bed89beb4f14
22,658
import requests def unemployed(year,manu, key,state='*'): #ex manu= 54 is professional, scientific, and technical service industries, year= 2017 """Yearly data on self-employed manufacturing sectors for all counties. Returns all receipts in thousands of dollars for all counties for the specified state for certain...
1ee03a5a0ee1faf2101b8785aadda688b722a96e
22,659
def stack_bricks(top_brick, bottom_brick): """Stacks two Duplo bricks, returns the attachment frame of the top brick.""" arena = composer.Arena() # Bottom brick is fixed in place, top brick has a freejoint. arena.attach(bottom_brick) attachment_frame = arena.add_free_entity(top_brick) # Attachment frame is ...
64b096bc77dfcd62c39cccdfad10241a1574a1ec
22,660
def trigger(name): """ @trigger decorator allow to register a function as a trigger with a given name Parameters ---------- name : str Name of the trigger """ _app = get_app_instance() return _app.trigger(name)
3af727c206565346b69ea5eb6735d9237cefeaf3
22,661
from typing import Dict from typing import List def get_components_to_remove(component_dict: Dict[str, ComponentImport]) -> List[str]: """Gets a list of components to remove from the dictionary using console input. Args: component_dict (Dict[str, ComponentImport]): The custom component dictionary. ...
fd423b0de58ef2e8d5db1a63d334f034a729f2f4
22,662
import requests def list_data_objects(): """ This endpoint translates DOS List requests into requests against indexd and converts the responses into GA4GH messages. :return: """ req_body = app.current_request.json_body if req_body: page_token = req_body.get('page_token', None) ...
0eae49f4e559a4d640ce304cfaa17ef3806b2937
22,663
from typing import Union def get_include_file_start_line(block: Block) -> Union[int, None]: """ >>> block = lib_test.get_test_block_ok() >>> # test start-line set to 10 >>> get_include_file_start_line(block) 10 >>> assert block.include_file_start_line == 10 >>> # test start-line not set ...
5e9ddeed83192f8a53acaca1a6ac4493a7dcbe36
22,664
def get_wcets(utils, periods): """ Returns WCET """ return [ui * ti for ui, ti in zip(utils, periods)] # return [math.ceil(ui * ti) for ui, ti in zip(utils, periods)]
f853459b2463fc75b91f5effe3357b9c4ec5c4f9
22,665
def aws_get_dynamodb_table_names(profile_name: str) -> list: """ get all DynamoDB tables :param profile_name: AWS IAM profile name :return: a list of DynamoDB table names """ dynamodb_client = aws_get_client("dynamodb", profile_name) table_names = [] more_to_evaluate = True last_ev...
fddc574e8f4f6a798e5fe0b339c898b09f18b527
22,666
from typing import Any def stack_images_vertical( image_0: NDArray[(Any, ...), Any], image_1: NDArray[(Any, ...), Any] ) -> NDArray[(Any, ...), Any]: """ Stack two images vertically. Args: image_0: The image to place on the top. image_1: The image to place on the bottom. Returns:...
bb83cc6246bef5df370b45ac0ce7ed5b58a974f7
22,667
def simulate_ids(num): """ 模拟生成一定数量的身份证号 """ ids = [] if num > 0: for i in range(1, num+1): id_raw = digit_1to6() + digit_7to10() + digit_11to14() + digit_15to17() id = id_raw + digit_18(id_raw) ids.append(id) else: return False return ids
2e74fb150f01b8d43eefffdab2d95790cad6f334
22,668
def geomean(x): """computes geometric mean """ return exp(sum(log(i) for i in x) / len(x))
7c5ad27938a6d6da7f304d7ac66fcc1a179162c2
22,669
from typing import Tuple def _get_mean_traces_for_iteration_line_plot( scenario_df: pd.DataFrame, ) -> Tuple[go.Scatter, go.Scatter, go.Scatter]: """Returns the traces for the mean of the success rate. Parameters ---------- scenario_df : pd.DataFrame DataFrame containing the columns "n_it...
04542d1b1f76173e8fa2431a5a6bd3b8e8627026
22,670
def create_graph_of_words(words, database, filename, window_size = 4): """ Function that creates a Graph of Words that contains all nodes from each document for easy comparison, inside the neo4j database, using the appropriate cypher queries. """ # Files that have word length < window size, are ski...
89560a26d2ab624a28b07bf2ff826a8eb34564e8
22,671
from pathlib import Path def get_dir(path): """ Функция возвращает директорию файла, если он является файлом, иначе возвращает объект Path из указанного пути """ if not isinstance(path, Path): path = Path(path) return path.parent if path.is_file() else path
b7ca7f60d88c06bc3181bd93039c13a13e2684a4
22,672
import hashlib def get_file_sha(fname): """ Calculates the SHA1 of a given file. `fname`: the file path return: the calculated SHA1 as hex """ result = '' if isfile(fname): sha1 = hashlib.sha1() with open(fname, 'rb') as f: while True: data = f....
c328f8c5b65a018016a02d39a54b753c33cd3217
22,673
def graphtool_to_gjgf(graph): """Convert a graph-tool graph object to gJGF. Parameters ---------- graph : graph object from graph-tool Returns ------- gjgf : dict Dictionary adhering to :doc:`gravis JSON Graph Format (gJGF) <../../format_specification>` Caution ---...
73ceca04270aaa1f754001d446dba9c796ef6822
22,674
def forbidden_error(error): """ 418 I'm a teapot """ return engine.get_template('errors/417.html').render({}), 418
43319b9aa95c970e75e392e584dd8af78199ceb0
22,675
def green(s: str) -> str: """green(s) color s with green. This function exists to encapsulate the coloring methods only in utils.py. """ return colorama.Fore.GREEN + s + colorama.Fore.RESET
56f12d56257d0728d7d71cba61256bede5c3a064
22,676
import pickle def cache_fun(fname_cache, fun): """Check whether cached data exists, otherwise call fun and return Parameters ---------- fname_cache: string name of cache to look for fun: function function to call in case cache doesn't exist probably a lambda function ...
0387f611ab12aeb8a2d7dfca664e08b0438b1905
22,677
def find_server_storage_UUIDs(serveruuid): """ @rtype : list @return: """ storageuuids = [] db = dbconnect() cursor = db.cursor() cursor.execute("SELECT UUID, ServerUUID FROM Storage WHERE ServerUUID = '%s'" % serveruuid) results = cursor.fetchall() for row in results: ...
48abd3e3a9dc49cef5f9eb52d7327e79a61602a4
22,678
import torch def unpack_bidirectional_lstm_state(state, num_directions=2): """ Unpack the packed hidden state of a BiLSTM s.t. the first dimension equals to the number of layers multiplied by the number of directions. """ batch_size = state.size(1) new_hidden_dim = int(state.size(2) / num_dire...
fa58ed9bcf2e9e95aa62b3d18110abe6abce6b1b
22,679
def macd_diff(close, window_slow=26, window_fast=12, window_sign=9, fillna=False): """Moving Average Convergence Divergence (MACD Diff) Shows the relationship between MACD and MACD Signal. https://en.wikipedia.org/wiki/MACD Args: close(pandas.Series): dataset 'Close' column. window_fa...
ef5b222c688026a25121b35d4354967e4f5c93fc
22,680
def spike_histogram(series, merge_spikes=True, window_duration=60, n_bins=8): """ Args: * series (pd.Series): watts * merge_spikes (bool): Default = True * window_duration (float): Width of each window in seconds * n_bins (int): number of bins per window. Returns: sp...
fc401d8c2b4aabde646a3570397f8fdb8087bf6b
22,681
def data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_information_rate_post(uuid, local_id, tapi_common_capacity_value=None): # noqa: E501 """data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_infor...
92cefba50ff813e2fd1797d383ae2df7e02a99da
22,682
def any(*args, span=None): """Create a new experssion of the union of all conditions in the arguments Parameters ---------- args : list List of symbolic boolean expressions span : Optional[Span] The location of this operator in the source code. Returns ------- expr: Ex...
697eb7e44d0fb9a0b9b947eea9fe4e8f68b78210
22,683
from typing import List from typing import Any def firstOrNone(list: List[Any]) -> Any: """ Return the first element of a list or None if it is not set """ return nthOrNone(list, 0)
9c51a2f72fe5f516258f2fd20210bd83a3cfbf2d
22,684
def ellipse_points( xy=[0,-5.], ex=254., ez=190., n=1000 ): """ :param ec: center of ellipse :param ex: xy radius of ellipse :param ez: z radius of ellipse :param n: number of points :return e: array of shape (n,2) of points on the ellipse """ t = np.linspace( 0, 2*np.pi, n ) e = np...
93b3aeccf6ab04ad8b0e96cdad80a52d9a6c46c4
22,685
def sum_dose_maps(dose_maps): """ sum a collection of dose maps to obtain the total dose """ ps.logger.debug('Summing %s dose_maps', len(dose_maps)) dose_maps = np.stack(dose_maps) return np.nansum(dose_maps, axis=0)
b05d54cc6e2276dca76eba68a643828ff14fa0fe
22,686
def ion_list(): """List of ions with pre-computed CLOUDY ionization fraction""" ions = np.array(['al2','c2','c3','c4','fe2','h1','mg2', 'n1','n2','n3','n4','n5','ne8','o1','o6', 'o7','o8','si2','si3','si4']) return ions
4fae0b3cf7956349a30807d4975b1d72cf10c9ec
22,687
def is_valid_filename(filename): """Determines if a filename is valid (with extension).""" valid_extensions = ['mp4', 'webm', 'ogg'] extension = get_extension(filename) return bool(extension and extension in valid_extensions)
6a493fac59fca900e5d3bf55075e897bf36528f7
22,688
import re def read(line_str, line_pos, pattern='[0-9a-zA-Z_:?!><=&]'): """ Read all tokens from a code line matching specific characters, starting at a specified position. Args: line_str (str): The code line. line_pos (int): The code line position to start reading. pattern (st...
95ece37e927ff3f8ea9579a7d78251b10b1ed0e6
22,689
from typing import Dict import random def demographic(population: int, highest_lvl_ratio: int = ONE_MILLION, num_levels: int = NUM_LEVELS) -> Dict[int, int]: """ Calculate the number of levelled NPCs in a given population. Args: population: The population to consider these levelled NP...
b45b26c7add41c85cf526789ba26f7c877db685a
22,690
def gencpppxd(env, exceptions=True, ts=None): """Generates all cpp_*.pxd Cython header files for an environment of modules. Parameters ---------- env : dict Environment dictonary mapping target module names to module description dictionaries. exceptions : bool or str, optional ...
627828bfc01c8282b0bf53f5e3cef234d0bdc816
22,691
import requests def configure_mongo_connection( key: str, host: str, port: int, dbname: str, username: str, password: str ): """ Configure the connection with the given `key` in fidesops with your PostgreSQL database credentials. Returns the response JSON if successful, or throws an error otherwise. ...
72746eb7bcebb747b4821f453e8f0f4543abc060
22,692
import random def fully_random(entries, count): """Choose completely at random from all entries""" return random.sample(entries, count)
a1f494f6b3cc635bc109378305bf547d48f29019
22,693
def _get_sets_grp(grpName="controllers_grp"): """Get set group Args: grpName (str, optional): group name Returns: PyNode: Set """ rig = _get_simple_rig_root() sets = rig.listConnections(type="objectSet") controllersGrp = None for oSet in sets: if grpName in oSe...
ec65ab91b69cb1c509412258b517f78f9e124f24
22,694
import re def clean_text(text, cvt_to_lowercase=True, norm_whitespaces=True): """ Cleans a text for language detection by transforming it to lowercase, removing unwanted characters and replacing whitespace characters for a simple space. :rtype : string :param text: Text to clean :param c...
7586112429f529d21f5d7a992bf40d3604dfe52a
22,695
def print(*args, **kwargs) -> None: """Proxy for Console print.""" console = get_console() return console.print(*args, **kwargs)
49b96ae3df30bf09e742f8355f0867341396bc44
22,696
def student_dashboard(lti=lti, user_id=None): # def student_dashboard(user_id=None): """ Dashboard froms a student view. Used for students, parents and advisors :param lti: pylti :param user_id: users Canvas ID :return: template or error message """ # TODO REMOVE ME - not using records anymo...
361fdbe0c27738229d2a0e911ad0509e85ada990
22,697
import yaml def _yaml_to_dict(yaml_string): """ Converts a yaml string to dictionary Args: yaml_string: String containing YAML Returns: Dictionary containing the same object """ return yaml.safe_load(yaml_string)
c7de0c860028d17302cd4d07e20c3215503b977b
22,698
import urllib from bs4 import BeautifulSoup def room_urls_for_search_url(url): """ the urls of all rooms that are yieled in a search url """ with urllib.request.urlopen(url) as response: html = response.read() soup = BeautifulSoup(html, 'html.parser') room_urls = {erg_list_entry.find('a...
8945b55e7379860defa0f4229690e53196acbe4d
22,699