content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def atomic_coordinates_as_json(pk): """Get atomic coordinates from database.""" subset = models.Subset.objects.get(pk=pk) vectors = models.NumericalValue.objects.filter( datapoint__subset=subset).filter( datapoint__symbols__isnull=True).order_by( 'datapoint_id', 'counter'...
515854e789a15e845b0dbcd754e17bedfc0bcf69
11,000
def additional_bases(): """"Manually added bases that cannot be retrieved from the REST API""" return [ { "facility_name": "Koltyr Northern Warpgate", "facility_id": 400014, "facility_type_id": 7, "facility_type": "Warpgate" }, { ...
e2a5ad97ca1b424466f5ebe340466eaf9f627e7e
11,001
def get_all_label_values(dataset_info): """Retrieves possible values for modeled labels from a `Seq2LabelDatasetInfo`. Args: dataset_info: a `Seq2LabelDatasetInfo` message. Returns: A dictionary mapping each label name to a tuple of its permissible values. """ return { label_info.name: tuple(l...
929db286b3f7ee8917618e9f46feabdff630d3b2
11,002
def load_input(file: str) -> ArrayLike: """Load the puzzle input and duplicate 5 times in each direction, adding 1 to the array for each copy. """ input = puzzle_1.load_input(file) input_1x5 = np.copy(input) for _ in range(4): input = np.clip(np.mod(input + 1, 10), a_min=1, a_max=Non...
91b2cd7854a793ebbbfee2400eddb22304fc18bd
11,003
def _get_xvals(end, dx): """Returns a integer numpy array of x-values incrementing by "dx" and ending with "end". Args: end (int) dx (int) """ arange = np.arange(0, end-1+dx, dx, dtype=int) xvals = arange[1:] return xvals
24a4d7b7c470abb881700a1775008d16c35c1fc3
11,004
import torch def top_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')): """ Filter a distribution of logits using top-k, top-p (nucleus) and/or threshold filtering Args: logits: logits distribution shape (vocabulary size) top_k: <=0: no filtering, >0: keep only top ...
5cbbd9959a80e72364f098fe031e5e3c78485826
11,005
def get_reference_shift( self, seqID ): """Get a ``reference_shift`` attached to a particular ``seqID``. If none was provided, it will return **1** as default. :param str seqID: |seqID_param|. :type shift: Union[:class:`int`, :class:`list`] :raises: :TypeError: |indf_error|. .. rubr...
4a8f9fe683c9cf0085754ca2ebb9132bbae427ea
11,006
import os import sys def which(cmd, mode=os.F_OK | os.X_OK, path=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get...
31fff48dd7984de5008bedf8a1da9687111fcfbf
11,007
def load_and_resolve_feature_metadata(eval_saved_model_path: Text, graph: tf.Graph): """Get feature data (feature columns, feature) from EvalSavedModel metadata. Like load_feature_metadata, but additionally resolves the Tensors in the given graph. Args: eval_saved_mod...
3377d66c962ccccab7b62abf563f88032a8a7b14
11,008
def greater_than_or_eq(quant1, quant2): """Binary function to call the operator""" return quant1 >= quant2
920c28da125b567bc32a149aec6aaade3645ef87
11,009
def pr_define_role(pe_id, role=None, role_type=None, entity_type=None, sub_type=None): """ Back-end method to define a new affiliates-role for a person entity @param pe_id: the person entity ID @param role: the role...
3f09ac9eca47347b51069a20b7b08b2192e2d452
11,010
def inherently_superior(df): """ Find rows in a dataframe with all values 'inherently superior', meaning that all values for certain metrics are as high or higher then for all other rows. Parameters ---------- df : DataFrame Pandas dataframe containing the columns to be compared...
02dd6db624efd4f1daa4c0ef4f126c6c60c0376e
11,011
def LineColourArray(): """Line colour options array""" Colour = [ 'Black', 'dimgrey', 'darkgrey', 'silver', 'lightgrey', 'maroon', 'darkred', 'firebrick', 'red', 'orangered', 'darkorange', 'orange', ...
94f91d17c6e539983ab38ca7fdadd211e6268bfb
11,012
import errno def os_to_maestral_error(exc, dbx_path=None, local_path=None): """ Gets the OSError and tries to add a reasonably informative error message. .. note:: The following exception types should not typically be raised during syncing: InterruptedError: Python will automatically ret...
7a99ce147e2fbe0a3cc94535ee1d84c9337b3791
11,013
from typing import Any def parse_ccu_sys_var(data: dict[str, Any]) -> tuple[str, Any]: """Helper to parse type of system variables of CCU.""" # pylint: disable=no-else-return if data[ATTR_TYPE] == ATTR_HM_LOGIC: return data[ATTR_NAME], data[ATTR_VALUE] == "true" if data[ATTR_TYPE] == ATTR_HM_A...
8b77dbbaa93739457a2e92aad79ac5b6bd3a6af0
11,014
def one_time_log_fixture(request, workspace) -> Single_Use_Log: """ Pytest Fixture for setting up a single use log file At test conclusion, runs the cleanup to delete the single use text file :return: Single_Use_Log class """ log_class = Single_Use_Log(workspace) request.addfinalizer(log_cl...
73332892ece76ee90c15d84294b70d935e8a2f4c
11,015
import json def details(request, path): """ Returns detailed information on the entity at path. :param path: Path to the entity (namespaceName/.../.../.../) :return: JSON Struct: {property1: value, property2: value, ...} """ item = CACHE.get(ENTITIES_DETAIL_CACHE_KEY) # ENTITIES_DETAIL : {"namespaceNam...
b460dc76f18f35b48509a1b2d8daa104bc89fbb5
11,016
def ca_get_container_capability_set(slot, h_container): """ Get the container capabilities of the given slot. :param int slot: target slot number :param int h_container: target container handle :return: result code, {id: val} dict of capabilities (None if command failed) """ slot_id = CK_SL...
cf97db8f201d0c5fce12902b92abdc3a819ac394
11,017
def load_pyfunc(model_file): """ Loads a Keras model as a PyFunc from the passed-in persisted Keras model file. :param model_file: Path to Keras model file. :return: PyFunc model. """ return _KerasModelWrapper(_load_model(model_file))
eb21f47a55f35bf3707ba7c5cb56e72948d24866
11,018
def business_days(start, stop): """ Return business days between two datetimes (inclusive). """ return dt_business_days(start.date(), stop.date())
1fa8c38e6cceca448bc988cd0c1eb24a27508a78
11,019
def empty_nzb_document(): """ Creates xmldoc XML document for a NZB file. """ # http://stackoverflow.com/questions/1980380/how-to-render-a-doctype-with-pythons-xml-dom-minidom imp = minidom.getDOMImplementation() dt = imp.createDocumentType("nzb", "-//newzBin//DTD NZB 1.1//EN", "http://...
7cd8aa73f201b4f432aa6adaed18d133ec08fa48
11,020
def get_output_directory(create_statistics=None, undersample=None, oversample=None): """ Determines the output directory given the balance of the dataset as well as columns. Parameters ---------- create_statistics: bool Whether the std, min and max columns have been created undersample: ...
c10859e1eba4afb61d967e56be8a8206f5202618
11,021
def removePrefixes(word, prefixes): """ Attempts to remove the given prefixes from the given word. Args: word (string): Word to remove prefixes from. prefixes (collections.Iterable or string): Prefixes to remove from given word. Returns: (string): Word with prefixes removed. ...
6932e5605b11eee004a350c7f9be831d8bb7ca9d
11,022
def isSol(res): """ Check if the string is of the type ai bj ck """ if not res or res[0] != 'a' or res[-1] != 'c': return False l = 0 r = len(res)-1 while res[l] == "a": l+=1 while res[r] == "c": r-=1 if r-l+1 <= 0: return False ...
14030e52a588dc13029602e81a5f2068707bca17
11,023
import pandas def _h1_to_dataframe(h1: Histogram1D) -> pandas.DataFrame: """Convert histogram to pandas DataFrame.""" return pandas.DataFrame( {"frequency": h1.frequencies, "error": h1.errors}, index=binning_to_index(h1.binning, name=h1.name), )
28aa8cc36abd21a17e0a30f4bde2bb996753864b
11,024
def wgt_area_sum(data, lat_wgt, lon_wgt): """wgt_area_sum() performas weighted area addition over a geographical area. data: data of which last 2 dimensions are lat and lon. Strictly needs to be a masked array lat_wgt: weights over latitude of area (usually cos(lat * pi/180)) lon_wgt: weights over long...
725f7f199e634cf56afb846ebff2a0917a92c685
11,025
import os def get_files_from_path(path, recurse=False, full_path=True): """ Get Files_Path From Input Path :param full_path: Full path flag :param path: Input Path :param recurse: Whether Recursive :return: List of Files_Path """ files_path_list = [] if not os.path.exists(path): ...
156088cd175a24bdb0bdd04c00fa6229470aab1f
11,026
def load(filename): """Load the labels and scores for Hits at K evaluation. Loads labels and model predictions from files of the format: Query \t Example \t Label \t Score :param filename: Filename to load. :return: list_of_list_of_labels, list_of_list_of_scores """ result_labels = [] re...
8d9570d794ebf09eb393342f926a5536dd0c1a75
11,027
def expanding_sum(a, axis = 0, data = None, state = None): """ equivalent to pandas a.expanding().sum(). - works with np.arrays - handles nan without forward filling. - supports state parameters :Parameters: ------------ a : array, pd.Series, pd.DataFrame or list/dict of these ...
ec3fb41784f7ce5ef268ec8e7d8fe8e65f222157
11,028
def accuracy(output, target, top_k=(1,)): """Calculate classification accuracy between output and target. :param output: output of classification network :type output: pytorch tensor :param target: ground truth from dataset :type target: pytorch tensor :param top_k: top k of metric, k is an int...
68b7c48e5bd832a637e7a06353c48ffa09b449cd
11,029
from typing import Dict from typing import Any import os import json def read_configuration_from_file(path: str) -> Dict[str, Any]: """ Read the JSON file and return a dict. :param path: path on file system :return: raw, unchanged dict """ if os.path.isfile(path): with open(path) as js...
57a8ea69507d4941b00e9ec2849084536eb7d44f
11,030
import typing import logging def logwrap( func: typing.Optional[typing.Callable] = None, *, log: logging.Logger = _log_wrap_shared.logger, log_level: int = logging.DEBUG, exc_level: int = logging.ERROR, max_indent: int = 20, spec: typing.Optional[typing.Callable] = None, blacklisted_na...
4c48dafc6c4f062fd1d165fd30bcc99209eabed3
11,031
def sum_digits(number): """ Write a function named sum_digits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. """ return sum(int(n) for n in str(number) if n.isdigit())
b6d8083a78d67a268316716174723f47d84b2287
11,032
import numpy def label(input, structure=None, output=None): """Labels features in an array. Args: input (cupy.ndarray): The input array. structure (array_like or None): A structuring element that defines feature connections. ```structure``` must be centersymmetric. If ...
fe3e4b7ee30f7dc1ae0541133f7db3d02c7d3157
11,033
import functools def get_experiment_fn(nnObj,data_dir, num_gpus,variable_strategy,use_distortion_for_training=True): """Returns an Experiment function. Experiments perform training on several workers in parallel, in other words experiments know how to invoke train and eval in a sensible fashion for distribut...
07ddb4ebac493826127464f76fd79ea17e7bf474
11,034
def calc_psnr(tar_img, ref_img): """ Compute the peak signal to noise ratio (PSNR) for an image. Parameters ---------- tar_img : sitk Test image. ref_img : sitk Ground-truth image. Returns ------- psnr : float The PSNR metric. References ---------- .....
61097170fb439b85583cd8aac8002c70d02c094b
11,035
import networkx as nx import os def celegans(path): """Load the neural network of the worm C. Elegans [@watts1998collective]. The neural network consists of around 300 neurons. Each connection between neurons is associated with a weight (positive integer) capturing the strength of the connection. Args: ...
fc7f63af1b70c58fab7655d33f6d9630d4bd003e
11,036
from typing import Callable from typing import Dict from typing import Any import functools def glacier_wrap( f: Callable[..., None], enum_map: Dict[str, Dict[str, Any]], ) -> Callable[..., None]: """ Return the new function which is click-compatible (has no enum signature arguments) from the arbi...
01f3a90179bb0dba29ffb0b2fa9d91be15e0ee7e
11,037
def _cluster_spec_to_device_list(cluster_spec, num_gpus_per_worker): """Returns a device list given a cluster spec.""" cluster_spec = multi_worker_util.normalize_cluster_spec(cluster_spec) devices = [] for task_type in ("chief", "worker"): for task_id in range(len(cluster_spec.as_dict().get(task_type, [])))...
3032a28f80dbed1fd870e4fc2ea06d724fc529ce
11,038
def group_by_time(df, col, by='day', fun='max', args=(), kwargs={}, index='categories'): """ See <https://pandas.pydata.org/pandas-docs/stable/api.html#groupby>_ for the set of `fun` parameters available. Examples are: 'count', 'max', 'min', 'median', etc .. Tip:: Since Access inherits from Tim...
6695d285b52757ee7dfd32ad5943aa433504322f
11,039
def fetch(url, params=None, keepalive=False, requireValidCert=False, debug=False): """ Fetches the desired @url using an HTTP GET request and appending and @params provided in a dictionary. If @keepalive is False, a fresh connection will be made for this request. If @requireValidCert is True, then an exceptio...
8edfa089e9ae40d32f4843e6c684b3a06783150a
11,040
def param_rischDE(fa, fd, G, DE): """ Solve a Parametric Risch Differential Equation: Dy + f*y == Sum(ci*Gi, (i, 1, m)). Given a derivation D in k(t), f in k(t), and G = [G1, ..., Gm] in k(t)^m, return h = [h1, ..., hr] in k(t)^r and a matrix A with m + r columns and entries in Const(k) such that ...
afb910a9590195fa637be9c64382419c1c79a885
11,041
from sys import path import yaml def main(df: pyam.IamDataFrame) -> pyam.IamDataFrame: """Main function for validation and processing (for the ARIADNE-intern instance)""" # load list of allowed scenario names with open(path / "scenarios.yml", "r") as stream: scenario_list = yaml.load(stream, Load...
8872d698e0e00baedfe24784b2db6b206ff32e04
11,042
import torch def huber_loss(x, delta=1.): """ Standard Huber loss of parameter delta https://en.wikipedia.org/wiki/Huber_loss returns 0.5 * x^2 if |a| <= \delta \delta * (|a| - 0.5 * \delta) o.w. """ if torch.abs(x) <= delta: return 0.5 * (x ** 2) else: return del...
b3493eb9d4e38fa36f92db80dc52a47c32caf3c9
11,043
def licenses_mapper(license, licenses, package): # NOQA """ Update package licensing and return package based on the `license` and `licenses` values found in a package. Licensing data structure has evolved over time and is a tad messy. https://docs.npmjs.com/files/package.json#license license(...
5568c323b342cc09d966ddef3455381abdca1ccc
11,044
def send_command(target, data): """sends a nudge api command""" url = urljoin(settings.NUDGE_REMOTE_ADDRESS, target) req = urllib2.Request(url, urllib.urlencode(data)) try: return urllib2.urlopen(req) except urllib2.HTTPError, e: raise CommandException( 'An exception occu...
fc6967f84568b755db7f132f5fc511ef9687369f
11,045
def logistic_log_partial_ij(x_i, y_i, beta, j): """i is index of point and j is index of derivative""" return (y_i - logistic(dot(x_i, beta))) * x_i[j]
a24f704bc3178c6f2d8b37ad075f1beea3666964
11,046
def expected_win(theirs, mine): """Compute the expected win rate of my strategy given theirs""" assert abs(theirs.r + theirs.p + theirs.s - 1) < 0.001 assert abs(mine.r + mine.p + mine.s - 1) < 0.001 wins = theirs.r * mine.p + theirs.p * mine.s + theirs.s * mine.r losses = theirs.r * mine.s + theirs...
92de2010287e0c027cb18c3dd01d95353e4653c4
11,047
def get_first_where(data, compare): """ Gets first dictionary in list that fit to compare-dictionary. :param data: List with dictionarys :param compare: Dictionary with keys for comparison {'key';'expected value'} :return: list with dictionarys that fit to compare """ l = get_all_where(data, compare) i...
fc961d7154aa265efd101a658f668ad2025c121f
11,048
import numpy def parse_megam_weights(s, features_count, explicit=True): """ Given the stdout output generated by ``megam`` when training a model, return a ``numpy`` array containing the corresponding weight vector. This function does not currently handle bias features. """ if numpy is None: ...
db172935fe7af892b420d515391565ccc2b44c55
11,049
from typing import Counter def project_statistics(contributions): """Returns a dictionary containing statistics about all projects.""" projects = {} for contribution in contributions: # Don't count unreviewed contributions if contribution["status"] == "unreviewed": continue ...
91c27b504fc974b26f4e76b8a3f78e3665a21efa
11,050
def exportSDFVisual(visualobj, linkobj, visualdata, indentation, modelname): """Simple wrapper for visual data of links. The visual object is required to determine the position (pose) of the object. If relative poses are used the data found in visualdata (key pose) is used. Otherwise the pose of the...
f556a1eb1cef42adfde28c481a3443f149219518
11,051
import resource def register_module(): """Callback for module registration. Sets up URL routes.""" global custom_module # pylint: disable=global-statement permissions = [ roles.Permission(EDIT_STUDENT_GROUPS_PERMISSION, messages.EDIT_STUDENT_GROUPS_PERMISSION_DESCRIPTIO...
82e8d57c2b0f73ae21b460da61ce047b4a25ebe3
11,052
from sys import version_info def build_texttable(events): """ value['date'], value["target"], value['module_name'], value['scan_unique_id'], value['options'], value['event'] build a text table with generated event related to the scan :param events: ...
477c40ce240aae8848d960c6c3bba1e52a4c6b67
11,053
def for_all_regions(get_client_func, catalog_entry, action_func, parsed_args): """ Run the provided function on all the available regions. Available regions are determined based on the user service catalog entries. """ result = [] cache_key = 'todo' cache_item = CACHE.get(cache_key, None...
9b1dfba7939aada8ca3c4c894d2ebbde08e757c6
11,054
import scipy def KL_distance(image1, image2): """ Given two images, calculate the KL divergence between the two 2d array is not supported, so we have to flatten the array and compare each pixel in the image1 to the corresponding pixel in the image2. """ return scipy.stats.entropy(image1.ravel(), ...
6419c2f6456365e027fc7eff6f4b171e5eb4fc5f
11,055
def stop_all_bots(): """ This function address RestAPI call to stop polling for all bots which have ever started polling. :return: """ bots_stopped = procedures.stop_all() # Stop all bots. botapi_logger.info('Successfully stopped {count} bots for polling in ' 's...
7e0bdaa0ae631e631cfbc56966311e59fc510d52
11,056
def load_word_embedding_dict(embedding, embedding_path, normalize_digits=True): """ load word embeddings from file :param embedding: :param embedding_path: :return: embedding dict, embedding dimention, caseless """ print "loading embedding: %s from %s" % (embedding, embedding_path) if em...
98cda8061aa49c708bc6986a6ab036e8941967f6
11,057
import sys def fibonacci(n: int) -> int: """Returns nth fib number, fib_0 = 0, fib_1 = 1, ...""" print(sys.platform) return nfibonacci(n + 1)[-1]
4f6b0c61709ad76e0600c395495b5b94c03c15ae
11,058
def random_exponential(shape=(40,60), a0=100, dtype=float) : """Returns numpy array of requested shape and type filled with exponential distribution for width a0. """ a = a0*np.random.standard_exponential(size=shape) return a.astype(dtype)
29d3e438145d4495191868c956942b9626b76918
11,059
import json def get_mpi_components_from_files(fileList, threads=False): """ Given a list of files to read input data from, gets a percentage of time spent in MPI, and a breakdown of that time in MPI """ percentDict = dict() timeDict = dict() for filename in fileList: filename ...
34549198676b823cf9e02ec927cb1e5fc30de2b8
11,060
import urllib def get_character_url(name): """Gets a character's tibia.com URL""" return url_character + urllib.parse.quote(name.encode('iso-8859-1'))
62dc27528b7b9b303367551b8cba0a02204d0eb6
11,061
def parse_input(lines): """Parse the input document, which contains validity rules for the various ticket fields, a representation of my ticket, and representations of a number of other observed tickets. Return a tuple of (rules, ticket, nearby_tickets) """ section = parse_sections(lines) ru...
cccf2a9b47768428b2004caab1b3cab15a369a68
11,062
from dateutil import tz def _cnv_prioritize(data): """Perform confidence interval based prioritization for CNVs. """ supported = {"cnvkit": {"inputs": ["call_file", "segmetrics"], "fn": _cnvkit_prioritize}} pcall = None priority_files = None for call in data.get("sv", []): if call["var...
a35c8b1d1fb7f38fc23439bbe5b9778062fc6aa7
11,063
from typing import Optional def maximum( left_node: NodeInput, right_node: NodeInput, auto_broadcast: str = "NUMPY", name: Optional[str] = None, ) -> Node: """Return node which applies the maximum operation to input nodes elementwise.""" return _get_node_factory_opset1().create( "Maxim...
9ca2ac093059a9c7c2a1b310635c551d1982b1bb
11,064
def create_template_error(): """ Создает заготовку для генерации ошибок """ return {'response': False}
f15c27cc980cf1bda6b82353d01bbe7871fdbff1
11,065
from typing import Any from typing import Tuple import os import logging import sys def download_and_extract_index(storage_bucket: Any, extract_destination_path: str) -> Tuple[str, Any, int]: """Downloads and extracts index zip from cloud storage. Args: storage_bucket (google.cloud.storage.bucket.Buc...
6d4ab60f6c0e95a9b9a52afc58b510f03d32c8d1
11,066
def e_qest(model, m): """ Calculation of photocounting statistics estimation from photon-number statistics estimation Parameters ---------- model : InvPBaseModel m : int Photocount number. """ return quicksum(model.T[m, n] * model.PEST[n] for n in model....
b4b5f9fb4ba1c142af3d91d170fdb90ae960dd0e
11,067
def load_input(fname): """Read in the data, return as a list.""" data = [""] with open(fname, "r") as f: for line in f.readlines(): if line.strip("\n"): data[-1] += line.strip("\n") + " " else: data[-1] = data[-1].strip(" ") dat...
f83021dd416e3a959996a16bb8d0a0e7352a471f
11,068
import json def parse_repo_layout_from_json(file_): """Parse the repo layout from a JSON file. Args: file_ (File): The source file. Returns: RepoLayout Raises: InvalidConfigFileError: The configuration file is invalid. """ def encode_dict(data): new_data = {...
db1b7843c26ecc6796233e0cc193b41336fecf2d
11,069
def SizeArray(input_matrix): """ Return the size of an array """ nrows=input_matrix.shape[0] ncolumns=input_matrix.shape[1] return nrows,ncolumns
3ac45e126c1fea5a70d9d7b35e967896c5d3be0b
11,070
def show_fun_elem_state_machine(fun_elem_str, xml_state_list, xml_transition_list, xml_fun_elem_list): """Creates lists with desired objects for <functional_element> state, send them to plantuml_adapter.py then returns url_diagram""" new_fun_elem_list = set() main_fun_el...
3d8b1426e791bcc40c9850723da9bf350bea361f
11,071
def get_bank_account_rows(*args, **kwargs): """ 获取列表 :param args: :param kwargs: :return: """ return db_instance.get_rows(BankAccount, *args, **kwargs)
0599b2bbae3b7bb044789db6c18f47604c3c9171
11,072
import importlib def load_class(class_name, module_name): """Dynamically load a class from strings or raise a helpful error.""" # TODO remove this nasty python 2 hack try: ModuleNotFoundError except NameError: ModuleNotFoundError = ImportError try: loaded_module = importl...
02ce2988e45b30da7603acc41fea4846481a94e3
11,073
def pybo_mod(tokens, tag_codes=[]): """extract text/pos tuples from Token objects""" txt_tags = [] for token in tokens: tags = [] tags.append(token.text) # Select and order the tags for tag_code in tag_codes: tags.append(get_tag(token, tag_code)) txt_tags....
e96bb6a4774a0e983f2288536921e98207aeaa4b
11,074
def acf( da: xr.DataArray, *, lag: int = 1, group: str | Grouper = "time.season" ) -> xr.DataArray: """Autocorrelation function. Autocorrelation with a lag over a time resolution and averaged over all years. Parameters ---------- da : xr.DataArray Variable on which to calculate the diagn...
630eb27574edb40f363f41656a23801f11cefb1c
11,075
import requests def username(UID: str) -> str: """ Get a users username from their user ID. >>> username("zx7gd1yx") '1' >>> username("7j477kvj") 'AnInternetTroll' >>> username("Sesame Street") Traceback (most recent call last): ... utils.UserError: User with uid 'Sesame Street' not found. """ R: dic...
c2d66af182a970783ef6e2236c1db3e5a3f80b50
11,076
import logging def handle_exceptions(func): """Exception handler helper function.""" logging.basicConfig(level = logging.INFO) def wrapper_func(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logging.error(f'{func.__name__} raised an error...
2d5c428e65cfb823d1afbf2d2c77f98b8722d685
11,077
def apply_hamming_window(image): """Cross correlate after applying hamming window to compensate side effects""" window_h = np.hamming(image.shape[0]) window_v = np.hamming(image.shape[1]) image = np.multiply(image.T, window_h).T return np.multiply(image, window_v)
f319506e9a51350664683ede7411e677bbf96ab3
11,078
from typing import Tuple from functools import reduce def calc_ewald_sum(dielectric_tensor: np.ndarray, real_lattice_set: np.ndarray, reciprocal_lattice_set: np.ndarray, mod_ewald_param: float, root_det_epsilon: float, volu...
5be08f833c8e44a4afeab48af0f5160278fbf88a
11,079
import time def proximal_descent( x0, grad, prox, step_size, momentum='fista', restarting=None, max_iter=100, early_stopping=True, eps=np.finfo(np.float64).eps, obj=None, benchmark=False): """ Proximal descent algorithm. Parameters ---------- x0 : array, shape (n_l...
e6a05c2ef4295b67e3bc3ac2b1608b16d43bc09e
11,080
import json def sign_tx(path, multisig_address, redeemscript, utxo_file, output_file, testnet=False): """ Sign a spend of a bitcoin 2-of-3 P2SH-multisig address using a Trezor One Hardware Wallet Args: path: BIP32 path of...
d9e16f5ce241b52f0cef0edb675936e52d3d2cf8
11,081
from stable_baselines_custom.common.atari_wrappers import wrap_deepmind def wrap_atari_dqn(env): """ wrap the environment in atari wrappers for DQN :param env: (Gym Environment) the environment :return: (Gym Environment) the wrapped environment """ return wrap_deepmind(env, frame_stack=True, ...
6c47492fe412b5620f22db17a45aa42968ed9a62
11,082
def get_Theta_CR_i_d_t(pv_setup, Theta_A_d_t, I_s_i_d_t): """加重平均太陽電池モジュール温度 (6) Args: pv_setup(str): 太陽電池アレイ設置方式 Theta_A_d_t(ndarray): 日付dの時刻tにおける外気温度(℃) I_s_i_d_t(ndarray): 日付dの時刻tにおける太陽電池アレイiの設置面の単位面積当たりの日射量(W/m2) Returns: ndarray: 日付dの時刻tにおける太陽電池アレイiの加重平均太陽電池モジュール温度 """ ...
6c96d9c4692de19909feccf647fd39126358b29c
11,083
from typing import Set def or_equality(input_1: Variable, input_2: Variable, output: Variable) -> Set[Clause]: """ Encode an OR-Gate into a CNF. :param input_1: variable representing the first input of the OR-Gate :param input_2: variable representing the second input of the OR-Gate :param output...
f101b1d7ae3d70e7849133562cd274275f8419a8
11,084
import math def keyPosition_to_keyIndex(key_position: int, key: int) -> int: """ キーポジションからどのキーのノーツなのかを変換します 引数 ---- key_position : int -> キーポジション key : int -> 全体のキー数、4Kなら4と入力 戻り値 ------ int -> キーインデックス、指定したキーの0~キー-1の間の数 """ return math.floor(key_position * key / 512)
e6edcc1711a283336da046e1f8f174cc7ff87760
11,085
import json def load_file_recipes(fh, enabled_only=False, expensive=False, logger=logger): """ Load all the recipes from a given file handle. :param enabled_only: Set True to limit to only enabled recipes. :param expensive: Set True to use 'expensive' configurations. :return: dict(name -> {recipe...
8a372981da76f9dc060c79e6cf282612fec8a4b6
11,086
from masonite.routes import Patch def patch(url, controller): """Shortcut for Patch HTTP class. Arguments: url {string} -- The url you want to use for the route controller {string|object} -- This can be a string controller or a normal object controller Returns: masonite.routes.Pa...
c267ca8c2e2c55369584a94cd07aaf26b0b7ae4b
11,087
def get_user(message: discord.Message, username: str): """ Get member by discord username or osu username. """ member = utils.find_member(guild=message.guild, name=username) if not member: for key, value in osu_tracking.items(): if value["new"]["username"].lower() == username.lower(): ...
323ac71e24e4da516263df3a4683ed5fd87138ce
11,088
import colorsys def resaturate_color(color, amount=0.5): """ Saturates the given color by setting saturation to the given amount. Input can be matplotlib color string, hex string, or RGB tuple. """ if not isinstance(color, np.ndarray) and color in matplotlib.colors.cnames: color = matplot...
2bd1b9b4d9e1d11390efc79f56a89bf7555cbe71
11,089
def create_reach_segment(upstream_point, downstream_point, polyline, identifier="HA", junctionID=0, isEnd=False): """Returns a polyline based on two bounding vertices found on the line. """ part = polyline.getPart (0) total_length = polyline.length lineArray = arcpy.Array () ...
c378fb05c1eda5cde35d5caf60a9d732578ae6d8
11,090
def sample_recipe(user, **params): """ Helper function for creating recipes """ """ for not writing every single time this fields """ defaults = { 'title': 'Sample recipe', 'time_minutes': 10, 'price': 5.00 } """ Override any field of the defaults dictionary. Updati...
11fe56c88cc0c641b1c04b279b2346615b2257c9
11,091
def _unary_geo(op, left, *args, **kwargs): # type: (str, np.array[geoms]) -> np.array[geoms] """Unary operation that returns new geometries""" # ensure 1D output, see note above data = np.empty(len(left), dtype=object) data[:] = [getattr(geom, op, None) for geom in left] return data
d302bdb41c74f7b127df4ccd24dd6bc56c694a56
11,092
def map_func(h, configs, args): """Polygons command line in parallel. """ if args.verbose: cmd = "python {} -i {}/threshold{}.tif -o {}/threshold{}.shp -v".format( configs["path"]["polygons"], configs["path"]["output"], h, configs["path"]["output"], h ) print cmd else: cmd = "python {} -i {}/...
4ff4e961b2d0eb9a19b277a0b8e2ef165aa43819
11,093
import os def _runopenssl(pem, *args): """ Run the command line openssl tool with the given arguments and write the given PEM to its stdin. Not safe for quotes. """ if os.name == 'posix': command = "openssl " + " ".join(["'%s'" % (arg.replace("'", "'\\''"),) for arg in args]) else: ...
ce61d5855d73365d13b28c447566f6ebb75aa030
11,094
def check_health(request: HttpRequest) -> bool: """Check app health.""" return True
20d572edd68e1518e51cbdbe331c17798bc850fe
11,095
def return_galo_tarsilo(message): """Middle function for returning "gaucho" vídeo. Parameters ---------- message : telebot.types.Message The message object. Returns ------- msg : str User/Chat alert list addition/removal. """ return 'https://www.youtube.com/watch?v...
58307b763d139dc38220b9a93af15644ccd32959
11,096
def preimage_func(f, x): """Pre-image a funcation at a set of input points. Parameters ---------- f : typing.Callable The function we would like to pre-image. The output type must be hashable. x : typing.Iterable Input points we would like to evaluate `f`. `x` must be of a type acce...
6ca0496aff52cff1ce07e327f845df4735e3266a
11,097
import dbm import sys def get_spec_id(mat_quality, mat_faction=None): """ Get the material_spec id corresponding to the material quality and faction. Args: mat_quality (str): A material quality like Basic, Fine, Choice etc... mat_faction (str): A material faction like Matis, Zoraï etc... ...
dbabe3fb6fd042a3510272aa8c353efd161b5651
11,098
def print_raw_data(raw_data, start_index=0, limit=200, flavor='fei4b', index_offset=0, select=None, tdc_trig_dist=False, trigger_data_mode=0): """Printing FEI4 raw data array for debugging. """ if not select: select = ['DH', 'TW', "AR", "VR", "SR", "DR", 'TDC', 'UNKNOWN FE WORD', 'UNKNOWN WORD'] ...
23464a46d5a3d05702fae3381e3d7623ad9017b5
11,099