content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import sys import os import shutil def CommitOffsite( backup_name, backup_suffix=None, output_stream=sys.stdout, preserve_ansi_escape_sequences=False, ): """\ Commits data previously generated by Offsite. This can be useful when additional steps must be taken (for example, upload) before a...
bfe523c2ecabb7c4bacd2fe3015929074dbae6f3
3,651,000
def get_impropers(bonds): """ Iterate over bonds to get impropers. Choose all three bonds that have one atom in common. For each set of bonds you have 3 impropers where one of the noncommon atoms is out of plane. Parameters ---------- bonds : list List of atom ids that make up bonds...
c5c2fe4684269407cd4387d86840bd982f1d3fa5
3,651,001
def get_ret_tev_return(*args): """get_ret_tev_return(int n) -> ea_t""" return _idaapi.get_ret_tev_return(*args)
94d476d12313b7df4da32cb45cfe644a0078debb
3,651,002
def make_figure_6(prefix=None, rng=None, colors=None): """ Figures 6, Comparison of Performance Ported from MATLAB Code Nicholas O'Donoughue 24 March 2021 :param prefix: output directory to place generated figure :param rng: random number generator :param colors: colormap for plotting...
761d6ddd541dfbe42e5b57cd680306c71ae978d9
3,651,003
def slim_form(domain_pk=None, form=None): """ What is going on? We want only one domain showing up in the choices. We are replacing the query set with just one object. Ther are two querysets. I'm not really sure what the first one does, but I know the second one (the widget) removes the choices. Th...
7b58674e307fbbd31f0546b70309c0c723d1021c
3,651,004
def input(*args): """ Create a new input :param args: args the define a TensorType, can be either a TensorType or a shape and a DType :return: the input expression """ tensor_type = _tensor_type_polymorhpic(*args) return InputTensor(tensor_type, ExpressionDAG.num_inputs)
47ab3a08f412b7dc9c679ae72bb44c76123a9057
3,651,005
def commong_substring(input_list): """Finds the common substring in a list of strings""" def longest_substring_finder(string1, string2): """Finds the common substring between two strings""" answer = "" len1, len2 = len(string1), len(string2) for i in range(len1): mat...
9e5e0878072a5416326ac1ed0d929adcb8511b37
3,651,006
def is_valid_url(url): """Checks if a URL is in proper format. Args: url (str): The URL that should be checked. Returns: bool: Result of the validity check in boolean form. """ valid = validators.url(url) if valid: return True else: return False
b55fd89267884dfc2507966825272a02e18d34f5
3,651,007
import re import requests def codepoint_to_url(codepoint, style): """ Given an emoji's codepoint (e.g. 'U+FE0E') and a non-apple emoji style, returns a url to to the png image of the emoji in that style. Only works for style = 'twemoji', 'noto', and 'blobmoji'. """ base = codepoint.replace(...
a5b47f5409d465132e3fb7141d81dbd617981ca8
3,651,008
def getRNCS(ChargeSA): """The calculation of relative negative charge surface area -->RNCS """ charge=[] for i in ChargeSA: charge.append(float(i[1])) temp=[] for i in ChargeSA: temp.append(i[2]) try: RNCG = min(charge)/sum([i for i in charge if i < 0.0]) ...
f03011de85e1bcac01b2aba4afde61a3dd9f7866
3,651,009
def handle_auth_manager_auth_exception(error): """Return a custom message and 403 status code""" response_header = {'X-REQUEST-ID': util.create_request_id()} return {'message': error.message}, 403, response_header
4b5212f4471a21cd54d012728705e83de5c7a86f
3,651,010
def get_default_converter(): """Intended only for advanced uses""" return _TYPECATS_DEFAULT_CONVERTER
f88cdb13d53a228ff1d77a9065c1dabd0f83ed1d
3,651,011
import json def login(request): """ :param: request :return: JSON data """ response = {} if request.method == 'GET': username = request.GET.get('username') password = request.GET.get('password') try: usr = models.User.objects.filter(username=username, passwo...
2d9b6791a2160ec63929d5a37e6d8336cca7709a
3,651,012
def average_win_rate(strategy, baseline=always_roll(4)): """Return the average win rate of STRATEGY against BASELINE. Averages the winrate when starting the game as player 0 and as player 1. """ win_rate_as_player_0 = 1 - make_averaged(winner)(strategy, baseline) win_rate_as_player_1 = make_averaged...
2e6b78127543456b7e931c837cf1a9468c013c33
3,651,013
def decode(chrom): """ Returns the communities of a locus-based adjacency codification in a vector of int where each position is a node id and the value of that position the id of the community where it belongs. To position with the same number means that those two nodes belongs to same community. ...
998a58e0d4efad2c079a9d023530aca37d0e226e
3,651,014
import math def bin_search(query, data): """ Query is a coordinate interval. Approximate binary search for the query in sorted data, which is a list of coordinates. Finishes when the closest overlapping value of query and data is found and returns the index in data. """ i = int(math.floor(len(data)/2)) # binar...
bb93034bc5c7e432c3fc55d4485949688e62b84a
3,651,015
def get_rating(business_id): """ GET Business rating""" rating = list( db.ratings.aggregate( [{"$group": {"_id": "$business", "pop": {"$avg": "$rating"}}}] ) ) if rating is None: return ( jsonify( { "success": False, ...
3a1cbf3e815c879b4ddaa5185477f141b261a859
3,651,016
def fwhm(x,y): """Calulate the FWHM for a set of x and y values. The FWHM is returned in the same units as those of x.""" maxVal = np.max(y) maxVal50 = 0.5*maxVal #this is to detect if there are multiple values biggerCondition = [a > maxVal50 for a in y] changePoints = [] xPoints...
2dc18d15d2940520acde39c5914413d89e9fbc71
3,651,017
import glob def parse_names(input_folder): """ :param input_folder: :return: """ name_set = set() if args.suffix: files = sorted(glob(f'{input_folder}/*{args.suffix}')) else: files = sorted(glob(f'{input_folder}/*')) for file in files: with open(file) as f: ...
10b72d9822d6c8057f9bc45936c8d1bfb1a029b6
3,651,018
from typing import Iterable from typing import Tuple from typing import Mapping from typing import Union def build_charencoder(corpus: Iterable[str], wordlen: int=None) \ -> Tuple[int, Mapping[str, int], TextEncoder]: """ Create a char-level encoder: a Callable, mapping strings into integer arrays. ...
207a5f499930f2c408ac88199ac45c60b3ed9d97
3,651,019
import struct def Decodingfunc(Codebyte): """This is the version 'A' of decoding function, that decodes data coded by 'A' coding function""" Decodedint=struct.unpack('b',Codebyte)[0] N=0 #number of repetitions L=0 # length of single/multiple sequence if Decodedint >= 0: #single N = 1 ...
450a3e6057106e9567952b33271935392702aea9
3,651,020
def _metric_notification_text(metric: MetricNotificationData) -> str: """Return the notification text for the metric.""" new_value = "?" if metric.new_metric_value is None else metric.new_metric_value old_value = "?" if metric.old_metric_value is None else metric.old_metric_value unit = metric.metric_un...
855ec000b3e37d9f54e4a12d7df4f973b15b706f
3,651,021
from typing import Optional from typing import Union from typing import List from typing import Dict def train_dist( domain: Text, config: Text, training_files: Optional[Union[Text, List[Text]]], output: Text = rasa.shared.constants.DEFAULT_MODELS_PATH, dry_run: bool = False, force_training: b...
1d1f55dca4a6274713cdd17a7ff5efcc90b46d14
3,651,022
import logging def convert_image_to_nifti(path_image, path_out_dir=None): """ converting normal image to Nifty Image :param str path_image: input image :param str path_out_dir: path to output folder :return str: resulted image >>> path_img = os.path.join(update_path('data-images'), 'images', ...
96783ad091e9b0949aa74a729b75337b9c96a0d0
3,651,023
def wav2vec2_base() -> Wav2Vec2Model: """Build wav2vec2 model with "base" configuration This is one of the model architecture used in *wav2vec 2.0* [:footcite:`baevski2020wav2vec`] for pretraining. Returns: Wav2Vec2Model: """ return _get_model( extractor_mode="group_norm", ...
fb288116f5ef57b314ecfde4a85b1a9bb5d437ce
3,651,024
from unittest.mock import patch def dont_handle_lock_expired_mock(app): """Takes in a raiden app and returns a mock context where lock_expired is not processed """ def do_nothing(raiden, message): # pylint: disable=unused-argument return [] return patch.object( app.raiden.message_ha...
2a893e7e755010104071b2b1a93b60a0417e5457
3,651,025
import sys import _warnings def _find_spec(name, path, target=None): """Find a module's spec.""" meta_path = sys.meta_path if meta_path is None: # PyImport_Cleanup() is running or has been called. raise ImportError("sys.meta_path is None, Python is likely " "shutt...
17fe8116db7f2fedd92ab98755d4e1b4971fac96
3,651,026
def system(_printer, ast): """Prints the instance system initialization.""" process_names_str = ' < '.join(map(lambda proc_block: ', '.join(proc_block), ast["processNames"])) return f'system {process_names_str};'
f16c6d5ebe1a029c07efd1f34d3079dd02eb4ac0
3,651,027
import random def genmove(proc, colour, pluck_random=True): """ Send either a `genmove` command to the client, or generate a random move until it is accepted by the client """ if pluck_random and random() < 0.05: for _count in range(100): proc.stdin.write('1000 play %s %s\n' % (colour,...
589a054be52c40507d8aba5f10a3d67489ec301b
3,651,028
def geojson_to_meta_str(txt): """ txt is assumed to be small """ vlayer = QgsVectorLayer(txt, "tmp", "ogr") crs_str = vlayer.sourceCrs().toWkt() wkb_type = vlayer.wkbType() geom_str = QgsWkbTypes.displayString(wkb_type) feat_cnt = vlayer.featureCount() return geom_str, crs_str, feat_cnt
33b0a2055ec70c2142977469384a20b99d26cee8
3,651,029
def tdf_UppestID(*args): """ * Returns ID 'ffffffff-ffff-ffff-ffff-ffffffffffff'. :rtype: Standard_GUID """ return _TDF.tdf_UppestID(*args)
1d9d5c528a2f202d49c104b7a56dd7a75b9bc795
3,651,030
def blend_multiply(cb: float, cs: float) -> float: """Blend mode 'multiply'.""" return cb * cs
d53c3a49585cf0c12bf05c233fc6a9dd30ad25b9
3,651,031
def print_data_distribution(y_classes, class_names): """ :param y_classes: class of each instance, for example, if there are 3 classes, and y[i] is [1,0,0], then instance[i] belongs to class[0] :param class_names: name of each class :return: None """ count = np.zeros(len(class_names)) pro = ...
289ada7cab00153f894e81dd32980b8d224d637c
3,651,032
import collections def reorder_conj_pols(pols): """ Reorders a list of pols, swapping pols that are conjugates of one another. For example ('xx', 'xy', 'yx', 'yy') -> ('xx', 'yx', 'xy', 'yy') This is useful for the _key2inds function in the case where an antenna pair is specified but the conjugate...
98730f8434eff02c9a63506e01fbcd478e23e76e
3,651,033
def get_machine_from_uuid(uuid): """Helper function that returns a Machine instance of this uuid.""" machine = Machine() machine.get_from_uuid(uuid) return machine
6f78afd9547af5c83abf49a1ac56209ee0e6b506
3,651,034
def convert_numbers(text): """Convert numbers to number words""" tokens = [] for token in text.split(" "): try: word = w2n.num_to_word(token) tokens.append(word) except: tokens.append(token) return " ".join(tokens)
8d6eb622076a0404824db2dbeaaba704f3bf6e79
3,651,035
def init_emulator(rom: bytes): """ For use in interactive mode """ emulator = NitroEmulator() emulator.load_nds_rom(rom, True) return emulator
9ecaa2a876b8e5bd93deece3ccc62b41ef9c6f3f
3,651,036
from typing import Dict from typing import Union import torch def sub_module_name_of_named_params(named_params: kParamDictType, module_name_sub_dict: Dict[str, str]) \ -> Union[Dict[str, nn.Parameter], Dict[str, torch.Tensor]]: """Sub named_parameters key's module name part with module_name_sub_dict. Arg...
8bbcdb865f2b0c452c773bc18767128561e806c7
3,651,037
import inspect def add_mongodb_document( m_client_db=get_mongodb_database(), collection=None, index_name=None, doc_type=None, doc_uuid=None, doc_body=None ): """ Funtion to add a MongoDB document by providing index_name, document type, document contents as doc and document id. """ status = { ...
08917c72a183d30d30d7e62ff4b5a827cf11de17
3,651,038
def my_func_1(x, y): """ Возвращает возведение числа x в степень y. Именованные параметры: x -- число y -- степень (number, number) -> number >>> my_func_1(2, 2) 4 """ return x ** y
9572566f1660a087056118bf974bf1913348dfa4
3,651,039
def indexer_testapp(es_app): """ Indexer testapp, meant for manually triggering indexing runs by posting to /index. Always uses the ES app (obviously, but not so obvious previously) """ environ = { 'HTTP_ACCEPT': 'application/json', 'REMOTE_USER': 'INDEXER', } return webtest.Test...
59343963307c39e43034664febb0ebf00f6ab1bd
3,651,040
def BNN_like(NN,cls=tfp.layers.DenseReparameterization,copy_weight=False,**kwargs): """ Create Bayesian Neural Network like input Neural Network shape Parameters ---------- NN : tf.keras.Model Neural Network for imitating shape cls : tfp.layers Bayes layers class copy_weight...
9039f70701fd832843fd160cd71d5d46f7b17b56
3,651,041
def matrix_mult(a, b): """ Function that multiplies two matrices a and b Parameters ---------- a,b : matrices Returns ------- new_array : matrix The matrix product of the inputs """ new_array = [] for i in range(len(a)): new_a...
5e0f27f29b6977ea38987fa243f08bb1748d4567
3,651,042
from typing import Tuple from typing import List from typing import Type from typing import _Final def build_type(tp) -> Tuple[str, List[Type]]: """ Build typescript type from python type. """ tokens = tokenize_python_type(tp) dependencies = [ token for token in tokens if t...
475362488b7fe07db035ce70ddb3ac40580412dd
3,651,043
def laplacian_radial_kernel(distance, bandwidth=1.0): """Laplacian radial kernel. Parameters ---------- distance : array-like Array of non-negative real values. bandwidth : float, optional (default=1.0) Positive scale parameter of the kernel. Returns ------- weight : ar...
fd5f777b0d21e3a7673a6589a76dd50f48384029
3,651,044
def build_eslog_config_param( group_id, task_name, rt_id, tasks, topic, table_name, hosts, http_port, transport, es_cluster_name, es_version, enable_auth, user, password, ): """ es参数构建 :param group_id: 集群名 :param task_name: 任务名 :param rt_id: rt...
826b8d97ef14792845b4ced98ab5dcb3f36e57f3
3,651,045
def disclosure(input_df, cur_period): """ Reading in a csv, converting to a data frame and converting some cols to int. :param input_df: The csv file that is converted into a data frame. :param cur_period: The current period for the results process. :return: None. """ input_df = pd.read_csv...
65702fa309884206f284b35c48e2e8c8a34aef2b
3,651,046
import os def get_all_file_paths(directory): """ Gets all the files in the specified input directory """ file_paths = [] for root, _, files in os.walk(directory): for filename in files: filepath = os.path.join(root, filename) file_paths.append(filepath) return ...
7055a3f3f3be5f6e0074cef55689c6234d38deb6
3,651,047
def kitchen_sink(): """Combines all of the test data.""" return word_frequencies.load(_KITCHEN_SINK_DATA)
4e0b0d38465fb02cd4f8aeb5e54c2f6bcbdf2cda
3,651,048
import torch def sim_matrix(a, b, eps=1e-8): """ added eps for numerical stability """ a = normalize_embeddings(a, eps) b = normalize_embeddings(b, eps) sim_mt = torch.mm(a, b.transpose(0, 1)) return sim_mt
d0caa5ce6e9f86b861910221321b80752b4f24e4
3,651,049
def read_addon_xml(path): """Parse the addon.xml and return an info dictionary""" info = dict( path='./', # '/storage/.kodi/addons/plugin.video.vrt.nu', profile='special://userdata', # 'special://profile/addon_data/plugin.video.vrt.nu/', type='xbmc.python.pluginsource', ) tree...
6ead602b97c12bfd78ddc7194102a84793aa631b
3,651,050
import requests def get_submission_list(start_timestamp, end_timestamp, args=None): """ Scrapes a subreddit for submissions between to given dates. Due to limitations of the underlying service, it may not return all the possible submissions, so it will be necessary to call this method again. The metho...
7fa053c27787136420a9004721c1954318deeedb
3,651,051
def loadDataSet(): """ load data from data set Args: Returns: dataSet: train input of x labelSet: train input of y """ # initialize x-trainInput,y-trainInput dataSet = [] labelSet = [] # open file reader fr = open('testSet.txt') for line in fr.readlines(): # strip() -- get rid of the space on bot...
38f42a8a7c6b12e3d46d757d98565222e931149f
3,651,052
def xds_read_xparm_new_style(xparm_file): """Parse the XPARM file to a dictionary.""" data = map(float, " ".join(open(xparm_file, "r").readlines()[1:]).split()) starting_frame = int(data[0]) phi_start, phi_width = data[1:3] axis = data[3:6] wavelength = data[6] beam = data[7:10] spac...
ba5a851c68c54aa0c9f82df1dc2334f427c8cea8
3,651,053
def clear_bit(val, offs): """Clear bit at offset 'offs' in value.""" return val & ~(1 << offs)
e50e5f8ccc3fe08d9b19248e290c2117b78379ee
3,651,054
def get_org_details(orgs): """Get node and site details, store in Org object""" org_details = [] for org in orgs: org_id = org['id'] org_name = org['name'] org_longname = org['longname'] Org = namedtuple('Org', ['org_id', 'org_name', 'org_longname']) org_details.exten...
94bec33c2fbee35210ca61f6b8d3694d198c80ee
3,651,055
import logging def flush_after(handler, delay): """Add 'handler' to the queue so that it is flushed after 'delay' seconds by the flush thread. Return the scheduled event which may be used for later cancellation (see cancel()). """ if not isinstance(handler, logging.Handler): raise TypeError(...
a8cb8197643dbd092f709bed0726d076997e4715
3,651,056
def _ExtractCLPath(output_of_where): """Gets the path to cl.exe based on the output of calling the environment setup batch file, followed by the equivalent of `where`.""" # Take the first line, as that's the first found in the PATH. for line in output_of_where.strip().splitlines(): if line.startswith('LOC:'...
6a0c0d4aa74b4e84de69de023e2721edd95c36bd
3,651,057
import math def logGamma(x): """The natural logarithm of the gamma function. Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz<BR> Applied Mathematics Division<BR> Argonne National Laboratory<BR> Argonne, IL 60439<BR> <P> References: <OL> <LI>W. J. Cody and K. E. Hillstrom, 'Chebyshev Appro...
36128e9a4b765dcc85ef42866fdbe7d16140ea1d
3,651,058
def regional_validity(query_point, regional_inclusion, regional_exclusions): """ regional_validity Returns whether a coordinate point is inside a polygon and outside of excluded regions. Input: A Point object, a Polygon Object of the inclusion region; a list of Polygon Objects of excluded regions. Output: True if t...
68e06b3d89e4783130f123d6c91dc5c43a9788ba
3,651,059
def get_word_vector_list(doc, w2v): """Get all the vectors for a text""" vectors = [] for word in doc: try: vectors.append(w2v.wv[word]) except KeyError: continue return vectors
f228c2100b6a622fdb677954257e2d1590dcc0ff
3,651,060
def solve(lines, n): """Apply the rules specified in the input lines to the starting pattern for n iterations. The number of lit pixels in the final pattern is returned. """ rules = load_rulebook(lines) pattern = START for _ in range(n): pattern = enhance(pattern, rules) return s...
781c349bfa186ac04daea60fe7e954431787ea15
3,651,061
def _to_plotly_color(scl, transparence=None): """ converts a rgb color in format (0-1,0-1,0-1) to a plotly color 'rgb(0-255,0-255,0-255)' """ plotly_col = [255 * _c for _c in mplc.to_rgba(scl)] if len(scl) == 3 else [255 * _c for _c in mplc.to_rgb(scl)] if transparence is not None: assert 0....
95b7686f913c69792e18f127176db68a3f72622f
3,651,062
def dense_attention_block(seqs_repr, is_training, num_layers, decay_variable, decay_constant, units, dropout, query_dropout, l2_scale, name=''): """ """ for i in range(num_layers): with tf.variable_scope('dense_attention{}'.format...
db50dd5e4d8d61622a9f989ec0ae9c02c5a4cfe1
3,651,063
def generate_schema_type(app_name: str, model: object) -> DjangoObjectType: """ Take a Django model and generate a Graphene Type class definition. Args: app_name (str): name of the application or plugin the Model is part of. model (object): Django Model Example: For a model wit...
b57cd78cce59dacf1fdb1d14c667405b6cfdcc90
3,651,064
def do_authorize(): """ Send a token request to the OP. """ oauth2.client_do_authorize() try: redirect = flask.session.pop("redirect") return flask.redirect(redirect) except KeyError: return flask.jsonify({"success": "connected with fence"})
1e19f501ac6da94058619e8dd5905d6cd2ab1a69
3,651,065
import re def get_windows(): """ Return all windows found by WM with CPU, fullscreen, process name, and class information. """ # Basic window information result = check_output('nice -n 19 wmctrl -l -p', shell=True) lines = [a for a in result.decode('utf8').split('\n') if a != ''] windows =...
dd0f6f702592cf7f2fdd8541959682890dcc271e
3,651,066
import google def get_google_open_id_connect_token(service_account_credentials): """Get an OpenID Connect token issued by Google for the service account. This function: 1. Generates a JWT signed with the service account's private key containing a special "target_audience" claim. 2. Sends it to t...
08e483865d26772112ffaf9837692f001598ced5
3,651,067
def term_to_atoms(terms): """Visitor to list atoms in term.""" if not isinstance(terms, list): terms = [terms] new_terms = [] for term in terms: if isinstance(term, And): new_terms += term_to_atoms(term.to_list()) elif isinstance(term, Or): new_terms += te...
6262ea7b1df124a4717d1452a23c33175b5da7a8
3,651,068
def expr_max(argv): """ Max aggregator function for :class:`Expression` objects Returns ------- exp : :class:`Expression` Max of given arguments Examples -------- >>> x = so.VariableGroup(10, name='x') >>> y = so.expr_max(2*x[i] for i in range(10)) """ return expr...
182157a627b12db6c41c79a99f135a7a493d4410
3,651,069
def handle_size(bytes_in=False, bytes_out=False): """ a function that converts bytes to human readable form. returns a string like: 42.31 TB. example: your_variable_name = make_readable(value_in_bytes) """ tib = 1024 ** 4 gib = 1024 ** 3 mib = 1024 ** 2 kib = 1024 if bytes_in: ...
6e2b3b758e1afc1cea43bbe7ac0c6179b1d32c5f
3,651,070
def return_elapsed(gs): """Returns a description of the elapsed time of recent operations. Args: gs: global state. Returns: A dictionary containing the count, minimum elapsed time, maximum elapsed time, average elapsed time, and list of elapsed time records. """ assert isinstance(gs, global_state....
af832a3bac239e24f610e39c5dee8fde6a1a25c8
3,651,071
def calculate_per_class_lwlrap(truth, scores): """Calculate label-weighted label-ranking average precision. Arguments: truth: np.array of (num_samples, num_classes) giving boolean ground-truth of presence of that class in that sample. scores: np.array of (num_samples, num_classes) giving the classi...
7cc9187f96d0899d0ce554164df553cc9b5f79a0
3,651,072
from typing import Tuple def chan_faces(n1: int, n2: int, xform, dim1: Tuple[float, float, float, float], dim2: Tuple[float, float, float, float]): """ ^y | 0--------7 | | | | | 5-----6 | | | +--|--|-------> z | | | 4-----3 ...
eb1b67dc3e0700adf1df83c7400e6fb076e0c3dd
3,651,073
import hashlib import zipfile from datetime import datetime def generate_manifest(name, p, h=None): """ generate_manifest(name, p, h) -> mapping Generates a mapping used as the manifest file. :param name: a dotted package name, as in setup.py :param p: the zip file with package content....
13c10ae405dbc6fe5acf92180e7981d07fdb9c60
3,651,074
def benchrun(methods, model, case_args, filename, cpus=1,): """ Parameters ---------- methods : list of str Voter systems to be assessed by the election model. model : func Election model running function as ...
414c96deb9a8d2f64b6808323465f8647aa5e48a
3,651,075
def retry( exceptions,times=3,sleep_second=0): """ Retry Decorator Retries the wrapped function/method `times` times if the exceptions listed in ``exceptions`` are thrown :param times: The number of times to repeat the wrapped function/method :type times: Int :param Exceptions: Lists of exceptions that trigg...
de715a0f903386358265c3fe4a13f1d91bcb177e
3,651,076
def positiveId(obj): """Return id(obj) as a non-negative integer.""" result = id(obj) if result < 0: result += _address_mask assert result > 0 return result
5d3f987c621cf3d43ac31e9300a4d54ba208a7a0
3,651,077
import zipfile import os def get_vroitems_from_package(package): """Get all the items from the vRO Package. Args: package (str): Path to a package file. Returns: VROElementMetadata[]: a list of VROElementMetadata. """ vro_items_id, vro_items = [], [] with zipfile.ZipFile(pack...
9e9257094f7da00da057dcb126b0355f2117281d
3,651,078
def compute_annualized_total_return_over_months(df, column_price, months): """ Computed the annualized total return over the specified number of months. This is equivalent to Compound Annual Growth Rate (CAGR). Note: If the period is less than one year, it is best not to use annualized total return as...
a75886ae85ab5bb146d93bd159a0a2a32f950678
3,651,079
from functools import reduce def build_sparse_ts_from_distributions(start_date, end_date, seasonalities, time_interval, dist_dict, **kwargs): """constructs a time series with given distributions and seasonalities in a given frequency time_interval""" ts_list = [] for (name, dist), seasonality in zip(dist_...
81d2ebc32a2b62ed967377faf90b3b58e7c753ff
3,651,080
def preprocess_label(labels, scored_classes, equivalent_classes): """ convert string labels to binary labels """ y = np.zeros((len(scored_classes)), np.float32) for label in labels: if label in equivalent_classes: label = equivalent_classes[label] if label in scored_classes: ...
3e2465bb0db04afaaca0576f6c97847bd0fd2b2e
3,651,081
from typing import Iterable import os from typing import cast import platform import stat def compile_on_disk(source_file: str, parser_name: str = '', compiler_suite: str = "", extension: str = ".xml") -> Iterable[Error]: """ Compiles the a source fi...
39ec45c2dc65bd9e289b7fd8726f2efd6a128085
3,651,082
import logging import yaml def load_settings(filename='settings.yaml'): """Read settings from a file. Keyword arguments: filename -- the source file (default settings.yaml) """ with open(filename, 'r') as settings_yaml: logging.debug("Reading settings from file: %s", filename) ret...
42a983d048b79f2ed5e8744ec32486b44c8f8a82
3,651,083
import math def vec_abs(field: SampledField): """ See `phi.math.vec_abs()` """ if isinstance(field, StaggeredGrid): field = field.at_centers() return field.with_values(math.vec_abs(field.values))
91395513b7e457bdfdded484db1069e8c3b95805
3,651,084
def spoofRequest(app): """ Make REQUEST variable to be available on the Zope application server. This allows acquisition to work properly """ _policy=PermissiveSecurityPolicy() _oldpolicy=setSecurityPolicy(_policy) newSecurityManager(None, OmnipotentUser().__of__(app.acl_users)) info = ...
d1b3bd1a37d69f6500d23e55b5318b6519ed04be
3,651,085
def data_to_percentage(data_list: pd.DataFrame) -> pd.DataFrame: """ Takes a dataframe with one or more columns filled with digits and returns a dataframe with the percentages corresponding to the number of times the numbers 1-9 appear in each column. Args: data_list: a dataframe of integer...
18316ddf999419290d572e77d2934241359e45a3
3,651,086
from .models.models import EncoderClassifier import torch def create_classifier_from_encoder(data:DataBunch, encoder_path:str=None, path=None, dropout1=0.5, device: torch.device = torch.device('cuda', 0), **kwargs): """Factory function to create classifier from encoder to allo...
736cfec768b6d659ab6fa1f087474a482409b66e
3,651,087
from typing import Hashable def filter_string( df: pd.DataFrame, column_name: Hashable, search_string: str, complement: bool = False, case: bool = True, flags: int = 0, na=None, regex: bool = True, ) -> pd.DataFrame: """Filter a string-based column according to whether it contains ...
9e5598a4afcff41ec5dc67c38b68efbacf3f09ec
3,651,088
from typing import List from typing import Dict from typing import Union import functools def on_demand_feature_view( features: List[Feature], inputs: Dict[str, Union[FeatureView, RequestDataSource]] ): """ Declare an on-demand feature view :param features: Output schema with feature names :param...
0ea45df22cb167ad2aa919a0be40f2a11574a69a
3,651,089
from typing import cast def get_error_string(ftdi): """ get_error_string(context ftdi) -> char * Get string representation for last error code Parameters: ----------- ftdi: pointer to ftdi_context Returns: -------- Pointer: to error string """ errstr = ftdi_get_er...
e0d3eaa19014fff9840e7a8e629651107ae25495
3,651,090
def DenseNet52k12(growth_rate = 12, reduction = 0.5): """ Parameters: ---------- Returns ------- """ return DenseNet(reduction = reduction, growth_rate = growth_rate, layers=52)
a295bcae685ae36bcbe356099d404403f7b8c0b6
3,651,091
def construct_fid_mask(catalog): """ Constructs the fidelity mask based off my results, not Robertos :param catalog: :return: """ line_widths = [i for i in range(3, 21, 2)] fid_catalog = load_table("fidelity_snr.out", start=0) fid_limit = 0.4 six_fids = [] for width in line_widt...
81f50ae4dd092482eb406bef331075245989d2f3
3,651,092
import os import sys def get_template(filename): """ return html mail template """ current_dir = os.path.dirname(__file__) tpl = read_file(os.path.join(current_dir,'templates',filename)) if not tpl: _log('Mailer error: could not load file "%s"'%filename) sys.exit(1) return ...
1a253d02c6fc90e13088d530c8e02272c8bcc28c
3,651,093
def _run_job(tgt, fun, arg, kwarg, tgt_type, timeout, retry): """ Helper function to send execution module command using ``client.run_job`` method and collect results using ``client.get_event_iter_returns``. Implements basic retry mechanism. If ``client.get_event_iter_returns`` return no results, `...
e23c189063e5d7df542d8e774acf655f4af61289
3,651,094
def _set_rank_colorbar(ax, img, norm): """ Set color bar for rankshow on the right of the ax """ divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(img, cax=cax) y_tick_values = cax.get_yticks() boundary_means = [np.mean((y_tick_values[...
f21f59ac69c79cf9449d28710abdeeb730004077
3,651,095
from typing import Optional from pathlib import Path import importlib def destination(stub: str) -> Optional[Path]: """Determine stub path Only handle micropython stubs, ignoring any cPython stdlib equivalents. """ prefix, _, suffix = stub.partition(".") if importlib.util.find_spec(prefix): ...
8b2552513dbeaa9dc09cb85703b736e17c4788b5
3,651,096
from os.path import join, isfile from wpylib.sugar import is_iterable from wpylib.file.file_utils import list_dir_entries from pyqmc.results.gafqmc_info import is_gafqmc_info def is_gafqmc_result_dir(D, files=None, dirs=None, file_pattern=None, parse_file=True): """Tests whether the directo...
938584931f4b1064dd2101e6230a134b9ce90a0b
3,651,097
def train_IPCA(X,n_dims,batch_size,model='ipca'): """ name: train_IPCA Linear dimensionality reduction using Singular Value Decomposition of centered data, keeping only the most significant singular vectors to project the data to a lower dimensional space. returns: the transformer model """...
282c885a562b5b3dbe356050ef5f270f49d7014d
3,651,098
def _str_cell(cell: Cell) -> str: """Строковое представление клетки. Данной строкой клетка будет выводится на экран. """ if cell.is_open: if cell.is_empty: return " " elif cell.value: return f" {cell.value} " elif cell.is_flagged: return "[F]" e...
2e4428196601a726b488e3ec4d966072033c5bfe
3,651,099