content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def inFileDict(inFileList): """ generate a nested dictionary of the input files organized by sample and barcode in the format: dict[sample][barcodeGroup][dataType]=fileName """ outDict = {} for f in inFileList: sample = f.split('_')[-3].split('/')[-1] barcodes = f.split('_')[-2] ...
c67183b85890128b3b1728d15f7a45532ee490a3
3,618,444
import re def smi_tokenizer(smi): """ Tokenize a SMILES molecule or reaction """ pattern = "(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])" regex = re.compile(pattern) tokens = [token for token in regex.findall(smi)] assert smi == '...
f9a8702047659991d32945dd73def6f825542576
3,618,446
import time def disable_user(client, username): """ disables user in keystone. Takes: * keystone client object * username Returns True is succeeded, false if issues. """ try: desc = "disabled_at:%s" % time.strftime("%d.%m.%Y") uid = client.users.list(name=username)[0].id ...
acefcdf820629db5212af947efed9b88d0f459e0
3,618,447
def pairs2dm(pairs): """ Convert eigenpair entries into eigenvalue and density matrix pairs. """ return [(v, ket2dm(e)) for v, e in pairs]
fc5ef0b9262397dcd59d73f7237371337b65a2c1
3,618,448
def find_closest_vertex(desired_hop, available_vertices): """ Find the closest downstream (greater than or equal) vertex in availbale vertices. If nothing exists, then return -1. Keyword arguments: desired_hop -- float representing the desired hop location available_location -- np array of avai...
bf2600e9da8bce32d9e99cea3ac6c92a3b612408
3,618,449
def mat_(path="~/.opticks/GMaterialIndexLocal.json"): """ Customized names to codes arranged to place more important materials at indices less than 0xF:: simon:~ blyth$ cat ~/.opticks/GMaterialIndexLocal.json { "ADTableStainlessSteel": "19", "Acrylic": "3", ...
c4ae5fb0da48141bfcada896b31103bc9a5b3c43
3,618,450
def add_model_components(m, d, scenario_directory, subproblem, stage): """ :param m: :param d: :return: """ def total_performance_standard_emissions_rule(mod, z, p): """ Calculate total emissions from all performance standard projects in performance standard zone ...
6cb3aaeb75dc6d51a18150d9b5eebaeb81efd55e
3,618,451
from typing import Optional def exp(x: VariableLike, *, out: Optional[VariableLike] = None) -> VariableLike: """Element-wise exponential. Parameters ---------- x: Input data. out: Optional output buffer. Returns ------- : e raised to the power of the input. ...
670c665697e12543df6c2d9b402c63b1f3d95610
3,618,453
def _config_generator( local_config, min_iter=None, max_iter=None, warmup=False, callback=None, ): """Configuration generator. Turns the iterable config into a generator of config dictionaries. Args: local_config: The configuration dictionary. All values must be iterable. ...
cdf9e99105798b26ef4c8bf41665d8b48796280a
3,618,454
def longest_ORF(dna): """ Finds the longest ORF on both strands of the specified DNA and returns it as a string #TAA TGA TAG >>> longest_ORF("ATGCGAATGTAGCATCAAA") ['ATGCTACATTCGCAT', 3, -1] >>> longest_ORF("AAAAAAAA") [''] """ lenlist = [] orflist = find_all_ORFs_both_strands(dn...
f3b7d89e30dc657febeb4270f6e9723ff2e5c1b4
3,618,455
def update_file(): """更新""" data = request.form file_id = data.get('file_id', None) content = data.get('content', None) file = FileName.query.get(file_id) if not file: return jsonify({'code': '404'}) file.content = content db.session.commit() return jsonify({'code': '201', 'm...
4a3f363e990ef56f8f32d0c749b78703f95064bd
3,618,456
def distribute_permissions(request): """ 权限分配 :param request: :return: """ user_id = request.GET.get('uid') # 业务中的用户表 user_model_class = import_string(settings.RBAC_USER_MODLE_CLASS) user_object = user_model_class.objects.filter(id=user_id).first() if not user_object: u...
bf808e93cc22395b4220d90c732029c6beffacab
3,618,457
def load_exec001_data(file_name): """Loads data from a saved MCC numpy trial file.""" with open(file_name, 'rb') as file: mcc = np.load(file) inc = np.load(file) prf = np.load(file) dem = np.load(file) return mcc, inc, prf, dem
b260cedc00802b783356b44312e41ceb54d03e0f
3,618,458
def get_password(hostname: str, port: int = 1433, database: str = "MOSAIQ"): """Get password from keyring storage Parameters ---------- hostname : str The MSSQL server hostname port : int, optional The MSSQL server port, by default 1433 database : str, optional The MSSQL...
abf8f7914f66fd5a8e5ae562733f915f0d484573
3,618,459
def get_guest_mailbox(mailbox_id): """ Return all guest mailboxes of mailbox with provided id """ return (guest_mailbox for guest_mailbox in get_mailbox_guests_query(mailbox_id))
6cc130cf12fa1aaece0fa054016d7e87d6cea397
3,618,460
def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret
dd707700de52020102ad51ad6f8494d0db489463
3,618,461
import re def is_valid_regex(string): """ Checks whether the re module can compile the given regular expression. :param string: str :return: boolean """ try: re.compile(string) is_valid = True except re.error: is_valid = False return is_valid
3893410afd8d3e6ed9310550159b35cc504dfffa
3,618,462
def get_vcf_allele(hgvs, genome, transcript=None): """Get an VCF-style allele from a HGVSName, a genome, and a transcript.""" chrom, start, end = hgvs.get_vcf_coords(transcript) _, alt = hgvs.get_ref_alt( transcript.tx_position.is_forward_strand if transcript else True) ref = get_genomic_sequenc...
66a9b025624727ba06aa92c88365069612135c64
3,618,463
def lr_grid( adata: AnnData, num_row: int = 10, num_col: int = 10, use_lr: str = "cci_lr_grid", radius: int = 1, verbose: bool = True, ) -> AnnData: """Calculate the proportion of known ligand-receptor co-expression among the neighbouring grids or within each grid Parameters -------...
3358913007c1a00156df8ea70390d5f27c6c58cf
3,618,464
def _read_amplifier_data(gain_filename, phase_filename, gain_offset=0): """ Gather frequency-dependent amplifier data from data files. Each data file should have columns for frequency, gain or phase data, and a third empty column. The gain should be in dB and the phase should be in degrees. Pa...
4652d4198a0e45af3e7823e46ca7a981cc3c17ba
3,618,465
import numpy def oht_model( gw, oro, fsns, flns, shfl, lhfl ): """parameters; must be dimensioned as specified: gwi : gaussian weights (lat) oroi : orography data array (lat,lon) requires the lat and lon are attached coordinates of oro and that oro and the following variables are 2D arrays (...
58f3378172026fe700c38bfb8fa76ff0a1f9c016
3,618,466
import logging def format_mulenc_args(args): """Format args for multi-encoder setup. It deals with following situations: (when args.num_encs=2): 1. args.elayers = None -> args.elayers = [4, 4]; 2. args.elayers = 4 -> args.elayers = [4, 4]; 3. args.elayers = [4, 4, 4] -> args.elayers = [4, 4]. ...
fbecf63e660ba0756e86a4334de95e7ae5f6736c
3,618,468
def expand_Hc(Hc): """Calculate the matricized quadratic operator that operates on the full Kronecker product. Parameters ---------- Hc : (r,s) ndarray The matricized quadratic tensor that operates on the compact Kronecker product. Here s = r * (r+1) / 2. Returns ------- ...
b041349e766b4de785b7a711d527b4c2400c389a
3,618,469
from typing import List from typing import Dict def get_best_paragraphs(data: pd.DataFrame, query: str, doc_id: str, sim, n_matching: int) -> List[Dict[str,str]]: """Retrieves the best paragraphs for expected doc using similarity model Args: data [pd.DataFrame]: data df with processed text at paragrap...
4503a9f476293607634abe6dc71d4e06efb36529
3,618,470
def get_word_stats(searchType, metaField): """ Return JSON with basic statistics concerning the distribution of a particular word form by values of one metafield. This function can be used to visualise word distributions across genres etc. If searchType == 'context', take into account the whole quer...
90c7be7320ba3b69fcb348cd6e6dd29330f8a915
3,618,472
from typing import Optional def get_order_item_by_name(expand: Optional[str] = None, order_item_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetOrderItemB...
392fec4b6e7ff4901a2c68004d04ac43840c5ff1
3,618,474
def did_detect(tuple_list, entry_zones, exit_zones): """ Determine if objects are coming or going """ # print('alwaysai.py: did_detect: entry zones: {}'.format(entry_zones)) global ENTER_CALLBACK global EXIT_CALLBACK for object_id, prediction in tuple_list: box = prediction.box ...
898f1666e1c0cbfed211da45b7a7bafd6afee3a8
3,618,475
def matmul_AT_B_A(a, b): """ Computes A.T * B * A, dealing automatically with sparsity and data modes. :param a: Tensor or SparseTensor with rank 2 or 3. :param b: Tensor or SparseTensor with rank 2 or 3. :return: Tensor or SparseTensor with rank = max(rank(a), rank(b)). """ at_b = matmul_AT...
6c86e6fb578298a218e310e147b8f14f32a44959
3,618,476
def run(): """Default Run Method""" return problem57(1000)
040a59863943c23fe1d595d66a225a60b1f8c08d
3,618,478
from typing import Optional import torch def elementwise_spatial_consistency_loss( input: Tensor, target: Optional[Tensor], pred: Tensor ) -> Tensor: """Apply elementwise weight and reduce loss between a batch of input and a batch of target. Args: input (Tensor): Original input shap...
e3dfa33c6e2c2ae91ec18732ac04a338a8e50a2f
3,618,479
def view_program_slides(eid): """ Creates the HTML slides for the songs associated with a program sheet. :param eid: The eid of the program for which the HTML slides are to be made. :type eid: int :returns: Renders the HTML slides. """ program = fill_program_information( pr...
d91211031c9efc9691f133aa85ef6705418c1e95
3,618,480
def register_implementation(card_view_flavor="simple", name=None): """Decorator for marking a function as implementation for an analysis function. :param card_view_flavor: defines how results for this function are displayed, see views.CARD_VIEW_FLAVORS :param name: human-readable name, default is to create...
66421af066723397c29256fdbec14eeee16d5d85
3,618,481
from .models import AbstractAttachment def get_attachment_model(): """ Returns the Attachment model that is active in this project. """ try: klass = django_apps.get_model(summernote_config["attachment_model"]) if not issubclass(klass, AbstractAttachment): raise ImproperlyCo...
777501f7f5ad6a8bc8a084eac965a7296cdfacf0
3,618,482
def get_date_effect_strategy(): """日历效应策略""" print("""根据天风证券研究表明,基金业绩在每年三月末具有较好的持续性,因此推荐在每年三月末测试日历效应策略""") funds = get_fund_ranking("gp") funds.extend(get_fund_ranking("hh")) funds.extend(get_fund_ranking("qdii")) funds = [f for f in funds if f["fundname"][-1] not in ["B", "C", "E", "H", "O"]] ...
15b26df314f97165568cb8a716a9f2bd88376efe
3,618,483
def setup_scanner(hass, config: dict, see, discovery_info=None): """Set up the iCloud Scanner.""" username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) account = config.get(CONF_ACCOUNTNAME, slugify(username.partition('@')[0])) icloudaccount = Icloud(hass, username, password, ac...
d96af1fa4b3f7ddac8ab80255a510d9b7be757a8
3,618,484
def parse_cluster_pubsub_numsub(res, **options): """ Result callback, handles different return types switchable by the `aggregate` flag. """ aggregate = options.get('aggregate', True) if not aggregate: return res numsub_d = {} for _, numsub_tups in res.items(): for chann...
0e499f8508b0f5507fa0b2c418d0a253d35a32f5
3,618,485
import warnings def get_font(font_name, font_size): """ Tries to load the named font at the given size but falls back on default font if this is not possible. @return: The named font at the given size if possible. """ try: return ImageFont.truetype(font_name, font_size) except: ...
d8890e2844ddc38a9ec2e2d8bccb91448db236cf
3,618,486
def convert_aux_to_base(new_aux: float, close: float): """converts the aux coin to the base coin Parameters ---------- new_base, the last amount maintained by the backtest close, the closing price of the coin Returns ------- float, amount of the last aux divided by the closin...
f76324e0a61a58a926d3f4cadf60315692d35fee
3,618,487
def _estimate_double_gaussian_parameters(x_data, y_data, fast_estimate=False): """ Estimate of double gaussian model parameters.""" maxsignal = np.percentile(x_data, 98) minsignal = np.percentile(x_data, 2) data_left = y_data[:int((len(y_data) / 2))] data_right = y_data[int((len(y_data) / 2)):] ...
6778a6c71c1ed1c0090d1a9a9d46c9b628ff9764
3,618,488
def clone_model_with_weights(model_to_clone): """Clone keras model with weights.""" cloned_model = keras.models.clone_model(model_to_clone) cloned_model.set_weights(model_to_clone.get_weights()) return cloned_model
6de9a1f1c15c80b0719532f6f83399648a3254c2
3,618,490
def fashion_mnist_load_data(): """Loads the Fashion-MNIST dataset. Returns: Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. """ file_path = '/file/oi-d/home/person/datasets/fashion_mnist' with gfile.Open('/gzip{}/train-labels-idx1-ubyte.gz'.format(file_path), 'rb') as l...
40b2d627a30e5063e81cae722093bce26d7ef2b2
3,618,491
def mk7z(): """ 创建7z包 Create 7z package :return: None """ return _mk7z()
b4efd4505034f315600bc390adef8c69687cc97f
3,618,492
def safe_str(obj): """ return the byte string representation of obj """ PY2=False basestring = str try: return str(obj) except UnicodeEncodeError: # obj is unicode mylogging("safe_str error", pr=True) return obj
988bfca47b499e0616e6e102863fe09860fd3784
3,618,493
def state_db(indicador="3102009001"): """Construct a State level DataFrame from INEGI API http://www.inegi.org.mx/desarrolladores/indicadores/apiindicadores.aspx """ #merge data from every state, create databases for each index: db_state, meta = INEGI(indicador=indicador,area="01") db_state.rese...
02f246a52423b71f6d2b90be05b4d9470ed150e2
3,618,494
def makeTernaryOperator(cond: ExprType, left: ExprType, right: ExprType) -> TernaryOperator: """ Create a TernaryOperator :param cond: Condition. :param left: Left-hand side. :param right: Right-hand side. """ expr = TernaryOperator() expr.cond.CopyFrom(makeExpr(cond)) expr.left...
ea02697512bfaf9b6aa7e712e789a824c1550eb2
3,618,495
def load_cbmc_json(json_file, root): """Load json file produced by goto-analyzer --reachable-functions --json.""" json_data = parse.parse_json_file(json_file, fail=True, goto_analyzer=True) return parse_cbmc_json(json_data, root)
545f16eee045ac1717659a8fda806ca5f34e8362
3,618,496
def get_coord(tic): """ Get TIC corrdinates Returns ------- TIC number """ try: catalog_data = Catalogs.query_object(objectname="TIC"+tic, catalog="TIC") ra = catalog_data[0]["ra"] dec = catalog_data[0]["dec"] return ra, dec except: print "ERROR: No gaia ID found for this TIC"
bf3a7d8e483f546fdccd5b441fd52d7e75b1f52b
3,618,497
import calendar def year_add(date, years): """Add number of years to date. >>> import datetime >>> year_add(datetime.datetime(2016, 2, 29), 1) datetime.date(2017, 2, 28) >>> year_add(datetime.date(2016, 2, 29), 1) datetime.date(2017, 2, 28) >>> year_add(datetime.date(2015, 2, 28), 1) ...
62be01b7051ddef27376ebae4b97f63e9b7ca979
3,618,498
def less_or_equal(a, b, *args): """Implements the '<=' operator with JS-style type coertion.""" return ( less(a, b) or soft_equals(a, b) ) and (not args or less_or_equal(b, *args))
309dd3f207244870f983c5875f0ea4068cc2bb3b
3,618,499
def survey_getQuestionFromCode(code, series_id=None): """ Function to return the question for the given series with the code that matches the one passed in """ s3db = current.s3db sertable = s3db.survey_series q_ltable = s3db.survey_question_list qsntable = s3db.survey_question ...
bd2483be4e1c4e2fa33806c2d4c80215c6414975
3,618,500
import glob def get_cityscapes_file_pairs(split='train', city='*', sequence='*', frame='*', ext='.*', gt_type='labelTrainIds', type='leftImg8bit', root_folder=CITYSCAPES_FOLDER, file_template=CITYSCAPES_FILE_TEMPLATE): """ Fetch pairs of filenames f...
dc4915dacf0862bde76938c96322e0895f84ccb2
3,618,502
def OT_retrieve_optfile(filename, mode='rsync-ssh', keyfile='', args='', sshargs=''): """ retrieve_optfile(...) is identical to retrieve_file(...), except that it returns a tuple that can be passed to optfile(...) that contains both the temporary file and ``filename``, thus indicating ``filename`` ...
3409d1f428e69b54b3e95fdbf03ce18d511129ad
3,618,503
def test_bounds_optional(): """Test that each object template can have passthrough bounds for any of its attributes.""" def link(): return LinkByUID(id=str(uuid4()), scope=str(uuid4())) for template_type, attribute_args in [ (MaterialTemplate, [ ('properties', PropertyTemplate), ...
85a852d303b47c7ef75f8b9e2e88726ffabc32ed
3,618,504
import json def is_session_active_api(request): """ API endpoint that tells if user has active session. """ user_id = request.user.id if request.user.is_authenticated else None return HttpResponse(json.dumps({'success': request.user.is_authenticated, 'user_id': ...
b05bc9c8ad45590ff123ff999f6688cfdb4a2aa6
3,618,505
def high_precision_keyword_read(hdr, keyword): """Read FITS header keywords, also if split in two. In the case where the keyword is split in two, like MJDREF = MJDREFI + MJDREFF in some missions, this function returns the summed value. Otherwise, the content of the single keyword Paramet...
c30ee16781b32cdc0a371413021df90d6dbf83ac
3,618,506
def build_assign_term_to_entities_request( term_guid, # type: str **kwargs # type: Any ): # type: (...) -> HttpRequest """Assign the given term to the provided list of related objects. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code f...
eabf9d843980186bf8f5ef8f3b952b9675098488
3,618,507
def calc_skier_position(skierposition,userinput): """ """ if userinput == "j": skierposition = skierposition - 1 if userinput == "k": skierposition = skierposition + 1 return skierposition
66f638f9d9b5311efed10bbfe28274a9e80b9dd7
3,618,508
def intersect_plane_with_box(tshape, plane_def): """For each 'unknown' dimension, let the knowns be the other dimensions. The known ones define the edges of the box. Then find the unknown by the plane-equation. But this gives also out-of-box points, so filter them out. """ normal,d = plane_def[:...
eb28d1ceed90a53a009e17c32a87200325b079b9
3,618,509
def _get_command_powershell_script(command): """Return a valid CMD command that runs a powershell script.""" return "powershell -NonInteractive -NoLogo -File {}".format(command)
fdd67ac942e7869417c57f8021f26480228bc0a7
3,618,510
def _getProductPath(product_name): """ Return the absolute path of the product's directory. """ try: # BBB: for GenericSetup 1.1 style product names product = __import__('Products.%s' % product_name, globals(), {}, ['initialize']) except ImportError: ...
e269c1d261bb60c92f3c83fce66e6168be486e84
3,618,511
from typing import Optional from typing import Dict from typing import Any def get_commit_sheet( access_key: str, url: str, owner: str, dataset: str, *, commit_id: str, sheet: str, with_record_count: Optional[bool] = None, schema_format: Optional[str] = None, ) -> Dict[str, Any]: ...
cdf448dd1be367afc8f97b739619cc58ee175ad3
3,618,512
def get_transport_and_path_from_url(url, config=None, **kwargs): """Obtain a git client from a URL. :param url: URL to open (a unicode string) :param config: Optional config object :param thin_packs: Whether or not thin packs should be retrieved :param report_activity: Optional callback for reporti...
368fb58aafbc9895bd7f5a7bcde2481dcdafa7e6
3,618,513
def getModelSupportTypes(data): """ 获取模型支持的分类 :return: """ temp = '' for i in data: temp = temp + ' ' + i return temp
b44a362ca231c65eff5aff8d17da9a46236106b6
3,618,514
from typing import List def get_function_argument_names_from_source_code(source_code: str) -> List[str]: """ Gets the names of the function arguments found in a particular line of source code. Specifically, it retrieves the names of the arguments in the first function call found in the source code string...
3eb7bf9dccf34112777ce35464a3f1b62821e914
3,618,515
def load_image(addr, resizeSize=None, imgType=np.float32): """Read an image and make sure it is of the correct type. Optionally resize it""" try: img = imread(addr, mode='F') except: img = 0.5*np.ones((512,512)) print("Image read failed") if resizeSize: img = cv2.re...
becd97a8004398d3b7278401564bd2bdb9a49847
3,618,516
import time def check_monit(dut): """ @summary: Check whether the Monit is running and whether the services which were monitored by Monit are in the correct status or not. @return: A dictionary contains the testing result (failed or not failed) and the status of each service. """ lo...
31b43b83636cdf27f836f7027a0271784ef0b75c
3,618,518
import inspect def generator(T): """Mark a class as a generator""" class generator_interposer(T): def __init__(self, *args, **kwargs): gen_i = self._get_int() # Capture the instantiation location frame = inspect.stack()[1] gen_...
80b570950268ecc43ca3ad0f7fbef73cb03dd92a
3,618,519
import numpy as _np def hausdorff_distance(polyline1,polyline2): """ Compute the hausdorff distance from `polyline1` to `polyline2` :Inputs: `polyline1`: a (k,n1) array for the n1 points of the 1st polyline in k-dimension `polyline2`: a (k,n2) array for the n2 points of...
7f19bedf1c6d17ff0535f9f6c0b7860532491c7d
3,618,520
def combine_two_nets(N_1,N_2): """ combines two networks and returns the new network and its POs For the moment each net can have only a single PO """ if N_1 == []: return N_2 if N_2 == 0: return N_1 N, (xlat_1, xlat_2) = pyzz.combine_cones(N_1, N_2) POs_N1 = list(N_1.get_POs()) ...
e668ae5546c05b8058ff084bab8fa47a95212d68
3,618,521
def merge_collected_sets(a: Column, b: Column): """Merge 2 collected sets keeping only unique items""" def merge_col(list_a, list_b): set_a = set() set_b = set() if isinstance(list_a, list): set_a = set(list_a) if isinstance(list_b, list): set_b = set(li...
fc039d112e483c2262b5a45457dd3053ab4e1702
3,618,522
def rank(accessing_obj, accessed_obj, *args, **kwargs): """ Use rank in an organization to see if we pass. If orgname is not specified, the org is assumed to be the accessed object. If rank is called incorrectly, we'll try to call the organization permission instead as a fallback. Usage: ...
d129f14696488e8cd5bff2967446289cc3d2871e
3,618,523
def cloud2cloud(source_msh, source_val, target_msh, unroll_axis=None, verbose=False, **kwargs): """ Interpolate source_val between source_msh and target_msh. :param source: ndarray(\*shape_sce, dim_msh) :param target: ndarray(\*shape_tgt, dim_msh) :param values: ndarray(\*shape_sce, \*shape_val) :param verbose: ...
0d568877ef1b83cc9de3e8bc271bbbca8c844887
3,618,526
def dVhatdYTrans(dcdVhat, U, s, VT): """ Apply action of [d(Vhat^{T})/d(Y)]^{T} to the array of derivatives [d(c)/d(Vhat^{T})]^{T} to obtain the derivatives d(c)/d(Y) Parameters ---------- dcdVhat : numpy.ndarray array of derivatives d(c)/d(Vhat) U : numpy.ndarray left singu...
2e79ff9fd841feb3b5c789ba4210e18b40f0f3fc
3,618,527
from pathlib import Path import json def latest_checkpoint(model_dir, model_name): """return path of latest checkpoint in a model_dir Args: model_dir: string, indicate your model dir(save ckpts, summarys, logs, etc). model_name: name of your model. we find ckpts by name Returns...
29acafdb72bbb549cda7d72cc15a5a93f5535dca
3,618,528
def user_key(username): """ Returns user auth key, used to access feed and user settings Args: username (str): registered user Returns: key (str): user key """ config = db.user_config(username) return config['CONFIG']['key']
be06c220cddd205679d48337bce45fdaaa33910b
3,618,529
def write_multiple_files( extmodule, dir_path, files_sum_repository=None, encoding='ascii' ): """writes extmodule to multiple files""" mfs = multiple_files_t( extmodule, dir_path, files_sum_repository=files_sum_repository, encoding=encoding ) mfs.write() return mfs.written_files
9cf6dcc134347c9468bb751a320d79cbaeb5f850
3,618,530
async def upload_zarr(sas_url=None, src_folder=None, dst_blob_name=None, timeout=30*60): """ Asyn upload a folder to Azure blob :param sas_url: str, the SAS url :param src_folder: str, full abs path to the folder :param dst_blob_name: str, relative (to container) timeout of the :param timeout: ...
38c136d1e470a3370a00d60827be5f1ae702d379
3,618,531
def line_coordinates(image_data, centroid_x, centroid_y, angle_vector_rad, \ step_division = 1, radius_approx = None, radius_approx_interval = 20): """Get the coordinates along each radial line of each specified angle For all angles specified in angle_vector_rad, the coordinates (x,y) ...
3b93a9fd28c970014b6c17fcca91491b23831b3d
3,618,532
def as_batch(img, shape, as_list=False): """Convert an image block group to a list After chop_to_blocks, the data has a structure like (jx, ix, 1, 400, 400, 3) convert this to: obj_detection : (ix*jx, 400, 400, 3) patch_identification : (ix*jx, 200, 200, 3) Args ---- img ( np....
77c2c5d83d88d2e4307f6f26a3d49a2e1f852a50
3,618,533
def dtw_sakoechiba(x=None, y=None, dist='square', window_size=0.1, precomputed_cost=None, return_cost=False, return_accumulated=False, return_path=False): """Dynamic Time Warping (DTW) distance with Sakoe-Chiba band constraint. .. deprecated:: 0.11 This function is...
fb27288ce62409af9aba1b270a4b91770c163500
3,618,534
import yaml def node_from_manifest(manifest): """Create V1Node object from a YAML manifest.""" manifest = yaml.safe_load(manifest) manifest['api_version'] = manifest.pop('apiVersion') return k8s.client.V1Node(**manifest)
d043418022bfe4973457dd48e4d7ec8cf2581eab
3,618,535
def _OverrideBinaryOperatorHelper(func, op_name, clazz_object=ops.Tensor): """Register operators with different tensor and scalar versions. If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices, sp_values, sp_shape, dense)` and outputs `(new_sp_values)`. Args: func: the operator op_na...
15164bc3428e0d5789bf6654e1513eeadf59475b
3,618,536
def generate_freenas_snapshot_name(name, iqn_prefix): """Create FREENAS snapshot / iscsitarget name from Cinder name.""" backend_snap = 'snap-' + name.split('-')[1] backend_target = 'target-' + name.split('-')[1] backend_iqn = iqn_prefix + backend_target return {'name': backend_snap, 'ta...
90594d19e0e04c92937e1f976d3e0c480b802dac
3,618,537
def GetTestPoint(name): """ Factory method to return a TestPoint object. @params name: Desired name of the object. """ global GLOBAL_TOGGLE # Only return a real object if # TestPoints are enabled if(GLOBAL_TOGGLE is True): return TestPoint(name) else: return DummyPo...
9ac51d71ca55387f5285baef9366c3a75af2882f
3,618,538
import copy import time import torch def train_classifier(model, optimizer, scheduler,dataloaders,device,kwargs): """This funcion performs training of classifier HEAD. It can be wrapped into the DNN module as a class function """ num_epochs=kwargs['ep'] writer=kwargs['writer'] best_l...
56228b761291cf0c0c7fc47fab7a3ecfb602af27
3,618,539
def get_token_list(text): """Returns a list of tokens. This function expects that the tokens in the text are separated by space character(s). Example: "ca n't , touch". This is the case at least for the public DiscoFuse and WikiSplit datasets. Args: text: String to be split into tokens. """ return t...
01a917fae5923cdfd693548bb688695a917fab70
3,618,540
def cut_string(string, limit=30): """Shorten the length of longer strings.""" if len(string) <= limit: return string else: return string[:limit-3] + '...'
842cfefcff84c4f146cc85a4e86dff1486e9a434
3,618,542
def dxp(u): """Backward finite differences in x direction. Args: u (ndarray): 2D input array. Returns: ndarray: Finite difference. """ u = np.mat(u) dx = np.hstack((u[:, 1:], u[:, -1])) - u return np.array(dx)
6ef92c85a29ef43ed6f227fcd81e6400ce1ff8f4
3,618,543
def is_unique_dist_mat_energy(geo, ene, geo_list, ene_list): """ compare given geo with list of geos all to see if any have the same distance matrix and energy """ unique = True for idx, geoi in enumerate(geo_list): enei = ene_list[idx] etol = 2.e-5 if abs(ene-enei) < etol: ...
606c8f2c9ab4767ee8538a18ab1feddddf52165e
3,618,544
def SeismogramEnsemble2Stream(sge): """ Convert a seismogram ensemble to stream :param sge: seismogram ensemble input :return: stream """ # This uses the same approach as TimeSeriesEnsemblet2Stream to handle # ensemble metadata. See comments there for potential maintenanc issues md = sg...
890e5906fd0342f56cdc2c2a485b30a136126cf9
3,618,545
def hrm_training_job_title(row): """ Which Job Titles(s) the person is active with """ try: person_id = row.hrm_training.person_id except AttributeError: # not available person_id = None if person_id: s3db = current.s3db table = s3db.hrm_human_resour...
dd91ac1a7d860e94f66a8aa72fb687f8bdafb396
3,618,546
import torch def dct_N(x, perm=None, expk=None): """ Batch Discrete Cosine Transformation without normalization to coefficients. Compute y_u = \sum_i x_i cos(pi*(2i+1)*u/(2N)), Impelements the N permuting trick to solve DCT with FFT in the following link, https://dsp.stackexchange.com/questions/2807/...
753148dec5c300001ad10b74d0f06de4f6aaa065
3,618,548
def portal(driver): """Return the 'portal' function, and the hint-annotator policy. The portal is the function that gets patched with a call to the JIT compiler. """ return tiny2.interpret, MyHintAnnotatorPolicy()
b9eb07439cabf0248ef7e6912c6432e7ea719f08
3,618,549
def format_results_for_suggestion(search_res: dict) -> list: """Format search movie results for `show_movie_suggestions()` Parameters ---------- search_res : dict result of `search_movie_from_query()` Returns ------- list List of formated tuple for displays. 1st ele...
165925bd65e09239c8c4c9ed7a62289ab09e962f
3,618,550
def recommended_from_views(request): """ get product recommendations based on products that the customer has viewed; gets list of tracking IDs of other customers who have viewed the products in the current customer's viewed products, and gets products that these other customers also viewed. """ t_i...
a53229f79baad8006640f7d3bd3ae46a1dd008ba
3,618,551
def heading(heading_string, underline='='): """ Takes a raw string and underlines it with the given underline char """ return '%s\n%s' % (heading_string, underline * len(heading_string))
369385ffef60b88ba7e3a5c376236f6d4043ac72
3,618,552
from typing import Union def cvx_kron( expr_1: Union[np.ndarray, Expression], expr_2: Union[np.ndarray, Expression] ) -> Expression: """ Compute Kronecker product between CVXPY objects. By default, CVXPY does not support taking the Kronecker product when the argument on the left is equal to a CVX...
0098816249de5cbabdee32cf88a652ab602899f3
3,618,553
def run_batch(): """[Runs batch of 2D parameter scans] Returns: None """ for gr_Sfission in gr_Sfission_Vec: for par0 in par0Vec: if gr_Sfission == 0: K_tot = K_tot_def * 6 else: K_tot = K_tot_def s...
7fbe312b46f32515e869c759dcc1fb8ff293c50d
3,618,554
from typing import Tuple def optionally_resample(key: RandomKey, log_weights: Array, samples: Array, resample_threshold: Array) -> Tuple[Array, Array]: """Call simple_resampling on log_weights/samples if ESS is below threshold. The resample_threshold is interpretted as a fraction of the t...
839607b0f57c7c8c7669426f65032190f7bc2a71
3,618,555
def composed_measurement(ec_measurement): """Fixture that returns a composed measurement""" measurement1 = ec_measurement.select(cycle=1) measurement2 = ec_measurement.select(cycle=3) return measurement1 + measurement2
f7aa5891b7a9f88e2d18723cd526ff48044d0fd8
3,618,556