content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_valid_action(state, x, y, direction): """ Checks if moving the piece at given x, y coordinates in the given direction is valid, given the current state. :param state: the current state :param x: the x coordinate of the piece :param y: the y coordinate of the piece :param direction: the d...
9be9d6a16d6ec3f766ee7f91c08d3ced7d5ff6b8
3,655,103
def range_(minimum, maximum): """ A validator that raises a :exc:`ValueError` if the initializer is called with a value that does not belong in the [minimum, maximum] range. The check is performed using ``minimum <= value and value <= maximum`` """ return _RangeValidator(minimum, maximum)
27dc9c9c814371eb03b25f99be874e39d48c1a52
3,655,104
def sigmoid_prime(z): """Helper function for backpropagation""" return sigmoid(z) * (1 - sigmoid(z))
13541050982152668cdcec728f3a913298f2aad8
3,655,105
def register_widget_util(ui_name, some_type, gen_widgets, apply_with_params): """ ui_name: the name of this utility in the UI some_type: this utility will appear in the sidebar whenever your view function returns a value of type ``some_type`` gen_widgets(val): a function that takes the report valu...
25273753e0e31472cc44ef3527200e9dfa797de2
3,655,106
from datetime import datetime def _CreateSamplePostsubmitReport(manifest=None, builder='linux-code-coverage', modifier_id=0): """Returns a sample PostsubmitReport for testing purpose. Note: only use this method if the exact values don't matter. ...
5c7bccda2648f4d8d26725e983a567d5b011dbb6
3,655,107
import typing def _fetch_measurement_stats_arrays( ssc_s: typing.List[_NIScopeSSC], scalar_measurements: typing.List[niscope.ScalarMeasurement], ): """ private function for fetching statics for selected functions. Obtains a waveform measurement and returns the measurement value. This method ma...
4acad87bc9b0cd682725ea5edcade10d996653a1
3,655,109
def generate_repository_dependencies_folder_label_from_key( repository_name, repository_owner, changeset_revision, key ): """Return a repository dependency label based on the repository dependency key.""" if key_is_current_repositorys_key( repository_name, repository_owner, changeset_revision, key ): la...
5654b29354b07f9742ef1cdf20c313ecbcfec02f
3,655,111
def weighted_characteristic_path_length(matrix): """Calculate the characteristic path length for weighted graphs.""" n_nodes = len(matrix) min_distances = weighted_shortest_path(matrix) sum_vector = np.empty(n_nodes) for i in range(n_nodes): # calculate the inner sum sum_vector[i] = (1/(n_nodes-1)) *...
ff171ad9bf7a6968ebf9d41dd5c508bb8b39b16a
3,655,112
def mean_IoU(threshold=0.5, center_crop=0, get_batch_mean=True): """ - y_true is a 3D array. Each channel represents the ground truth BINARY channel - y_pred is a 3D array. Each channel represents the predicted BINARY channel """ def _f(y_true, y_pred): y_true = fix_input(y_true) y_...
0c9ee55b694e11615bd6ab023ce1f43354b986b1
3,655,114
import csv def ConvertCSVStringToList(csv_string): """Helper to convert a csv string to a list.""" reader = csv.reader([csv_string]) return list(reader)[0]
fa244d2a1c8c50b2b097883f964f1b5bb7ccf393
3,655,115
def get_section_range_pairs(orig_section, new_pdf): """Return MatchingSection for a section.""" other_section = new_pdf.find_corresponding_section(orig_section) if not other_section: print("Skipping section {} - no match in the other doc!".format( orig_section.title)) return None...
ff1ef7bedcc0a1264a8cd191267d35a75c302eac
3,655,116
import sqlite3 from typing import Any import logging def atomic_transaction(conn: sqlite3.Connection, sql: str, *args: Any) -> sqlite3.Cursor: """Perform an **atomic** transaction. The transaction is committed if there are no exceptions else the transaction is rolled back. Args...
9748a6e315521278c4dc60df891081dcd77c98b9
3,655,117
def convert_to_tensor(narray, device): """Convert numpy to tensor.""" return tf.convert_to_tensor(narray, tf.float32)
699f4cbdad83bc72525d237549420e67d0d464f8
3,655,118
def get_instance_ip() -> str: """ For a given identifier for a deployment (env var of IDENTIFIER), find the cluster that was deployed, find the tasks within the cluster (there should only be one), find the network interfaces on that task, and return the public IP of the instance :returns: str The pu...
6b52f6c385e2d96e500458397465f67550a0deeb
3,655,120
def is_hign_level_admin(): """超级管理员""" return is_admin() and request.user.level == 1
7faa7872f556307b67afd1e5604c104aa6aa242d
3,655,121
def object_metadata(save_path): """Retrieves information about the objects in a checkpoint. Example usage: ```python object_graph = tf.contrib.checkpoint.object_metadata( tf.train.latest_checkpoint(checkpoint_directory)) ckpt_variable_names = set() for node in object_graph.nodes: for attribute i...
8a01cc2a60298a466921c81144bfbd9c4e43aa97
3,655,122
async def login(_request: Request, _user: User) -> response.HTTPResponse: """ Login redirect """ return redirect(app.url_for("pages.portfolios"))
375452df081f619db9c887359b6bb0217aa8e802
3,655,123
def delete_source(source_uuid: SourceId, database: Database): """Delete a source.""" data_model = latest_datamodel(database) reports = latest_reports(database) data = SourceData(data_model, reports, source_uuid) delta_description = ( f"{{user}} deleted the source '{data.source_name}' from me...
f160a8304df54a20026155f1afb763c0077d05a9
3,655,124
def find_object_with_matching_attr(iterable, attr_name, value): """ Finds the first item in an iterable that has an attribute with the given name and value. Returns None otherwise. Returns: Matching item or None """ for item in iterable: try: if getattr(item, attr_na...
e37b7620bf484ce887e6a75f31592951ed93ac74
3,655,125
def send_message(token, message: str) -> str: """ A function that notifies LINENotify of the character string given as an argument :param message: A string to be notified :param token: LineNotify Access Token :return response: server response (thats like 200 etc...) """ ...
995abdc61398d9e977323e18f3a3e008fbaa1f3b
3,655,126
def _fix(node): """Fix the naive construction of the adjont. See `fixes.py` for details. This function also returns the result of reaching definitions analysis so that `split` mode can use this to carry over the state from primal to adjoint. Args: node: A module with the primal and adjoint function d...
27c6836366afc033e12fea254d9cf13a902d1ee7
3,655,127
def greyscale(state): """ Preprocess state (210, 160, 3) image into a (80, 80, 1) image in grey scale """ state = np.reshape(state, [210, 160, 3]).astype(np.float32) # grey scale state = state[:, :, 0] * 0.299 + state[:, :, 1] * 0.587 + state[:, :, 2] * 0.114 # karpathy state = sta...
446651be7573eb1352a84e48780b908b0383e0ca
3,655,128
def functional_common_information(dist, rvs=None, crvs=None, rv_mode=None): """ Compute the functional common information, F, of `dist`. It is the entropy of the smallest random variable W such that all the variables in `rvs` are rendered independent conditioned on W, and W is a function of `rvs`. ...
cbeef4f042fc5a28d4d909419c1991c0501c0522
3,655,129
def kubernetes_client() -> BatchV1Api: """ returns a kubernetes client """ config.load_config() return BatchV1Api()
6323d5074f1af02f52eb99b62f7109793908c549
3,655,130
def create_simple(): """Create an instance of the `Simple` class.""" return Simple()
98180d64e264c7842596c8f74ce28574459d2648
3,655,132
def contains_rep_info(line): """ Checks does that line contains link to the github repo (pretty simple 'algorithm' at the moment) :param line: string from aa readme file :return: true if it has link to the github repository :type line:string :rtype: boolean """ return True if line.find(...
335e10a654510a4eda7d28d8df71030f31f98ff1
3,655,133
def GetAtomPairFingerprintAsBitVect(mol): """ Returns the Atom-pair fingerprint for a molecule as a SparseBitVect. Note that this doesn't match the standard definition of atom pairs, which uses counts of the pairs, not just their presence. **Arguments**: - mol: a molecule **Returns**: a SparseBitVect...
9a63aa57f25d9a856d5628ec53bab0378e8088d1
3,655,134
import sqlite3 def get_registrations_by_player_id(db_cursor: sqlite3.Cursor, player_id: int) -> list[registration.Registration]: """ Get a list of registrations by player id. :param db_cursor: database object to interact with database :param player_id: player id :return: a list of registrations ...
3e87d0f7379ac7657f85225be95dd6c1d7697300
3,655,135
from re import L def run_sim(alpha,db,m,DELTA,game,game_constants,i): """run a single simulation and save interaction data for each clone""" rates = (DEATH_RATE,DEATH_RATE/db) rand = np.random.RandomState() data = [get_areas_and_fitnesses(tissue,DELTA,game,game_constants) for tissue in...
2201a836ff8c3da4c289908e561558c52206256b
3,655,137
def IMDB(*args, **kwargs): """ Defines IMDB datasets. The labels includes: - 0 : Negative - 1 : Positive Create sentiment analysis dataset: IMDB Separately returns the training and test dataset Arguments: root: Directory where the datasets are saved. Default: "...
4bb55c88fc108fce350dc3c29a2ac4497ab205b1
3,655,138
from typing import List def load_multiples(image_file_list: List, method: str='mean', stretch: bool=True, **kwargs) -> ImageLike: """Combine multiple image files into one superimposed image. Parameters ---------- image_file_list : list A list of the files to be superimposed. method : {'me...
f61f51c89f3318d17f2223640e34573282280e4a
3,655,139
def select_seeds( img: np.ndarray, clust_result: np.ndarray, FN: int = 500, TN: int = 700, n_clust_object: int = 2 ): """ Sample seeds from the fluid and retina regions acording to the procedure described in Rashno et al. 2017 Args: img (np.ndarray): Image from where to sample the seeds....
afdfe7654b53b5269f42c6c74d07265623839d75
3,655,140
def common(list1, list2): """ This function is passed two lists and returns a new list containing those elements that appear in both of the lists passed in. """ common_list = [] temp_list = list1.copy() temp_list.extend(list2) temp_list = list(set(temp_list)) temp_list.sort() for...
021605a2aad6c939155a9a35b8845992870100f0
3,655,141
def create_combobox(root, values, **kwargs): """Creates and Grids A Combobox""" box = ttk.Combobox(root, values=values, **kwargs) box.set(values[0]) return box
7406dca6ab99d9130a09a6cb25220c1e40148cc0
3,655,142
def chi_x2(samples,df): """ Compute the central chi-squared statistics for set of chi-squared distributed samples. Parameters: - - - - - samples : chi-square random variables df : degrees of freedom """ return chi2.pdf(samples,df)
5700803396e78c7a5658c05ff1b7bd7ae3bd6722
3,655,144
def integrate( pc2i, eos, initial_frac=DEFAULT_INITIAL_FRAC, rtol=DEFAULT_RTOL, ): """integrate the TOV equations with central pressure "pc2i" and equation of state described by energy density "eps/c2" and pressure "p/c2" expects eos = (logenthalpy, pressurec2, energy_density...
5934da344fc6927d397dccc7c2a730436e1106d5
3,655,145
import oci.exceptions def add_ingress_port_to_security_lists(**kwargs): """Checks if the given ingress port already is a security list, if not it gets added. Args: **kwargs: Optional parameters Keyword Args: security_lists (list): A list of security_lists. port (int): The por...
0fd1cdc05ea3c035c5424f2e179d2655e4b84bd4
3,655,146
def list_statistics_keys(): """ListStatistics definition""" return ["list", "counts"]
39521910b4dbde3fc6c9836460c73945561be731
3,655,149
def forecast_handler(req, req_body, res, res_body, zip): """Handles forecast requests""" return True
a2e35eaad472cfd52dead476d18d18ee2bcd3f6f
3,655,150
def refToMastoidsNP(data, M1, M2): """ """ mastoidsMean = np.mean([M1, M2], axis=0) mastoidsMean = mastoidsMean.reshape(mastoidsMean.shape[0], 1) newData = data - mastoidsMean return newData
15f50718fb1ea0d7b0fc2961a3a9b8d1baa98636
3,655,152
from typing import Dict from typing import Callable from typing import Any def override_kwargs( kwargs: Dict[str, str], func: Callable[..., Any], filter: Callable[..., Any] = lambda _: True, ) -> Dict[str, str]: """Override the kwargs of a function given a function to apply and an optional filter. ...
31c689a1e2df1e5168f784011fbac6cf4a86bf13
3,655,153
def prepare_for_revival(bucket, obj_prefix): """ Makes a manifest for reviving any deleted objects in the bucket. A deleted object is one that has a delete marker as its latest version. :param bucket: The bucket that contains the stanzas. :param obj_prefix: The prefix of the uploaded stanzas. :...
879182e354d94f1c24cddd233e7c004939c4d0c0
3,655,154
def make_subparser(sub, command_name, help, command_func=None, details=None, **kwargs): """ Create the "sub-parser" for our command-line parser. This facilitates having multiple "commands" for a single script, for example "norm_yaml", "make_rest", etc. """ if command_func is None: comma...
acd2467c78f2ff477a5f0412cf48cbef19882f2c
3,655,156
def application(): """ Flask application fixture. """ def _view(): return 'OK', 200 application = Flask('test-application') application.testing = True application.add_url_rule('/', 'page', view_func=_view) return application
bd9168a66cb8db8c7a2b816f1521d5633fbdcbf8
3,655,158
def get_qe_specific_fp_run_inputs( configure, code_pw, code_wannier90, code_pw2wannier90, get_repeated_pw_input, get_metadata_singlecore ): """ Creates the InSb inputs for the QE fp_run workflow. For the higher-level workflows (fp_tb, optimize_*), these are passed in the 'fp_run' namespace. ...
b0f8fd6536a237ade55139ef0ec6daaad8c0fb08
3,655,159
def _get_cohort_representation(cohort, course): """ Returns a JSON representation of a cohort. """ group_id, partition_id = cohorts.get_group_info_for_cohort(cohort) assignment_type = cohorts.get_assignment_type(cohort) return { 'name': cohort.name, 'id': cohort.id, 'user...
aaa2c7b9c53e3a49ebc97e738077a0f6873d0559
3,655,160
import json def config_string(cfg_dict): """ Pretty-print cfg_dict with one-line queries """ upper_level = ["queries", "show_attributes", "priority", "gtf", "bed", "prefix", "outdir", "threads", "output_by_query"] query_level = ["feature", "feature_anchor", "distance", "strand", "relative_location", "filter_attr...
c6533512b6f87fea1726573c0588bbd3ddd54e41
3,655,161
def area_km2_per_grid(infra_dataset, df_store): """Total area in km2 per assettype per grid, given in geographic coordinates Arguments: *infra_dataset* : a shapely object with WGS-84 coordinates *df_store* : (empty) geopandas dataframe containing coordinates per grid for each grid R...
3d4b516429235f6b20a56801b0ef98e3fd80306d
3,655,162
from click.testing import CliRunner def cli_runner(script_info): """Create a CLI runner for testing a CLI command. Scope: module .. code-block:: python def test_cmd(cli_runner): result = cli_runner(mycmd) assert result.exit_code == 0 """ def cli_invoke(command, ...
3593354dd190bcc36f2099a92bad247c9f7c7cf1
3,655,163
def sgf_to_gamestate(sgf_string): """ Creates a GameState object from the first game in the given collection """ # Don't Repeat Yourself; parsing handled by sgf_iter_states for (gs, move, player) in sgf_iter_states(sgf_string, True): pass # gs has been updated in-place to the final s...
1c1a6274769abb654d51dc02d0b3182e7a9fd1f6
3,655,164
def get_titlebar_text(): """Return (style, text) tuples for startup.""" return [ ("class:title", "Hello World!"), ("class:title", " (Press <Exit> to quit.)"), ]
947b94f2e85d7a172f5c0ba84db0ec78045a0f6c
3,655,165
import json def image_fnames_captions(captions_file, images_dir, partition): """ Loads annotations file and return lists with each image's path and caption Arguments: partition: string either 'train' or 'val' Returns: all_captions: list of strings list with ea...
f592decefaded079fca92091ad795d67150b4ca8
3,655,166
def build_menu( buttons: list, columns: int = 3, header_button=None, footer_button=None, resize_keyboard: bool = True ): """Хелпер для удобного построения меню.""" menu = [buttons[i:i + columns] for i in range(0, len(buttons), columns)] if header_button: menu....
d375a7af5f5e45e4b08520561c70d8c2664af4ef
3,655,167
def pandas_dataframe_to_unit_arrays(df, column_units=None): """Attach units to data in pandas dataframes and return united arrays. Parameters ---------- df : `pandas.DataFrame` Data in pandas dataframe. column_units : dict Dictionary of units to attach to columns of the dataframe. ...
41aff3bd785139f4d99d677e09def2764448acf2
3,655,168
from typing import Any def is_empty(value: Any) -> bool: """ empty means given value is one of none, zero length string, empty list, empty dict """ if value is None: return True elif isinstance(value, str): return len(value) == 0 elif isinstance(value, list): return len(value) == 0 elif isinstance(value,...
fd4c68dd5f0369e0836ab775d73424360bad9219
3,655,169
import caffe_parser import numpy as np def read_caffe_mean(caffe_mean_file): """ Reads caffe formatted mean file :param caffe_mean_file: path to caffe mean file, presumably with 'binaryproto' suffix :return: mean image, converted from BGR to RGB format """ mean_blob = caffe_parser.caffe_pb2.B...
6835bf429f3caca6308db450bb18e9254ff2b9a0
3,655,171
def estimate_pauli_sum(pauli_terms, basis_transform_dict, program, variance_bound, quantum_resource, commutation_check=True, symmetrize=True, rand_samples=16):...
8dc63069229cf83164196c1ca2e29d20c5be2756
3,655,172
def GetQuasiSequenceOrderp(ProteinSequence, maxlag=30, weight=0.1, distancematrix={}): """ ############################################################################### Computing quasi-sequence-order descriptors for a given protein. [1]:Kuo-Chen Chou. Prediction of Protein Subcellar Locations by ...
f59c60826e2dc40db6827ac263423cf69c338d89
3,655,173
def check(lst: list, search_element: int) -> bool: """Check if the list contains the search_element.""" return any([True for i in lst if i == search_element])
15f35ceff44e9fde28f577663e79a2216ffce148
3,655,174
def halfcube(random_start=0,random_end=32,halfwidth0=1,pow=-1): """ Produce a halfcube with given dimension and decaying power :param random_start: decay starting parameter :param random_end: decay ending parameter :param halfwidth0: base halfwidth :param pow: decaying power :return: A (rand...
eb3acfe76abf2ba2ddec73973a875ad7509cd265
3,655,175
def valid_passphrase(module, **kwargs): """Tests whether the given passphrase is valid for the specified device. Return: <boolean> <error>""" for req in ["device", "passphrase"]: if req not in kwargs or kwargs[req] is None: errmsg = "valid_passphrase: {0} is a required parameter".format...
c6355a4c75b8973372b5d01817fa59569746ed6c
3,655,176
def contract_address(deploy_hash_base16: str, fn_store_id: int) -> bytes: """ Should match what the EE does (new_function_address) //32 bytes for deploy hash + 4 bytes ID blake2b256( [0;32] ++ [0;4] ) deploy_hash ++ fn_store_id """ def hash(data: bytes) -> bytes: h = blake2...
0623209f88a59c1a2cbe8460603f920ff66575f1
3,655,177
import json def dump_js_escaped_json(obj, cls=EdxJSONEncoder): """ JSON dumps and escapes objects that are safe to be embedded in JavaScript. Use this for anything but strings (e.g. dicts, tuples, lists, bools, and numbers). For strings, use js_escaped_string. The output of this method is also ...
eba36fbf101c0779fe5756fa6fbfe8f0d2c5686c
3,655,178
from typing import NamedTuple def RawTuple(num_fields, name_prefix='field'): """ Creates a tuple of `num_field` untyped scalars. """ assert isinstance(num_fields, int) assert num_fields >= 0 return NamedTuple(name_prefix, *([np.void] * num_fields))
3287a827099098e1550141e9e99321f75a9317f6
3,655,179
def pose2mat(R, p): """ convert pose to transformation matrix """ p0 = p.ravel() H = np.block([ [R, p0[:, np.newaxis]], [np.zeros(3), 1] ]) return H
626cbfcf5c188d4379f60b0e2d7b399aece67e8c
3,655,180
def _fill_missing_values(df=None): """replace missing values with NaN""" # fills in rows where lake refroze in same season df['WINTER'].replace(to_replace='"', method='ffill', inplace=True) # use nan as the missing value for headr in ['DAYS', 'OPENED', 'CLOSED']: df[headr].replace(to_replac...
b86bfdac06d6e22c47d7b905d9cb7b5feba40fdb
3,655,181
def csi_prelu(data, alpha, axis, out_dtype, q_params, layer_name=""): """Quantized activation relu. Parameters ---------- data : relay.Expr The quantized input data. alpha : relay.Expr The quantized alpha. out_dtype : str Specifies the output data type for mixed precisi...
8e8e3c09ae7c3cb3b89f1229cfb83836682e5bc8
3,655,182
def json(filename): """Returns the parsed contents of the given JSON fixture file.""" content = contents(filename) return json_.loads(content)
fc66afdfe1a04ac8ef65272e55283de98c145f8c
3,655,183
def _parse_assayData(assayData, assay): """Parse Rpy2 assayData (Environment object) assayData: Rpy2 Environment object. assay: An assay name indicating the data to be loaded. Return a parsed expression dataframe (Pandas). """ pandas2ri.activate() mat = assayData[assay] # rpy2 expression ...
aea2e5fe25eaf563fdd7ed981d7486fdf39098b4
3,655,184
def method_list(): """ list of available electronic structure methods """ return theory.METHOD_LST
d1ad84bc709db1973f83e5a743bf4aed21f98652
3,655,185
def readReadQualities(fastqfile): """ Reads a .fastqfile and calculates a defined readscore input: fastq file output: fastq dictionary key = readid; value = qualstr @type fastqfile: string @param fastqfile: path to fastq file @rtype: dictionary @return: dictionary containin...
8af9c0fc0c2d8f3a4d2f93ef81489098cb572643
3,655,186
from typing import Optional from typing import Any from typing import Dict async def default_field_resolver( parent: Optional[Any], args: Dict[str, Any], ctx: Optional[Any], info: "ResolveInfo", ) -> Any: """ Default callable to use as resolver for field which doesn't implement a custom on...
d0458cc10a968c359c9165ac59be60ece0270c41
3,655,187
from typing import List from typing import Dict def revision_list_to_str(diffs: List[Dict]) -> str: """Convert list of diff ids to a comma separated list, prefixed with "D".""" return ', '.join([diff_to_str(d['id']) for d in diffs])
fbaa4473daf1e4b52d089c801f2db46aa7485972
3,655,188
from typing import Optional from pathlib import Path import time def get_path_of_latest_file() -> Optional[Path]: """Gets the path of the latest produced file that contains weight information""" path = Path(storage_folder) latest_file = None time_stamp_latest = -1 for entry in path.iterdir(): ...
a72308c4b3852429d6959552cc90779a4ee03dc5
3,655,189
def index(): """ A function than returns the home page when called upon """ #get all available news sources news_sources = get_sources() #get all news articles available everything = get_everything() print(everything) # title = 'Home - Find all the current news at your convinien...
4cf1eacaa550ce1ffd0ed954b60a7c7adf1702a6
3,655,190
def blur(img): """ :param img: SimpleImage, the input image :return: the processed image which is blurred the function calculate the every position and its neighbors' pixel color and then average then set it as the new pixel's RGB """ sum_red = 0 sum_blue = 0 sum_green = 0 neigh...
a4b9e98e97b7d4a27b76b8151fa91493b58fc4a6
3,655,192
def delete_project_api_document_annotations_url(document_id: int, annotation_id: int) -> str: """ Delete the annotation of a document. :param document_id: ID of the document as integer :param annotation_id: ID of the annotation as integer :return: URL to delete annotation of a document """ ...
470a9bb602c4a9327839f811f818e469747e6758
3,655,193
def GetHomeFunctorViaPose(): """ Deprecated. Returns a function that will move the robot to the home position when called. """ js_home = GetPlanToHomeService() req = ServoToPoseRequest() pose_home = GetHomePoseKDL() req.target = pm.toMsg(pose_home) open_gripper = GetOpenGripperService()...
7160f326c1aa0249da16dbfbf6fd740774284a4a
3,655,195
import requests def getAveragePlatPrice(item_name): """ Get the current average price of the item on the Warframe marketplace. Args: item_name (str): The name of the item. Returns: float: the average platinum market price of the item. """ avg_price = -1 item_name = clean...
221abd20125df49f40cfe246869a321943c5afbc
3,655,196
def mode_strength(n, kr, sphere_type='rigid'): """Mode strength b_n(kr) for an incident plane wave on sphere. Parameters ---------- n : int Degree. kr : array_like kr vector, product of wavenumber k and radius r_0. sphere_type : 'rigid' or 'open' Returns ------- b_n...
888981e34d444934e1c4b3d25c3042deabbe5005
3,655,197
from pathlib import Path def data_dir(test_dir: Path) -> Path: """ Create a directory for storing the mock data set. """ _data_dir = test_dir / 'data' _data_dir.mkdir(exist_ok=True) return _data_dir
3b204816252a2c87698197a416a4e2de218f639d
3,655,198
import multiprocessing def get_runtime_brief(): """ A digest version of get_runtime to be used more frequently """ return {"cpu_count": multiprocessing.cpu_count()}
9dbb54c476d303bae401d52ce76197e094ee5d71
3,655,199
def dict_compare(d1, d2): """ compares all differences between 2x dicts. returns sub-dicts: "added", "removed", "modified", "same" """ d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_ke...
284368eade7de1e1abfd629ea903f6dff113e279
3,655,200
from datetime import datetime def toLocalTime(seconds, microseconds=0): """toLocalTime(seconds, microseconds=0) -> datetime Converts the given number of seconds since the GPS Epoch (midnight on January 6th, 1980) to this computer's local time. Returns a Python datetime object. Examples: >>...
9dd9352003b19b5e785766c7fb6e11716284c3ed
3,655,201
def get_part_01_answer(): """ Static method that will return the answer to Day01.01 :return: The product result :rtype: float """ return prod(summation_equals(puzzle_inputs, 2020, 2))
4fcc108bef3d0e5117caff4f02ff7797021a0efd
3,655,202
def eig_of_series(matrices): """Returns the eigenvalues and eigenvectors for a series of matrices. Parameters ---------- matrices : array_like, shape(n,m,m) A series of square matrices. Returns ------- eigenvalues : ndarray, shape(n,m) The eigenvalues of the matrices. e...
fd34bdb1dc1458d0d495259a07572e0b0a2e685a
3,655,203
from re import T def injectable( cls: T = None, *, qualifier: str = None, primary: bool = False, namespace: str = None, group: str = None, singleton: bool = False, ) -> T: """ Class decorator to mark it as an injectable dependency. This decorator accepts customization paramete...
06f1b6d5b3747d92e91cf751e62d90222e06d9a8
3,655,204
def build_graph(defined_routes): """ build the graph form route definitions """ G = {} for row in defined_routes: t_fk_oid = int(row["t_fk_oid"]) t_pk_oid = int(row["t_pk_oid"]) if not t_fk_oid in G: G[t_fk_oid] = {} if not t_pk_oid in G: G[t_p...
16962ee1f4e336a9a1edc7cc05712113461f9a1a
3,655,205
def grando_transform_gauss_batch(batch_of_images, mean, variance): """Input: batch of images; type: ndarray: size: (batch, 784) Output: batch of images with gaussian nois; we use clip function to be assured that numbers in matrixs belong to interval (0,1); type: ndarray; size: (batch, 784); """ ...
4def857b315c425337d3edb6273af16f052cb1ba
3,655,206
def LF_DG_DISTANCE_SHORT(c): """ This LF is designed to make sure that the disease mention and the gene mention aren't right next to each other. """ return -1 if len(list(get_between_tokens(c))) <= 2 else 0
23b5450b844f91d6cae0993f2b7cda5c80460be1
3,655,208
def populate_user_flags(conf, args): """Populate a dictionary of configuration flag parameters, "conf", from values supplied on the command line in the structure, "args".""" if args.cflags: conf['cflags'] = args.cflags.split(sep=' ') if args.ldflags: conf['ldflags'] = args.ldflags.sp...
3f3fe64e2e352e0685a048747c9c8351575e40fb
3,655,209
def combine_raytrace(input_list): """ Produce a combined output from a list of raytrace outputs. """ profiler.start('combine_raytrace') output = dict() output['config'] = input_list[0]['config'] output['total'] = dict() output['total']['meta'] = dict() output['total']['image'] = dic...
2ed47dc60585e793bdc40fa39e04057c26db347d
3,655,210
def is_dict(): """Expects any dictionary""" return TypeMatcher(dict)
81bed05f5c8dae6ba3b8e77caa4d2d7777fb7ea9
3,655,211
import re def get_list_from_comma_separated_string(comma_separated_list): """ get a python list of resource names from comma separated list :param str comma_separated_list: :return: """ # remove all extra whitespace after commas and before/after string but NOT in between resource names rem...
73df5fe431aceec0fec42d6019269a247b5587a5
3,655,213
def cci(series, window=14): """ compute commodity channel index """ price = typical_price(series) typical_mean = rolling_mean(price, window) res = (price - typical_mean) / (.015 * np.std(typical_mean)) return pd.Series(index=series.index, data=res)
b3eeabd4369fc1a041c3a714edc193deced804dc
3,655,214
def load_definition_from_string(qualified_module, cache=True): """Load a definition based on a fully qualified string. Returns: None or the loaded object Example: .. code-block:: python definition = load_definition_from_string('watson.http.messages.Request') request = definit...
c435b4945878c5b5c2f5c7e252259da2be2345d0
3,655,215
import requests import logging def get_session(auth_mechanism, username, password, host): """Takes a username, password and authentication mechanism, logs into ICAT and returns a session ID""" # The ICAT Rest API does not accept json in the body of the HTTP request. # Instead it takes the form parame...
2395751bc64300ae32c052e5a9aba04e50f7941f
3,655,216
from typing import List def _create_all_aux_operators(num_modals: List[int]) -> List[VibrationalOp]: """Generates the common auxiliary operators out of the given WatsonHamiltonian. Args: num_modals: the number of modals per mode. Returns: A list of VibrationalOps. For each mode the numbe...
58a30221757bfcaa5c8b8790fd5556b060ecc8d1
3,655,217
from typing import List from typing import Concatenate def add_conv(X: tf.Tensor, filters: List[int], kernel_sizes: List[int], output_n_filters: int) -> tf.Tensor: """ Builds a single convolutional layer. :param X: input layer. :param filters: number of output filters in the convolution....
69e907fc87780ce754c69500108dc00866fef716
3,655,218
def show_toast(view, message, timeout=DEFAULT_TIMEOUT, style=DEFAULT_STYLE): # type: (sublime.View, str, int, Dict[str, str]) -> Callable[[], None] """Show a toast popup at the bottom of the view. A timeout of -1 makes a "sticky" toast. """ messages_by_line = escape_text(message).splitlines() c...
910809b3efca6c1256af3540acbe42449080bebc
3,655,219