content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Any from typing import Dict def execute( schema: GraphQLSchema, document: DocumentNode, root_value: Any=None, context_value: Any=None, variable_values: Dict[str, Any]=None, operation_name: str=None, field_resolver: GraphQLFieldResolver=None ) -> MaybeAwaitabl...
5cc9d6f26001c312a43c7da410f5edf616185057
54,300
def _two_func_initializer(freqs, signal): """ This is a helper function for heuristic estimation of the initial parameters used in fitting dual peak functions _do_two_lorentzian_fit _do_two_gaussian_fit """ # Use the signal for a rough estimate of the parameters for initialization: r_signal = n...
023561a6a09c157cff284055cb6d5a24b6cc297c
54,301
from pathlib import Path import os def task_benchbase_run(): """ BenchBase: run a specific benchmark. """ def invoke_benchbase(benchmark, config, args): if config is None: config = ARTIFACTS_PATH / f"config/postgres/{benchmark}_config.xml" elif not config.startswith("/"): ...
81ae7cc0e4670968e67e23825fa1c3cddb852f51
54,302
def ReadContourStructures(DCM): """Reads a dicom (.dcm) file and returns a dictionary with contour information. The information including colour, name and contour data Contour data include all the (x,y,z) data points used to build the contour """ contours = [] ds = dicom.read_file(DCM) num...
423f57fb6ee41adfb04e551237b4d9f4bbef7574
54,303
def list_projects(request): """ Tags: projects --- Lists projects on cloud. Only supported for EquinixMetal. For other providers,returns an empty list READ permission required on cloud. --- cloud: in: path required: true type: string """ auth_context = auth_...
9834f3c6b50aa69b7e4722f00bc2556d02aa1179
54,304
def run_policy_loop(agent, env, max_num_episodes, fps): """Execute the policy and render onto the screen, using the standard agent interface.""" agent.initialize() episode_rewards = [] for _ in range(max_num_episodes): obs, done = env.reset(), False episode_reward = 0 while not...
a6dd2d0629cb2463ace7687163b0d0e0fcf36873
54,305
def calc_energy_forces_3D(pos, cell_dim, bond_indices, angle_indices, angle_bond_indices, param): """ calc_energy_forces(pos, cell_dim, bond_indices, angle_indices, angle_bond_indices, vdw_coeff, param) Return tot potential energy and forces on each bead in simulation Parameters ---------- dxy: array_like (fl...
1d312a318a3347fd3687e5d0abc1d1856011c8e3
54,306
def gen_range(start, end): """Return a list of the numbers between |start| and |end|. This filters out surrogate pairs. """ return [x for x in range(start, end) if x < 0xd800 or x >= 0xe000]
009b0af854b5ad6d8a06d01a24cf08b26a644dbc
54,307
def cmp_to_key(mycmp): """functools.cmp_to_key backport""" class KeyClass(object): """Key class""" def __init__(self, obj, *args): # pylint: disable=unused-argument self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(s...
685035bff0e2df45c5c5698787a012a38f623142
54,308
import socket def compress_ipv6(ipv6_addr): """ Compress ipv6 address, i.e: compress_ipv6(0001:0001:0000:0000:0000:1111:0000:0000') -> '1:1::1111:0:0' """ ipv6_addr = is_valid_ipv6_ret(ipv6_addr) return socket.inet_ntop(socket.AF_INET6, ipv6_addr)
258fd4911092d33b591f66dfa04ddda8ba5f5d9c
54,309
def _whois(COMMAND, nick, mask='', prefix='', msg=None): """Returns a WHOIS for nick.""" if conf.supybot.protocols.irc.strictRfc(): assert areNicks(nick), repr(nick) if msg and not prefix: prefix = msg.prefix args = (nick,) if mask: args = (nick, mask) return IrcMsg(prefi...
de1fb928dde32de79cf1d709e379001a2906b9f1
54,310
def fit_learning_curve(train_set_size, error_test, error_train=None, pinit=(1.0, -1.0), funcs=1): """ returns parameters to predict learning curve as a power function with the form y = a + b * x**alpha where x is the training set size, i.e., the independent variable You provi...
d4f3f609aee475d390f62262f16db7848b69e4c7
54,311
from typing import Optional import argparse from typing import List def load_from_args( *, parser: Optional[argparse.ArgumentParser] = None, arguments: Optional[List[str]] = None, ordered: bool = False ) -> (argparse.Namespace, Storage): """Parses command line arguments, loads conf...
47edbc2f4ed4fba3af5f2a65d2557dc49d5151d1
54,312
def textsize(txt, font=None): """ Calculates the bounding box of the text, as drawn in the specified font. This method is most useful for when the :py:class:`~luma.core.legacy.font.proportional` wrapper is used. :param txt: the text string to calculate the bounds for :type txt: str :param fo...
ef64f0712bc720984290e503cc7dc1c6d62b1ca2
54,313
def chirp_amp_phase(v,i, t, start=0.0, end=19.9, down_rate=20000.0, min_freq=0.2, max_freq=20.): """ Calculate amplitude and phase of chirp responses Parameters ---------- sweep_set: SweepSet Set of chirp sweeps start: float (optional, default 0.6) Start of chirp stimulus in...
cf395e390cf8b6f32e0458fea12a456b7ec2d820
54,314
def push_code( idx, code ) : """ Push code to browser -------------------- idx : CodeMirror editor index code : code to push """ logger.debug("Pushing code, idx = " + str(idx) + " | " + code ) for ch, replacement in escapechars : code = code.replace( ch, replacement ) lock...
4af4007925c678fbbfa3041150f1abe438469c42
54,315
def off_target_coverage(bam, bed, dir): """ Calculate (using mosdepth and the off_target_bed) the mean coverage in the off target regions, with coverage weighted by length of the intervals. Return as dictionary to be inserted in the coverage DataFrame """ df = mosdepth(bam, bed, dir, prefix="off...
eeef9d21a0366d725202b531584c10ac8e683bdc
54,316
import json def get_json_data(): """Fixture to return the json data as a Python variable.""" def _method(_file): """Fixture to return the json data as a Python variable, given a file location Args: _file (str): The location of the json file to input data from. Returns: ...
8544db10f0d4558c030ffb8a1455aed91b832ac3
54,317
def convert_model(saved_model_dir): """ Convert a SavedModel into Tensorflow Lite Format. `saved_model_dir`: the path to the SavedModel directory returns: the converted Tensorflow Lite model """ logger.info('Converting SavedModel from: {}'.format(saved_model_dir)) converter = tf.lite.TFLiteC...
2dd2436285acd0dc488d0023d091a75cf4ecad07
54,318
def connect(): """ Open a connection to the typesense server. """ with open('/etc/typesense/typesense-server.ini') as f: lines = f.readlines() api_key = [line[10:] for line in lines if line.startswith('api-key = ')][0].rstrip() return typesense.Client({ 'nodes': [{ 'host'...
dadc9ec6667aedc080aa4421020b0be7ec1c41a2
54,319
def _make_url(raw, sig, quick=True): """ Return usable url. Set quick=False to disable ratebypass override. """ if quick and "ratebypass=" not in raw: raw += "&ratebypass=yes" if "signature=" not in raw: if sig is None: raise IOError("Error retrieving url") raw += "&si...
b1c3c61ba60f21b436a70a9eff3d629600b76fc6
54,320
from typing import Optional from typing import Any def get_component_exceptions( cluster: str, environ: str, topology: str, component: str, role: Optional[str]=None, ) -> Any: """Get exceptions for 'component' for 'topology'.""" base_url = create_url(EXCEPTIONS_URL_FMT) params = { "clu...
cadabb7e306ca56fed1d8254ce5a6b6ec399b6e1
54,321
def UnpackHWIDDigest(base, header): """Unpacks HWID digest section.""" offset = base + GBB_HWID_DIGEST_OFFSET size = GBB_HWID_DIGEST_SIZE return GBBField(header.hwid_digest.hex(), offset, size)
6c6a37090e149f4dcc0a1c74bb1c0399bc204a97
54,322
import itertools def group_into_dict(items, key_fn): """ Groups items into a dictionary based on a key generated by a given function Examples: items = [ Car(make="Honda", model="Civic"), Car(make="Honda", model="Accord"), Car(make="Ford", model="F150"), ...
bdf4fbb4cd1df0b187e0aed2fc8916530711365d
54,323
def _get_table_meta(): """gets the meta data about fields from meta.agolitems """ mapping = {} with pyodbc.connect(config.get_source_connection()[6:]) as connection: cursor = connection.cursor() cursor.execute('SELECT [TABLENAME],[AGOL_PUBLISHED_NAME],[GEOMETRY_TYPE] FROM [SGID].[META]...
fbafb21ce24101b980702b374cc588522e5a5705
54,324
def _estimate_ratios_by_kmeans(obs, guess, **kmeans_kws): """ Adapted kmeans to use norm1 distances (identical to euclidean-norm2 for 1D) and using median() for each guess, to ignore outliers and identify "gear-lines". """ def _1d_kmeans(obs, guess, guess_func, thresh=1e-5): """ The "ra...
cc2b727e7fc9f64292438c2755fe31c6da77f3d2
54,325
from typing import Collection import logging def construct_grammar(grammar_config: GrammarConfig, vocab: Collection[str]) -> state_tree.NQCFG: """Builds the grammar according to `grammar_config`.""" productions = [] # Lexical rules. if grammar_config.grammar_type in ( GrammarType...
a16caaf212ae2d843f295d0c3f2ae29444e97547
54,326
import requests def get_channel_id(username, API_KEY): """ i might have been entering the wrong usernames or something but, this thing only works half of the time """ url = f"https://www.googleapis.com/youtube/v3/channels" payload = {"forUsername":username, "part":"id,snippet", "key":API_K...
da90cdec623d5c3e4ee210cc133ee9900db340f9
54,327
def pick_npoints_on_hemisphere(N = 2500): """Randomly pick N points on the upper part of a hemisphere. see http://mathworld.wolfram.com/SpherePointPicking.html """ xs, ys, zs = [], [], [] us, vs = np.random.rand(N) * 2 * np.pi, np.arccos(np.random.rand(N)) for i in range(N): x, y, z = u...
40e469bdb2eb4b35e8e6e7f22f961d4777082281
54,328
import os def to_sequence_example(image, decoder, vocab): """Builds a SequenceExample proto for an image-caption pair. Args: image: An ImageMetadata object. decoder: An ImageDecoder object. vocab: A Vocabulary object. Returns: A SequenceExample proto. """ filename = output_file =...
837f033ad46d0ebec29bcb7da60b85b64f137e59
54,329
import scipy def plot_histogram( ax, x, maxima: bool = False, maxima_props: dict = None, annotate_props: dict = None, hist_props: dict = None, ax_props: dict = None, plot_props: dict = None, inter_props: dict = None): """Plot a histogram from...
237776e080ad9ded2950f13fe7d1fa06306f80ee
54,330
import json def print_columns(response, response_type): """prints a column style output for a list of networks currently only supports 'pureport accounts network list :param response: the response object :type response: array :returns a formatted output string :rtype: str """ colu...
328ec7f12856b69c8290d5bed3c2efc3cfe4ceb1
54,331
from datetime import datetime def get_geo(hdfname, monotonic_lons=True,root_name=None): """ given the name of any hdf file from the Cloudsat data archive return lat,lon,time_vals,prof_times,dem_elevation for the cloudsat orbital swath usage: lat,lon,date_times,prof_times,dem_elevation=get_ge...
3908d697bc92098ca6b9dc25de3bb03cd69f9b30
54,332
def get_metadata(tsuid): """ Get metadata from metadata api If `fid` is in the user provided pattern add that to metadata :param tsuid: TSUID to get metadata from IKATS :type tsuid: str :return: the metadata list for this timeseries :rtype dict """ metadata = IkatsApi.md.read(tsui...
c402fbe554e99089a2d4457489ff42c49e7cb58b
54,333
def get_author_list(): """ Get author list --- responses: 200: description: Returns author list schema: id: AuthorList properties: code: type: string message: ...
0a1d68466b8c84f0a01924bf53ce83ef78c8a29a
54,334
import re def parse_extra_metadata_to_selector(option: str, operation: str, value: str) -> str: """Method tries to convert the extra metadata received into selectors :param option: option (extra, python_version, sys_platform) :param operation: (>, >=, <, <=, ==, !=) :param value: value after the oper...
4be00559ada260d569a1efe7d027f843dbf3e8b1
54,335
def vgg11_quantized(num_classes=10, dataset='cifar10'): """VGG 11-layer model (configuration "A")""" return VGG(make_layers(cfg['A']), num_classes, dataset)
471bb48d930c790e633ffb04c13278d750b23e99
54,336
def get_paint_dc(win): """ A utility function for obtaining a BufferedPaintDC on Windows. """ if get_platform() == 'windows': dc = wx.BufferedPaintDC(win) dc.SetBrush(wx.Brush((win if win.UseBgCol() else win.GetParent()).GetBackgroundColour())) dc.SetPen(wx.TRANSPARENT_PEN) dc.Dr...
9e5f7b72ef835ce4957a46c4f65f85e605b552a9
54,337
def average_data(df): """ Average data over eval runs then scenario runs """ df = df.astype({"solved": int}) avg_eval_df = df.groupby(["scenario", "agent", "run"]).mean().reset_index() eval_err = df.groupby(["scenario", "agent", "run"]).sem().reset_index() # run_err = avg_eval_df.groupby(["scenario"...
e0f6bc8f8ee59b6b5855324baf6a2ecee4a25e2e
54,338
def get_value_names_from_timestamp(timestamp, file_id=None, mode='r'): """ Returns value_names from the HDF5 file specified by timestamp. :param timestamp: (str) measurement timestamp of form YYYYMMDD_hhmmsss :return: list of value_names """ folder = a_tools.get_folder(timestamp) h5filepath ...
dd5a4ff776715cb67e553d4a8284dfc415de73ff
54,339
def get_element(X, bb, shape): """ returns the bounding box area from the image X """ x,y,w,h = bb x,y,w,h = int(x),int(y),int(w),int(h) return resize(X[y:y+h,x:x+w], shape, mode='constant')
010cb2809efa919228229252418427ee8fb54b74
54,340
def convert_verbose(verbose): """Convert the results of the --verbose flag into a list of logger names if --verbose is not provided, args.verbose will be None and logging should be at the info level. if --verbose is provided, but not followed by any arguments, then args.verbose = [] and debug loggi...
ce11aee9ba6ef150cfb858b265339c3648821a66
54,341
def non_psd_kernel(a, b): """An implementation of a non-psd kernel. Args: a: A vector b: A vector """ if(np.allclose(a,b,rtol=1e-5)): return -1 return 0
f52b891bab20d29b955f5df13dc8449af5ddfb38
54,342
def delta_func(beta): """ Compute delta_beta as per Heuristic 1. """ rep = ((pi * beta) ** (1 / beta)) * beta / (2 * pi * exp(1)) rep = rep ** (1 / (2 * (beta - 1))) return rep
2f8bf7bfbae8d8f5fcd4a6f7dff9b44648655eb1
54,343
def encode(plain_text, a_value, b_value): """ Encode text """ if gcd(a_value, 26) != 1: raise ValueError("a and m must be coprime.") plain_text = list(filter(lambda x: x.isalnum(), list(plain_text))) for index, char in enumerate(plain_text): if char.isalpha(): new...
cba8a4d84b4d2bdd06d1502047fc164bd42969e1
54,344
def pad_to_shape(d, dshape, mode = "constant"): """ pad array d to shape dshape """ if d.shape == dshape: return d diff = np.array(dshape)- np.array(d.shape) #first shrink slices = tuple(slice(-x//2,x//2) if x<0 else slice(None,None) for x in diff) res = d[slices] #then pad...
61786ff3ea975015cf56bc2716cedb3b359fb8b4
54,345
import sys def query_memory_timeline(records, db_url, db_name, db_collection, max_items=20, similarity=TIMELINE_SIMILARITY): """ Query database for similar memory items committed previously """ def timeline_key(item): """ Defines order for timeline report entries """ order = 0 ...
7e386ea87d16cb81f5e16056b0602c2d96753aa5
54,346
from datetime import datetime def addFooter(template, clientAddress=None): """Add a footer:: -- <3 BridgeDB ________________________________________________________________________ Public Keys: https://bridges.torproject.org/keys This email was generated with rainbows, unico...
e4e679e1d49e3368a77ec00702742864614c6958
54,347
def _trace_lines(frame, event, arg): """ Function used for tracing executed lines. Inserts into log: lineno : Tuple[line_str, locals] """ global logger co = frame.f_code parent = frame.f_back.f_code func_name = co.co_name if event == 'line': if func_name.split('::')[-1] ...
274890305c9b1b1399c63d65924f597e1bbdc683
54,348
def confirm_superuser_changes(request, user_id): """Renders the confirmation page to confirm the successful changes made to the selected user's account settings by the group superuser. Parameters: request - The request object sent with the call to the confirm page if the request...
3ded3fae6f8d9af55da076631c6e9addeb3be503
54,349
def grad_refactor_simple_2(x, y, z): """ add """ return x * y + z + x * y * z + x + x * y
38bc1120ec6804f364d8c98f91d6301ef609ecf4
54,350
def heading_section(title: str, to_list: bool = False): """Construct a section heading. """ linelist = [title, hr(len(title), '=')] return linelist if to_list else '\n'.join(linelist)
f5f6d7fa1e0b3a459df7a3f40247f7eec54123fc
54,351
from jinja2 import Environment, FileSystemLoader import os import numpy import pandas import re from sys import version def _featureSelectionReport(dataset, destinationPath=None, withArtifactualFiltering=False): """ Report on feature quality Generates a summary of the number of features passing feature se...
c30417d9b37116d4eca118bc822ef361b0a5ae70
54,352
def _GetStarredIssues(cnxn, logged_in_user_id, services): """Get the set of issues that the logged in user has starred.""" starred_iids = services.issue_star.LookupStarredItemIDs( cnxn, logged_in_user_id) return set(starred_iids)
6185371138da1e79673d7347770073a18f82b099
54,353
import pytz def AdaptReadableDatetime(date_obj): """Adapts a datetime.datetime object to its ISO-8601 date/time notation.""" try: date_obj = date_obj.astimezone(pytz.utc) except ValueError: pass # naive datetime object return date_obj.isoformat()
feceafb58995001acdeb2285fa5782bec7cc756d
54,354
def iou_loss(true, pred): """ Calcaulate the intersection over union metric """ intersection = true * pred notTrue = 1 - true union = true + (notTrue * pred) return tf.subtract(1.0, tf.reduce_sum(intersection)/tf.reduce_sum(union))
7d2dae13252d472749932363a37716bde8addfed
54,355
def get_gop_pos(frame_idx, representation): """given frame idx to find the group idx and the position inside a group""" gop_index = frame_idx // GOP_SIZE gop_pos = frame_idx % GOP_SIZE if representation in ['residual', 'mv', 'flow']: if gop_pos == 0: # use the previous frame's residual and MV...
6c284bc957c24b553b66bf4ddb23814ad7246f03
54,356
import asyncio async def _get_server_host_key(host, port=(), *, tunnel=(), family=(), flags=0, local_addr=None, client_version=(), kex_algs=(), server_host_key_algs=(), config=(), options=None): """Retrieve an SSH server's host key This is a coro...
ad7837090e8fc43ff68797c4b722c79fd4c88b20
54,357
def prompt_choice(length, select_action, per_page): """ Prompt the user for a choice of entry, to continue or to quit. An invalid choice will repeat the prompt. @param length: the largest choosable value @param select_action: description of what choosing an entry will result in. @param per_pag...
4b957479d96e5b8c642db4e888faf92c8c9cf945
54,358
from re import T def _e_step(psamples, W_list, b_list, n_steps=100, eps=1e-5): """ Performs 'n_steps' of mean-field inference (used to compute positive phase statistics) Parameters ---------- psamples : array-like object of theano shared variables State of each layer of the DBM (durin...
8bafc87c33367ed999d80de027201d7680db1d40
54,359
from typing import Tuple def get_stencils( stencil_sizes: Tuple[int, ...], offset: Tuple[float, ...], steps: Tuple[float, ...] ) -> Tuple[np.ndarray]: """Computes stencils locations. Generates stencils such that the target offset is placed at (0.,)*ndims. This is needed to obtain correct polynomial...
72ec1d453533dc6787825e03702b4c6226493e5e
54,360
import time def neo_start(self, container_name, project_name, port, pwd): """ 启动neo4j Args: pwd: port: project_name: self: container_name: Returns: """ # 在js取到 data['state'] != 'CREATE NEO4J SANDBOX' 后将配置展示(仅仅展示) self.update_state( state="S...
ab85d0f2d4de5279812bdc9f81a45bc51770c69b
54,361
def normalize(data, axis=None, index=None): """ Normalize data on the given axis data: a multi-dim array. axis: axis or axes which makes subarrays to be normalized together. E.g., axis=-1 means to normalize the innermost dimension. None (i.e., all axes) or int or tuple of int. index: in...
a901b794ff4e1f4dc5944494d9163a2cecabddb7
54,362
import os import textwrap import sys import stat def generate_script( bin_dir, script_name, executable=None, code_dir=None, inject_coverage=False, inject_sitecustomize=False, ): """ Generate script """ if not os.path.isdir(bin_dir): os.makedirs(bin_dir) cli_script_...
4fad4518027b8169a8b12be8ba8b35b70dc19647
54,363
import collections def make_map(connections): """Return the map of caves based on connections.""" neighbors = collections.defaultdict(list) for start, end in connections: neighbors[start].append(end) neighbors[end].append(start) return neighbors
10f35208fa75b5ae4723d9d55e022a0fcc857e51
54,364
def des_key_64(K): """ Return an 64-bit des key by adding a zero to the least significant bit of each character. K should be a 7 char string """ in_key = K + "\0" out_key = [K[0]] for ix in xrange(1,len(in_key)): out_key.append(chr( ((ord(in_key[ix-1]) << (8-ix)) & 0xFF) | (ord(i...
bffbb3217d6818c6bfece656978af6ff413ecb41
54,365
def l2_norm(x): """ Returns ------- normalization of data in range(0,1) with method euclidean distance Parameters ---------- x: x is we data in shape Matrix note -------- most import numpy as np """ a = np.sqrt(np.square(x)) size_of_vector = np.sqrt(np.sum(a ** 2, a...
4a130f8abb4b1a9adb5dbeb932cd43ea0889c296
54,366
from typing import Tuple def info_to_table(rows: list) -> Tuple[list, list]: """ Formats raw row data into a table format that will be used with other render functions. This function is where column headers should be defined. Arguments: rows(list): Rows of data Return: ...
3f92acccb3d93aa539ef34f136c557ca3ecb324b
54,367
def calcExRIndex(inputRasterImage,mode): """ calcExRIndex. :param inputRasterImage: (Image) input raster image. :param mode: (String) mode RGB or GBR :returns outputRasterImage: (Image) output raster image. """ if mode=='RGB' : chRed,chGreen,chBlue = cv2.split(inputRasterImage) else: chGreen,chRed,chBlu...
8ee2ea0b767bae69a22b790229fa78645c29121e
54,368
import os import pickle def grade_assignments(notebook_dir, image="ucbdsinfra/otter-grader", verbose=False, scripts=False, no_kill=False, output_path="./", debug=False, zips=False, pdfs=False): """ Grades multiple submissions in a directory using a single docker container. If no PDF assignment is want...
6ddc289abdf4da93ca68d6704588cef64bdbe8fe
54,369
def random_type(): """Return type of monster.""" types = ( ('Slime'), ('Skeleton'), ('Zombie'), ('Blue Wizard'), ('Red Wizard'), ('Bear'), ('Wolf'), ('Barbarian'), ('Minotaur'), ('Goblin'), ('Ogre'), ) return choice(...
c3801b9446bfae34d09952904c31641beed87bec
54,370
def get_ip(server, net_type, ip_version): """Return the server's IP of the given type and version.""" if net_type in server.addresses: for ip in server.addresses[net_type]: if ip['version'] == ip_version: return ip['addr']
a8b983fb27ed01f5a76aab3f0e8a345f0273e153
54,371
import random import torch def random_crop(image, boxes, labels): """ Performs a random crop operation with multiple possibilities as in the paper. Helpful when detecting bigger objects(windows, doors, buildings). Ref: https://github.com/amdegroot/ssd.pytorch/blob/master/utils/augmentations.py ""...
a6afd940af21206cae367b4b96a95ce1a0992874
54,372
from sklearn.impute import IterativeImputer from sklearn.ensemble import RandomForestRegressor from sklearn.preprocessing import LabelEncoder from sklearn.neighbors import KNeighborsRegressor def impute_missing_values(data, verbose: int, estimator): """Imputation of missing values using the IterativeImputer metho...
7fd741a258073cae3e6b2b2676dd11a774dcc0ec
54,373
def service_http_delete(request, application_id, service_http_id): """ Delete service model """ service = get_object_or_404(HTTPCodeService, pk=service_http_id) service.service.delete() return redirect(reverse('project', args=[application_id]))
bc820603161a537a7e0d2444249ceab65e3869dd
54,374
from app.shortener import shortener def create_app(config): """ Flask application factory to create the app object. """ app = Flask(__name__) app.config.from_object(config) db.init_app(app) app.register_blueprint(shortener) return app
8464e6bce15bc929ab10e8f3a6534fcc669b32f6
54,375
import os def is_uptodate(picklefile, path_list=None, min_time=1343682423): """Check if the pickle files is uptodate compare to a list of files. If no files are given, the pickle files is checked against it\' current directory""" if not os.path.exists(picklefile): return False ...
57b5e5377780a043e547ceb4657f97d111d84062
54,376
from bs4 import BeautifulSoup import re import pytz from datetime import datetime def ilmaandmed_veebist(dt_utc): """ Tagastab etteantud ajahetke (dt_utc) viimase möödunud täistunni ilmaandmed ilmateenistus.ee veebilehelt """ jaam = 'Valga' cols = ['airtemperature', 'relativehumidi...
182615fb52a067d8daa14e0255c0784fa64b29bb
54,377
def set_value(obj, value): """ 设置固定数值 :param value: 数值 :return: 数值 """ return value
1ecb69bebb841a8a36d752544560f87d95f07c5f
54,378
def AddSliceTag(slicename, key, value, node, nodegroup): """ AddSliceTag() calls s.api.AddSliceTag() with the correct set of arguments. Args: slicename - string slicename i.e. "iupui_ndt" key - the slice tag name, i.e. "vsys" value - the value for the slice tag, i.e. "web...
3c7884724d6b4a14ab4b488113d7d65e2bde89d4
54,379
def initialize_all(y0, t0, t1, n): """ An initialization routine for the different ODE solving methods in the lab. This initializes Y, T, and h. """ if isinstance(y0, np.ndarray): Y = np.empty((n, y0.size),dtype=complex).squeeze() else: Y = np.empty(n,dtype=complex) Y[0] = y0 T = np.linspace(t0, t1, n) h =...
2a14fa5a8eceae1504a5d2cc69b57306d6703b4b
54,380
import random import string def generate_points(num_points): """ :param num_points: an integer, the number of data points :return: """ points = [Point() for _ in range(num_points)] vmin, vmax = 100, 0 for p in points: vector = np.random.choice(list(range(1000)), 2) word = '...
f2e220ebc3b2d651009b6c93758172596ad358f6
54,381
def camel_shuffle(sequence): """ Inspired by https://stackoverflow.com/q/42549212/610569 >>> list(range(12)) # Linear. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>> camel_shuffle(list(range(12))) # M-shape. [0, 4, 8, 9, 5, 1, 2, 6, 10, 11, 7, 3] >>> camel_shuffle(list(rev...
710e8b1fd626019e2af8cac1f2ecdb295dbef022
54,382
def random_date(start, end, prop): """ get random date between start and end """ return str_time_prop(start, end, '%Y-%m-%d %I:%M:%S', prop)
423815406e9b5522e971bbaefcada3596c99b5bf
54,383
def calc_distances(x, targets): """ within and between class distances """ def c_s(l): l.sort() s, r = 0, 0 n = len(l) for i in range(n - 1): s += l[i] r += 2 * (n - i - 1) * l[i] s += l[-1] return (n - 1) * s - r within_class = 0 for y, inclass_x ...
079c7085bb275b905b7342cfca98db074f801c53
54,384
def check_symmetry_and_dim(number, dim=3): """ check if it is a valid number for the given symmetry Args: number: int dim: 0, 1, 2, 3 """ valid = True msg = 'This is a valid group number' numbers = [56, 75, 80, 230] if dim not in [0, 1, 2, 3]: msg = "invalid...
1097eb78dbd58f0e164ae5f10fdc9f88a3c00ccc
54,385
import _json def merge_layers(input_layer, merge_layer, merge_attributes=None, output_name=None, gis=None, context=None, future=False): """ .. image:: _static/images/merge_layers/merge_layers.png ...
459db54a89fd30694e3ba248b0b52ce396f61b7e
54,386
def anonymous_required(redirect_url): """For views that allow only unauthenticated users to access view. Usage: @anonymous_required(redirect_url='company_info') def homepage(request): return render(request, 'homepage.html') """ def _wrapped(view_func, *args, **kwargs): def check...
b2cf7fe55cf16da320e1baa7ae9570ef708bb724
54,387
import collections def get_buffers(layer_instance, include_sublayer=True): """ Returns Variable buffers of decorated layers. If set `include_sublayer` True, the Variable buffers created in sub layers will be added. """ buffers = collections.OrderedDict() if layer_instance is not None: ...
01500c4692280e0db24aac442d274b66b8f08129
54,388
def user(): """ exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://.....
10c394bd3bd325ab2d7b9e996524d0f1a120de15
54,389
def pagerank(A, p=0.85, personalize=None, reverse=False): """ Calculates PageRank given a csr graph Inputs: ------- G: a csr graph. p: damping factor personlize: if not None, should be an array with the size of the nodes containing probability distributions. It wi...
7400dc7a85871ed90671621158f7c662b4bb2e67
54,390
def create_transforms(input_config): """Create transforms from configuration Parameters ---------- input_config : dict Dictionary containing the configuration options for input pre-processing. Returns ------- train_transforms : list List of transforms to be applied to the i...
5e5e40d3df048c9d8f9701c5b413af431497273b
54,391
from typing import Optional from typing import List from typing import Literal from typing import Dict from typing import Callable import inspect def pulse_diagram_plotly( schedule: Schedule, port_list: Optional[List[str]] = None, fig_ch_height: float = 300, fig_width: float = 1000, modulation: Li...
6e977f8a6be9e527f68ccdf0263df349fa251247
54,392
def unbiased_std_factor(n): """ Returns 1/c4(n) """ if is_arraylike(n): wh = n < 343 ans = np.ones(np.shape(n)) * (4. * n - 3.) / (4. * n - 4.) n = n[wh] ans[wh] = spec.gamma((n - 1) / 2) / np.sqrt(2 / (n - 1)) / spec.gamma(n / 2) return ans else: ans...
dea4e8670ebefe8f9e3139ee84061def8a8354ae
54,393
import sys def is_test(): """ Detects if the application is currently running as a celery worker. """ return 'test' in sys.argv[1]
5552a8e3d7adf1b0fc5f17c2ae56c5fa640dc4a5
54,394
def _ion_number_density(field, data): """ Creates the function for a derived field for following the number_density of an ion over a dataset given that the specified ion's ion_fraction field exists in the dataset. """ if isinstance(field.name, tuple): ftype = field.name[0] field_...
e049c55c92df3afa65f5554f05cfd4241751ee62
54,395
def normalize_by_population(tidy_df): """ Normalize by population the column "value" of a dataframe with lines being the country ISO """ pop = get_populations() normalized_values = (tidy_df.set_index('iso')['value'] / pop.set_index('ISO3')['Population']) # NAs appea...
3257178aa4071820946715593bb84524c398f2bf
54,396
def _hex_to_int(input: str) -> int: """Given a hex string representing bytes, returns an int.""" valid_bytes = input[1:] if (len(input) % 2 != 0 and input[0] == "0") else input hex_bytes = bytes.fromhex(valid_bytes) return int.from_bytes(hex_bytes, BYTE_ORDER)
79c5d5505a72c825722996458f43f503438bfb62
54,397
import platform import os def get_creation_time(filepath, verbose=True): """ Try to get the date that a file was created, falling back to when it was last modified if that isn't possible. See http://stackoverflow.com/a/39501288/1709587 for explanation. """ if platform.system() == "Windows": ...
cdd2cdab00cca89d86ec500cfbb8beb215e16e13
54,398
async def update_objects_by_id(model, conn, obj_id_list, data: dict) -> int: """Массовое обновление объектов в БД. Args: model (Table): обновляемая модель (таблица) в БД. conn (SAConnection): открытое соединение с БД. obj_id_list (list of int or int): список идентификаторов ...
e433f17b700770a2fee0927ce7c8c5e170d13e23
54,399