content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_extensions(dtypes): """ Find available extensions for the specified dtypes """ return _filter_entities(_tb_extensions, dtypes)
7fdfcc5919f56568db75a84e496c278cf9f86da5
3,629,800
def remove_blocks(pattern, source): """Given a pattern and a source, replace all matching blocks with a placeholder and then return the updated source and blocks as a tuple.""" blocks = {} match = pattern.search(source) while match: key = placeholder() original_block = match.group(0)...
a79ad21ba3702958c9c63c721dde3b70efa7e98f
3,629,801
def asintegerarrays(*arrays, requirements=None, min_itemsize=None): """Cast the given array(s) to the same integer type. Not a public function. This is useful when calling cython functions. Args: *arrays (array-like): At least one array-like. requirements (str/list[str], optional): S...
1c61938800ea444bd57f376076c9bd8a3597345c
3,629,802
def tune_hyperparameters(X_train, y_train, group, model, ct, param_dict, n_iter, score): """Tunes hyperparameters for a ML model with LOGO randomizedCV. Note: This function is not included in my final solution, as the time required to run it (even with GPU) takes much too long in Kaggle. Parameters ...
0abe011d3bdb922a6735f80caf472348a7838983
3,629,803
def _design_matrix(X, fit_intercept=True): """Make design matrix For ordinary linear square, it would be X.T@X, ie the Gram matrix Override it, if you need. Arguments: X {2D array} -- input data fit_intercept {bool} -- whether to add intercept to the design matrix Ret...
6c739a303af0674bbccce6dd832442f673e07016
3,629,804
def simulate_gym_user(num_days=1000, noise_frac=0.0, periodicity=3, success_prob=0.5): """ Small routine returning an artificial binary visit timeseries of a very regular user for regularity analysis. time_window: pd.DatetimeIndex, used as index for the timeseries visit_dates: List, values between 0 and...
b48b810dc527325e152a6de7200643e7699d8a2d
3,629,805
def get_new_session_notification_actions(session_id, link): """ Get the actions associated with a notification of an event getting a new session proposal. :param session_id: id of the session. :param link: link to view the session. :return: actions """ view_session_action = NotificationActio...
fe788e9c64535b29c6c563a71d4ef0a203f740f3
3,629,806
from typing import Tuple from typing import Any def pack_data(*args: Tuple[Any, str]) -> bytes: """Normalize data and pack them into a byte array""" values, abi_types = zip(*args) normalized_values = map_abi_data([abi_address_to_hex], abi_types, values) return decode_hex( "".join( ...
b9ce5c2f06edd05ab053f4d8809a845c5e01afa1
3,629,807
import json import re def _get_gh_issue_title(issue_id: int, repo_short_name: str) -> str: """ Get the title of a GitHub issue. :param repo_short_name: `current` refer to the repo_short_name where we are, otherwise a repo_short_name short name (e.g., "amp") """ repo_full_name_with_host, r...
f707b723db38a1d758ac6e6b4d3e605a9cbc878b
3,629,808
def cls_list_inputs(cls): """Return a list of inputs in a Component class""" return [k for k, v in cls.__class_traits__.iteritems() if v.iotype == 'in' and k not in Component.__class_traits__ and not v.vartypename == None]
2f4b40642822e612daf22c007726fafa407bd6d4
3,629,809
import torchvision import torch def load_trained_model(model_name=None, model_path="", class_num=10): """ Load trained model from .pth file. Supported models: * "resnet": resnet18 * "vgg": vgg11 * "inception": inception v3 * "mobilenet": mobilenet v2 """ model = None # load models if mo...
e3e47bede7b8607029b20012e360b3dc35086448
3,629,810
def get_note(identifier): """ Return a Document object for a single note instance. """ note = notes[identifier] return Document( url='/' + identifier, title='Note', content={ 'description': note['description'], 'complete': note['complete'], ...
ce193684d24e3d29595db60ba55aea70d42864f4
3,629,811
from .util import imhist from .classical import histeq from .exact import histeq_exact def contrast_restoration(im, method, remove_bits=1, blur_sigma=0, **kwargs): """ Performs contrast enhancement by degrading an image with degrade_image then performing histogram equalization to restore the original hist...
b11144382e36406df5c4aab899e7fa041f44d5cf
3,629,812
def benchmark_matrix_inverse(): """ Benchmark the user's setup by measuring the time taken by matrix inversion Performs a benchmark of the user's setup by inverting a 6400x6400 matrix filled with random numbers. This function then returns the time in ms taken for this operation. Good performan...
2821ebba8fc74a5a2c3bd34471a834f58ea14bd7
3,629,813
def psiBlastRun(sequence, cycles=2, filename=None, **kwargs): """Returns the results from a full PSI-BLAST run (multiple cycles). All arguments are the same as psiBlastCycle and are passed to it except for cycles. :arg cycles: the number of cycles to run default is 2 :type cycles: int "...
d2782d283739dcc65e6a5cf23f69e31d45ab6662
3,629,814
from pathlib import Path def filter_files(names: list[Path]) -> list[Path]: """只要文件,不要文件夹""" return [x for x in names if x.is_file()]
25c1258891e2df7c35f700a26cadf01013329337
3,629,815
from datetime import datetime def get_user_input(): """Returns validated user input for inclusion into a database.""" print('--- New appointment entry ---') while True: title = input("Appointment's title? ") if len(title) == 0: print('Title can not be empty') else: ...
f355dd2ab8332f6bcdfb21d4ee16dba47346e253
3,629,816
def send_data_frame(writer, filename, mime_type=None, **kwargs): """ Convert data frame into the format expected by the Download component. :param writer: a data frame writer :param filename: the name of the file :param mime_type: mime type of the file (optional, passed to Blob in the javascript lay...
77e725c9a2f8178bc573a987011327fdbb3bdc12
3,629,817
def find_path(node1, node2): """Finds the length of the path from node1 to node2 This is done by looking at the list of parents and finding the first common parent. """ parents1 = get_parents(node1) parents2 = get_parents(node2) for l1 in range(len(parents1)): if parents1[l1] in pa...
dd0469d6659e2f2cdc0a85e9d205b94ee656e68b
3,629,818
import os import yaml def _load_test_config(): """Loads information of the pre-configured gcp project.""" dirname, _ = os.path.split( os.path.abspath(django_cloud_deploy.tests.__file__)) config_path = os.path.join(dirname, 'integration', 'data', 'integration_test_co...
6b45d2932409ac5373a940460c01ca0884a91987
3,629,819
def load_play_bcc(): """ Play : 8 samples, 3 features, 2 classifications """ FEATURES = ['Temperature', 'Humidity', 'Pressure'] CLASSES = ['Rainy', 'Play'] data = pd.DataFrame( [ #T,H,P R,P [0, 0, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1...
a543a273331609c4c74d53d0cdf4a63644a7d8db
3,629,820
from typing import Dict from typing import Any def _pseudodata2dict(data: PseudopotentialData) -> Dict[str, Any]: """ Convert a PseudopotentialData to a compatible dict with: * Decimals replaced by strings * the required attrs set on the root * the key "coefficients" replaced with "coeffs" """...
e9feacd5f4ab51b18be92c7ea17bb9372fc59154
3,629,821
import hashlib def hashkey(key): """Returns the sha1 hash for key""" # hash keys so we don't pay the sha1 overhead each time we call this one if key not in HASH_CACHE: HASH_CACHE[key] = hashlib.sha1(str.encode(key)).hexdigest() return HASH_CACHE[key]
a301ac524299eea1bbbe684d0a6ad011ca298619
3,629,822
def get_geocoder(email): """Get geocode function for geocoding through Nominatim with supplied email address as the user_agent, as per Nominatim's usage policy. This geocoder will take at least 1 second per Address queried in accordance with Nominatim's terms of service. Note: this process cannot ...
1a2ae6ecd0d3e2607bbdaa2f24ae6615e26ddd92
3,629,823
def move_ship_waypoint(instructions: list) -> list: """Move the ship using the waypoint movement rules :param instructions: List of movement instructions :return: Final position of the ship """ waypoint = [10, 1] ship = [0, 0] for instruction in instructions: cmd, val = instruction ...
7202392e4826d522287455d94f7b06c0e2f931ee
3,629,824
def within_image_supervised_pixel_contrastive_loss( features, labels, ignore_labels, temperature): """Computes within-image supervised pixel contrastive loss. Args: features: A tensor of shape [batch_size, num_pixels, num_channels] labels: A tensor of shape [batch_size, num_pixels, 1] ignore_la...
8e121d23c0c02b97dc1ad25d0093aff8519d7074
3,629,825
def _transform_indicators(metadata: dict) -> pd.DataFrame: """Transform indicators metadata into a formatted DataFrame.""" df = pd.DataFrame.from_dict(metadata.get("indicators")) df = df[ ["id", "code", "shortName", "name", "numerator", "denominator", "annualized"] ] df.columns = [ "...
882b66cf1dbe2e1e5f1189134efec357d5983c5c
3,629,826
def symmetricMatrix(seq): """ creates a symmetric 3x3 matrix from a sequence (list, tuple, Matrix) with 6 elements """ assert isinstance(seq, (list, tuple, symbolics.Matrix)) M=symbolics.Matrix([[seq[0], seq[1], seq[3]], [seq[1], seq[2], seq[4]], ...
0b90a12fc0d95b412b142dcbe19dfa7e2910948a
3,629,827
import ray def get_actor(name: str) -> ray.actor.ActorHandle: """Get a named actor which was previously created. If the actor doesn't exist, an exception will be raised. Args: name: The name of the named actor. Returns: The ActorHandle object corresponding to the name. """ l...
6856200cf1ee61d3f0e069c048189f37dc0d06ff
3,629,828
import itertools def get_hyperparams_combinations(hyperparams): """Get list of hyperparmeter (dict) combinations.""" # transforms tuning hyperparams to a list of dict params for each option return [ {k:v for k,v in zip(hyperparams.keys(), hypms)} for hypms in itertools.product(*[...
e5f52a8eddb8a2a476e0daa47f63161d440263f2
3,629,829
import os def import_curves_data_csv_file(): """ Import user curves data CSV file as a *Nuke* *ColorLookup* node. Returns ------- ColorLookup ColorLookup node. """ file = nuke.getFilename('Choose ColorLookup Node Curves Data CSV File', '*.csv') if ...
61b9842bf8b26b7024955827d1784ac1e536a326
3,629,830
from typing import Tuple def get_cropped_axes(image: np.ndarray, boundary_width: int = 5) -> Tuple[slice, ...]: """ Return the min and max values on both x and y axes where the image is not empty Method: find the min and max of all non-zero pixels in the image, and add a border :param image: the image...
9650f114cc9637e09550956c92a29a28d0062147
3,629,831
def addressable_list(type_constraint): """Marks a list's values as satisfying a given type constraint. Some (or all) elements of the list may be :class:`pants.engine.exp.objects.Resolvable` elements to resolve later. See :class:`AddressableDescriptor` for more details. :param type_constraint: The type cons...
b0769cd11cb4c15e4f1b585141809a5b715a16bf
3,629,832
def user(): """Returns a user with name='mesh', token='token', trakt={'trakt': 'auth'}""" return User('mesh', 'token', {'trakt': 'auth'})
d73d4ae88af53c5b315dcad99510028c75052e6b
3,629,833
from datetime import datetime import json import logging def convert_from_poolfile_to_sequence_set_and_back(inp_fp_path, op_path, conversion_type, description="", run_id=None): """ In this function we take either pool file or Sequence Set and convert from one to the other. Sequence Set is out...
ad46eb491840aa75764b013495a113ae746144ba
3,629,834
from typing import List def read_basis_format(basis_format: str) -> List[int]: """Read the basis set using the specified format.""" s = basis_format.replace('[', '').split(']')[0] fss = list(map(int, s.split(','))) fss = fss[4:] # cp2k coefficient formats start in column 5 return fss
9701309ab43eb7a0227aa141653688dbdce40811
3,629,835
def _central_crop(image_list, crop_height, crop_width): """Performs central crops of the given image list. Args: image_list: a list of image tensors of the same dimension but possibly varying channel. crop_height: the height of the image following the crop. crop_width: the width of the image foll...
16481f8db0be53b08fe3b4d4173ae3c9bd71ceb2
3,629,836
def concat_combining_function(a, b): """ Combines the tensor `a` and `b` by concatenating them. :param a: the tensor a :type a: tf.Tensor :param b: the tensor b :type b: tf.Tensor :return: a combination of the tensors :rtype: tf.Tensor """ if a.shape.rank == 2: a = tf.ex...
6c96fac311ef4085f282e8419ffa8d7b98ad38ed
3,629,837
def filter_list_zones(auth_context, cloud_id, zones=None, perm='read', cached=False): """Filter the zones of the specific cloud based on the RBAC policy""" if zones is None: zones = list_zones(auth_context.owner, cloud_id, cached=cached) if auth_context.is_owner(): retu...
11e1d099d1af9f46379f6c8f4f6b63d3d9bf4280
3,629,838
def pixel_weighted_categorical_crossentropy(weights,target, output, from_logits=False, axis=-1): """ pixel weighted version of tf.keras.backend.categorical_crossentropy copy of https://github.com/tensorflow/tensorflow/blob/v2.3.1/tensorflow/python/keras/backend.py#L4640-L4708 except for last line where wei...
f54117bd362ff0e3e01d77f16650f98bd832402a
3,629,839
def auth_required(f): """ Decorator for aiohttp web handlers with primitive auth check """ @wraps(f) async def _wrapper(request): if 'auth' not in request: raise HTTPUnauthorized() return await f(request) return _wrapper
03a71418314b1caf7f40d95c41a6386f8d4eb10e
3,629,840
def p_to_stars(p, thres=(0.1, 0.05, 0.01)): """Return stars for significance values.""" stars = [] for t in thres: if p < t: stars.append("*") return "".join(stars)
d88c2fd6c1b4e2d75a9cb664dfc10fab308bc6ee
3,629,841
def permuteToBlocks(arr, blockshape): """Permute an array so that it consists of linearized blocks. Example: A two-dimensional array of the form 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 would be turned into an array like this with (2, 2) blocks: ...
b5edc7c64ed3facf39354e7c38955cd5e218d3a3
3,629,842
from typing import Iterable from typing import Dict from typing import Tuple def _polygonise_splits( arr: np.ndarray, named_slices: Iterable[Dict[str, Tuple]] ) -> Dict[str, gpd.GeoDataFrame]: """ Create polygons from multiple sub-arrays of the given array. Note: Indices for `named_slices` mu...
41eea39a96e1dbacb161c4e160ae73ed49762deb
3,629,843
import warnings def getPointInTheMiddle(start_point, end_point, time_diff, point_idx): """ Calculates a new point between two points depending of the time difference between them and the point index. Parameters ---------- start_point: DataFrame end_point: DataFrame time_diff: float ...
b5b76bbb1bc4b5cb37e5959b009106d1d50369a6
3,629,844
def get_style_dependencies(style_name=None, base_url=DEFAULT_BASE_URL): """Get the values of dependencies in a style. Args: style_name (str): Name of style; default is "default" style base_url (str): Ignore unless you need to specify a custom domain, port or version to connect to th...
8d297294c7f5da5f4f2bbea80c659a57e2207aba
3,629,845
import logging def bpt_nii(maps, ax = None, snr_min = None, deredden = False, return_figure = True, plot_map = False, plot_kde = False, radial_bin = None, return_data = None, overplot_dk_bpt = False, dk_bpt_k...
a45801c3672cae2750133dbf7011dd7dfad50b3d
3,629,846
def correct_dcm(dcm): """ Correct DCM image which were actually signed data, but were treated as unsigned """ x = dcm.pixel_array + 1000 px_mode = 4096 x[x>=px_mode] = x[x>=px_mode] - px_mode dcm.PixelData = x.tobytes() dcm.RescaleIntercept = -1000 return dcm.pixel_array, dcm.RescaleIntercep...
0186ab3fc4b606902da3a50a5835eb227a1b7733
3,629,847
def multiaz_subnets( name_prefix: str, cidr_block: str, region: str, vpc: object = None, vpc_id: str = None, no_of_subnets: int = 4, network_acl: object = None, network_acl_id: str = None, route_table: object = None, route_table_id: str = None, ) -> list: """Split given CIDR ...
58cd2d5eea2873683202907a1c91dc4dbefcb9d6
3,629,848
def EPdiv(a, da, b, db, covar=0): """ C = A / B """ return ( a / b, np.sqrt( ((da / b) ** 2 + ((a ** 2) * (db ** 2) / (b ** 4))) - (2 * covar * a / (b ** 3)) ), )
ec8fa19845e4c014c271badfba3d7ad6a503e096
3,629,849
def factorial_r(number): """ Calculates the factorial of a number, using a recursive process. :param number: The number. :return: n! """ # Check to make sure the argument is valid. if number < 0: raise ValueError # This is the recursive part of the function. if number == 0...
e5c28edac93b965f438bd61c5bb1c0a935c96700
3,629,850
def obstacles_to_grid(obstacles): """ Transforms a list of obstacles into an m x n grid where 1 represents the cell is covered by an obstacle and 0 represents no obstacle. m and n are derived by the canvas height/width and grid width. The assumption is that the obstacles fall precisely on grid lines. ...
15034a36bda253d6b045926291c2996c5867b272
3,629,851
def get_gps_data(filename, traversal_id): """ Gets GPS time series gathered from a traversal :param filename: <String> csv file from GPS team in format |date|time|name|latitude|longitude|heading :return: <pandas DataFrame> time_stamp|latitude|longitude """ delimiter = r"\s+" # some of the column...
2aeaa6b06025951c48cb9213dd9994d0e1dbb61d
3,629,852
def infection_rate_symptomatic_30x60(): """ Real Name: b'infection rate symptomatic 30x60' Original Eqn: b'Susceptible 60*Infected symptomatic 30x60*contact infectivity symptomatic 30x60*(self quarantine policy SWITCH self 60\\\\ *self quarantine policy 60+(1-self quarantine policy SWITCH self 60))/non cont...
af8f774612cfd866b6931690ecff9c986f415769
3,629,853
def compute_rewards(rl_batch, batch_actions, episode_lengths, batch_size=None): """Compute rewards for each episode in the batch. Args: rl_batch: A data.RLBatch instance. This holds information about the task each episode is solving, and a reward function for each episode. batch_actions: ...
6d757007f74552421648f19dfd915a306bc68d86
3,629,854
def _translate_args(t=tuple(), d=dict(), unfreeze=False): """ _make_wrapper_argsでラッパー関数を作成する際の補助関数。 関数呼び出しを行うS式の引数部分に埋め込む文字列を作成する。 e.g.) (func)なるS式を送り込む場合 ""を生成することを担当する。 (func args)なるS式を送り込む場合 " args"を生成することを担当する。(冒頭のスペースに留意) 文字列を埋め込む際変数は適切に評価を行ってから埋め込む。 Euslispにはハッシュのリテラル表現はな...
25ca61d7a0682ad817a2b4d6a4103ad25ba47fbe
3,629,855
def merge_date_time2(data, date_column, time_column=None): """This method merges columns date and time .. note: If time is missing default is 00:00. .. note: Also convert date using dt.apply(str). import datetime datetime.time.fromisoformat() Parameters ---------- Returns -------...
3d4ecf8e67b7bfa3cb3b967332c1878f8a1d7293
3,629,856
def logistic(x): """ A function that returns a value between 0 and 1 for x in the range [0, infinity] and -1 to 1 for x in the range [-infinity, infinity]. Useful for cost functions. """ return 2.0 / (1 + exp(-x)) - 1.0
39c45ebbcef74c11bbb4bd554757b0c738dfc99e
3,629,857
def make_perturbed_cmtsolution(py, src_frechet_directory, cmtsolution_directory, output_directory): """ make the pertured cmtsolution based on src_frechet. """ script = f"ibrun -n 1 {py} -m seisflow.scripts.source_inversion.make_perturbed_cmtsolution --src_frechet_directory {src_frechet_directory} --cmt...
07bb69751ddaee9d7aa6389c6cab9bc6021758ed
3,629,858
def weight_correct_incorrect(rslt): """Return a pair of floating-point numbers denoting the weight of (correct, incorrect) instances in EvaluationResult rslt. >>> listInstCorrect = [Instance([],True,0.25)] >>> listInstIncorrect = [Instance([],False,0.50)] >>> rslt = EvaluationResult(listInstCorrect, listInstIncor...
5a7ef1d338821f10b58ba06224059e532180c50d
3,629,859
import pathlib import csv def get_data_info(path): """ Get metadata of the iamges. """ samples = [] # the data is in subfolders parent = pathlib.Path(path) for csv_file in parent.glob('**/*.csv'): with open(str(csv_file), 'r') as f: reader = csv.reader(f) f...
53f3dd1b6ff18d43a656f4a3f6da26ab1e60a6c2
3,629,860
import math def BmatPRV(q): """ BmatPRV(Q) B = BmatPRV(Q) returns the 3x3 matrix which relates the body angular velocity vector w to the derivative of principal rotation vector Q. dQ/dt = [B(Q)] w """ p = np.linalg.norm(q) c = 1 / p / p * (1 - p / 2 / math.tan(p / 2)) B...
f1977d5eb0c3913454dd692861c8f32e80fbb035
3,629,861
import random def shuffle(x, y): """ Shuffle the datasets. """ for n in range(len(x) - 1): rnd = random.randint(0, (len(x) - 1)) x1 = x[rnd] x2 = x[rnd - 1] y1 = y[rnd] y2 = y[rnd - 1] x[rnd - 1] = x1 x[rnd] = x2 y[rnd - 1] = y1 y[rnd...
c9f198d3796c5d64eba818753701957ea1a0e924
3,629,862
from typing import FrozenSet def induced_subgraph(G: Graph, S: FrozenSet[Ind]) -> Graph: """ Generate the subgraph of G induced by the set of nodes S. See Also -------- https://en.wikipedia.org/wiki/Induced_subgraph Parameters ---------- G : Graph S : Set of nodes Returns ...
488a97e278abb8961abaf4b889525123d5588ab8
3,629,863
import os import base64 def getKey(key, namespace=None): """Returns a key.""" app_id = os.environ.get('APPLICATION_ID', '') if app_id: app_id += '.' if namespace: key = '%(namespace)s.%(key)s' % locals() key = '%(app_id)s%(key)s' % locals() return base64.b64encode(key)
d29c091d7c22391b4a364e9b9be65790fa4fa15f
3,629,864
def make_peptide_bond(mol, res = None, start = "N", end = "C", delete = "OXT"): """Performs one condesation rxn between a molecule and residue/itself default creates peptide bond Parameters ---------- mol : rdkmol Main molecule on which reaction is performed res : rdkmol ...
fcf167b259a016ebaf0b82d2cee219f1c24646ce
3,629,865
def get_data_names(data, data_names): """ Get default names for data fields if none are given based on the data. Examples -------- >>> import numpy as np >>> east, north, up = [np.arange(10)]*3 >>> get_data_names((east,), data_names=None) ('scalars',) >>> get_data_names((east, nort...
e2097d6dbf2c8cc52fd4a60124727cad5fe9fbc4
3,629,866
import pandas def get_labels_from_file(filename): """Get labels on the last column from file. Args: filename: file name Returns: List[str]: label list """ data_frame = pandas.read_csv(filename) labels = data_frame['summary'].tolist() return labels
605e9a464eb9fc007d2421fadcab362b7c22ebf5
3,629,867
def css3_lists(): """Return a list of all css3 color names, and a corresponding list of the colors' RGB values.""" css3_db = CSS3_HEX_TO_NAMES names = [] rgb_values = [] for color_hex, color_name in css3_db.items(): names.append(color_name) rgb_values.append(hex_to_rgb(color_hex)) ...
f1656566f8099b2dd5cc9f5c5662d45e9e820f84
3,629,868
from typing import Union def kmeans( embedding: np.ndarray, n_clusters: int = 1, init: Union[str, np.ndarray] = 'k-means++', n_init: int = 10, max_iter: int = 300, tolerance: float = 0.0001, precompute_distances='auto', verbose: int = 0, random_s...
4738a2b9b77c8812017b37cce0d80c0d028854c2
3,629,869
import six from datetime import datetime def get_json_struct(jsonobj, template=None): """ :param jsonobj: Object to parse and adjust so could be loaded into big query :param template: An input object to use as abasis as a template defaullt no template provided :return: A json object that is a templ...
f4c505fa6a593ab9fa1df5ab47f986f11f854d57
3,629,870
import logging def pin_to_cpu(op): """Returns a CPU device for the given node.""" device = op.device if op.device is not None else "" dev = pydev.from_string(device) if not dev.device_type: return set_cpu0(device) if dev.device_type == "CPU": return device logging.info("Operation %s has been ass...
0b9f248e53f2df5e26945bb0bfb5bac2544d1d45
3,629,871
def build_df(data): """ Creates and returns a pandas DataFrame from the given pandas Series with the original index as a column. It also extracts and returns the original column and index name to restore the DataFrame to its original column and index name. :param data: pandas Series :return: tu...
0f34a6787a452b6d4e1cbcf2d99807c0e7d75141
3,629,872
def _map_spectrum_weight(map, spectrum=None): """Weight a map with a spectrum. This requires map to have an "energy" axis. The weights are normalised so that they sum to 1. The mean and unit of the output image is the same as of the input cube. At the moment this is used to get a weighted exposure...
c27b1c342e51ed47270648f8598b6f66c3538f23
3,629,873
def clean_date_metadata(df): """Clean the collection and submission date metadata """ df.loc[:, "collection_date"] = df["covv_collection_date"].astype(str).str.strip() df.loc[:, "submission_date"] = df["covv_subm_date"].astype(str).str.strip() # Filter out really unspecific collection dates # ...
6b407c57cc998dee31d2f169c9f45a91a125a1a8
3,629,874
def countries_reaction(t, react_time, top_countries): """ Computes how long a country takes to react once the deceased limit is exceeded. Parameters ---------- t : int Simulation instant. react_time : int Parameter of the exponential distribution. top_countries : list ...
b75402686250de48f5bafd8f0f4c5ca6a1251708
3,629,875
import struct import numpy as np def binaryread_struct(file, vartype, shape=(1), charlen=16): """ Read text, a scalar value, or an array of values from a binary file. file is an open file object vartype is the return variable type: str, numpy.int32, numpy.float32, or numpy.float64 ...
c9e718e929598560206f2ee73a2b92f9347be5d6
3,629,876
def flatten_and_structure_dimensions(op, parameters, number_of_dimensions=None): """ Unrolls nested lists into one flat lists, applies the operation and rolls the resulting flat list back into nested lists. ---------- op : Operation to apply to the tuple of flat lists, resulting in one flat list. parame...
0e52c8f19204a064bf73b15276fde8820263135f
3,629,877
from typing import Any def create_result_scalar(name: str, item_type: str, value: Any) -> dict: """ Create a scalar result for posting to EMPAIA App API. :param name: Name of the result :param item_type: Type of result :param value: Value of the result """ result = {"name": name, "type": ...
3fb16c540cc8c76cfc42e4a906e4be280346b802
3,629,878
def create_edge(source_id, target_id, relationship_type, vitrage_is_deleted=False, update_timestamp=None, metadata=None): """A builder to create an edge :param update_timestamp: :param source_id: :type source_id: str :p...
e6a367ec0d05fbbe92a1f763d3039c2e02bf8b9d
3,629,879
def hg_ui_with_checkers(hg_ui, checkers): """Get test mercurial ui with checkers config set up.""" for key, value in checkers.items(): hg_ui.setconfig('hg_commit_sanity', key, value) hg_commit_sanity.reposetup(hg_ui, hg_repo) return hg_ui
c818ac9b77505cc6bee54a06db4b8b1556a96ba7
3,629,880
def get_inbox_status(): """Return current inbox status""" emails = get_inbox_emails(EMAIL) new = get_new_emails(emails) (direct, cced) = get_direct_emails(emails, MY_EMAILS) nb_total = len(emails) nb_direct = len(direct) nb_cced = len(cced) nb_total_new = get_nb_new(new) nb_direct...
444772b165b9cd9d868e7599b6eea5d71226ea52
3,629,881
def fill_correlation_matrix(c_vec): """ Create a Theano tensor object representing a correlation matrix of a multivariate normal distribution. :param c_vec: PyMC3 model variable corresponding to the `LKJCorr` prior on elements of the correlation matrix :return: correlation matrix...
e32037b7ce573c1a9faefab5b57f771ea7cd90a2
3,629,882
def find_isomorphism(G1, G2): """Search for isomorphism between two graphs Args: G1 (networkx.Graph) G2 (networkx.Graph) Returns: If no isomorphism is found, returns None. Otherwise, returns dict with keys as nodes from graph 1 and values as corresponding nodes fro...
b1688167e805f454150284ba557bd731aef37500
3,629,883
def list_bancos(request): """ Lista Bancos""" usuario = request.user dados = {} try: funcionario = Funcionario.objects.get(usuario_fun=usuario) except Exception: raise Http404() if funcionario: #id pesquisa termo_pesquisa = request.GET.get('pesquisa', None) ...
2a56d07314d08cae1516a9db8514688a5b5b413f
3,629,884
def encode_jwt_token(data, api_secret_code=None): """ Encode Python dictionary as JWT token. :param data: Dictionary with payload. :param api_secret_code: optional string, application secret key is used by default. :return: JWT token string with encoded and signed data. """ if api_secret_cod...
a934b94687c7767bff9e5f8403f14c1ca9dae5ae
3,629,885
import logging def setup(): """Performs setup tasks for the program. Creates and configures a logger, creates and configures a webdriver and creates and configures a sqlite database connection. Returns: A Chromium based Selenium webdriver. """ logger_helper() db_helper() ...
5ebb01c2e8a8a4a6325d3d420ad35fa82e9056eb
3,629,886
from typing import Union from typing import Sequence from typing import Hashable from typing import Callable from typing import Iterable import PIL def handwrite( text: str, template: Union[Template, Sequence[Template]], seed: Hashable = None, mapper: Callable[[Callable, Iterable], Ite...
27552d307f964f274e4c6080f183c3e99be0c3c0
3,629,887
def printMathExp(btree: BinaryTree) -> str: """Print the whole math expression""" s = '' if btree is not None: if btree.left is not None: s += '(' s += printMathExp(btree.left) s += str(btree.key) s += printMathExp(btree.right) if btree.right is not None: ...
e7499d99ec55785f1a2e8744b90ddd3f1d0acdf5
3,629,888
import os import time import requests def download_from_url(url: str, file_path='', attempts=28): """Downloads a URL content into a file (with large file support by streaming) :param url: URL to download :param file_path: Local file name to contain the data downloaded :param attempts: Number of attem...
c0b6eeef5711dcfffeab7d8fc2760743bf1a0eda
3,629,889
import logging def create_presigned_url(bucket_name, bucket_key, expiration=3600, signature_version=s3_signature['v4']): """Generate a presigned URL for the S3 object :param bucket_name: string :param bucket_key: string :param expiration: Time in seconds for the presigned URL to remain valid :para...
2d3198cd7db5f09ab08a8a1e0abcaa1d85adf288
3,629,890
import os def setup(): """Load all resources.""" quote_files = ['./_data/DogQuotes/DogQuotesTXT.txt', './_data/DogQuotes/DogQuotesDOCX.docx', './_data/DogQuotes/DogQuotesPDF.pdf', './_data/DogQuotes/DogQuotesCSV.csv'] quotes = [] for in_file in...
a21818600ae0d9c7bc3dd4d95c44638114480d00
3,629,891
def softmax_op(node, ctx=None): """ This function computes its softmax along an axis. Parameters: ---- node : Node Input variable. Returns: ---- A new Node instance created by Op. """ return SoftmaxOp(node, ctx=ctx)
5cca012944bb41364cc41b3311d9b6a9ce386d55
3,629,892
def circle_fit(coords): """ Find the least squares circle fitting a set of 2D points ``(x,y)``. Parameters ---------- coords : (N, 2) ndarray Set of ``x`` and ``y`` coordinates. Returns ------- centre_i : (2,) The 2D coordinates of the centre of the circle. r_i : do...
cac5275b1b3d59040c0acc94c12e492d78dfd647
3,629,893
import http def dispatcher(request, slug, view_name, *args, **kwargs): """Dispatcher that loads configuration corresponding to `slug` and dispatches view corresponding to `view_name` on said configuration. The configuration will be added to the `extra_context` attribute of all dispatched views. ...
70c672b6802e71c7151a202a107cb5f722d7ba0c
3,629,894
def LayerSet_toLayers(ifc_file): """ Returns a dictionary where keys are the Id of the IfcMaterialLayerSet and where the values are a list (ListOfLayers) with an element per material layer. The material layer information is stored at the same time within a list containing Id (number), material and t...
eaac63c2ee264e32dcf885036671a97bdffd50ba
3,629,895
def conv2d_annotate_fn(expr): # pylint: disable=unused-variable """Check if nn.conv2d is supported by TensorRT.""" attrs, args = expr.attrs, expr.args if not is_supported_trt_dtype(args): return False if not isinstance(args[1], Constant): logger.info("nn.conv2d: kernel argument must be...
b5567d4369e9f9eeaabbacb34e9b6ae7554a4d41
3,629,896
from google.cloud import bigquery from typing import List from datetime import datetime def create_bq_view_of_joined_features_and_entities( source: BigQuerySource, entity_source: BigQuerySource, entity_names: List[str] ) -> BigQuerySource: """ Creates BQ view that joins tables from `source` and `entity_so...
358d8f3b6d3ba98ed1b431c6c201ffdc7d3e30da
3,629,897
import sqlite3 def get_db(): """Connect to the application's configured database. The connection is unique for each request and will be reused if this is called again. """ if "db" not in g: g.db = sqlite3.connect( current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLT...
95bcd9e7338b402c040307e02d5dbbe4893453f8
3,629,898
import struct def _go_test_impl(ctx): """go_test_impl implements go testing. It emits an action to run the test generator, and then compiles the test into a binary.""" go = go_context(ctx) # Compile the library to test with internal white box tests internal_library = go.new_library(go, test...
e6f5b5fd0cde681809495db4bfc9eb9fe4fe106c
3,629,899