content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import matplotlib as mpl from photutils.centroids import fit_2dgaussian import textwrap def centroid_plots(c_obj, cd, hdr, _pfdf, toidf, figsize=(30,20), Tmag_cutoff=16, findercachedir='~/.astrobase/stamp-cache'): """ cd = { 'm_oot_flux':m_oot_flux, # mean OOT image 'm_oot_f...
0410165845400427937aea0a8d4172a6075a6d5e
66,200
def load_learned_warp_parameters(filepath): """Loads the pickle file of alignment parameters at filepath. Args: filepath: (str) A filepath to an alignment.npy file. Returns: Numpy alignment parameters of shape [S, H, W, 2] for aligning stacks using libs.image_alignment where S is the number of panor...
2d58b8568bcb26fdc344b46f3f9b4b919d79b3f2
66,201
def merge_relu(xgraph, bottom_Xs, X, top_Xs, **kwargs): # type: (XGraph, List[XLayer], XLayer, List[XLayer]) -> XLayer """ Try to merge Relu layer into preceding Convolution/Eltwise/BatchNorm/Scale layer """ changes = False if 'ReLU' in X.type or 'pReLU' in X.type: if len(bottom_Xs) ...
9c174633cf67030b8a0e7e7a67c8a5529ce92a39
66,202
from typing import List from typing import Optional from typing import Dict import tempfile import asyncio import shlex def launch_cluster( descs: List[MachineDesc], nonce: str, subnet_id: str, key_name: Optional[str], security_group_id: str, instance_profile: Optional[str], extra_tags: Di...
cf737d89a18c9f5238ef2ac608be2594ab38d0dd
66,203
from typing import Iterator def summary(x, axis=None, shorten=False, float_precision=2): """ Return string of statistical summary given series `x` {#:%s|mi:%s|q1:%s|md:%s|mn:%s|q3:%s|ma:%s|sd:%s} """ if isinstance(x, Iterator): x = list(x) if isinstance(x, (tuple, list, set)): x = np.array(x) me...
926098bc1fcce47c1ece4c76daa452cc8b15ebf2
66,204
import requests def macro_china_bond_public(): """ 中国-债券信息披露-债券发行 http://www.chinamoney.com.cn/chinese/xzjfx/ :return: 债券发行 :rtype: pandas.DataFrame """ url = "http://www.chinamoney.com.cn/ags/ms/cm-u-bond-an/bnBondEmit" payload = { "enty": "", "bondType": "", "...
9b9860d63cf6b14e4877306cadfb4ecfb514506c
66,205
import json def evaluate_summaries(summaries): """Evaluate a list of workload generator summary files.""" result = {} t_median = [] t_max = [] t_min = [] t_average = [] t_percentile = [] failure_rates = [] num_machines = 0 for summary in summaries: try: wit...
f5cf8df1f78204b8513d80d0af07a6831e7965d6
66,206
import time import hashlib def calc_md5_with_blocking_retries(file_path): """Calculate the MD5 checksum of the given file. IMPORTANT: This method calls time.sleep(), which blocks execution. So you should only use this outside the main thread. Parameters ---------- file_path : str The...
465d15260f1d8bcbe6c603da3b660d9f55b9369a
66,207
def _gam_param(x, z): """ Compute the parameters of a gamma density from data weighted points Parameters ---------- x: array of shape(nbitem) the learning points z: array of shape(nbitem), their membership within the class Notes ----- if no point is positive then the couple (1, 1) is r...
08b1c10d745b76c30820d439401efdd4e59df207
66,208
from typing import List import re def identify_headers(lines: List[str]) -> List[str]: """ Filters a list of lines to the header lines. Identifies headers of the 'leading-hashtag' type as well as headers of the 'subsequent-line' type by using regex. :param lines: List of header and text lines. ...
46f463d6c4178d5a5bef76ecb02bd68046278633
66,209
def _generate_summary(sentences, sentenceValue, threshold): """get the summary: if value above the threshold Args: sentences (list): all sentences sentenceValue (dict): the dict storing its value threshold (int): threshold to select sentences Returns: (str): summary """...
58f432dcc419288b9977d827abf1684d80e3a404
66,210
def select_FFNN_features(dataset, shared_features=True, shared_feature_list=None, original_bert=False, has_2=True, ): """Only sentence level features Input: dataset: the data in p...
da5ec4d44d296807c3dbabda57bb278e7ea9a56a
66,211
def _GetFields(trace=None): """Returns the field names to include in the help text for a component.""" del trace # Unused. return [ 'type_name', 'string_form', 'file', 'line', 'docstring', 'init_docstring', 'class_docstring', 'call_docstring', 'length', ...
acf8a1c62853f7648082689002b3ced2689892fe
66,212
def report_cursor() -> tuple[int, int] | None: """Get position of cursor""" print("\x1b[6n") chars = getch() posy, posx = chars[2:-1].split(";") if not posx.isdigit() or not posy.isdigit(): return None return int(posx), int(posy)
daf44e19af3c3644ed8d3f38f719a2123523025e
66,213
import subprocess def samtools(items): """Ensure samtools has parallel processing required for piped analysis. """ samtools = config_utils.get_program("samtools", items[0]["config"]) p = subprocess.Popen([samtools, "sort", "-h"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)...
5d4dffaeefc555958e19a6d0a87751fdd83a14f1
66,214
import os def filter_inputs_based_on_number_of_channel( input_directory: str, filter_criteria: int = 2, ) -> bool: """ Args: input_directory: filter_criteria: Returns: """ metadata_filepath = os.path.join(input_directory, 'metadata.xml') tree = ET.parse(metad...
eb80255bacefbc24df5f5e1566b38c5a7179ca95
66,215
import builtins def iscallable(t): """True if type ``t`` is a code object that can be called""" return builtins.callable(t) and hasattr(t, '__call__')
9dc806eff1ebce90d9df8a3f3c53256ef73f0f66
66,216
def extract_body_schema(schema): """Return the body parameter schema from an operation schema.""" matching_body_schemas = filter_params_by_type(schema, 'body') # There can be only one body param return matching_body_schemas[0] if matching_body_schemas else None
1e9f3cc3d6b951148e25f7b48510a3597d5c08bf
66,217
def as_token(ctx: ParserRuleContext) -> str: """ Extract the token for an identifier from the context. Tokens can be: * ID - The name of a JSG definition * idref -- A reference to an existing JSG definition * LEXER_ID - The name of a match pattern definition * LEXER_ID_REF - A reference to an existi...
0ffa87ee71019f1f9e5b3774c1bfe94168d4c8a5
66,218
def calculate_cost(problem: np.ndarray, solution: np.ndarray, k: int) -> float: """ Calculates the overall cost as the L2 norm of the cost vector. :param problem: The problem matrix. :param solution: The solution vector. :param k: The number of folds. :return: The scalar cost. """ retur...
652130c94a48f0c99df6e2567f529ecc654970a1
66,219
import ast def matheval(expr, numtype=float): """ >>> matheval('2^6') 4 >>> matheval('2**6') 64 >>> matheval('1 + 2*3**(4^5) / (6 + -7)') -5.0 """ return eval_(ast.parse(expr, mode='eval').body, numtype)
26469e8f92f67f5a83645be4f06c550c50265264
66,220
def normalize(value, minimum, maximum): """min-max normalization""" if value < minimum: value = minimum if value > maximum: value = maximum return (value - minimum)/(maximum - minimum)
0c1318d71db43eeb27ff59ac743f8909279451b5
66,221
def _normalise_X(X): """Helper function to normalise X using the z-score standardisation""" # get the number of attributes and instances num_atts = X.shape[1] num_insts = X.shape[0] df = pd.DataFrame() for x in X.columns: col = X[x] data = [] for y in range(num_insts): ...
86ae2fef7558db4cdc22da62bce706cd9fce585d
66,222
def recursive_parse_xml_to_dict(xml): """Recursively parses XML contents to python dict. We assume that `object` tags are the only ones that can appear multiple times at the same level of a tree. Args: xml: xml tree obtained by parsing XML file contents using lxml.etree Returns: Python dictionary h...
f9f48396d1de1e21e0122261caff238a6ba82e32
66,223
import platform def _PathForExecutable(executable_name): """Fetches the executable from cloud storage, and returns its path.""" arch_name = platform.GetHostPlatform().GetArchName() return binary_manager.FetchPath(executable_name, arch_name, 'mac')
ec440a58e44231632c5a96d4ad9836385c0c5d29
66,224
def get_baseurl_from_request(request): """Use the request object to build a base url""" assert isinstance(request, HttpRequest),\ "request must be a django.http.HttpRequest object""" urlParts = urlparse(request.build_absolute_uri()) return '%s://%s' % (urlParts.scheme, urlParts.netloc)
a4e89c4694d3651968fccb3a57cf646a0151dfe0
66,225
import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt def example_cartopy(ax=None, **options): """ Draws a map of France with :epkg:`cartopy`. @param ax axis @param options look at the code @return ax """ ...
501f510e918276d8db08fc229d99776d7caac9ff
66,226
def us30History( token="", version="stable", filter="", format="json", **timeseries_kwargs ): """Economic data https://iexcloud.io/docs/api/#economic-data Args: token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-resu...
82338c790ce6416355dea0a3f67c38384b0b844e
66,227
from typing import Dict from typing import Any def new_from_at_rest(transaction_type_data: Dict[str, Any]) -> "TransactionTypeModel": """ Construct a transaction type model from at rest (cached storage) """ if transaction_type_data.get("version") == "1": # V1 custom indexes are not supported, ...
67068417bb683cfc4d20cdfcf0345f6ac7d8ac28
66,228
def load_object(module: str, name: str, *, raise_ex: bool = True) -> tp.Any: """Loads the specified object from the specified `module`. Parameters ---------- module : str The (full) name of the module to load the object from. name : str The name of the object to load from the given ...
a8ca051299a7368a7fb1a854e7e5539a63c8b74a
66,229
def validate_tokens_input(func): """check provide key and refresh token from the request and make sure they are all provide and valid""" def dec(request): try: key = request.data['key'] refresh_token = request.headers['Authorization'] if refresh_token == '': ...
57c89efc5c87684be175f0dc4aeec0362250e233
66,230
from typing import List from typing import Tuple import os def handle_arguments(argv: List) -> Tuple: """Handles the arguments. Handles the arguments when the program is run and exports it into a enumeration of it. :param argv: Vector with the ordered input arguments :type argv: List :return...
c5392d35bcf191da0b8e3742c22afae87601ac5a
66,231
def sbar(Ss): """ calculate average s,sigma from list of "s"s. """ if type(Ss) == list: Ss = np.array(Ss) npts = Ss.shape[0] Ss = Ss.transpose() avd, avs = [], [] # D=np.array([Ss[0],Ss[1],Ss[2],Ss[3]+0.5*(Ss[0]+Ss[1]),Ss[4]+0.5*(Ss[1]+Ss[2]),Ss[5]+0.5*(Ss[0]+Ss[2])]).transpose(...
cb31f9703126eef4daa569281efad32a9e2542de
66,232
def resize(img, size, interpolation=cv2.INTER_LINEAR): """ resize """ if isinstance(size, int): h, w = img.shape[:2] # hwc min_hw = min(h, w) if size == min_hw: return img percent = float(size) / min_hw rw = int(round(w * percent)) rh = int(round(h ...
e6d0734808f051dea641438c112724420998bb2d
66,233
def _get_version(name): """Get a dataset version.""" if not has_dataset(name): return None return _data_path(name=name, return_version=True)[1]
088232676b1e5d5754b06d48ce3828b82599c430
66,234
import os import subprocess def extract_wave(idx): """ Reads .dat file and returns in numpy array. Assumes 2 channels. The returned array is n x 3 where n is the number of samples. The first column is the sample number and the second two are the first and second channel respectively. """ ...
9cb8d011efaeedaccd48ed7424937014e298fe6b
66,235
def validateMembers(members, profile_entry, annotation): """ Validate an profile_entry of Members and its count annotation """ rsvLogger.debug('Testing members \n\t' + str((members, profile_entry, annotation))) if not validateRequirement('Mandatory', members): return False if "MinCount" ...
55154c93a175a4dbbf57a9e532c467b97bfd365e
66,236
import sys import os import argparse import logging def arg_parse(): """Base all default folders from script location scripts: ./pymetric/tools/download tools: ./pymetric/tools output: ./pymetric/nlcd """ script_folder = sys.path[0] code_folder = os.path.dirname(script_folde...
c7af8f769e318e23dbc8909607886cbffd987de6
66,237
def jobscript_get_exec_prefix(jg : JobGeneration): """ Prefix before executable Returns ------- string multiline text for scripts """ content = "" content += jg.runtime.get_jobscript_plan_exec_prefix(jg.compile, jg.runtime) return content
58f7ffede5369ea150e0f882b871bfba22683261
66,238
from .services.price_service import PriceServiceProvider from typing import Optional def calculate_token_eth_price_task(token_address: ChecksumAddress, redis_key: str, force_recalculation: bool = False) -> Optional[EthValueWithTimestamp]: """ Do price calculation for token i...
3a0c48327ac93f2f81f98aa5d9e0534b977ce1bd
66,239
from datetime import datetime import os def setup_new_project(project_name, path, config=None): """ Setup a project directory with a config file and the directories for train and valid videos and add an entry to the projects overview config. If an existing project config is given, this one will be use...
cf1b60315f3060f89e2b1ba1d54433446eacb012
66,240
def get_log_dirs(parent_path,prog_name): """get logs paths""" ### high priority at the begin of the list ### low priority at the end of the list pathnames_list=[] pathnames_list.append( pathnames.get_log_dir(prog_name,PROG_PUBLISHER) ) pathnames_list.append( pathnames.join_pathname(parent_path,LOGS_DIRECTORY) ) ...
21501cd871d88811ae77f668385fe693ce4e2655
66,241
def get_valid_values(value, min_value, max_value): """Assumes value a string, min_value and max_value integers. If value is in the range returns True. Otherwise returns False.""" valid_values = [i for i in range(min_value, max_value + 1)] try: value = int(value) except ValueError: ...
4385f8328cfbe6497f7a723be37e54f0a86f9fbf
66,242
import torch def _spherical_harmonics_l0(xyz): """Compute the l=0 Spherical Harmonics Args: xyz : array (Nbatch,Nelec,Nrbf,Ndim) x,y,z, of (Point - Center) Returns Y00 = 1/2 \sqrt(1 / \pi) """ return 0.2820948 * torch.ones_like(xyz[..., 0])
83831d0a140d85dc356ae04bcbaeeda74c5a9fee
66,243
def sanitizeString(string: str) -> str: """ Sanitize a string to be safe for filenames Args: string: String to sanitize for filenames Returns: Version of input string safe for filenames """ return string.replace("|", "-").\ replace("/","-").\ replace("\\","-").\ ...
c0aefd6c7af0aca9c1bdd4071b9e76041731c183
66,244
def upload_lu(v_uuid, lu, io_handle, f_size, sha_chksum=None, upload_type=UploadType.IO_STREAM): """Uploads a data stream to an existing SSP Logical Unit. :param v_uuid: The UUID of the Virtual I/O Server through which to perform the upload. :param lu: LU Wrapper representi...
c240697565cf975a3542d493f91a9537753188e0
66,245
def top_1_acc(output, target): """ Computes the top 1 accuracy """ return top_k_acc(output, target, k=1)
3ae7d2faf996144ed112a8a752df94494777b7df
66,246
def add_DenseNet_convX_body(model, block_counts, dim_in, dim_inner, group_rate): """Add a DenseNet body from input data up through the res5 (aka conv5) stage. The final res5/conv5 stage may be optionally excluded (hence convX, where X = 4 or 5).""" freeze_at = cfg.TRAIN.FREEZE_AT assert freeze_at in...
9deb1898d37a77beffd47d3237954157af4b1faf
66,247
def index_all(elm, lst): """return list[int] all positions where elm appears in lst. Empty list if not found""" if type(list)!=list: lst=list(lst) return [i for i,e in enumerate(lst) if e==elm]
0db325714d6c8de5b1a1fbb516287c56931cf0a9
66,248
def get_heartbeat(request): """Return information about server health.""" status = {} def heartbeat_check(name, func): status[name] = False status[name] = func(request) # Since the heartbeat checks run concurrently, their transactions # overlap and might end in shared lock e...
aee6f1c16fbb915dfdd4b7c38ab11e4bf00a3bf9
66,249
import math def subsampleCorrelatedData(A_t, g=None, fast=False, conservative=False, verbose=False): """Determine the indices of an uncorrelated subsample of the data. Parameters ---------- A_t : np.ndarray A_t[t] is the t-th value of timeseries A(t). Length is deduced from vector. g : f...
8c00a7fc0aaeec2b8e8409192bfb9e74463d9e82
66,250
def ValueIteration(gamma=0.95, th=0.01): """ value iterationで全状態の価値評価する. はじめ,すべての状態は価値0とする. 以下の価値更処理をすべての状態に行う.何度も繰り返し,更新幅がth未満になったら終了. ・終了状態に遷移できたら,その状態の価値を1とする. ・遷移可能な状態のうち最大価値に割引率gammaをかけたものをその状態の価値とする. 繰り返しごとに終了状態に近いものから順に価値が伝搬していくイメージ. return:状態価値テーブルV """ actions = list(ran...
9422371711fdb01a26f1219870751edb63d8d4de
66,251
import sys import os import eventlet from eventlet.green import urllib2 import dryxPython.commonutils as dcu import socket import re import base64 def multiWebDocumentDownloader( urlList, downloadDirectory, log, timeStamp=1, timeout=180, concurrentDownloads=10, resetFilename=False, cre...
4c5c2904ea413fa2abb9589495dc869627b34112
66,252
def _get_effective_credentials(cli_ctx, existing_credentials, account_name): """Returns AzureStorageCredentialInfo for the account :param models.AzureStorageCredentialsInfo existing_credentials: known credentials :param str account_name: storage account name :return models.AzureStorageCredentialsInfo: ...
dddcfcc98400ef30884320768e29f72d3623dba5
66,253
import logging def add_phab_project(project_information, project_columns): """Add a project on Phabricator. Parameters ---------- project_information : dict project_columns: dict """ logging.info("Adding Phabricator project.") name = project_information[project_columns["english_name"]...
9d21d281e110d41606461bc799a6071b2e47f1b7
66,254
def mixture_mse(params, targets, **kwargs): """Given log-unnormalized mixture weights for equi-spaced truncated Gaussians on the unit interval, return the likelihoods for targets. (Currently unused.) Args: params: N x d x 3*ncomp tensor of parameters of mixture model. targets: N x d x 1 ...
f6c908c8d518f1b35941915b58ff316f034c40c2
66,255
def socfaker_timestamp_current(): """ The current timestamp Returns: str: Returns the current timestamp in ISO 8601 format """ if validate_request(request): return { 'value': socfaker.timestamp.current }
833ab3b23194ef033065f340826dc21d4098ba4c
66,256
def get_lines(file_path): """ get all lines in file """ with open(file_path, encoding='utf-8') as data_file: lines = map(lambda line: line.strip(), data_file.readlines()) return lines
caf42286bc985c609076cb31432242552483a661
66,257
def str_of_max_length(length): """Validate that the value is a string with a max length.""" def validator(instance, attribute, value): instance_of(str)(instance, attribute, value) if len(value) > length: raise ValueError( '{0.name} must be at most {1} chars, ' ...
2b2dc062026b1c81f6b984669f169cd96bda57da
66,258
def version(server, component=None): """ Returns the version of the specified component. If *component* is None, then a list of all of the components available will be returned. :param CasparServer server: The :py:class:`~caspartalk.CasparServer` that the *amcp_command* will be sent to. :param str ...
642d80ede6afee88484095f631b1b194e32fac4b
66,259
from typing import Dict from typing import Any from typing import Optional from typing import List import logging def gather_gene_dict_from_contig( contig: str, variant_source: cyvcf2.VCFReader, config: Dict[str, Any], panelapp_data: PanelAppDict, singletons: bool, blacklist: Optional[List[str...
25219bc32531602c44db202bde350be9402c5b18
66,260
from typing import Type from typing import Union from typing import Sequence from typing import Optional from typing import Dict from typing import Tuple import types def _make_examples_impl( data_dir: j3d.Path, *, split: str, metadata_cls: Type[MetadataHandler], image_idxs: Union[None, int, Seque...
c22e5c1e4bc8ddffd600db9e67b4e04427fa5cfb
66,261
def DSDMatmulimpl(input_w1, input_w2, input_v, output_y={}, kernel_name='DSDMatmulimpl'): """ dense sparse to densne matmul""" # shape_w1 = input_w1.get('shape') # shape_w2 = input_w2.get('shape') # shape_v = input_v.get('shape') if util.get_product_version() == util.VERSION_MINI: tik_inst =...
e7249fdadbbbbc83c746dd8d787eb631c22338b9
66,262
import socket def translate_addrmask(af, addr): """Validate IP address""" addr_mask = addr.split("/") try: socket.inet_pton(af, addr_mask[0]) except socket.error: raise BadRequestError("Invalid IP address") # Test v4 or v6 mask max_cidr_prefix = 32 if af == socket.AF_INET else...
bc2a20c5f7ee803cf908e8f710ce62bc3b5e1dea
66,263
import asyncio async def network_list(cluster_id: str): """Get All Virtual Network from cluster""" try: session = create_session( _id=cluster_id, get_xen_clusters=Settings.get_xen_clusters() ) networks = Network.get_all(session=session) __santilized_networks = awa...
85f4aa966ecb4e09221b48ce91d0cb03f4e73312
66,264
def train_dgcnn(graphs, graph_labels, n_epochs=50): """ Build and train DGCNN model """ generator = PaddedGraphGenerator(graphs=graphs) k = graphs[0].number_of_nodes() # the number of rows for the output tensor, no truncation # done here because all graphs have same number of nod...
3af30a8189f905a5c7b898b9013721d687cc5549
66,265
def modelSimilarity(ex_submodel, ex_ts, valid_new_submodel, new_ts, submod_type): """ This function calcualtes the evaluation measure for the run. ex_submodel = (DataFrame) either existing/expert demand_summary or hourly_profiles submodel valid_new_submodel = (DataFrame) output from dataIntegrity f...
cf1bb5076d52eec159100527718171f75582574f
66,266
def _GKEConnectNamespace(kube_client, project_id): """Returns the namespaces into which to install or update the connect agent. Connect namespaces are identified by the presence of the hub.gke.io/project label. If there are existing namespaces with this label in the cluster, then a list of all those namespaces...
d8d1e666fb28e4c44fd9880b7234dc5cd9cec637
66,267
import torch def lm_forward_step(data, model, args, timers, mems, eval_metric=None): """Forward step.""" # Get the batch. if timers is not None: timers('batch generator').start() if 'mask' in data: data['attention_mask'] = data.pop('mask') tokens, labels, loss_mask, attention_mask...
0db8ea0f3e7ebca0287e0fd0f1c68bd3fa848147
66,268
def load_vars(basepath, results, vault_password=None): """ Load variables from any potential yaml filename combinations of basepath, returning result. """ paths_to_check = [ "".join([basepath, ext]) for ext in C.YAML_FILENAME_EXTENSIONS ] found_paths = [] for path i...
721391474076e92e6b1ffd260d7630716e45d881
66,269
def print_pred(query, corpus, model): """Prints details about input query relative to a corpus and model: - The cleaned query text - The bag of words - Query topic predictions - Topics for individual words from the query.""" def word_topics(word_id): return(model.get_term_topics(wor...
90cf10e19a91ad7ceb545f47e74b2e50db2def7f
66,270
async def url_callback_func(fetcher, range_stream, url): """ Async function which puts the URL onto the storage class's list of values """ return CallbackMutatedClass.values.append(url)
0de9f98378ad3a18e4c4d7b0bc836b900938f6ca
66,271
import struct def short_string(value): """ Encode a string. :param value: Value to encode :type value: bytes or str or unicode :rtype: bytes :raises: TypeError """ if PYTHON3 and not isinstance(value, (bytes, str)): raise TypeError('bytes or str required') elif not PYTHON3 an...
95de1b4aa1e92a8a265913a9fc7b88940cb8e23f
66,272
def example_check_main_engine(app_configs=None, **kwargs): """ Check for existence of the "Main engine" component in the database """ # your check logic here errors = [] logger.info("Our check has been called :]") if not Component.objects.filter(title="Main engine").exists(): errors...
b65f2001a12e50da72ace09eff5e7ea71df0fcff
66,273
def shift_objects(data, solar_za, solar_az, sensor_za, sensor_az, h, num_workers): """ Shifts objects along x and y dimensions Args: data (DataArray): The data to shift. solar_za (Da...
59aca73ebf57f2911ab2d3a8a39643b8d570c690
66,274
def build_A_analytical(material_property_library, mesh, materials): """ While not intended for long term use, this function demonstrates that our steady state model matches the analytical solution. inputs: material_property_library contains relevant material data mesh contains the radial positions of ...
d3f9b0d46852b1664018b0a941b84c07818fd2e1
66,275
def earthsun_distance(unixtime, delta_t, numthreads=1): """ Calculates the distance from the earth to the sun using the NREL SPA algorithm described in [1]. Parameters ---------- unixtime : numpy array Array of unix/epoch timestamps to calculate solar position for. Unixtime is t...
8d06d5e61de386d987bec07af351420db87b2c10
66,276
def backward_prop(data, labels, params,lamb=0.0): """ return gradient of parameters """ W1 = params['W1'] b1 = params['b1'] W2 = params['W2'] b2 = params['b2'] ### YOUR CODE HERE h, y, cost = forward_prop(data,labels,params) y = y-labels gradW2 = h.T.dot(y) gradb2 = np.s...
578ddeea44398cfc1565195b1880728c0b3575e4
66,277
import hashlib import time import os def get_new_dir(title): """ Returns always new directory path. """ name = TEST_REPO_PREFIX if title: name = '-'.join((name, title)) hex = hashlib.sha1(str(time.time())).hexdigest() name = '-'.join((name, hex)) path = os.path.join(TEST_DIR, n...
457494ce43487074242184c71a477b0ac80e3ef8
66,278
import sys def _blocks_to_samples(sig_data, n_samp, fmt): """ Convert uint8 blocks into signal samples for unaligned dat formats. Parameters ---------- sig_data : ndarray The uint8 data blocks. n_samp : int The number of samples contained in the bytes. fmt : list T...
fff6176e8d4de8e1d0e6343200145f9fa042015e
66,279
def list_available_networks(caller_id): """ @cmview_admin_cm @response{list(dict)} AvailableNetwork.dict property for each requested AvailableNetwork """ response = [] for network in AvailableNetwork.objects.all(): response.append(network.dict) return response
b8bcf54acbe85bed1e36968fed1c1cac4a122854
66,280
import logging def blocking_prob(n_servers, n_sources, total_traffic, alg=Algorithm.NEWTON, max_n_iters=1024, tol=pow(2, -24), **kwargs): """Blocking probability in the Engset model. Parameters ---...
36ce12e60589519270fffe2960f794835774b662
66,281
def update(): """ Update me """ req_data = request.get_json() data = personal_schema.load(req_data, partial=True) if error: return custom_response(error, 400) user = personalModel.get_one_student(g.user.get('id')) user.update(data) ser_user = personal_schema.dump(user) return custom_response(se...
049966c6877ef59f3bcd651736f4e69a8c466361
66,282
import select def win32select(r, w, e, timeout=None): """Win32 select wrapper.""" if not (r or w): # windows select() exits immediately when no sockets if timeout is None: timeout = 0.01 else: timeout = min(timeout, 0.001) sleep(timeout) return [...
d909eefa6576b41373869a3f5fa4c02245bfde7b
66,283
def rbf_svm_classify_roc(X_train, X_test, Y_train, Y_test): """ Parameters ---------- X_train : numpy.ndarray training feature vectors X_test : numpy.ndarray testing feature vectors Y_train : numpy.ndarray training set labels Y_test : numpy.ndarray test se...
a9da4c635f27d8ef7a324ecfa26e343db3fda6b5
66,284
def _sbprofile_colors(): """Return an iterator of colors good for the surface brightness profile plots. https://seaborn.pydata.org/generated/seaborn.color_palette.html#seaborn.color_palette """ _colors = sns.color_palette('Set1', n_colors=11, desat=0.75) colors = iter([ _colors[1], _colors[2], _col...
dd0d0f5fef44032d3fbcecaa35a267fddfa3e896
66,285
import os def non_overlap_momentum_strategy_ttest(target_dir, ttest_tail="two-sided", mode="normal"): """ Arguments: target_dir -- the directory of the target file. The target file need to be a "intraday_detail" data file consisted of momentum strategy portfolio val...
125cf8a997539f39c885f57e471a95632d9f8c31
66,286
def dice_loss(y_true, y_pred, smooth=1e-6): """ Loss function base on dice coefficient. Parameters ---------- y_true : keras tensor tensor containing target mask. y_pred : keras tensor tensor containing predicted mask. smooth : float small real value used for avoiding di...
8f2011e60308a57d6abba71c4fce0cb042db1d24
66,287
def render_form(parser, token): """ render_form takes one argument in one of the following formats: {% render_build_form form_instance %} """ try: _, arg = token.split_contents() arg = "form=" + arg name, value = arg.split("=", 1) except ValueError: raise templa...
c32b91299700283a6ab5a5269f2f39a4856d5b44
66,288
def produce_phrases(file): """ Function, which implements all the magic with Markov's chains. As you can see, looks pretty easy:) @param file: input file, consisted of text to be converted into sensible phrases @return: "sensible phrases of MIPT teachers" """ with open(file, "r", enc...
e7ab6e22ce1fa5b8a01995b67159499fdbcdc280
66,289
from pathlib import Path import json def load_processing_unit(unit_path): """Load a :class:`ProcessingUnit` from a persisted processing unit directory""" unit_path = Path(unit_path) with (unit_path / "metadata.json").open(encoding="utf8") as f: metadata = json.load(f) unit = _get_unit_type...
15650de7c6724287d0e4ee0f204852e70da21320
66,290
def get_meraki_device_clients(org_name, device_name): """Query Meraki for Clients.""" dashboard = meraki.DashboardAPI(suppress_logging=True) return dashboard.devices.getDeviceClients(_name_to_serial(org_name, device_name))
9682132355feb59b943edf856fb0d5ff59bd5a97
66,291
def rec_to_bintable(arr, name=None): """ Construct an `astropy.io.fits.BinTableHDU` from a record array. Args: arr (`numpy.recarray`): The data array to write to a binary table. name (:obj:`str`, optional): The name for the binary table extension. Returns: ...
fd1aeda99cf3bb45a24b646afbf263610a19175d
66,292
import contextlib import pathlib import requests def upload(*, sodar_url, sodar_api_token, project_uuid, file_paths): """Upload and replace ISA-tab sample sheet to SODAR.""" while sodar_url.endswith("/"): sodar_url = sodar_url[:-1] url_tpl = "%(sodar_url)s/samplesheets/api/import/%(project_uuid)s"...
a82a04a52e9ddc6f699c96681e70c0fb4ea3018b
66,293
import http def node_identifiers_post(auth, node, **kwargs): """Create identifier pair for a node. Node must be a public registration. """ if not node.is_public or node.is_retracted: raise HTTPError(http.BAD_REQUEST) if node.get_identifier('doi') or node.get_identifier('ark'): raise HT...
ab0d799b40925333476fd331a09b9a4b36143e0b
66,294
def getPluginsDisabled(): """ Return the names of plugin that were disabled. """ if not options: return () return tuple(set(options.plugins_disabled))
0feb34a7d4a840f3828a8f6939944d29de23b915
66,295
def match(pattern, text): """Match pattern against start of text; return longest match found or None.""" remainders = matchset(pattern, text) if remainders: shortest = min(remainders, key=len) return text[: len(text) - len(shortest)]
4bbe38e1f459a9e57cf13f3afb77edbdf110df7b
66,296
import logging from pathlib import Path import re import copy import json def recursive_parse( *, sub_dir=None, data_function, player_match=None, identifier_rules=[], multi=False, ): """ Function that recurses through directories to find replay files and then parse them """ ...
f305ac2869b20535cb3d48a2d381dc7e65986ed8
66,297
def meanclip(x, axis=None, lsig=3.0, hsig=3.0, maxiter=5, minfrac=0.001, full_output=False, dtype=np.float64): """Average `x` after iteratively removing outlying points. Clipping is performed about the median. NaNs are ignored. Parameters ---------- x : array axis : int, optional...
871bc533fafe643d47e1fe30f46d463b8f8a5e4f
66,298
def getClasspathOptions(): """gets the classpath of the vmx86 distributions""" return mx.get_runtime_jvm_args(['VM', 'VMX86_LAUNCHER', 'CORE', 'POSIX'])
b53420a14a0fb6192a83e11fe7927b5a0fb6ef32
66,299