content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List def construct_outgoing_unicast_answers( answers: _AnswerWithAdditionalsType, ucast_source: bool, questions: List[DNSQuestion], id_: int ) -> DNSOutgoing: """Add answers and additionals to a DNSOutgoing.""" out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA, multicast=False, id_=id_) ...
6d9b2036850dbf58f4c83a28479008becf518ed0
3,619,400
import matplotlib.pyplot as mp import numpy as np def parabola(list1, list2, list3, plo=False, pri=False, **kwargs): """Plots a parabola on pre-existing graph between points list1, list2, and list3, returns the parameters of the parabola as in the form y = ax^2 + bx + c, and optionally prints the ...
286c90e94c06431cd22f478a4843c43d2e5a2e43
3,619,401
def attention_mask(nd, ns, *, dtype): """1's in the lower triangle, counting from the lower right corner. Same as tf.matrix_band_part(tf.ones([nd, ns]), -1, ns-nd), but doesn't produce garbage on TPUs. """ i = np.arange(nd)[:, None] j = np.arange(ns) m = i >= j - ns + nd return np.array(m, ...
9f660e93ae589d5501d02e187e41d9bc4fbe7c88
3,619,402
def preview_progress(Task_Options, net, device, preview_loader): """Returns preprocessed and augmented input and target data. For details on all input parameter dictionaries, see: /spectrai/spectrai/configs/*.yml Arguments: Task_Options: dictionary of task options net: PyTorch neural ...
7fde77638323815659dc7e24341e507cb07cf3c5
3,619,403
def is_cellv2_init_ready(): """Determine if we're ready to initialize the cell v2 databases Cells v2 init requires transport_url and database connections to be set in nova.conf. """ amqp = ch_context.AMQPContext() shared_db = nova_cc_context.NovaCellV2SharedDBContext() if (ch_utils.CompareO...
2bac1f9c8f0f25fcc96cf768d378f59eb0a0f971
3,619,404
from typing import Any def get_calendar(obj: Any, dim: str = "time") -> str: """Return the calendar of an object. Parameters ---------- obj : Any An object defining some date. If `obj` is an array/dataset with a datetime coordinate, use `dim` to specify its name. Values must have ei...
a5603b3a322252390e8310fa124a88df27ed5a5e
3,619,405
def twilio_settings_doctype_in_integrations() -> bool: """Check Twilio Settings doctype exists in integrations module or not. """ return frappe.db.exists("DocType", {'name': 'Twilio Settings', 'module': 'Integrations'})
5fcaedec7e8eaf6363622833809d6ddeea16bfcb
3,619,406
async def item_unoshield(ctx): """ Okay so we're playing uno now apparently, this acually seems pretty useful though. The reverse shield can reverse a single rob or nuke. After that it just disappears. like, \*poof\*, and its gone. *\* oh yeah, and it doubles the amount robbed. so thats nice.....
3025869f0327edee97bc97df527eefd96ad6d16b
3,619,407
def merge_two(n1,n2): """ Given two sorted linked list with head nodes n1 and n2, merges n2 into n1 so that the resulting list is still sorted. """ if n1 is None: return n2 if n2 is None: return n1 n_prev1 = None; n_prev2 = None while True: while (n1 i...
95e31b18c9c86b5c5d1314e1b394d91c268e6a52
3,619,408
def find_golden_token(): """ Function indentical to the 'find_silver_token', excepts for the fact that the sought token now are golden. Also in this case the tokens are searched only in the semi-plane in front of the robot (-90 < token.rot_y < 90). """ dist=100 for token in R.see(): ...
b4aadc890fa14d3f52361cd4f92bc9e9e6e8abb6
3,619,409
def filter_data_of_insts(data, to_remove=set()): """ Remove midi.Pattern or MidiObj from an iterable data container if they contain instrument numbers in 'to_remove'. These numbers are same as midi standard -1. """ ret = [] for x in data: keep = True for evnt in utils.evnt_gen(x)...
1e776b1579ab1cf58ce3a46a6e8f2fb1f48fdbbc
3,619,410
def build_text_row(node): """Build a row for the french data""" french_word = bhsa2french.get(str(node), {}) row_data = {'bhsa_node': node} ref = french_word.get('ref') row_data.update({ 'french': french_word.get('french', ''), 'french_verse': frenchverses.get(ref, ''), }) ...
0b78c1721a8544ed12dc0cd646ecd2fec5b8e896
3,619,411
from typing import Dict from typing import Any def to_json_schema( schema: Dict[str, Any], *, nullable_name: str, copy: bool = True, is_response_schema: bool = False ) -> Dict[str, Any]: """Convert Open API parameters to JSON Schema. NOTE. This function is applied to all keywords (including nested) durin...
f7de7f9caa18d634d1aef9f921860c2b67f022b3
3,619,412
from typing import Dict from typing import Tuple def harm_longterm( out_dep: pd.DataFrame, out_ctl: pd.DataFrame, selected: np.array, outcomes: Dict, ) -> Tuple[float, int]: """Calculate the harm from a long-term credit outcome.""" # Impact rates sel_acq_nsuc = np.logical_and(out_dep.succe...
6800b41fab9e755e8ab564a7460827bcc9fd30a1
3,619,413
async def upload_nextcloud_zipfile(file_name: str): """ Upload a .zip File to later be imported into Mealie """ file = BACKUP_DIR.joinpath(file_name) if file.is_file: return FileResponse( file, media_type="application/octet-stream", filename=file_name ) else: return ...
f24dc49d0e76236fbb68cd69583f50b4cdaf1542
3,619,414
def rotators_encrypt(_rotators, _text): """ The rotators work by being given both an initial value as well as a frequency of how often it shifts up. The last rotator always increments one for every character encoded/decoded and other rotators can be configured for different frequencies. If Rotat...
7a12e370d74ae40079205b20f11e19a301063b1f
3,619,415
def ms_ssim(img1, img2, max_val=255, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03, weights=None): """Return the MS-SSIM score between `img1` and `img2`. This function implements Multi-Scale Structural Similarity (MS-SSIM) Image Quality Assessment according to Zhou Wang's paper, "Multi-sca...
b7a3a76343cb8996585d8a7c599874f6e40ed059
3,619,416
import lingam def estimate_corr(data, algorithm="ica", lower_limit=0.01, prior_knowledge=None): """Generate DAG of pair-wise LiNGAM coefficient""" def _model(alg, _kwargs): if alg == "ica": return lingam.ICALiNGAM(**_kwargs) elif alg == "direct": return lingam.DirectLi...
cb95a24fe82b93a8d9a955a7231aae854ce6e925
3,619,417
def fluo_amplitude(elem, line, excitation=None, barn_unit=False): """Get the fluorescence cross section for a given element/line Parameters ---------- elem : string or number element line : string emission line Siegban (e.g. 'LA1') or IUPAC (e.g. 'L3M5') excitation : float (opti...
bf7fa71a6eaae1ce9ad215ecaba26f9b258e9652
3,619,418
def fmt_sec(sec): """Take a time in seconds and convert it to mm:ss.ms""" return fmt_ms(int(sec) * 1000)
bf991385e53ac7b149062aca2b1d63d6be0c2eb5
3,619,419
def accountingEnabledForRecord(record): """ Determine if accounting is enabled for the given record. """ enabledRecordGUIDs = config.AccountingPrincipals if "*" in enabledRecordGUIDs: return True return record.uid in enabledRecordGUIDs
7f7f3ad1fb7da72ff573063994b20f37aa3c9c60
3,619,420
def inventory_reset(): """ Removes all inventory from the database """ Inventory.remove_all() return make_response('', status.HTTP_204_NO_CONTENT)
da334e34f6b4c75f5f9c684b7984c9a503c8fc3a
3,619,421
def make_data_fn(is_training, timesteps2use): """returns data function for processing and returning a feed dictionary to be passed to model""" def data_fn(data): text_batch = Variable(data[0].long(), requires_grad=False, volatile=not is_training) mask = Variable(data[1], requires_grad=False, volatile=not is_train...
5916f237a137a129243f1a3c0d843d1de7053494
3,619,422
def shift_left(x, axis=1): """Shift the input to the right by padding and slicing on axis.""" pad_widths = [(0, 0)] * len(x.shape) pad_widths[axis] = (0, 1) padded = jnp.pad( x, pad_widths, mode='constant', constant_values=x.dtype.type(0) ) # print(padded) return lax.dynamic_slice_in...
6381b105887e75a10e4bbd84ac9bb85154301d7b
3,619,423
def load_cows(filename): """ Read the contents of the given file. Assumes the file contents contain data in the form of comma-separated cow name, weight pairs, and return a dictionary containing cow names as keys and corresponding weights as values. Parameters: filename - the name of the data ...
aa44df075a4aa8d44d37743b8a351ef57133d148
3,619,424
def find_bin_edges(cbins): """ Given bin centres, find the bin edges. Examples -------- >>> print find_bin_edges([1, 2.1, 3.3, 4.6]) [ 0.45 1.55 2.7 3.95 5.25] """ cbins = np.asarray(cbins) edges = cbins[:-1] + 0.5 * (cbins[1:] - cbins[:-1]) edges = np.concatenate( ([2*cbins[0]...
ab235735cf6ccacebea4fe51cb11a022412721f6
3,619,425
import torch def retrieval_collate(data): """Creates mini-batch tensors from the list of tuples (src_seq, trg_seq).""" # separate source and target sequences t2i_batch, i2t_batch = list(zip(*data)) # t2i def generate_inputs(_batch): sent, att_feats, img_masks, box_feats, obj_labels, pos_l...
14ebc659e5d5e40cb7819eeec0d5376dcececc61
3,619,426
def index(): """ represents dashboard home page """ member = Member.query.count() product = Product.query.count() paid_off = Order.query.filter_by(paid_off=True).count() unpaid_off = Order.query.filter_by(paid_off=False).count() return render_template( "dashboard/index.html", ...
f0cd4c3f75e279b673d3751228026227719d311b
3,619,427
def wrap_hashlib(hasher, length=None): """ Wraps hashlib's functions, returning a function that returns the hex-digest of its input. >>> from hashlib import sha1 >>> wrap_hashlib(sha1)(b'heyo') 'f8bb1031d6d82b30817a872b8a2ec31d5380cee5' :param hasher: A function from :mod:`hashlib` :return...
dbd07d4151a5c5c523fe75c3f29b72abfd15c3b8
3,619,428
from googleapiclient import discovery def export_fhir_store_gcs(project_id, location, dataset_id, fhir_store_id, gcs_uri): """Export resources to a Google Cloud Storage bucket by copying them from the FHIR store. See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-clie...
3ac26fd0ba4733d1a5bf0ca3d7ae639d378142c8
3,619,429
from pathlib import Path async def read_fastq_headers(path: Path) -> list: """ Return a list of FASTQ headers for the FASTQ file located at `path`. Only accepts uncompressed FASTQ files. :param path: the path to the FASTQ file :return: a list of FASTQ headers """ headers = list() had_pl...
e344c86346544a0c8c1c854d30661058ae9550a5
3,619,430
from typing import Counter def batch_status(): """ Same as status, but for a list of IDs. INput message shall be { "ids": [id1, id2, ...] } where ids are task-ids The returned global status will be PENDING unless all tasks are SUCCESSful :return: json message with {"status": global status, "progre...
33c4bb7ccf7f1ec1447baa2c62d924f2f1e7a8ce
3,619,431
import os import requests def download_wukrii(program_abs_path, wukrii_page_num): """Downloads latest Wukrii comics.""" # Create/change appropriate comic folder. comic_folder = os.path.join(program_abs_path, "wukrii") if os.path.exists(comic_folder): os.chdir(comic_folder) else: os...
ff89400ade4eefc4ac4df400cfb0289bd6951ea7
3,619,432
def _get_lastword_range(prefix, stringlist, tokenizer=None): """ Get the range of lastword tokenized index in label_ids Args: prefix: list(str), list of text with its last word removed(a.k.a. "prefix") in form of str stringlist: list(str), list of text, same as it is in split_by_last_word ...
6a3a74752d52fb3712fb43976ff47b1ee3f84492
3,619,433
def is_valid_solution(G, c, k): """ Checks whether D is a valid mapping of G, by checking every room adheres to the stress budget. Args: G: networkx.Graph c: List of cities to remove k: List of edges to remove (List of tuples) Returns: bool: false if removing k and c disc...
caea354dab043cc038c92f83f8d709e6807e8dee
3,619,434
def get_loss_layer(mlp_out, action, precision, batch_size): """The loss layer used for the MLP network is obtained through this class.""" scale_factor = tf.constant(2*batch_size, dtype='float') uP = batched_matrix_vector_multiply(action - mlp_out, precision) uPu = tf.reduce_sum(uP*(action - mlp_out)) #...
7051df7c6868fa485a45933bd4da0ecaa2285e7f
3,619,435
def view_task_info(token, dstore): """ Display statistical information about the tasks performance. It is possible to get full information about a specific task with a command like this one, for a classical calculation:: $ oq show task_info:classical """ args = token.split(':')[1:] # cal...
38304935b8990b1895f6d2e945e2c187e356773d
3,619,436
def revision_exists(git_dir, revision): """ check if the provided revision exists With attempt to find if the provided revision values (be it a branch, tag or hash value) exists in the provided Git directory. Args: git_dir: the Git directory revision: the revision (branch, tag, has...
b04398d523da53acaccc66472ef50cf5efb78821
3,619,437
import os import time def isOldEnough(nzbFile): """ Determine if the NZB file's modification time is > Hellanzb.NZBQUEUE_MDELAY """ mtime = os.stat(nzbFile).st_mtime now = time.time() if mtime < now and now - mtime < Hellanzb.NZBQUEUE_MDELAY: debug('Delaying enqueue of %s: mtime: %i Hellanzb.N...
5d1a96d7a774d0af475361aaaf484428ed13b65f
3,619,438
import re def isBlank(s): """ Returns True if string contains only space characters.""" return bool(re.compile("^\s*$").match(s))
1e6f7f7cefa4fea3d5b7443d74a265a79c3db3d7
3,619,439
from gluon.contrib.simplejson import dumps from os import mkdir from PIL import Image from sys import path def nicedit_image_upload(): """ Controller to upload images with nicedit """ page_id = request.args(0) pathname = path.join(request.folder,'static','images', 'pages_content', page_id) i...
98d0efb4d80b775a3b57010a23138fe23fa3de45
3,619,440
def __extract_tzd(m): """Return the Time Zone Designator as an offset in seconds from UTC.""" if not m: return 0 tzd = m.group("tzd") if not tzd: return 0 if tzd == "Z": return 0 hours = int(m.group("tzdhours"), 10) minutes = m.group("tzdminutes") if minutes: ...
5e786cab67a2151df8ed8851dc19a6adbc365aea
3,619,441
def measure(dataframe, lasers=[405, 488, 561, 638], channels=[1, 2, 3, 4, 5, 6], create_fcs=False, outfile_name='sample_output.fcs'): """ This is a function that will measure fluorescence intensity for any given sample DataFrame and laser/channel parameters. Output will be just a pandas Data...
5cb8ec3a0ad0145b799bc44e15235a1d377704f1
3,619,442
def print_errors_result(result, verbose=False): """ """ spacers = 4 if verbose: print(f"\nTotal Stats\n{spacers*' '}max. err.: {result[0]:6.3f};") print(f"{(spacers-2)*' '}c-avg. err.: {result[1]:6.3f};") print(f"{(spacers-2)*' '}t-avg. err.: {result[2]:6.3f}") r...
83fadbb6fe977c262a822d7217f0103cd7f9ecde
3,619,443
def filter_country_stats(stats, top_n, latest_date): """Filter the top n country statistics Arguments: stats {dict} -- The country statistics top_n {int} -- The top n results to retrieve latest_date {datetime} -- The latest date Returns: dict -- The filtered country...
66b0cedea261887c53fd197b1ffda56866ff8627
3,619,444
def list_dict(l): """ return a dictionary with all items of l being the keys of the dictionary """ return dict([(i,None) for i in l])
cb5a9c3acc4a0e6d162482d6b72e1eb52f6fad53
3,619,445
def readnetcdfInitial(name, value,default = 0.0): """ load initial condition from netcdf format """ filename = os.path.normpath(name) try: nf1 = Dataset(filename, 'r') except: msg = "Netcdf Initial file: \n" raise CWATMFileError(filename,msg) if value in nf1.variable...
346aad3162927f59cbb7a46b638ab1607dd158e7
3,619,446
from operator import ne def value_at_location(x, single_vol=False, single_pts=False, force_post_absolute_val=True): """ Extracts value at given point. """ # vol is batch_size, *vol_shape, nb_feats # loc_pts is batch_size, nb_surface_pts, D or D+1 vol, loc_pts = x fn = lambda y: ne.ut...
ca68d189604edf8a06734a8528990dfd1d693b29
3,619,447
def is_reference(key: str) -> bool: """ Does this key represent a berglas reference """ return key.startswith(REFERENCE_PREFIX)
700a7fcaaadfa636dc72f44d135bb9f9272d6d19
3,619,448
def compute_heuristic_conn_4(init_pos, coord): """Returns Manhattan heuristic for distance from coord to init_pos init_pos - coordinate of position of goal configuration coord - coordinate of configuration for which heursitic is being computed Returns the heuristic distance to goal t...
873fcbad5ebadcb8d0f0009c6d3bb615146bab5a
3,619,449
import pandas import types def hpat_pandas_series_floordiv(self, other, level=None, fill_value=None, axis=0): """ Pandas Series method :meth:`pandas.Series.floordiv` implementation. .. only:: developer Test: python -m hpat.runtests hpat.tests.test_series.TestSeries.test_series_op5 ...
3abe10214fbbb336ad13078e87e310c2ecae01cc
3,619,450
def subs_si(expr: Expr) -> Expr: """Substitute any ConstantSymbols in an Expression with their value in a SI units Args: expr: Expr, the sympy expression in which to substitute constant symbols for values Returns: Expr, the substituted expression """ return _subs_const_...
3caa133c24508f7d54cbe0f6a7eba46a4834479d
3,619,451
def generateGenericCell(nBuildings, pAgents, pPHHagents, pAgriculture, pDHN, pPVplants, pHeatpumps, pCHP, pBTypes, nSepBSLAgents, pAgricultureBSLsep, region, hist=0): """ Create a cell of a generic energy system The...
62272f03b6c3e6bffe03fb4e7a3f9c058cace9fa
3,619,452
def cancel_and_stop_intent_handler(handler_input): """Single handler for Cancel and Stop Intent.""" speech_text = "OK Mate calm down." attr = handler_input.attributes_manager.session_attributes attr['readShows'] = False attr['readMovies'] = False attr['readBoth'] = False attr['active_reques...
c31bdbdb7810e0afd71e073c4bbc6f6486294782
3,619,453
def get_excluded_apps_and_models(excludes): """ :param excludes: list of app labels ("app_label.model_name" or "app_label") to exclude :return: Tuple containing two sets: Set of AppConfigs to exclude, Set of model classes to excluded. """ excluded_apps = set() excluded_models = set() for exc...
57fb09de6dc2162386a7e15a15a8ebe7c5795a2a
3,619,454
import subprocess import argparse def subprocess_run(args, **kwargs): """ Emulate Python 3 "subprocess.run" Don't help the caller remember to say: stdin=subprocess.PIPE """ # Trust the library, if available if hasattr(subprocess, "run"): run = subprocess.run(args, **kwargs) # pyli...
39ed817b56b6c3869d8565a0fc5a862bcd331441
3,619,455
def frequency(text, char): """ Counts frequency of a character in a string. """ count = 0 for c in text: if c == char: count += 1 return count
5a58161f6aed1f8ba88ed6490891b544b23449cd
3,619,456
def Interpolate(a,h,image,BP,sig_data=1,K=Squared_Expo,width=9): """ Interpolate(a,h,image,BP,sig_data=1,K=Squared_Expo,width=9) Correcting the values of bad pixels by interpolation. Parameters ---------- a: float Same as in GPR_Kernel. h: float or shape (2,) array-like ...
d55a5b42dcb3787770f75b92ebad5989d9d34945
3,619,457
import warnings def ripser( X, maxdim=1, thresh=np.inf, coeff=2, distance_matrix=False, do_cocycles=False, metric="euclidean", ): """Compute persistence diagrams for X data array. If X is not a distance matrix, it will be converted to a distance matrix using the chosen metric. Par...
2053225473556b8d9d15314ab12b74248616292c
3,619,458
from typing import List import itertools def slice_spec_from_stats( # pylint: disable=invalid-name statistics: statistics_pb2.DatasetFeatureStatisticsList, categorical_uniques_threshold: int = 100, max_cross_size: int = 2) -> List[slicer.SingleSliceSpec]: """Generates slicing spec from statistics. A...
ffbcc6d229bec3016f8dfc746e186de061f30409
3,619,459
def is_benchmark_supported(benchmark : Benchmark): """returns True if the provided benchmark is supported by the tool and if the given benchmark should appear on the generated benchmark list""" # Check for unsupported input languages: everything but PRISM currently if benchmark.is_prism(): # Tempor...
54d635d7f39e1a89ad42c11d3810bc7b20e03b0d
3,619,460
from typing import Optional def get_regional_map_file( atlas_id: str, parcellation_id: str, region_id: str, space_id: Optional[str] = None): """ Returns a regional map for given region name. """ roi, space_of_interest = parse_region_selection( atlas_id, parcella...
1d5a70fb5972f0a43f1eae5938e309df33928ded
3,619,461
import sys import os def main(): """ NAME ani_depthplot.py DESCRIPTION plots tau, V3_inc, V1_dec, P and chi versus core_depth SYNTAX ani_depthplot.py [command line optins] # or, for Anaconda users: ani_depthplot_anaconda [command line options] OPTIONS ...
f92407df0a88ca0565f75a967ca50b55c1319dd0
3,619,462
def get_parent_execution(execution_db): """Get the action execution for the parent workflow Useful for finding the parent workflow. Pass in any ActionExecutionDB instance, and this function will return the action execution of the parent workflow. :param execution_db: The ActionExecutionDB instance for...
1dddbbd9cbb3edcd1b8c9c7d536551f6aa14b22e
3,619,463
def counts(short_question, course_code): """Return number of comments by star for a given course code, question, and fiscal year. """ course_code = course_code.upper() # Unpack arguments fiscal_year = request.args.get('fiscal_year', '') # Run query; return dict of 0s in case of invalid arguments try: counts...
129d6d145458d2e4502cb563ab608dcdb85378aa
3,619,464
from skmob.core import trajectorydataframe import pandas as pd import logging def get_route_geometry(locs_or_traj): """ Computes a map-matched geometry for a list of locations or TrajDataFrame Parameters ---------- locs_or_traj : list | TrajDataFrame Either a list of coordinates in the fo...
7a87ac19e4615d38aa180f14c2381b6a51db9e36
3,619,465
import os def build_index(root, base_url): """ Create a new data.xml index file, by combining the xml description files for various packages and collections. ``root`` should be the path to a directory containing the package xml and zip files; and the collection xml files. The ``root`` directory is expecte...
4bced06d755d9d952674e857b29eb72344eccb1a
3,619,466
from typing import Tuple import struct async def read_scoreframe(data: bytearray) -> Tuple[ScoreFrame, int]: """ Read an osu! scoreframe from `data`. """ offset = 29 s = ScoreFrame(*struct.unpack('<iBHHHHHHiHH?BB?', data[:offset])) if s.score_v2: s.combo_portion, s.bonus_portion = struct.unpa...
45e1ea7faebacc62be08cd84f877291560b85726
3,619,467
from operator import and_ from operator import or_ def status_log_for_each_instrument(): """Get a dictionary containing the most recent log entry for each instrument with log entries. Returns ------- Dictionary with the instrument ids for each log as the key and a dictionary for the log's 'author', '...
6ed2f7016a91c0084cdb94216385c37e400e24de
3,619,468
def update_blog(title): """This defines the creation of a new form """ blog = Blog.query.filter_by(title = title).first() form = BlogForm() if form.validate_on_submit(): blog.title = form.title.data blog.meta_title = form.meta_title.data blog.body = form.blog.data bl...
b2bc77fe6647ac3cefb7923103865dfccc1a1d6b
3,619,469
def softmax_pooler_output(nr_class, *, exclusive_classes=True, **cfg): """Select features from the pooler output, (if necessary) mean-pool them to produce one vector per item, and then softmax them. The gradients of the class vectors are incremented in the backward pass, to allow fine-tuning. """ ...
3a5610cafb182b60eda30d17e78c4f33429e6517
3,619,470
def get_latest_tle_from_restapi(number): """ :param number: get the latest TLE from Restful API :return: a TLE """ return "see restful_client.py"
ac6c5e908bea386a12427ac07cd0249cf1b6f7e7
3,619,471
import pandas as pd import os def mroz2(path): """mroz Data loads lazily. Type data(mroz) into the console. A data.frame with 753 rows and 22 variables: - inlf. =1 if in lab frce, 1975 - hours. hours worked, 1975 - kidslt6. # kids < 6 years - kidsge6. # kids 6-18 - age. woman's age in yrs ...
285f1e6d81bb369661425fb510a59e06a426fe7a
3,619,472
import time def measure_command(func, kwargs): """ Measures the execution time of a function :param func: function :param kwargs: dict keyword arguments :return: float, result (time, result of fucntion) """ time_start = time.time() r = func(**kwargs) dt = time.time() -...
33ca8627681b3f32d8d39fc088175a6a38d51097
3,619,473
from bs4 import BeautifulSoup def get_soup_object(response_content: str) -> BeautifulSoup: """ Note: possible to get page even if content is not desired """ # TODO: error handling here if empty string return BeautifulSoup(response_content, "lxml")
486306d5a42f286d36fa96fd01a606154ccaa2ec
3,619,474
import os import zipfile def in_pyz(): """ Determine if running in pyz archive """ pyz_file = os.path.abspath(os.path.dirname(__file__)) if zipfile.is_zipfile(pyz_file): return True else: return False
0f9eae66abeec4f6f916cd037e16c743b0f3a77b
3,619,475
def generator(input_dim=2,activation_function='linear',bias=True): """ Purpose: ------- This is a network that can used to represent element in a given presentation. The choice is the one made in the paper. Arguments: --------- dim : integer dime...
eb7eeb5245abbbfe911941db83070d3ce987f08c
3,619,476
from datetime import datetime def _test_dt(code): """判断股票上市时间是否晚于指定时间""" try: return datetime.datetime(2005, 1, 1) >= get_ipo_date(code) except: return False
ff0fb6beb759235bb05637be735f73c1a8270ef4
3,619,477
from typing import List from typing import Optional from typing import Mapping def edit_equipment_type( client: SymphonyClient, name: str, new_positions_list: List[str], new_port_definitions: List[EquipmentPortDefinition], new_properties: Optional[Mapping[str, PropertyValue]] = None, ) -> Equipmen...
3c69176d7175c411f0a96359d3379e0b1e0cff1d
3,619,478
def get_color(pred_class, labels): """ Function to color the barplots. Defaults to blue, but it colors the prediction green/red if it's correct/incorrect :param pred_class: :param labels: :return: """ num_classes = 10 # Hard coded for the 10 MNIST labels target_class = np.argmax(lab...
3bc47c2c28d6177e01f2513b7c826a852e1c7e61
3,619,479
def add_member(client_session, esg_name, pool_name, member_name, member_ip, port=None, monitor_port=None, weight=None, max_conn=None, min_conn=None): """ This function creates a Member inside a Server Pool on an ESG :type client_session: nsxramlclient.client.NsxClient :param client_sessi...
c58f6d28ebc0da3929f1d2572da6e0e227085073
3,619,480
def check_auth_shared_secret(auth = True, ): """ Authentication via HMAC signatures, nonces, and a local keypair DB. """ def decorator(func): def proxyfunc(self, *args, **kw): user_key = dict(self.request.headers).get("Key", False) ...
441d1d8e898ca561f8c0cec59dfa17461d305f47
3,619,481
def _find_new_wire(wires: Wires) -> int: """Finds a new wire label that is not in ``wires``.""" ctr = 0 while ctr in wires: ctr += 1 return ctr
b03afa0f77615f37d6c1f2f11d5d72c73fadeba5
3,619,482
import psutil def is_linux_ready(path): """ linux下的文件是否已经准备好 :param path: :return: """ for proc in psutil.process_iter(): try: for item in proc.open_files(): if path == item.path: return False except Exception: pass ...
b373cbcb34977bce784021787c5b55b7bf06df99
3,619,483
import time import torch def evaluate_model( model, eval_loader, device, k=1, split_name="VAL", log_file="log.txt" ): """ Evaluate model (nn.Module) on data loaded by eval_loader (torch.utils.data.DataLoader) Check top `k` (default: 1) predictions for each class while evaluating class accuracies R...
cf5b636dcd5e1cce7092e7e7cd107e63e8b98f24
3,619,484
import inspect from functools import partial def cli_handle_exception(exception_handler, exception_classes): """ deal with exception stack info, and then just throw the wrapper exception by cli >>> def cli_handler1(ex): ... assert False, 'Need root permission' >>> @cli_handle_exception(cli_han...
2cfa6a074de1c55142a4f8f2d71ed08a66ec726a
3,619,485
def getMonthlyReportList(userId, year, month): """選択された月の1ヶ月分の月報データを取得するMapperを呼び出す :param userId: 登録ユーザID :param year: 登録年 :param month: 登録月 """ dto = __getList(userId, year, month) return dto
be54298534bda05ca65a48aa69a2158fa94a5c10
3,619,486
def frequency_sort(items): """ Return rating by frequency """ if sorted(items) == list(set(items)): return items elif len(set([items.count(x) for x in items])) == 1: return sorted(items) else: return sorted( sorted(items, reverse=True), key=lambda k: (item...
e782c137c5efececd46db6d9ac013790e943d8c8
3,619,487
def read_ts_guess_atomic_numbers(content): """Read structure from xtbscan.log file """ atom_symbols = [] number_of_atoms = int(content.split('\n')[0].strip()) ts_guess_energy, ts_index = read_ts_guess_energy(content) ts_index = int(ts_index) i = 0 for line in content.split('\n'): i...
a24f1d23377c82c320d108944c21c8833ed35628
3,619,488
def templatepartsmap(spec, t, partnames): """Create a mapping of {part: ref}""" partsmap = {spec.ref: spec.ref} # initial ref must exist in t if spec.mapfile: partsmap.update((p, p) for p in partnames if p in t) elif spec.ref: for part in partnames: ref = '%s:%s' % (spec.ref...
22ea9a0d474d832cf427568ee2e04adf1e00e0d4
3,619,489
def _gen_chamnet_v2(depth_multiplier, num_classes=1000, **kwargs): """ Generate Chameleon Network (ChamNet) Paper: https://arxiv.org/abs/1812.08934 Ref Impl: https://github.com/facebookresearch/maskrcnn-benchmark/blob/master/maskrcnn_benchmark/modeling/backbone/fbnet_modeldef.py FIXME: this a bit of a...
51f70f287f837a3f2e88c18e92ddbdf6ec347db0
3,619,490
def two_p(name, space="nm", index_key=None): """ Return expression representing a 1-boson operator name (str): Name of operator space (str): Name of boson space """ x = Idx(0, space, fermion=False) y = Idx(1, space, fermion=False) t1 = Term( 1, [Sigma(x), Sigma(y)], [Tensor([x, ...
0645ca6a27ea8b40b9f9ebb9fc2cf9ac4722a80b
3,619,491
import re def create_sig_selectors(width, bandwidth, scheme): """Generate indices for LSH band selectors :param width: :type width: int :param bandwidth: :type bandwidth: int :param scheme: :type scheme: str :return: :rtype: tuple """ split_res = re.split(r'\b([a-zA-Z]+)(...
a1ee500b62f91452d6ea9674f0c797258ef40c0e
3,619,492
import numpy def non_nan_values_per_image(input_data): """Create boolean mask to index nans in original data, assuming all samples in the dataset have nans at the same position""" boolean_nan_idx = numpy.isnan(input_data[:, 0, 0]) count = numpy.count_nonzero(numpy.isnan(input_data[:, 0, 0])) non_n...
e963193bd4d5fcfcefb06b1e3687010ecf851745
3,619,493
def fit_pipeline(j_dataset, j_model, df): """ fit the model with data provided in the dataframe df, and information on the dataset in json format :param j_dataset: dataset info in json format :param j_model: model as a json :param df: data as dataframe (including x and y columns and columns not use...
d6260b1c9813574b70c7db92a8b2acf9790be0e0
3,619,494
def _find_sub_prog(): """ Returns the first job submission command found on the system. Currently, only qsub and sbatch are supported """ possible_sub_prog_list = ['sbatch', 'qsub'] for prog in possible_sub_prog_list: if popen('command -v ' + prog).read() != '': return prog ...
3842751031238e64c3f10b203c60fb0eccf7b702
3,619,495
import os def processed_json_filename(path): """Take the path to a raw json asset and return the filename of the binary asset.""" return os.path.basename(processed_json_path(path))
4a110484a1a37aabcf71d964c1be29c9dfeb31e2
3,619,496
from typing import Tuple from typing import Dict from typing import Any from typing import List def generate_evaluation_table( evaluation_directory: str, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]], str]: """ Generate a table from the currently selected results.json summary file. Parameters -...
586603cb3f2f21d334e7ffe41f590a5e850c3499
3,619,497
import json def recommendation(request): """ Get: Returns a list of recommendations Input: { from: optional(str), to: optional(str), } Output: [ Recommendations ] === Input: { feedback_id: int, feedback: str, } Output...
0a51d3426ac59c19e2773cd23f5dc2a9ce50d09e
3,619,498
def get_active_days_in_range( range_start, range_end, ad_delivery_start_time_series, last_active_date_series): """Calculate the days an ad was active in a given range. Args: range_start: datetime.date Start of period of interest range_end: datetime.date End of period of interest ...
e94c1f7e38342395790236d109dde2688ec3b50c
3,619,499