content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import typing from typing import Generator def xpdacq_composer( beamtime: Beamtime, sample: typing.Union[int, dict, typing.List[int]], plan: typing.Union[int, Generator, typing.List[int], typing.Generator], *, robot: bool = False, shutter_control: typing.Tuple[Device, typing.Any] = None, d...
f37bab40b7b956d5923528baddc596adef22b11e
75,167
def generate_badge(): """Renders a badge for a user and redirects to a page displaying it.""" username = request.form['username'] upscale_method = upscaling.get( request.form.get('upscaling'), Image.ANTIALIAS) try: badge = weasyl_badge(username, upscale_method) except AvatarFetchErro...
51921cc72fb803a7cf5a80ad082a52ae3d94d6eb
75,168
def permissions_required_with_403(perms, request): """ Works similar to django.contrib.auth.decorators.permission_required but (a) displays a 403.html template instead of redirecting to login, and (b) requires all permissions listed """ def _checkperm(user, perm): return (user.has_perm(p...
cc72888c79d607fce0c7b8547fc264359ee9b7f2
75,169
def test_input_fn_cifar10(data_dir, params): """Test input function for the MNIST dataset. Args: data_dir: (string) path to the data directory params: (Params) contains hyperparameters of the model (ex: `params.num_epochs`) """ dataset = cifar10_dataset.distorted_inputs("test", params.b...
cb455785cf606be222daaf002a983001cc097626
75,170
def ascii(str): """Return a string with all non-ascii characters hex-encoded""" if type(str) != type(''): return map(ascii, str) rv = '' for c in str: if c in ('\t', '\n', '\r') or ' ' <= c < chr(0x7f): rv = rv + c else: rv = rv + '\\' + 'x%02.2x' % ord(c)...
7224579507cc9e0efb0bb1700e2b8b0096422532
75,171
import imp def Map_Geoid_grid(detail="grid geoid l100", title="Geoid undulation High resolution"): """ Makes a Matplotlib figure with the map, geoid and labels """ G_Grid, G_Long, G_Lat = imp.Load_GLl(detail) levels = 40 limits = emap.get_limits(G_Long, G_Lat) FIG1, AX1 = emap.Make_Map(limits...
613a1ca8846f1674e864e670ea3cd52f6e43c4a5
75,172
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)): """A block that has a conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle ...
ff7d094f8cca25a782db03918bd3348f2564ad2a
75,173
def right_shift(number, n): """ Right shift on 10 base number. Parameters ---------- number : integer the number to be shift n : integer the number of digit to shift Returns ------- shifted number : integer the number right shifted by n digit Examples ...
e6d23b5bd630449aba54cb38c2c6d9be174386c0
75,176
def get_interconnector_index(data) -> list: """Get interconnector index""" return [i['@InterconnectorID'] for i in (data.get('NEMSPDCaseFile') .get('NemSpdInputs') .get('PeriodCollection') ...
9cb2a8a09e98ad308b23d670283d2b358abc9856
75,177
def halonet_h1_c4c5(pretrained=False, **kwargs): """ HaloNet-H1 config w/ attention in last two stages. """ return _create_byoanet('halonet_h1_c4c5', pretrained=pretrained, **kwargs)
622f4722745e2741cfb9efa230dc6183da354f7c
75,178
from typing import Dict def truvari_recall_events( logits: np.ndarray, one_hot_targets: np.ndarray, ) -> Dict[str, float]: """Computes event-level recall, regardless of the genotype match. Args: logits: float array; Output of model in shape [batch, ..., num_classes]. one_hot_targets: Multi hot ve...
6242b22488ba0545533233c884ec4e267f960b34
75,179
def searchpaths(scope): """Iterator over search paths. >>> searchpaths(dict(host="titi")) ['host/titi', 'common'] >>> searchpaths(dict(host="titi.sk1", shorthost="titi", location="sk1")) ['host/titi.sk1', 'host/sk1/titi', 'groups/sk1', 'common'] >>> searchpaths(dict(groups=["tor", "tor-bgp"], l...
c0f0adc3677c370cddddac072553031c33d6f1ee
75,180
def load_plugin(): """! Returns plugin available in this module """ return HostTestPluginResetMethod_pyOCD()
61e31041560ccf1e78aec91243cfd5af4d2b2ce1
75,181
def pauli_measurement(circuit, pauli, qr, cr, barrier=False): """ Add the proper post-rotation gate on the circuit. Args: circuit (QuantumCircuit): the circuit to be modified. pauli (Pauli): the pauli will be added. qr (QuantumRegister): the quantum register associated with the circ...
558cca36c8754a49896a6855a9e8989577b693a5
75,182
def check_sched(sched): """Parse the YAML for the resulting schedule of a scheduling algorithm. .. literalinclude:: ../../wikipedia-sched.yaml :language: yaml :linenos: :param task_list: List of sched descriptors, as in the example above. :type task_list: List of dictionaries. :re...
7eb2e00813d38993072ae326da16069b607faea2
75,185
def build_tell_heartbeat(username, session): """Builds a new heartbeat packet. :param username: The username to set in the header :param session: The session to set in the header :returns: A new packet instance """ return build_bare_packet(username, session, c.PACKET_TYPE_TELL_HEARTBEAT)
1580f8acab579cdbdf32d68158c9947048f9dfef
75,186
def _fit_alpha(Xs, Xt, centers, sigma): """ Fit alpha coeficients to compute J-score """ A = pairwise.rbf_kernel(Xt, centers, sigma) b = np.mean(pairwise.rbf_kernel(centers, Xs, sigma), axis=1) b = b.reshape(-1, 1) alpha = np.ones((len(centers), 1)) / len(centers) previous_objective = -...
8fe31f3792d4d69ebd7c52811ebd06e0892ed824
75,188
def binarygap(u): """maximal sequence of consecutive zeros >>> binarygap(6) 1 >>> binarygap(9) 2 >>> binarygap(129) 6 """ s = format(u, 'b').split('1') return 0 if len(s) < 3 else len(max(s))
3909779446dd500f6d3897c9fabd2628371d8f08
75,189
def duplicated(array): """ Check if it is duplicated. """ s = np.sort(array, axis=None) duplicated = s[:-1][s[1:] == s[:-1]] return np.isin(s, duplicated)
db89fd1e538342773cdab2ce523a8efda55c8abd
75,190
from typing import List def to_gst_objects_info(objects: List[dict]) -> GstObjectInfoArray: """Converts List of objects to GstObjectInfoMeta """ gst_objects_info = GstObjectInfoArray() gst_objects_info.size = len(objects) gst_objects_info.items = (GstObjectInfo * gst_objects_info.size)() for i, o...
9a899e232c3b128231fad846777d247d55ed3e68
75,191
import torch import math def log_lerp(x: torch.Tensor, b: float): """ Linearly extrapolated log for x < b. """ assert b > 0 return torch.where(x >= b, x.log(), math.log(b) + (x - b) / b)
c09eef11de46a3bf6905627f619df35e9de6e37f
75,192
def editOrder(order, data): """Edit some field of an order""" newStatus = data.get("status") if newStatus: order.status = newStatus newPayment = data.get("paymentMethod") if newPayment: order.paymentMethod = newPayment driverId = data.get("driverId") if driverId: dr...
ad937fcb8a38eccf343cbebf886c6459344444f1
75,195
def read_rgb_and_polar_images(path_rgb, path_polar): """Read an RGB image and its polarimetric equivalent. Args path_rgb: Path to the RGB image. path_polar: Path to the polarimetric image. """ image_rgb = cv2.imread(path_rgb) image_rgb_rs = cv2.resize(ima...
f96e549245f5e23e4f25bb4b9e872be345557107
75,197
from typing import Optional def fathers_day(date: dt.date) -> Optional[str]: """Third Sunday in June""" if not is_nth_day(date, 2, 6, 6): return None return "Father's Day"
1ecd700e84ef81fc4886ce8132fca76eb183c7be
75,199
def arcosh(x: REAL) -> float: """Inverse hyperbolic cosine.""" if x < 1: raise ArgumentError(x, "x >= 1") return ln(x + (x**2 - 1)**0.5)
2f71aa7aa764684424875d7a7826d10fdfcebc20
75,201
import re def replace_with_dash(text): """Replaces a set of symbols with '-' in provided text. Args: text (string): markdown text that is going to be processed. Returns: string: text once it is processed. """ dash_regex = re.compile(r'(•|–|·|—|−|―|▪)') text = dash_regex.sub(r'-',text) text = text.replace...
d4a2757e1af6944ac3222e1877a5562a7c54e7dd
75,202
def unzip_s3_data(bucket, key, suffixes=None): """store the content of a zipped key on S3. suffixes is a filter (a list of suffixes) for file names inside the zip file. Returns a list of individual file contents. """ s3_stream = boto3.client('s3').get_object(Bucket=bucket, Key=key)['Body'].read() ...
6345dc6c843686d2c30d629b078b578de2ac5821
75,203
def fast_multiply(matrix, value): """ Fast multiply list on value :param matrix: List of values :param value: Multiplier :return: Multiplied list """ for ix in range(0, matrix.shape[0]): matrix[ix] *= value return matrix
8a9eb29b1c6c0cc56b35f43f128e2595b45e1ff6
75,204
import re def _ext_validator(image_file, ext): """Check image is valid based on extension.""" try: valid_img = all( bool(re.search(img_file_patterns[ext], img)) for img in image_file ) error_message = img_file_error[ext] except KeyError: valid_img = False ...
0ec92a8f79805525338aee21aeba9fa7026f082f
75,205
import requests from bs4 import BeautifulSoup import asyncio async def very(event): """Random porn post""" reply_to = await reply_id(event) sub_r = event.pattern_match.group(1) await edit_or_reply(event, "**Just hold a sec u horny kid...**") if await age_verification(event, reply_to): retu...
82b953d907588a84ec9909f56e402d87250029cf
75,206
def freeze(x): """Freezes a dictionary, i.e. makes it immutable and thus hashable.""" frozen = {} for k, v in x.items(): if isinstance(v, list): frozen[k] = tuple(v) else: frozen[k] = v return frozenset(frozen.items())
fc3bf21419057563f2389ab7e26279bb1f37436b
75,207
def humanize(seconds): """ Convert a duration in seconds to an human-readable form """ assert type(seconds) is int if seconds >= 86400: res = seconds // 86400 return '%s day' % res if res == 1 else '%s days' % res if seconds >= 3600: res = seconds // 3600 return '...
2a32c7b54b1be58ce571910edbf8d5383db66aa2
75,208
def get_statistics(dbp_resource: str) -> dict: """Return information about the types and properties of `dbp_resource`.""" global __RESOURCE_STATISTICS__ if '__RESOURCE_STATISTICS__' not in globals(): __RESOURCE_STATISTICS__ = {} if dbp_resource not in __RESOURCE_STATISTICS__: __RESOURCE_...
e2ec757b453938f3b3e519dbf2b52e0785f3f2b0
75,209
def fresnel_reflectance(kn: np.ndarray) -> np.ndarray: """ :param kn: wavevectors normal to surface, shape: (number_q, number_layers) :return: fresnel reflectance between layers, shape: (number_q, number_layers-1) """ return (kn[:, :-1] - kn[:, 1:]) / (kn[:, :-1] + kn[:, 1:])
9923718af10e32bc1787aa7e43cf42c31de8ef2a
75,210
import requests import json def getNLP(url = "http://nlp.ailab.lv/api/nlp", data = { "data" : { "text":"change me"}, "steps": ["tokenizer", "morpho", "parser", "ner"], "model": "default", "config": None}, headers = {'content-type': 'application/json'}): """Gi...
cb63deaa4a0a98cf6641eae56ad5fb9fd81173ca
75,212
from typing import Tuple def get_arrow_transform(window: sg.Window) -> Tuple[str, str, str, str]: """Get the mask transformation of the REC window. Args: window: The element representing the main GUI window. Returns: new_transform: The transformation to apply to REC mask,...
642826b4eacb7ea3ff4842bc0171c725525a00c0
75,213
async def read_account_info(user, cur: Cursor): """read account info (username, description, time)""" await cur.execute(""" SELECT `name`,`description`,`time` FROM `account` WHERE `id`=? """, (user,)) data = await cur.fetchone() if data is None: return None name, description, nti...
8b8a66553e7122aa53ffcbed909e9107a865efb4
75,214
def get_cert_IPAddresses(cert): """ Given a cert, extracts the IP addresses listed in SAN :param cert: a x509 certificate which is going to be used :return: a list of strings representing the respective IP addresses """ try: ext = cert.extensions.get_extension_for_oid(x509.oid.ExtensionOID....
c5d3e2bbcce79156be404e2e80a2ddf87aa3b53c
75,215
import requests import json def login(username, password, url, asserts_in=None): """ Login Tendrl user. Args: username: name of user that is going logged in password: password for username asserts_in: assert values for this call and this method Returns requests auth object (ins...
a33e2aeb64146a8c0f9015416aead553b8418822
75,216
def rule_VisibleTo_for_door(x, actor, world) : """A door is visible if it is a door to the visible container of the location of the actor.""" return x in world.activity.get_room_doors(world[VisibleContainer(world[Location(actor)])])
28ffe193b1191bf881be719ef49516072a7eb47f
75,217
def check_func5(file): """ Checks that the function transpose (no options) works correctly Parameter file: The file to check Precondition: file is a string """ func = 'transpose' opts = {} result = verifier.grade_func(file,func,opts,0) if not result[0]: print("The functi...
34f926286be93fc416e98a0ee6e5cb9336ae73f4
75,218
def con_unequal_two_neighbouring_edges(v012,eps,**kwargs): """ oriented edge1,edge2 l1>=l2 <==> l1^2-l2^2*(1+eps)=s^2 (v1-v)^2-(v2-v)^2*(1+eps) = s^2 """ w = kwargs.get('nonsymmetric') mesh = kwargs.get('mesh') X = kwargs.get('X') N = kwargs.get('N') Nnonsym = kwa...
418bba36adb76bec47ab04e697e5dcb5e3afbb17
75,220
def adjust_brainstate(M, dt, ma_thr=20, ma_state=3, flatten_tnrem=False, keep_MA=[1,4,5], noise_state=2): """ Handle microarousals and transition states in brainstate annotation @Params M - brain state annotation dt - s per time bin in M ma_thr - microarousal threshold ma_state - brain state...
1e666abb5dd1610ed70335a09537b8d605acdece
75,223
def schema_input_type(schema): """Input type from schema :param schema: :return: simple/list """ if isinstance(schema, list): return 'list' return 'simple'
cdcc9b724005083995f26a767d9b2ab95645ad79
75,224
def integrator_RK(x,step_size,function_system): """ Integrate with Runga Kutta Parameters x : state step_size function_system """ k1 = function_system(x) k2 = function_system(x + step_size * k1 / 2) k3 = function_system(x + step_size * k2 / 2) k4 = function_system(x + step_s...
97380328a9bf1c3e91f161a3a39d7a06c479690c
75,225
def level1(img, bbox, FOnly=True): """ LEVEL-1 img: gray image bbox: bounding box of face """ F, EN, NM = getCNNs(level=1) # F f_bbox = bbox.subBBox(-0.05, 1.05, -0.05, 1.05) f_face = img[f_bbox.top:f_bbox.bottom+1,f_bbox.left:f_bbox.right+1] f_face = cv2.resize(f_fac...
dcaeaf82508f9c81194b54fca273c8d649da2f23
75,226
def plot(stats): """Plot the bars, draw all supporting features, run tests, paint according to test results.""" global y1, y2, lines bars = redraw() if y1 == y2: print('plot equals case') add_line(y1) ax.set_title('Mean comparison against y = {}'.format(int(y1))) ttres...
7b81aaa262d2797f9ffa5a7c54fde5a1328e1054
75,227
import json def coperson_roles_add(self, coperson_id: int, cou_id: int, status: str = None, affiliation: str = None) -> dict: """ Add a new CO Person Role. :param self: :param affiliation: :param coperson_id: :param cou_id: :param status: :return { "ResponseType":...
691d440de7390e2edd6ab97a8a0cddaf2c535339
75,228
import torch def get_predefined_featurizer(): """ This featurizer loads static features from a given file. :param graph_dataset: :return: """ path = get_config().data.predefined_features_path assert path is not None, "You must provide data.predefined_features_path" predefined_vectors ...
39d3186d6a9a9dd87e3f20bc9eb332bcfb68bfe4
75,230
def _light_map(mat): """ :param mat: """ tex = material.light_map(mat) if tex is None: return logger.info("Found light texture map %s", tex.name) light = { constants.MAP_LIGHT: texture.file_name(tex), constants.MAP_LIGHT_ANISOTROPY: texture...
569aa4ef8e1613bfceb881740b62bdde56f14b41
75,231
def _jwt_decode_handler_with_defaults(token): # pylint: disable=unused-argument """ Accepts anything as a token and returns a fake JWT payload with defaults. """ return { 'scopes': ['fake:scope'], 'is_restricted': True, 'filters': ['fake:filter'], }
9374f03065a8592448ae3984e56bb9cae962059f
75,232
def distance_hyperbox(b1,b2): """ The distance between boxes """ return max(0,np.max(np.hstack((b1.l-b2.u,b2.l-b1.u))))
75c99883554fd71b8c2b73bd7a29b69499ce45c0
75,234
from typing import Tuple def sortFunctionTypes(functions: list) -> Tuple[list, list]: """ sortFunctionTypes(): separate classic functions from functionnal components. returns a tuple of 2 lists: functionnalComponents[], normalFunctions[] @functions: a list of Functions that is not sorted """ ...
d15b0d66498cb1c511363484d158dae1ebc7247e
75,235
def rootfinder_n_out(*args): """ Number of rootfinder outputs. rootfinder_n_out() -> int """ return _casadi.rootfinder_n_out(*args)
fe2ed56045d6775e474d4be0a6ae2c42b25d570b
75,236
def search(): """Search page.""" return render_template(current_app.config['SEARCH_BASE_TEMPLATE'])
dd38285ab0b4848f331b2da5637080681e503b51
75,237
def seconds_to_time(seconds): """Return a nicely formatted time given the number of seconds.""" m, s = divmod(seconds, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) return "%d days, %02d hours, %02d minutes, %02d seconds" % (d, h, m, s)
bf87da51527af08f60b3425169af1f696ecc9020
75,238
def agg_over_categories(df_org): """Aggregates expenses over categories""" pivot = pd.pivot_table( df_org, values="amount", columns="year", index="category", fill_value=0, margins=True, aggfunc=np.sum, ).iloc[:, :-1] pivot["Change (%)"] = (pivot.il...
923e0e8c3fef4d76a1493b8782e1f7e7288c8c69
75,239
def read_file(filename): """ This function reads the names of wallpapers out of the configuration file, filename. Assumed data: """ with open(filename, 'r') as f: file_lines = f.read().split('\n') if file_lines.count('') != 0: file_lines.remove('') return file_lines
db1a1b0673f1889bd65bc921ca72397aeb03d0f8
75,240
from typing import Union def write_with_number(i: Union[int, float]): """ Write number with emoji :Basic usage: >>> write_with_number(23) '2⃣3⃣' >>> write_with_number(-23) '➖2⃣3⃣' >>> write_with_number(-23.34) '➖2⃣3⃣.3⃣4⃣' >>> write_with_number(-1234567890.098) '➖1⃣2⃣3⃣4⃣...
cdd2f1b29e71ddc6be879044db2c9be93b52ade9
75,241
from typing import Any import json def loads(data: str) -> Any: """Load a Python object from JSON.""" return json.loads(data, cls=ISO8601JSONDecoder)
7ce9c43e8c042d9ba50ef23e3c59a3d4dbb6a278
75,242
def get_file_type(file_name): """Returns file type as Jinja or None Args: file_name (string): file path with extension Returns: string: jinja or None """ if is_valid_file_type(file_name): return LANGUAGE_JINJA return None
8da5d924ec8dfe6cf54de176746441d5bc8f20e1
75,243
def run_task(cluster, task_definition): """Run a task in a cluster.""" client = get_client("ecs") params = {} params["cluster"] = cluster params["taskDefinition"] = task_definition return client.run_task(**params)
bc9425fdeb016fd06df54181f33abbd8ee54e307
75,244
def qvm_run_payload(quil_program, classical_addresses, trials, needs_compilation, isa, measurement_noise, gate_noise, random_seed): """REST payload for :py:func:`ForestConnection._qvm_run`""" if not quil_program: raise ValueError("You have attempted to run an empty program." ...
38d5f72f8d623fc3ac477c48842a365e8ee9348e
75,245
def divide_possibly_zero(array_a, array_b): """return 0 for nans""" out = array_a / array_b out[np.isnan(out)] = 0 return out
f9bcfcb7a6221b4735759f6f4123a48854d98f95
75,246
def dailystats_date_json(): """Return a /dailystats/<DATE> response.""" return { "id": 0, "day": "2018-06-04", "mint": 12.779999999999999, "maxt": 33.329999999999998, "icon": 2, "percentage": 100, "wateringFlag": 0, "vibration": [100, 100, 100, 100...
7bffa4d1f7d2a00aa51f1cc8929a2cd3383375fe
75,249
def force_error_analytic_pp( potential_type: str, cutoff_length: float, screening_length: float, alpha_ewald: float, rescaling_const: float ): """ Calculate the short-range part of the force error from the approximation formula given in :cite:`Dharuman2017`. Parameters ---------- potential_type...
70e82aa4f09c76920e68028d03ba12a6ce5dd103
75,250
def softplus_inverse(x): """ Inverse of the softplus function :param x: must be > 0 :return: inverse-softplus(x) """ return tf.math.log(tf.exp(x) - 1)
47ea16b43fb4fc1ddc143c36d5e2063fc7be69c4
75,251
def shouldSupportHSIntroV0(version): """Returns true if a Hidden Service is old enough to support the Hidden Service intro protocol version 0. See :func:`~leekspin.rendezvous.generateProtocolVersionsLine`. :param str version: One of :data:`SERVER_VERSIONS`. :rtype: bool :returns: ``True`` if w...
123524518c60e7276ed4c461ae5d317401691b81
75,252
import copy def update_if_missing_data(cfg_in, gridset): """Modify cfg to add a missing legend if the gridset's data has any missing values.""" cfg = copy.deepcopy(cfg_in) if not _gridset_data_has_missing(gridset): cfg = _prune_keys(cfg, 'missing_legend') return cfg
b769fcf74787c53fc87f7d9c11b14272002b37d1
75,253
def histogram(data_in, rows=1, columns=1, bins=50, fig=None, color=None, fontsize=None, dpi=None): """Wrapper for the histogram function in subplots""" # create a new figure window if fig is None: if dpi is None: dpi = 300 else: dpi = dpi fig = plt.figure(dpi=...
722f5ed1f52563a3b486b2736d97bf6a376b560d
75,255
def find_args(text, start=None): """ Finds arguments within function invocation. :type text: str :rtype: [ arguments ] or :data:NOT_FOUND if arguments could not be found. """ return __THE_PARSER.find_args(text, start)
3fb6ed2ab7e2d3cd60d21ed76f74b37aac363104
75,256
def task_delete(request, task_id, response_format='html'): """Task delete""" task = get_object_or_404(Task, pk=task_id) if not request.user.profile.has_permission(task, mode='w'): return user_denied(request, message="You don't have access to this Task") if request.POST: if 'delete' in ...
9718867dffe4ce1c6ede3b7ba49196131328d01c
75,257
def char_fun(A, b): """ Returns True if dictionary b is a subset of dictionary A and False otherwise. """ result = b.items() <= A.items() return result
e8d2f9bc69f1d3b164e5d80a35fca870f66a632a
75,259
def safe_check_lens_eq(arr1, arr2, msg=None): """ Check if it is safe to check if two arrays are equal safe_check_lens_eq(None, 1) safe_check_lens_eq([3], [2, 4]) """ if msg is None: msg = 'outer lengths do not correspond' if arr1 is None or arr2 is None: return True els...
09163acf03148710f670cda180e7c026f507b0df
75,262
def mdia_to_xyz_minCurve(deviation): """ Returns a tuple whose elements are 1D arrays corresponding to the sequences x, y, and tvd_z values from a well path deviation file (csv) with columns MD[m], incl[m], azi[deg]. Uses the minimum curvature method, [drillingformulas.com](http://bit.ly/2MNp7U0) A...
13ddd71f0bcac8e189cd8411cdae90746de71cd8
75,263
def fetchWords(): """Retrieve the word library (roughly 500k). return pwds: common passwords :type list """ prtcl, hstdmn, xtnsn, hdrs = defineAccessPoint() destination = "{}://{}.ly/".format(prtcl, hstdmn) # Generate the request to the bit.ly server req = Request(url = destination + xtnsn...
cc0dc842481aa614b12ac2141e7c3b746c3f7d79
75,264
def calc_wtd_exp(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, nbin=16): """Calculate the effective exposure. Parameters ---------- skydir : `~astropy.coordinates.SkyCoord` ltc : `~fermipy.irfs.LTCube` nbin : int Number of points per decade with w...
037b6554ee83ed0047573e437cb0d90e39050327
75,265
def read_tb_grout(in_name): """ Read energies and gradients from a Turbomole grad.out TDDFT file. Parameters ---------- in_name : str Name of the file to read Returns ------- energy : float Excited state energy in Hartree grad : numpy array of floats Energy g...
f8a46442188bb0856ab8683edcb55e0561683c2a
75,266
def _ng86(seq1, seq2, k, codon_table): """Main function for NG86 method (PRIVATE). """ S_sites1, N_sites1 = _count_site_NG86(seq1, codon_table=codon_table, k=k) S_sites2, N_sites2 = _count_site_NG86(seq2, codon_table=cod...
40634a9fb1c6cf5e2a0b6e00e55ac3586bd3848d
75,267
def silence(time): """ Create silence (time in seconds)""" return AudioSegment.silent(time*1000)
21e18ebfa1d7069ab4bd6a4c2a03f4c63fbb94aa
75,268
def principal_angles_deg(A, B): """Returns the principal angles between two subspaces in degrees Args: A (jax.numpy.ndarray): ONB for the first subspace B (jax.numpy.ndarray): ONB for the second subspace Returns: (jax.numpy.ndarray): The list of principal angles between two subspac...
a06cb42b5651b840caa200ebc5f0ad3e32dcc671
75,269
def get_guider_number(xml_file, observation_number): """"Parse the guider number for a particular FGSExternalCalibration or WfscGlobalAlignment observation. """ observation_number = int(observation_number) apt_namespace = '{http://www.stsci.edu/JWST/APT}' fgs_namespace = '{http://www.stsci.edu/J...
a7fd6e5e9b96416e1bc61d0a7940770c6b1f2f84
75,270
def get_exif_data(image): """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags""" exif_data = {} info = getattr(image, '_getexif', lambda: None)() if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "G...
55ce003041c3f5a8a2764ea93a24e8596d6526e9
75,271
def compute_surface_overlap_at_tolerance(surface_distances, tolerance_mm): """Computes the overlap of the surfaces at a specified tolerance. Computes the overlap of the ground truth surface with the predicted surface and vice versa allowing a specified tolerance (maximum surface-to-surface distance that is rega...
1715408a8a0dc26556aeb75c9732f6365091ed36
75,272
import torch def hamming_diff(seq1, seq2, p1=None, p2=None, ps=None): """ Return the difference between the hamming distance of the two sequences and the expected hamming distance between two random vectors. If p is specified, use it as the common p for both vector. Otherwise, calculate each vecto...
d7439ae7d1ce79fbb40eaab0f67f75f7e6e671bc
75,273
import time import torch def train_Contrastive(args, model, model_head, device, train_loader, optimizer, epoch, num_classes): """ This train step is based on one single encoder shared across both simCLR branches. :param args: :param model: :param model_head: :param device: :param train_lo...
bb734d832f4304562731988b76ab67c8479bccff
75,274
def join_contexts(curcontext): """ This function will join the global context with the current context. It will overwrite any commands in the global context with any commands that are defined in the current context. I.e., so if you have a command that generally functions one way, you can define it i...
98530247d2ebfc88348679311d0773725138472f
75,276
def _resize_clip_char_boxes(polygons, im_scale, im_shape): """ Clip polygons to image boundaries. :param polygons: [N, 4* num_classes] :param im_shape: tuple of 2 :return: [N, 4* num_classes] """ # x1 >= 0 polygons[:, :8] = np.round(polygons[:, :8]*im_scale) polygons[:, 0:8:2] = np.m...
e0955e806de357124d13aa0570b2e6265469736b
75,277
import re def postgisraster_test_serial(): """ Test the ability to connect to a data source if it has no primary key, but uses a sequence instead. """ if gdaltest.postgisrasterDriver is None: return 'skip' src_ds = gdal.Open( gdaltest.postgisraster_connection_string + "table='small_wo...
aad1265be53c2d3189f4778281d7c43c5e1ee165
75,278
def convert_user_to_entity(user_data): """Returns entity specific to UserData Args: user_data: UserData to be converted to datastore entity Yields: Entity Converted entity object from UserData """ entity_key = get_user_key(user_data.user_id) user_entity = datast...
0d1e339e0afef8ea96cbee46da34f4c6e116509f
75,279
import random def generate_exact_cover(num_of_subsets): """Generates a new exact cover problem with the given number of random filled subsets""" subset = set() while len(subset) < num_of_subsets: subset.add(frozenset(random.sample(range(1 ,num_of_subsets + 1), random.randint(0, num_of_subsets)))) ...
2e63bdc7181caa312ed42d48578989c8ddc29050
75,280
def delete_addresses(account_id, address_id): """ Delete an Address This endpoint will delete an Address based the id specified in the path """ app.logger.info("Request to delete Address %s for Account id: %s", (address_id, account_id)) address = Address.find(address_id) if address: ...
dffd4df9c81040f0ee0b41e2f029c7d96f19d375
75,281
def read_long_description(path: str) -> str: """Utility function to read the README file.""" with open(path) as file: data: str = file.read() return data
c206f2cec2613fde5217845c1e36cd507924716e
75,282
import time def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :...
40b9e608dd80830a8fc2a60fa15fffb8e41419eb
75,283
import inspect def get_ctx() -> commands.Context: """Attempts to retrieve discord context from the call stack.""" frame = inspect.currentframe() while frame: _locals = dict(frame.f_locals) for k, v in _locals.items(): if isinstance(v, commands.Context): return v...
2fa3d6846f690ef2bf9f55328c18a33fa9af1bad
75,284
def _assemble_gap(stmt): """Assemble Gap statements into text.""" subj_str = _assemble_agent_str(stmt.gap) obj_str = _assemble_agent_str(stmt.ras) stmt_str = subj_str + ' is a GAP for ' + obj_str return _make_sentence(stmt_str)
5b511661706ef26fda96e2a84a7c0b82e2e7ce15
75,285
def post(*args, **kw): """Mark the decorated function as a handler for POST requests.""" return _make_handler_decorator('POST', *args, **kw)
36ef843509d4e5ebb01852a068a1f22752910c82
75,286
def delete_user(user_id=None): """ Delete a user (with all its data). """ user = User.query.filter(User.id==user_id).first() db.session.delete(user) db.session.commit() return redirect(redirect_url())
f918d737eacdadbe0321df7db6b165832d9f1e3d
75,287
def _is_match(source: schema.NormalizedLocation, candidate: dict) -> bool: """Return True if candidate is so similar it must be a match""" source_links = ( set("{}:{}".format(link.authority, link.id) for link in source.links) if source.links else set() ) candidate = candidate["p...
a0029f9045f7e35c0bbfb93b341146769c1b588f
75,288
def permute(nums: list[int]) -> list[list[int]]: """ALGORITHM""" # DS's/res uniq_perms = [[]] for curr_num in nums: uniq_perms = [ perm[:insertion_idx] + [curr_num] + perm[insertion_idx:] for perm in uniq_perms for insertion_idx in range(len(perm) + 1) ...
3da21c4bdaf77a1e55c3ece4b90a90d53a3565f7
75,289