content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_product_type_name(stac_item): """ Create a ProductType name from a STAC Items metadata """ properties = stac_item['properties'] assets = stac_item['assets'] parts = [] platform = properties.get('platform') or properties.get('eo:platform') instruments = properties.get('instruments'...
fc7351c513eae63233b32b86fe6e5098a1571c8a
15,921
def get_show_default(): """ gets the defaults """ return SHOW_DEFAULT
88f6b202ae16155b8ec87eb566535703e33033b7
15,922
import torch def sample_langevin_v2(x, model, stepsize, n_steps, noise_scale=None, intermediate_samples=False, clip_x=None, clip_grad=None, reject_boundary=False, noise_anneal=None, spherical=False, mh=False, temperature=None, norm=False, cut=True): """Langevin Monte Carlo ...
a3dd79facb089afbeafc4e9845cf1324de75226b
15,923
def fpoly(x, m): """Compute the first `m` simple polynomials. Parameters ---------- x : array-like Compute the simple polynomials at these abscissa values. m : :class:`int` The number of simple polynomials to compute. For example, if :math:`m = 3`, :math:`x^0`, :math:`x^1` ...
335c73bf4008be1331d8f030266f5f89d072ed2c
15,924
def _function_fullname(f): """Return the full name of the callable `f`, including also its module name.""" function, _ = getfunc(f) # get the raw function also for OOP methods if not function.__module__: # At least macros defined in the REPL have `__module__=None`. return function.__qualname__ ...
eb6fd829081a4606c7be4520a15d627960360b8f
15,927
def dists2centroids_numpy(a): """ :param a: dist ndarray, shape = (*, h, w, 4=(t, r, b, l)) :return a: Box ndarray, shape is (*, h, w, 4=(cx, cy, w, h)) """ return corners2centroids_numpy(dists2corners_numpy(a))
a85122d871179a9d0fb7fa9b844caa448398184c
15,928
import math def heatmap(data_df, figsize=None, cmap="Blues", heatmap_kw=None, gridspec_kw=None): """ Plot a residue matrix as a color-encoded matrix. Parameters ---------- data_df : :class:`pandas.DataFrame` A residue matrix produced with :func:`~luna.analysis.residues.generate_residue_matrix...
99ba802f82f9425fa3946253be78730b6216d9c9
15,929
import torch def combined_loss(x, reconstructed_x, mean, log_var, args): """ MSE loss for reconstruction, KLD loss as per VAE. Also want to output dimension (element) wise RCL and KLD """ # First, binary data loss1 = torch.nn.BCEWithLogitsLoss(size_average=False) loss1_per_element = torch....
162b2706f9643f66ebb0c3b000ea025d411029e2
15,930
def isfloat(string: str) -> bool: """ This function receives a string and returns if it is a float or not. :param str string: The string to check. :return: A boolean representing if the string is a float. :rtype: bool """ try: float(string) return True except (ValueErro...
ac6d8fcbbcf6b8cb442c50895576f417618a7429
15,931
import re def parse_path_kvs(file_path): """ Find all key-value pairs in a file path; the pattern is *_KEY=VALUE_*. """ parser = re.compile("(?<=[/_])[a-z0-9]+=[a-zA-Z0-9]+[.]?[0-9]*(?=[_/.])") kvs = parser.findall(file_path) kvs = [kv.split("=") for kv in kvs] return {kv[0]: to_...
65d3711752808299272383f4b1328336ba9c463c
15,932
def user_count_by_type(utype: str) -> int: """Returns the total number of users that match a given type""" return get_count('users', 'type', (utype.lower(),))
232c4cc40ba31b4fb60f40708f2a38ae73096aea
15,933
def grouperElements(liste, function=len): """ fonctions qui groupe selon la fonction qu'on lui donne. Ainsi pour le kalaba comme pour les graphèmes, nous aurons besoin de la longueur, """ lexique=[] data=sorted(liste, key=function) for k,g in groupby(data, function): lexique.append(list(g)) return lexique
e75e8e379378ac1207ae0ee9521f630c04cff2f7
15,935
def SensorLocation_Cast(*args): """ Cast(BaseObject o) -> SensorLocation SensorLocation_Cast(Seiscomp::Core::BaseObjectPtr o) -> SensorLocation """ return _DataModel.SensorLocation_Cast(*args)
85a5a6f711c0c5d77f0b93b2e6f819bdfd466ce1
15,936
def fatorial(num=1, show=False): """ -> Calcula o fatorial de um número. :param num: Fatorial a ser calculado :param show: (opicional) Mostra a conta :return: Fatorial de num. """ print('-=' * 20) fat = 1 for i in range(num, 0, -1): fat *= i if show: resp = f'{str...
80ca60d2ba64a7089f3747a13c109de0bc7c159c
15,937
def linear_trend(series=None, coeffs=None, index=None, x=None, median=False): """Get a series of points representing a linear trend through `series` First computes the lienar regression, the evaluates at each dates of `series.index` Args: series (pandas.Series): data with DatetimeIndex as the ...
6bd09089ffd828fd3d408c0c2b03c3facfcfbd6b
15,939
def snapshot_metadata_get(context, snapshot_id): """Get all metadata for a snapshot.""" return IMPL.snapshot_metadata_get(context, snapshot_id)
8dda987916cb772d6498cd295056ef2b5465c00d
15,940
def graph_from_tensors(g, is_real=True): """ """ loop_edges = list(nx.selfloop_edges(g)) if len(loop_edges) > 0: g.remove_edges_from(loop_edges) if is_real: subgraph = (g.subgraph(c) for c in nx.connected_components(g)) g = max(subgraph, key=len) g = nx.convert_node_...
7f43531f7cbf9221a6b00a56a24325b58f60ea84
15,941
def hook(t): """Calculate the progress from download callbacks (For progress bar)""" def inner(bytes_amount): t.update(bytes_amount) # Update progress bar return inner
d8228b9dec203aaa32d268dea8feef52e8db6137
15,942
def delete(event, context): """ Delete a cfn stack using an assumed role """ stack_id = event["PhysicalResourceId"] if '[$LATEST]' in stack_id: # No stack was created, so exiting return stack_id, {} cfn_client = get_client("cloudformation", event, context) cfn_client.delete_s...
555682546aa6f1bbbc133538003b51f02e744d70
15,943
from typing import Match import six def _rec_compare(lhs, rhs, ignore, only, key, report_mode, value_cmp_func, _regex_adapter=RegexAdapter): """ Recursive deep comparison implementation "...
b7d26ed038152ee98a7b50821f3485cdc66a29d4
15,944
def exists_job_onqueue(queuename, when, hour): """ Check if a job is present on queue """ scheduler = Scheduler(connection=Redis()) jobs = scheduler.get_jobs() for job in jobs: if 'reset_stats_queue' in job.func_name: args = job.args if queuename == args[0] an...
165bb3da4746267d789d39ee30ebd9b098ea7c1e
15,945
def q_inv_batch_of_sequences(seq): """ :param seq: (n_batch x n_frames x 32 x 4) :return: """ n_batch = seq.size(0) n_frames = seq.size(1) n_joints = seq.size(2) seq = seq.reshape((n_batch * n_frames * n_joints, 4)) seq = qinv(seq) seq = seq.reshape((n_batch, n_frames, n_joints, ...
9c2035a1864e47e99ac074815199217867da0c96
15,946
def msa_job_space_demand(job_space_demand): """ Job space demand aggregated to the MSA. """ df = job_space_demand.local return df.fillna(0).sum(axis=1).to_frame('msa')
044fe6e814c2773629b8f648b789ba99bbdf0108
15,947
def get_pdf_cdf_3(corr, bins_pdf, bins_cdf, add_point=True, cdf_bool=True, checknan=False): """ corr is a 3d array, the first dimension are the iterations, the second dimension is usually the cells the function gives back the pdf and the cdf add_point option duplicated the last po...
0c6983bf6c3f77aebb7a9c667c54a560ed4a3cf0
15,948
def incidence_matrix( H, order=None, sparse=True, index=False, weight=lambda node, edge, H: 1 ): """ A function to generate a weighted incidence matrix from a Hypergraph object, where the rows correspond to nodes and the columns correspond to edges. Parameters ---------- H: Hypergraph objec...
efbac24664f30a1cd424843042d7e203a0e96c37
15,951
def initial_landing_distance(interest_area, fixation_sequence): """ Given an interest area and fixation sequence, return the initial landing distance on that interest area. The initial landing distance is the pixel distance between the first fixation to land in an interest area and the left edge of ...
b3512ea7cb149667e09c56541340122ec1dddcb1
15,952
import gzip import pickle def load_object(filename): """ Load saved object from file :param filename: The file to load :return: the loaded object """ with gzip.GzipFile(filename, 'rb') as f: return pickle.load(f)
f7e15216c371e1ab05169d40ca4df15611fa7978
15,953
from typing import Dict from typing import Tuple def list_events_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]: """Lists all events and return outputs in Demisto's format Args: client: Client object with request args: Usually demisto.args() Returns: Outputs ""...
b4e3916ee8d65a47e2128453fd042d998184ea7b
15,954
def response_map(fetch_map): """Create an expected FETCH response map from the given request map. Most of the keys returned in a FETCH response are unmodified from the request. The exceptions are BODY.PEEK and BODY partial range. A BODY.PEEK request is answered without the .PEEK suffix. A partial range (e.g. BODY...
42d992662e5bba62046c2fc1a50f0f8275798ef8
15,956
def RigidTendonMuscle_getClassName(): """RigidTendonMuscle_getClassName() -> std::string const &""" return _actuators.RigidTendonMuscle_getClassName()
8c6bd6604350e6e2a30ee48c018307bc68dea76f
15,957
import json import time import uuid def submit(): """Receives the new paste and stores it in the database.""" if request.method == 'POST': form = request.get_json(force=True) pasteText = json.dumps(form['pasteText']) nonce = json.dumps(form['nonce']) burnAfterRead = json.dumps...
3f88b665b226c81785b0ecafe3389bb15dcbeaa4
15,958
def money_recall_at_k(recommended_list, bought_list, prices_recommended, prices_bought, k=5): """ Доля дохода по релевантным рекомендованным объектам :param recommended_list - список id рекомендаций :param bought_list - список id покупок :param prices_recommended - список цен для рекомендаций :param...
edeb6c56c5ce6a2af0321aee350c5f129737cab0
15,959
import networkx def get_clustering_fips( collection_of_fips, adj = None ): """ Finds the *separate* clusters of counties or territorial units that are clustered together. This is used to identify possibly *different* clusters of counties that may be separate from each other. If one does not supply an adjacenc...
acdd6daa9b0b5d200d98271a4c989e5a5912a684
15,960
def stop_after(space_number): """ Decorator that determines when to stop tab-completion Decorator that tells command specific complete function (ex. "complete_use") when to stop tab-completion. Decorator counts number of spaces (' ') in line in order to determine when to stop. ex. "use explo...
f0ca0bb0f33c938f6a1de619f70b204e92b20974
15,961
def find_cut_line(img_closed_original): # 对于正反面粘连情况的处理,求取最小点作为中线 """ 根据规则,强行将粘连的区域切分 :param img_closed_original: 二值化图片 :return: 处理后的二值化图片 """ img_closed = img_closed_original.copy() img_closed = img_closed // 250 #print(img_closed.shape) width_sum = img_closed.sum(axis=1) # 沿宽度方向求和...
28e5e64e15cb349df186752c669ae16d01e21549
15,962
def _search(progtext, qs=None): """ Perform memoized url fetch, display progtext. """ loadmsg = "Searching for '%s'" % (progtext) wdata = pafy.call_gdata('search', qs) def iter_songs(): wdata2 = wdata while True: for song in get_tracks_from_json(wdata2): yiel...
55310c4ad05b597b48e32dde810eff9db51d66c0
15,963
import numpy def img_to_vector(img_fn, label=0): """Read the first 32 characters of the first 32 rows of an image file. @return <ndarray>: a 1x(1024+1) numpy array with data and label, while the label is defaults to 0. """ img = "" for line in open(img_fn).readlines()[:32]:...
f1d7161a0bc4d6ffebc6ee1b32eafb28c4d75f7f
15,964
import appdirs def get_config(): """Return a user configuration object.""" config_filename = appdirs.user_config_dir(_SCRIPT_NAME, _COMPANY) + ".ini" config = _MyConfigParser() config.optionxform = str config.read(config_filename) config.set_filename(config_filename) return config
192ea496f80d77f241ec6deb6a4aa4b1ef7d17cf
15,965
import asyncio import websockets def launch_matchcomms_server() -> MatchcommsServerThread: """ Launches a background process that handles match communications. """ host = 'localhost' port = find_free_port() # deliberately not using a fixed port to prevent hardcoding fragility. event_loop = a...
4c23c599a61f029972ae3e54ceb3066a4ce9f207
15,966
def acq_randmaxvar(): """Initialise a RandMaxVar fixture. Returns ------- RandMaxVar Acquisition method. """ gp, prior = _get_dependencies_acq_fn() # Initialising the acquisition method. method_acq = RandMaxVar(model=gp, prior=prior) return method_acq
5f306d104032abc993ab7726e08453d5c18f2526
15,967
import json def from_config(func): """Run a function from a JSON configuration file.""" def decorator(filename): with open(filename, 'r') as file_in: config = json.load(file_in) return func(**config) return decorator
4342a5f6fab8f8274b9dfb762be3255672f4f332
15,968
def update_user(user, domain, password=None): """ create/update user record. if password is None, the user is removed. Password should already be SHA512-CRYPT'd """ passwdf = PASSWDFILE % {"domain": domain} passwdb = KeyValueFile.open_file(passwdf, separator=":", lineformat=USERLINE+"\n") passw...
6e65be52fe0fb737c5189da295694bf482be9f5d
15,969
def puzzle_pieces(n): """Return a dictionary holding all 1, 3, and 7 k primes.""" kprimes = defaultdict(list) kprimes = {key : [] for key in [7, 3, 1]} upper = 0 for k in sorted(kprimes.keys(), reverse=True): if k == 7: kprimes[k].extend(count_Kprimes(k, 2, n)) if not...
4ad36f316a2dfa39aca9c2b574781f9199fb13ef
15,970
import warnings def periodogram_snr(periodogram,periods,index_to_evaluate,duration,per_type, freq_window_epsilon=3.,rms_window_bin_size=100): """ Calculate the periodogram SNR of the best period Assumes fixed frequency spacing for periods periodogram - the periodogram values ...
6b1f84d03796dc839cdb87b94bce69a8eef4f60e
15,971
def derivative_overview(storage_service_id, storage_location_id=None): """Return a summary of derivatives across AIPs with a mapping created between the original format and the preservation copy. """ report = {} aips = AIP.query.filter_by(storage_service_id=storage_service_id) if storage_locatio...
ab688e89c9bc9cec408e022a487d824a229a80a9
15,972
import tarfile def fetch_packages(vendor_dir, packages): """ Fetches all packages from github. """ for package in packages: tar_filename = format_tar_path(vendor_dir, package) vendor_owner_dir = ensure_vendor_owner_dir(vendor_dir, package['owner']) url = format_tarball_url(pack...
4589ce242ab8221a34ea87ce020f53a7874e73cb
15,973
def execute_search(search_term, sort_by, **kwargs): """ Simple search API to query Elasticsearch """ # Get the Elasticsearch client client = get_client() # Perform the search ons_index = get_index() # Init SearchEngine s = SearchEngine(using=client, index=ons_index) # Define t...
48ec250c6deceaca850230e4be2e0e282f5838e4
15,974
def last_char_to_aou(word): """Intended for abbreviations, returns "a" or "ä" based on vowel harmony for the last char.""" assert isinstance(word, str) ch = last_char_to_vowel(word) if ch in "aou": return "a" return "ä"
3a37e97e19e1ca90ccf26d81756db57445f68a26
15,975
def times_vector(mat, vec): """Returns the symmetric block-concatenated matrix multiplied by a vector. Specifically, each value in the vector is multiplied by a row of the full matrix. That is, the vector is broadcast and multiplied element-wise. Note this would be the transpose of full_mat * vec if full_mat r...
5b90ebd293535810c7ad8e1ad681033997e8c1c8
15,976
import pathlib def ensure_path(path:[str, pathlib.Path]): """ Check if the input path is a string or Path object, and return a path object. :param path: String or Path object with a path to a resource. :return: Path object instance """ return path if isinstance(path, pathlib.Path) else pathlib...
40cd2e1271f7f74adbf0928f769ca1a3d89acd50
15,977
def examine_mode(mode): """ Returns a numerical index corresponding to a mode :param str mode: the subset user wishes to examine :return: the numerical index """ if mode == 'test': idx_set = 2 elif mode == 'valid': idx_set = 1 elif mode == 'train': idx_set = 0 ...
4fee6f018cacff4c760cb92ef250cad21b497697
15,978
def create_pinata(profile_name: str) -> Pinata: """ Get or create a Pinata SDK instance with the given profile name. If the profile does not exist, you will be prompted to create one, which means you will be prompted for your API key and secret. After that, they will be stored securely using ``keyri...
a1b88b8bb5b85a73a8bce01860398a9cbf2d1491
15,980
def create_tfid_weighted_vec(tokens, w2v, n_dim, tfidf): """ Create train, test vecs using the tf-idf weighting method Parameters ---------- tokens : np.array data (tokenized) where each line corresponds to a document w2v : gensim.Word2Vec word2vec model n_dim : in...
8503932c2b268ff81752fb22e8640ce9413ad2e5
15,981
def miniimagenet(folder, shots, ways, shuffle=True, test_shots=None, seed=None, **kwargs): """Helper function to create a meta-dataset for the Mini-Imagenet dataset. Parameters ---------- folder : string Root directory where the dataset folder `miniimagenet` exists. shots ...
a9be1fff33b8e5163d6a5af4bd48dc71dcb88864
15,982
def process_account_request(request, order_id, receipt_code): """ Process payment via online account like PayPal, Amazon ...etc """ order = get_object_or_404(Order, id=order_id, receipt_code=receipt_code) if request.method == "POST": gateway_name = request.POST["gateway_name"] gatewa...
be5bdb027034e2f2791968755e41bbac762d1dda
15,983
def add_classification_categories(json_object, classes_file): """ Reads the name of classes from the file *classes_file* and adds them to the JSON object *json_object*. The function assumes that the first line corresponds to output no. 0, i.e. we use 0-based indexing. Modifies json_object in-place....
ef92902210f275238271c21e20f8f0eec90253b0
15,984
import copy def create_compound_states(reference_thermodynamic_state, top, protocol, region=None, restraint=False): """ Return alchemically modified thermodynamic states. Parameters ---------- ...
9ef5c14628237f3754e8522d11aa6bcbe399e1b3
15,985
def tts_init(): """ Initialize choosen TTS. Returns: tts (TextToSpeech) """ if (TTS_NAME == "IBM"): return IBM_initialization() elif (TTS_NAME == "pytts"): return pytts_initialization() else: print("ERROR - WRONG TTS")
4de36b27298d015b808cbc4973daf02354780787
15,987
def string_dumper(dumper, value, _tag=u'tag:yaml.org,2002:str'): """ Ensure that all scalars are dumped as UTF-8 unicode, folded and quoted in the sanest and most readable way. """ if not isinstance(value, basestring): value = repr(value) if isinstance(value, str): value = value...
081e0adaa45072f2b75c9eb1374ce2009bf4fd1d
15,988
import math def to_hours_from_seconds(value): """From seconds to rounded hours""" return Decimal(math.ceil((value / Decimal(60)) / Decimal(60)))
2ceb1f74690d26f0d0d8f60ffdc012b801dd6be3
15,989
def extract_named_geoms(sde_floodplains = None, where_clause = None, clipping_geom_obj = None): """ Clips SDE flood delineations to the boundary of FEMA floodplain changes, and then saves the geometry and DRAINAGE name to a list of dictionaries. :param sde_floodplains: {st...
d56b5caf8a11358db4fc43f51b8a29840698fd3a
15,990
from typing import Sequence from typing import List from typing import Any def convert_examples_to_features(examples: Sequence[InputExampleTC], labels: List[str], tokenizer: Any, max_length: int = 512, ...
f051cb9fd68aaf08da15e99f978a6bdc24fea5d3
15,992
def update_setup_cfg(setupcfg: ConfigUpdater, opts: ScaffoldOpts): """Update `pyscaffold` in setupcfg and ensure some values are there as expected""" if "options" not in setupcfg: template = templates.setup_cfg(opts) new_section = ConfigUpdater().read_string(template)["options"] setupcfg...
b08b0faa0645151b24d8eb40b2920e63caf764e9
15,994
def testable_renderable() -> CXRenderable: """ Provides a generic CXRenderable useful for testin the base class. """ chart: CanvasXpress = CanvasXpress( render_to="canvasId", data=CXDictData( { "y": { "vars": ["Gene1"], ...
3e37096e51e081da8c3fa43f973248252c0276dd
15,995
def secondSolution( fixed, c1, c2, c3 ): """ If given four tangent circles, calculate the other one that is tangent to the last three. @param fixed: The fixed circle touches the other three, but not the one to be calculated. @param c1, c2, c3: Three circles to which the other tangent circle ...
1a6aca3e5d6a26f77b1fbc432ff26fba441e02f7
15,996
def collect3d(v1a,ga,v2a,use_nonan=True): """ set desired line properties """ v1a = np.real(v1a) ga = np.real(ga) v2a = np.real(v2a) # remove nans for linewidth stuff later. ga_nonan = ga[~np.isnan(ga)*(~np.isnan(v1a))*(~np.isnan(v2a))] v1a_nonan = v1a[~np.isnan(ga)*(~np.is...
de53fcb859c8c95b1b95a4ad2ffea102a090e94e
15,997
import urllib import requests def get_job_priorities(rest_url): """This retrieves priorities of all active jobs""" url = urllib.parse.urljoin(rest_url, "/jobs/priorities") resp = requests.get(url) return resp.json()
020e825d531394798c041f32683bccfea19684c9
15,999
def create_vertices_intrinsics(disparity, intrinsics): """3D mesh vertices from a given disparity and intrinsics. Args: disparity: [B, H, W] inverse depth intrinsics: [B, 4] reference intrinsics Returns: [B, L, H*W, 3] vertex coordinates. """ # Focal lengths fx = intrinsics[:, 0] fy = int...
d476767c71fb1a8cefe121a3aaf8cbf9a19e7943
16,000
def _find_smart_path(challbs, preferences, combinations): """Find challenge path with server hints. Can be called if combinations is included. Function uses a simple ranking system to choose the combo with the lowest cost. """ chall_cost = {} max_cost = 1 for i, chall_cls in enumerate(pref...
96f55288bfa08de32badd9f1a96b3decd76573c8
16,001
def run_generator_and_test(test_case, mlmd_connection, generator_class, pipeline, task_queue, use_task_queue, service_job_manager, ...
c7f03b5db9f100c8c5eec029e843ce4ab1cdb84e
16,002
def sort_func(kd1, kd2): """ Compares 2 key descriptions :param kd1: First key description :param kd2: Second key description :return: -1,0,1 depending on whether kd1 le,eq or gt then kd2 """ _c = type_order(kd1, kd2) if _c is not None: return _c return kid_order(kd1, kd2)
2ac9100f9c69c283266cc4ba4f6d6262551ce1b5
16,003
def sumdigits(a: int): """Sum of the digits of an integer""" return sum(map(int, str(a)))
018bcc429e6ea3842fd9e9e2580820aed29bc0aa
16,004
from datetime import datetime def nth_weekday_of_month(y, m, n, w): """ y = 2020; m = 2 assert nth_weekday_of_month(y, m, -1, 'sat') == dt(2020, 2, 29) assert nth_weekday_of_month(y, m, -2, 'sat') == dt(2020, 2, 22) assert nth_weekday_of_month(y, m, 1, 'sat') == dt(2020, 2, 1) assert nth_weekd...
2f422b3fac4d97db64f541b54158248c44afad14
16,005
def getBits(val, hiIdx: int, loIdx: int) -> int: """Returns a bit slice of a value. Args: val: Original value. hiIdx: Upper (high) index of slice. loIdx: Lower index of slice. Returns: The bit slice. """ return (~(MASK_32<<(hiIdx-loIdx+1)) & (val>>loIdx))
acaf1a36fceb12ee99140aca0769dde084ee08d6
16,006
def get_hostname(): """Returns the hostname, from /etc/hostname.""" hostname = "" try: with open('/etc/hostname') as f: hostname = f.read().rstrip() if len(hostname) == 0: hostname = "Unknown" except: hostname = "Unknown" return hostname
4cd4ffc1c8c56bc2e440443fdbc315d27fb94033
16,007
def is_valid_body(val): """Body must be a dictionary.""" return isinstance(val, dict)
ef3a605e1e84ce9d74f77c07799d1abb58aaf61a
16,008
def _vba_to_python_op(op, is_boolean): """ Convert a VBA boolean operator to a Python boolean operator. """ op_map = { "Not" : "not", "And" : "and", "AndAlso" : "and", "Or" : "or", "OrElse" : "or", "Eqv" : "|eq|", "=" : "|eq|", ">" : ">", ...
a6ed0c65c6c2d2635f14fb664540eaf283ee4065
16,009
def file_diff_format(filename1, filename2): """ Inputs: filename1 - name of first file filename2 - name of second file Output: Returns a four line string showing the location of the first difference between the two files named by the inputs. If the files are identical, the fun...
c2027767ac6694620d895ef1565a03e7b706c2e7
16,010
def get_label_number(window): """This method assigns to each label of a window a number.""" mode_list = ["bike", "car", "walk", "bus", "train"] current_label_number = 0 for mode in enumerate(mode_list): if window[1] == mode[1]: current_label_number = mode[0] return current_labe...
5ed3c683e8619e1b07857992f54079bc68fdfa58
16,012
def midi_array_to_event(midi_as_array): """ Take converted MIDI array and convert to array of Event objects """ # Sort MIDI array midi = sorted(midi_as_array, key=itemgetter(2)) # Init result result = [] # Accumulators for computing start and end times active_notes = [] curr_time = 0 # For comparing velociti...
63391a1fa045f2185ce22c3ab5da186169d445e7
16,013
from typing import Dict from typing import Type def find_benchmarks(module) -> Dict[str, Type[Benchmark]]: """Enumerate benchmarks in `module`.""" found = {} for name in module.__all__: benchmark_type = getattr(module, name) found[benchmark_type.name] = benchmark_type return found
4b456a44963629da0b6072dcb9e6e8946cbaef23
16,014
def out_folder_android_armv8_clang(ctx, section_name, option_name, value): """ Configure output folder for Android ARMv8 Clang """ if not _is_user_input_allowed(ctx, option_name, value): Logs.info('\nUser Input disabled.\nUsing default value "%s" for option: "%s"' % (value, option_name)) return ...
b713642879cfcffe78fc415adbbea7c13c319925
16,015
def MCTS(root, verbose = False): """initialization of the chemical trees and grammar trees""" run_time=time.time()+600*2 rootnode = Node(state = root) state = root.Clone() maxnum=0 iteration_num=0 start_time=time.time() """----------------------------------------------------------------...
686a412c0f4cc4cd81d96872e9929d1ce51e7ed8
16,017
def update_internalnodes_MRTKStandard() -> bpy.types.NodeGroup: """定義中のノードグループの内部ノードを更新する Returns: bpy.types.NodeGroup: 作成ノードグループの参照 """ # データ内に既にMRTKStandardのノードグループが定義されているか確認する # (get関数は対象が存在しない場合 None が返る) get_nodegroup = bpy.data.node_groups.get(def_nodegroup_name) # ノードグ...
14d152377b58de842ff6cc228e80fbb0c48c5128
16,018
def _ensure_consistent_schema( frame: SparkDF, schemas_df: pd.DataFrame, ) -> SparkDF: """Ensure the dataframe is consistent with the schema. If there are column data type mismatches, (more than one data type for a column name in the column schemas) then will try to convert the data type if pos...
653f2740fa2ba090c1a1ace71b09523848d52be7
16,019
def shave_bd(img, bd): """ Shave border area of spatial views. A common operation in SR. :param img: :param bd: :return: """ return img[bd:-bd, bd:-bd, :]
4b822c5e57787edb74955fd350ad361080b8640b
16,020
def plotly_single(ma, average_type, color, label, plot_type='line'): """A plotly version of plot_single. Returns a list of traces""" summary = list(np.ma.__getattribute__(average_type)(ma, axis=0)) x = list(np.arange(len(summary))) if isinstance(color, str): color = list(matplotlib.colors.to_rgb...
b568d0e4496fc424aa5b07ff90bf45880a374d56
16,022
from pathlib import Path def create_task(className, *args, projectDirectory='.', dryrun=None, force=None, source=False): """Generates task class from the parameters derived from :class:`.Task` Fails if the target file already exists unless ``force=True`` or ``--force`` in the CLI is set. Setting the ``-...
028e751a43930e167f000d5ff0d0c76d1340cec4
16,023
def asciitable(columns, rows): """Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``. """ rows = [tuple(str(i) for i i...
d65e0dfef94060db243de2a3a4f162aa01e12537
16,024
def __resolve_key(key: Handle) -> PyHKEY: """ Returns the full path to the key >>> # Setup >>> fake_registry = fake_reg_tools.get_minimal_windows_testregistry() >>> load_fake_registry(fake_registry) >>> # Connect registry and get PyHkey Type >>> reg_handle = ConnectRegistry(None, HKEY_CURR...
70344ac3b068793a0c40e4151fb210c269dba743
16,025
def vec3f_unitZ(): """vec3f_unitZ() -> vec3f""" return _libvncxx.vec3f_unitZ()
dd0b6e28333a8d72918113b0f5caf788fb51bd43
16,026
def get_public_key(public_key_path=None, private_key_path=None): """get_public_key. Loads public key. If no path is specified, loads signing_key.pem.pub from the current directory. If a private key path is provided, the public key path is ignored and the public key is loaded from the private key. ...
f37bb64e9a0971c77986b6c82b8519153f3f8eaa
16,028
def InitializeState(binaryString): """ State initializer """ state = np.zeros(shape=(4, 4), dtype=np.uint8) plaintextBytes = SplitByN(binaryString, 8) for col in range(4): for row in range(4): binary = plaintextBytes[col * 4 + row] state[row, col] = int(binary, 2)...
b8de68bba8837865f9e74c43be1b6144774d69ad
16,029
from typing import Dict from typing import Any def _apply_modifier(s: str, modifier: str, d: Dict[Any, str]) -> str: """ This will search for the ^ signs and replace the next digit or (digits when {} is used) with its/their uppercase representation. :param s: Latex string code :param modifier: Mo...
c54a2c66ff6ee768e588b14472fa5707edf9bc56
16,030
import concurrent def threaded_polling(data, max_workers): """ Multithreaded polling method to get the data from cryptocompare :param data: dictionary containing the details to be fetched :param max_workers: maximum number of threads to spawn :return list: containing the high low metrics for each ...
587a07912b8ea6d0267638c72a98fdbeb6b0ebf0
16,031
from typing import Dict from typing import Any from typing import List def sub(attrs: Dict[str, Any], in_xlayers: List[XLayer]) -> Dict[str, List[int]]: """Return numpy-style subtraction layer registration information (shape) NOTE: https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html""" asser...
ebe4160dc92c259d2d6fd58a96eb78c697c0a5e4
16,032
import re def word_column_filter_df(dataframe, column_to_filter, column_freeze, word_list): # La fonction .where() donne une position qu'il faut transformer en index # Il faut entrer le nom d'une colonne repère (exemple: code produit) pour retrouver l'index, ou construire un colonne de re-indexée. """Filtre les c...
f58acf2188a192c1aa6cedecbfeeb66d7d073ba5
16,033
def adjust_learning_rate(optimizer, iteration, epoch_size, hyp, epoch, epochs): """adjust learning rate, warmup and lr decay :param optimizer: optimizer :param gamma: gamma :param iteration: iteration :param epoch_size: epoch_size :param hyp: hyperparameters :param epoch: epoch :param e...
c90c61fcecca99d31214c96cdf7d96b6ba682daa
16,034
import numpy as np from scipy.io import loadmat import numpy as np import h5py from numpy import fromfile, empty, append def reading_data(data_file): """ Read in a data file (16 bit) and obtain the entire data set that is multiplexed between ECG and Pulse data. The data is then extracted and appended ...
0ba4980db08a8877fabdfcc282d45c18d868a0a3
16,035
from typing import Callable def two_body_mc_grad(env1: AtomicEnvironment, env2: AtomicEnvironment, d1: int, d2: int, hyps: 'ndarray', cutoffs: 'ndarray', cutoff_func: Callable = cf.quadratic_cutoff) \ -> (float, 'ndarray'): """2-body multi-element kernel between t...
8cba89674c5e1dea999d026aad8f9b393a57f5cc
16,036