content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def hour_angle (sid_UT, loc, ra) : """Hour angle for sidereal_time `sid_UT`, location `loc`, and right ascension `ra`. `sid_UT` and `ra` must be Angle_D/Angle_R instances. """ ### J. Meeus, p. 92 lon = loc.longitude_meuss ha = (sid_UT - lon - ra).degrees if abs (ha) >= 360.0 : ...
55839e5afac00a2fa12256f559c688244bbcff12
38,642
def gaussian_mle_1d(x, photon_count, pixel_size, initial_position=None, initial_sigma=0.250): """Calculate the maximum likelihood estimate of the model parameters given measured photon count for 1D data. Parameters ---------- x : array-like Position data at which the function is to be evaluated...
7722f23f433ec268386bba3b398abbb58afbc0f4
38,643
def compute_num_sim_ftrs(sim_func_names, num_doc_fields, num_user_fields, num_deep): """Computes the number of similarity features :param num_doc_fields Number of document fields :param num_user_fields Number of user fields :param num_deep Number of deep features :param sim_func_names Similarity fu...
9700b14bbe4c550c3c3161d995ed87012d9356af
38,644
def brent(f, a, b, args=(), max_iteration=100, tolerance=1e-8): """ Calculate roots using Brent's method. Parameters ---------- f: function Objective function. a: float Lower bound for the roots. b: float Upper bound for the roots. args: tuple, optional A...
a9648956b7bd5bafa15d971cf389cacfcc0b2413
38,645
def square_slerp(xy, base_pts): """Transforms a square in [0,1]^2 to a spherical quadrilateral defined by base_pts, using spherical linear interpolation Args: xy: Array, shape [..., 2]. XY coordinates on the square. base_pts: Array, shape [4, ..., 3]. Coordinates of the square. ...
ada12eb806f16d087772c9dfff24683de2cd8597
38,647
def encrypted(text, key): """Ceasarchifferskryptering Args: text (_str_): Den text som ska krypteras. key (_int_): Hur många steg ska vi skifta? """ encrypted = "" # loop through the message char by char for char in text: # check if it's an upper case letter ...
46f85f9db742daf02e67030eb75f7bf035b073d8
38,648
import torch def dist(batch_reprs, eps = 1e-16, squared=False): """ Efficient function to compute the distance matrix for a matrix A. Args: batch_reprs: vector representations eps: float, minimal distance/clampling value to ensure no zero values. Returns: distance_matrix, clamped to ensure no zero values ...
be4d50e35ed11255eef2dc1acb4645de1453964c
38,649
def check_write_entity(entity, authz): """Implement the cross-effects of mutable flag and the authz system for serialisers and API.""" if authz.is_admin: return True collection_id = ensure_dict(entity.get("collection")).get("id") collection_id = entity.get("collection_id", collection_id) ...
3b12d562940af03e447fc30cb2ffa08058785354
38,650
import array def get_timed_data(wb,sheetname): """ Get the data from Tsys vs time data sheet """ sheet = wb.get_sheet_by_name(sheetname) date_nums = date2num(array(get_column(sheet,"Date/Time"))) ras = get_column(sheet,"R.A.") decs = get_column(sheet,"Decl.") azs = get_column(sheet,"A...
78ecab215dc88886ceee1c0518742279d90aa907
38,651
def juniper_items_to_list_of_dicts(module, data): """Recursively convert Juniper PyEZ Table/View items to list of dicts. """ resources = [] # data.items() is a list of tuples for table_key, table_fields in data.items(): # sample: # ('fxp0', [('neighbor_interface', '1'), ('local_inter...
2415d6608bb182dcf5c5fd45c067b4a8c34ca898
38,652
def unquote(s): """Strip single quotes from the string. :param s: string to remove quotes from :return: string with quotes removed """ return s.strip("'")
15d29698e6a3db53243fc4d1f277184958092bc6
38,653
def construct_banded_matrix_from_band( num_lower_diagonals: int, num_upper_diagonals: int, rect_mat: np.ndarray ) -> np.ndarray: """ Constructs a square banded matrix from a representation of the band. :param num_lower_diagonals: aka ``l`` :param num_upper_diagonals: aka ``u`` :param rect_mat: ...
0c93a6af563a93bf9885e42ae62a5bd3d17f0741
38,654
def create_jet_model_image(width, j_length, cj_length, max_flux, imsize, center, gauss_peak=0.001, dist_from_core=24, gauss_bmaj=10, gauss_e=1., gauss_bpa=0., gauss_peak_jet=0.0, dist_from_core_jet=24, gauss_bmaj...
396f080f987c1628df110bbf79e55ea65394d3b6
38,655
def choose_square(empty_squares, row_candidates, col_candidates, square_candidates): """ Iterates through all the squares, and returns the most constrained squares. Constrained factor is defined as length of intersection of that square's row, column and encompassing sq...
6c0dc97fe8e5d370c155be0abadbc02927da47e1
38,656
import string def normalize(text): """ Remove all punctuation for now """ return ''.join('' if c in string.punctuation else c for c in text)
9332583adb0ff3bfbe37170b2acdd58f09b3fe5e
38,658
def zyz_unitary(ϕ, θ, λ): """ Unitary decomposed as Rz, Ry, Rz rotations. Angles are in matrix order, not in circuit order! """ return expm(-0.5j*ϕ*pZ)@expm(-0.5j*θ*pY)@expm(-0.5j*λ*pZ)
bd0f4a394893717486fe68a88419c45266bdc9fa
38,659
def build_model(idkey): """ Default parameters: ImageTransformer(leak=0, norm_type='batch', DWS=True,DWSFL=False, outerK=3,resgroups=1, filters=[8,16,16], shuffle=False, blocks=[2,2,...
614de0669a77c5959291c9cd91df8f2d6e0e61f2
38,660
def p_AB(A, b, L): """ Numerator of function f. """ a11, a12, a13, a21, a22, a23, a31, a32, a33 = \ A[0, 0], A[0, 1], A[0, 2], \ A[1, 0], A[1, 1], A[1, 2], \ A[2, 0], A[2, 1], A[2, 2] b1, b2, b3 = b[0, 0], b[1, 0], b[2, 0] return L**4*(-a11*a22*b3**2 + a11*a23*b2*b3 + a11*a32...
530655f0e6e56ef6aca4ad82d5076543caec0ddb
38,661
def disqus_num_replies(context, shortname=''): """ Return the HTML/js code which transforms links that end with an #disqus_thread anchor into the threads comment count. """ shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname) return { 'shortname': shortname, 'con...
64e5fd5f12c2ec7e3ad4b28cdf4fdaeccf08fd06
38,662
def infer_flags(bytecode, is_async=None): """Infer the proper flags for a bytecode based on the instructions. Because the bytecode does not have enough context to guess if a function is asynchronous the algorithm tries to be conservative and will never turn a previously async code into a sync one. ...
02744153c3af35468268cfe9eb0353c8039ac351
38,663
def form_generic_id(request, id1, template_name=None, form_class=None, request_url_post=None, request_url_get=None, success_msg=lambda desc: _('Success'), ask_msg=lambda x: '', confirmation=_('Yes'), request_url_both=None, ajax_success_status=0, id_key=None): ...
7809d7eefbc311244f94c1420b7c27d794c66a8c
38,664
def gromov_barycenters(N, Cs, ps, p, lambdas, loss_fun, epsilon, max_iter=1000, tol=1e-9, verbose=False, log=False, init_C=None): """ Returns the gromov-wasserstein barycenters of S measured similarity matrices (Cs)_{s=1}^{s=S} The function solves the following optimization prob...
51bc85b192c34514e803e5a5ab5f1b3caad6273a
38,665
def check_elemental_balance(model, r_id, tol=1e-6): """ Check elemental balance of a reaction in a model. Notes: Since some metabolites can have multiple formulas associated, it will check if at least one possible combination of all formulas results in a balanced reaction. Args: mo...
8a0344b4e2ccbd82aba63b63397cee7ec3804d1c
38,666
def BB_flux(E1, E2, T): """ Wrapper to compute black body flux given minimum and maximum energies (in eV) and a black body temperature. """ x1 = E1 / (const.k_boltz * T) / const.eV_erg x2 = E2 / (const.k_boltz * T) / const.eV_erg A = 2.0 * const.k_boltz**4 * T**4 / (const.h**3 * const.c**...
a76381c9a033bf65e403adb9dfe08d5cc021ed97
38,667
def asn1_parse(template, data): """Parse a data structure according to an ASN.1 template. @param template: tuples comprising the ASN.1 template @param data: byte string data to parse @return: decoded structure """ data = bytearray(data) r = [] i = 0 try: for t in template: ...
308bdc1864dffa13d2f94f67910cb21cb54882a6
38,668
import re def _parse_faces(obj_faces): """Parse the OBJ encoding of the face attribute index buffers. A value of -1 in the index array of the texture means the index is undefined (i.e. no texture is mapped to this face corner). Returns: faces faces_texture faces_normals "...
d9d22f70fd98de28b3bbfbeb080e52ed60cca03f
38,670
def binary_to_decimal(binary): """ Converts a binary number into a decimal number. """ decimal = 0 index = 0 while binary > 0: last = binary % 10 binary = binary / 10 decimal += (last * (2 ** index)) index += 1 return decimal
f1efdf19c802345e6badfed430dd82e3f067a419
38,671
def namelist(names: list) -> str: """ Format a string of names like 'Bart, Lisa & Maggie' :param names: an array containing hashes of names :return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersa...
b0b931f3f9365824931173c2aec3ac213342e0c3
38,672
import functools def update_wrapper(): """Copy wrapped function information.""" def do_nothing(): "Doing nothing." def wrapper(): """Wraps a function that does nothing.""" return do_nothing() wrapper_alias = functools.update_wrapper(wrapper, do_nothing) return wrapper_alias is w...
bf629c54a0c8205de5041fafd5cb042acfc3bcce
38,673
def makeFlowField(a,b,c): """ Make a vector from 3 components <div class=jython> makeVector(a,b,c) = [a,b,c] </div> """ return DerivedGridFactory.createFlowVectors(a,b,c)
2f1ea8b2283f850c01d527b344858cddc28935b9
38,674
import numpy def arraytodk3d(x): """ Convert back 1d array of independent elements to correct complex array fft-style """ nmesh = round(x.shape[0]**(1/3.)) y = numpy.zeros((nmesh, nmesh, nmesh/2+1), dtype = numpy.complex128) # Structure saved- # - first the real and complex part of N*N*...
54d29be8a70069430e8e9f3ac43eef05687c5327
38,675
def handler(context, inputs): """ Create IPAM object, define deaalocate_ip function and start deallocation function """ ipam = IPAM(context, inputs) IPAM.do_deallocate_ip = do_deallocate_ip return ipam.deallocate_ip()
a107971aa45959e715c3d242dce16038ca94bae0
38,676
def _n_centred_onedgaussian_Inorm(pars, I=None, sigma=None): """ Returns a function that provides the sum over N 1D gaussians, where N is the length of I,sigma *OR* N = len(pars) / 2 The background "height" is assumed to be zero (you must "baseline" your spectrum before fitting) pars - a...
3860656a23ef8b81a652ae3a1b21af9e13aa4f08
38,677
def prepare_plot_dir(dirpath): """ Add a trailing / to the plot dir if missing and creat dir if needed. :param dirpath: path of existing or planned directory :return: dirpath with / as the final character """ # add a slash to filename if it wasn't provided. if dirpath[-1] != '/': di...
95b136e0e74d767f46610f051f48e4c250969422
38,678
def o목록(message): """제가 지원하는 기능들을 알려줘요.""" return ', '.join(_목록()) +" 같은게 있어요!"
86c9e633c8d33cbae94d68aff143fcd0ef7955e1
38,679
def testvolc(compareto,volcfiles,runshortname): """Performing the volcanic test Input: compaareto = the flag to decide whether to compare to LENS2 or B1850 or both volcfiles = the file listing for the volcanic test for your test case runshortname = the shortname for labelling the test case...
729199b0e0fa09d2687aa545bf9ae5817a30ac7a
38,680
def parse_select_job_input_file(file): """ INPUT file = micrographs_ctf.star file used as input to the Select job RETURNS ordered_list_of_micrographs = list of entries as they appear in the input file, e.g.: [ _rlnMicrographName1, _rlnMicrographName2, ... ] """ print(" >>> P...
cc4fa7d9fd51f67892f3a7bd33ed69eff56ca367
38,681
def selectordialog(args): """ Emulates a selector control that is lvalues compatible for subsequent conditionals in Kodi settings args is a list of strings that is kwarg 'like'. 'id=myid': (Required) where myid is the settings.xml id that will be updated The plain id will contain the actual inde...
bfed44f866c01c100485ce6e5b8d5400df706ea2
38,682
def create_hmac_hash(hmac_payload: str, hmac_secret_key: str) -> str: """Returns sha256 HMAC hexdigest.""" if hmac_secret_key is None: raise RuntimeError('hmac_secret_key cannot be None, please set a secret for the application in dotenv file!') return new( hmac_secret_key.encode('utf-8'), ...
84775b9c1550420ab829ba31c6f8d322efda2fbb
38,683
def loadIUPACcompatibilities(IUPAC, useGU): """ Generating a hash containing all compatibilities of all IUPAC RNA NUCLEOTIDES """ compatible = {} for nuc1 in IUPAC: # ITERATING OVER THE DIFFERENT GROUPS OF IUPAC CODE sn1 = list(IUPAC[nuc1]) for nuc2 in IUPAC: # ITERATING OVER THE D...
931f2a765ec9499b8553d13d7de93c6b261622de
38,684
def update_offer_viewed(offer_counter, merged_data, consumer_id, offer_id, offer_end): """ Update the dataframe with information related to an offer being viewed. """ i = get_row_indices(merged_data, consumer_id, offer_id) merged_data.at[i[offer_counter], "offer_viewed"] = True retu...
c523bb34470333d7244333f867750f367c7b55e1
38,685
def to_fullspec(rs, es, hds): """ Rotationally symmetric dump of a list of each to fullspec """ output = [] for idx in range(0, len(rs)): row = {"r": [rs[idx]], "e": [es[idx]], "d": hds[idx] * 2} output.append(row) return output
98cac8ba938249d6af0decfeffedf594ab1d6660
38,687
def command_generation(): """Adds a generate cell to Notebook.""" return jsonify(generate(request.json["query"], request.json["context"]))
6a1263ca26b77babd79a4d71d3ba7453a5965437
38,689
from django.db.models.fields.related import ManyToManyField def rubric_model_to_dict(obj, fields=None, exclude=None, ct_id=None): """ Returns a dict containing the data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If pro...
e9beed1a4d472997384c15853553d9783c674cf0
38,691
def get_uniq_list(data): """ 列表去重并保持顺序(数据量大时效率不高) :param data: list :return: list """ ret = list(set(data)) ret.sort(key=data.index) return ret
d4a43acd42608210c022317999673bd281e5e247
38,692
def train_val_test_split(messages, labels, split_frac, random_seed=None): """ Zero Pad input messages :param messages: Input list of encoded messages :param labels: Input list of encoded labels :param split_frac: Input float, training split percentage :return: tuple of arrays train_x, val_x, tes...
db7a24a9ffdf00185dafd115877c8eafd584b378
38,694
import fastapi import pydantic import http async def delete_anime( *, session: aio_session.AsyncSession = fastapi.Depends( dependencies.get_session), anime_id: pydantic.UUID4, current_patron: patron_model.Patron = fastapi.Depends( # pylint: disable=unused-argument dependencies.get_cur...
1ee8b4ca5f7290387fbb3bf7342e158f5fb6a2e1
38,695
def jaccard_similarity(mat): """ get jaccard similarity matrix :param mat: scipy.sparse.csc_matrix :return: similarity matrix of nodes """ # make it a binary matrix mat_bin = mat.copy() mat_bin.data[:] = 1 col_sum = mat_bin.getnnz(axis=0) ab = mat_bin.dot(mat_bin.T) aa = np....
69a8cdcb890275a9b44ac1587ece56325884e23d
38,696
from typing import Optional from typing import Dict def mnist_dataset( split: str, has_labels: bool, flatten_images: bool, device_batch_size: int, repeat: bool, shuffle: bool, drop_remainder: bool, seed: Optional[int] = None, multi_device: bool = True, reshuffle_each_iteration:...
7a064572ce272e178983f293a266365238ce0a7e
38,697
def favorite_mange(manga_id): """ endpoint: /manga/<manga_id>/favorite method: POST response: total: total_favorited status: False """ user = User.query.get(g.uid) user_manga = UsersManga.query.filter_by( user_uid=g.uid, manga_id=manga_id ).first() if ...
b6e78310e3a5f2dc081c391aa537de444a5bf82b
38,698
from typing import Optional from typing import List def get_plugins( user_id : Optional[int] = None, search_term : Optional[str] = None, ) -> List[str]: """ Return a list of registered plugins. """ return get_api_connector().get_plugins(user_id=user_id, search_term=search_term)
da314ee59182360461e86ad19f76d89165a4c132
38,700
def get_tile_rect(x, y): """Converts tile indices to a pygame.Rect""" return Rect(x*SIZE, y*SIZE, SIZE, SIZE)
70b9b514037fa5916bbccd771766bc20d693a438
38,701
from scipy.spatial import Delaunay def checkBlockageQHull(plane1,plane2,planeB,nargout=1): """ Using ConvexHull. This is slower, but worth having as it's more intuitive. We can use this to have a third opinion. Check wheter plane1 and plane2 are blocked by planeB. plane1, plane2, planeB are...
ea8b20d16baf3bc62701e7c4322967326f03dedf
38,702
def getLinks(laneID): """getLinks(string) -> list((string, bool, bool, bool)) A list containing ids of successor lanes together with priority, open and foe. """ return _getUniversal(tc.LANE_LINKS, laneID)
9066791739da9ad7b869fabb99f08a0551c3e13a
38,703
from typing import Tuple def calc_center_position(pos: Tuple[int, int]): """ ボックスの中央の座標を取得する Parameters ---------- pos : (int,int) ボックスの座標(左上を原点とし、(横、縦)する) Returns ------- position : (int,int) ボックスの中央の座標 """ box_size = calc_box_size(row, column) pos_x, pos...
7127a9063b451aedd206e8e4c2f65b2ed762db71
38,704
def ws_sheet_names(xlsx_file, log_on_open=True): """Return the sheet names in the XLSX file.""" if log_on_open: log('SCAN: [!c]{:s}[!/c]', xlsx_file) with closing(load_ro_workbook(xlsx_file)) as wb: return [str(i) for i in wb.sheetnames]
39e97f0bc170acb9f30f669afc3a2a939a2554d2
38,705
def process_citeauthor( s: str, lang: str, **kwargs ) -> str: """ Transforms all citeauthor to [cite]. For example: ``'This is from \citeauthor{Pizarro}, and that is from \citeauthor{cite1, cite2}'`` to ``'This is from [author], and that is from [authors]'``. :param s: Latex...
2622e2b2d8e59a34f4dbd1d1968eb7bd4a181871
38,706
import re def normalize_newlines(text): """Normalizes CRLF and CR newlines to just LF.""" # text = force_text(text) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines return re_newlines.sub('\n', text)
835f038f0873546db96d8e9d2a0d622b4e974f7d
38,707
def power_curve_se_42m140(): """Power curve for Senvion 4.2M140 Extracted by hand from offial spec-sheet at: https://www.senvion.com/global/en/products-services/wind-turbines/4xm/ """ wind_speeds = np.hstack(([0., 1., 2., 3.], np.arange(4, 27, step=2), [27., 40.])) generation_kw = [0., 0., 0., 0...
40c1823242c4f2f2fbd3c50c0b2e6b9cae926c09
38,708
def close_ring(coordinates): """ checks if the first and last points of a ring are equal and closes the ring """ if not points_equal(coordinates[0], coordinates[len(coordinates) - 1]): coordinates.append(coordinates[0]) return coordinates
14d121dc25dd774f326845b3c83d2d605d1d69d2
38,710
def check_families(trace_events, families, event_definitions): """ Looks for event types found in the trace that are not specified in the event definitions. :param trace_events: Events found in the trace (filtered by family). :param families: Families to look for. :param event_definitions: Even...
2533835283d388ad2fe37d79f6e87f14103a5bee
38,711
def broken_search(nums, target): """ Функция должна вернуть индекс элемента, равного k Eсли такой есть в массиве (нумерация с нуля). Если элемент не найден, функция должна вернуть -1 Изменять массив нельзя. """ return binary_s(nums, target, left=0, right=len(nums)-1)
f427cad35db6ea641e33d26054e64aec9721a462
38,712
def str_to_timedelta(td_str): """ Returns a timedelta parsed from the native string output of a timedelta. Timedelta displays in the format ``X day(s), H:MM:SS.ffffff`` Both the days section and the microseconds section are optional and ``days`` is singular in cases where there is only one day. ...
dc86def0716afda5e1e4808281275ed2e9514ace
38,713
def get_distribution_strategy(): """Returns the current `DistributionStrategy` object. Prefer to use `get_tower_context()` or `get_cross_tower_context()` instead when possible. Returns: A `DistributionStrategy` object. Inside a `with distribution_strategy.scope()` block, it returns `distribution_s...
4a20795c098c6b7ad8e7e1f6f42fead24c55e771
38,715
def exists_project_slug(slug): """ Whether the slug has been taken by an existing project of any kind. """ return bool(ActiveProject.objects.filter(slug=slug) or ArchivedProject.objects.filter(slug=slug) or PublishedProject.objects.filter(slug=slug))
ce2baf58cab1227b9a1a480c1fed0c2ba8da235f
38,716
import logging def main(args): """ Main entry point for program :param args: :return: """ desc = """ Version {version} Annotates NDEx with INDRA and optionally loads networks into NDEx (http://ndexbio.org). To connect to NDEx server a configuration file must be passed ...
243d65d41f92615bd87a41db52097b7873193099
38,717
def merge_dupes(list_cxs, cutoff, func=cp.bader_score, npasses=1): """ cxs: list of sets Requires multiple passes to be more certain of fewer complex pairs passing the merge threshold. But higher passes results in overcollapse when cutoff < 1. """ cxs = list(list_cxs) cxs_remaining = lis...
e397ccfa2715882ab200be5a66767197b9e8eb97
38,719
import re def convertSQL_LIKE2REGEXP(sql_like_pattern): """Convert a standard SQL LIKE pattern to a REGEXP pattern. Function that transforms a SQL LIKE pattern to a supported python regexp. Returns a python regular expression (i.e. regexp). sql_like_pattern[in] pattern in the SQL LIKE form to be con...
16589a99327885dc034fb33af1e69a42a453ccbd
38,720
from typing import Any def diag(tensor: ChargeArray) -> Any: """ Return a diagonal `BlockSparseTensor` from a `ChargeArray`, or return the diagonal of a `BlockSparseTensor` as a `ChargeArray`. For input of type `BlockSparseTensor`: The full diagonal is obtained from finding the diagonal blocks of the ...
996cea2164d867fa67812fac8f156d4851eaaf6e
38,721
import math def box_heightmap(box: BoxCorner, hm: HeightMap, qp_a: QP, qp_b: QP) -> Contact: """Returns contact between a box corner and a height map.""" # Note that this only checks box corners against height map surfaces, and is # missing box planes against height map points. pos, vel = qp_a.to_world(box.co...
ac7e63eba9c29fa945710aa05a958f97083a7804
38,723
def rjmcmc_chisq_convergence(k, thin=1, sparse=False, split=True, merge_cells=True, correction=True, use_likelihood_ratio=False, class_lookup=None, min_expected_count=5): ...
a91033ce32dc164591cd070144e8da0b99a50f37
38,724
def remove_vars_match(mat,fmla): """ Remove the variables bindings from a match. This is used to prevent variable capture when applying the match to premises. Make sure free variables are not captured by fmla """ res = dict((s,v) for s,v in mat.iteritems() if il.is_ui_sort(s)) sympairs = [(s,v) for ...
ed8082e28ee5195a7d8a6f3a54d510509759b477
38,725
def str_exp(exp, ak, den, diff=0.05): """ Function that returns a string k^(a/den) if the absolute difference between the value a/den and the exponent ak is below diff. Arguments: exp -- initial string (given by the previous best estimation) ak -- slope den -- denominator of th...
deb5c74a938b81bb10f81724bcd50c7c683e901c
38,726
from re import T def stack(x, axis=0): """Join a sequence of tensors along a new axis """ return T.stack(x, axis=axis)
76dd3b65db7d3011ba5d223104a686ee5ed9e219
38,728
import typing def or_value( maybe_value: typing.Optional[typing.Any], fallback_value: typing.Any, ) -> typing.Any: """Return maybe_value if not None; otherwise, return fallback_value. Parameters ---------- maybe_value The value to test and return if it is not None. fallback_value ...
6f67fac29fb56b68ef5701a30b0fd6527fb1cc1b
38,729
def form_from_fields(name, form=forms.Form, fields={}): """ Returns a forms.Form class with a name, `name`, a Form baseclass, `form`, and a dictionary of fields, `fields`. """ return DeclarativeFieldsMetaclass(name, (form,), fields)
16d355a14257b430b1eb802ca7b4996562351f48
38,731
def make_enumeration(entries, divider=', '): """ :param entries: :param divider: :return: """ enumeration = { 'type': 'enumeration', 'entries': entries, 'divider': divider } return enumeration
0fee40bf69613944b57f2d1967ee0cdb87e7493b
38,732
def list_available_node_types(): """returns the friendly names of all available node types """ return list(type_map.keys())
f51536b4a399f6dd73a491f6cf48f954946a1ef3
38,733
def h(P, T, region = 0): """Specific enthalpy [kJ / kg]""" if region is 0: region = idRegion(P, T) if region is 1: return region1.h(P, T) elif region is 2: return region2.h(P, T) else: return 0.000
6b38283b79eb6bc63088885aac5e0096c37064bd
38,735
def instagram_posts(username, limit=12): """ Put a list of Instagram posts into the template context. """ CACHE_KEY = "instagram_%s" % username posts = cache.get(CACHE_KEY) # Serve from cache if available if posts is not None: return posts[:limit] # Else, fetch and store in cac...
e8f9c94fa5d472921c271cd8f30b36d293139a54
38,736
def establish_connection() -> storage.client.Client: """ Establish a connection to Google Cloud Storage storing agriculture data. :return: client connection """ storage_client = storage.Client.from_service_account_json(find('Agriculture.json', '/home')) return storage_client
e2409745ddc0174f2feb242789de437998f1170b
38,738
def is_authenticated_decorator(function): """Декоратор, чтобы не пускать неавторизованных пользователей""" def wrapper(request, *args, **kwargs): """Если пользователь авторизован -> вернем функцию, иначе переведем на страницу логина""" if is_authenticated_user(request): return functi...
2a5f894dc45abcecd8bf4591116d90bc18cb1d42
38,739
def preprocess_text(sentence): """ 前處理,處理奇怪的輸入。例如:'i',需要轉成大寫。 """ cleaned = [] words = sentence.split(' ') for w in words: if w == 'i': w = 'I' if w == "i'm": w = "I'm" cleaned.append(w) return ' '.join(cleaned)
b70bf2f454dba8de6bf639f66369755bcf474948
38,740
def compact(number): """Convert the number to the minimal representation. This strips surrounding whitespace and separation dash.""" return clean(number, '.,- ').upper().strip()
2b1471cdc8d524bf02d18719acb708ebbe8cdd13
38,742
def draw_candidate_matchings(members, min_size, n_candidates, initial_seed=0): """Create multiple random groupings in list-format. Args: members (pd.Series): Integer series with indeces over which we group. min_size (int): Minimum group size. n_candidates (int): Number of candidate grou...
a927242dcb130e1b881605f595961d777a7bc7d3
38,745
def get_module_name(): """ モジュール名取得 Return: モジュール名 """ return __name__
45836eb290ff628baf9082829b9e95d9d4e45d78
38,746
import torch def torch_ravel_multi_index(multi_index, dims=None, device=None, strides_=None): """ Implementation of `numpy.ravel_multi_index` for torch Tensors Args: multi_index (List[Tensor] | Tensor) : either a list of indices for each dimension, or a tensor containing the same infor...
d7f79c6266b75aab29974e698e5d62ef6319f952
38,747
def get_base_folder(image_file): """The base folder""" return '/'.join(image_file.split('/')[:-6])
14f212e80d57b71d2b379d2f5024c8f89ea438f3
38,748
def parse(fname): """ XMLファイルから内容をパースしてフィールドと値を格納した辞書を返す """ tree = ET.parse(fname) root = tree.getroot() parsed = [] for e in root.getiterator(): cur_dict = e.attrib.copy() cur_dict['elem'] = e.tag parsed.append(cur_dict) # for child in root: # ...
89ea2c62c64f09be9a99c0bd86b83854c83d4c20
38,749
import tqdm def optimization_hyperopt_loo(imgs, grades, args, loss, groups=None): """Optimizes hyperparameters for MRELBP and local standardization using tree of Parzen estimators and leave-one-out split for training multiple optimizations. Parameters ---------- imgs : list List of input ...
8935728576840238fdb8694612c2015de01fd071
38,751
def latex_plt(matplotlib): """ This function updates the matplotlib library to use Latex and changes some default plot parameters :param matplotlib: Matplotlib instance :return: Updated matplotlib instance """ # Use Latex for matplotlib pgf_with_latex = { "font.family": "serif", ...
06042b9625d6cf1a7d56144962ae0795f1f73e34
38,752
def _str_n_grade(df: pd.DataFrame, grade: str) -> str: """Print the number of cards with grade `grade`.""" n_cards = len(df) n_grade = len(df[(df["grade"]) == grade]) perc = round((n_grade / n_cards) * 100, 2) return ( f"– The number of cards with grade {grade} is {n_grade} " f"of {...
91cee7bb1f8faae1cf60c279b95d1cca7912fb19
38,753
def add_nodes_elements_from_bmesh(structure, bmesh, line_type=None, mesh_type=None, thermal=False): """ Adds the Blender mesh's nodes, edges and faces to the Structure object. Parameters ---------- structure : obj Structure object to update. bmesh : obj Blender mesh object. ...
d91515963245554df2c5a09a2a0b2827c13e5314
38,754
from datetime import datetime def _makefilename(lidvid: str, ts: datetime, kind: str, ext: str) -> str: """Make a filename. Make a PDS filename for the given ``lidvid`` by dropping its URN prefix, splitting it into LID and VID, adding the date part of the ``ts`` timestamp, slapping on the ``kind`` of fil...
6d9cc048ccb61d51c1ee328edc8da15a2ae3797f
38,755
import logging def extract(client, output_path, index): """ Scroll an index with a match-all query, dumping document source to ``outdir/documents.json``. :param client: Elasticsearch client used to extract data :param output_path: Destination directory for corpus dump :param index: Name of index ...
089abc87d722adb000d9db4c7f125ee21e12aa3d
38,756
from astroquery.gaia import Gaia import getpass def gaia_log_in(gaia_user = None, gaia_paswd = None): """ This routine log in to the Gaia archive. """ while True: try: Gaia.login(user=gaia_user, password=gaia_paswd) print("Welcome to the Gaia server!") break except...
76d004d22ac981fc635279b70652c899c903a1c7
38,757
import re def parse_class(name, doc): """ Extract a class declaration from a docstring. """ match = re.search(r"class ({}(\([^)]*\))?):".format(name), doc) csig = match.group(1) start = match.start() end = doc.find("```", start) doc = doc[start:end] variables = [] start = doc...
ed42aa330cf817df7fd35dced37b55010e38ff71
38,758
def is_acceptable_smiles(smile: str, allowed_chars=SMILES_ENCODING_['indices_token'].values(), min_len=SMILES_ENCODING_['min_smiles_len'], max_len=SMILES_ENCODING_['max_smiles_len']): """ Checks which smiles Args: smile: (str) smiles string allowed_chars: (lst) list of ...
7bef7d266caf9bfd540cc1d53b99bbc887bca140
38,759
from typing import List from typing import Union def parse_planes( planes_to_parse: List[Union[int, str]], n_planes: int, default: Union[int, List[int]] = 0, name: str = 'planes' ) -> List[int]: """ Get a set of planes from a list of plane indexes and ranges. Parameters ---------- planes_...
5bed291bf525fe06a709563f73490277aff6a600
38,760
def get_api(api_id): """Get a single api. Args: api_id (int): The id of the api. Returns: dict: The api. """ api = API.query.get(api_id) if not api: abort(404) return api.to_dict()
3031ff5ad6b0b0eaa0f57d9c1a1e706a08afa246
38,761