content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_graph(conf): """Retrieve Neo4j graph credentials and create Graph object""" graph = Graph(user=conf.get('neo4j', 'user'), password=conf.get('neo4j', 'pass')) if graph is not None: print("Loaded Neo4j graph") return graph
4076b6643f91cd98f038361098aa7e92abdb107e
77,487
def accepts_nfa(N, s, chatty=False): """NFA acceptance. Input : N : given NFA s : given string chatty : Boolean (prints accepting path, which is the state-sets encountered). """ Q0 = N["Q0"] if (run_nfa(N, Q0, s, chatty) & N["F"]) != set({}): ...
06682c0a29b5b00ecf9951693f7132bb5548586b
77,488
import sqlite3 def authenticate(): """ Performs the master authentication, and returns a Fernet object if authentication succeeded. Returns literal None if authentication fails. External modules should directly call only this method. """ conn = master_db_connect() username = '' master_...
e878e8edcdc52756fc25665fccbad8d1b92e5931
77,489
from typing import Iterable def concatenate_lists(*list_of_lists: Iterable) -> list: """Combines the Iterables provided as arguments into one list. Examples -------- Normal usage:: concatenate_lists([1, 2], [3, 4], [5]) # returns [1, 2, 3, 4, 5] """ return [item for lst in li...
e630fd31888753814e3f486c02b0fc1e67f269ef
77,490
def celv(kc, p, c, s): """ vectorized version of the cel integral above """ # if kc == 0: # return NaN errtol = 0.000001 n = len(kc) k = np.abs(kc) em = np.ones(n, dtype=float) cc = c.copy() pp = p.copy() ss = s.copy() # apply a mask for evaluation of respectiv...
87409d6a5a2129f58adce76e636d96a994c70044
77,491
import json def firstbloods(tick_id=None): """The ``/scores/firstbloods`` endpoint requires authentication and takes an optional ``tick_id`` argument. It returns all of the firstbloods that have occurred during tick_id if tick_id is present It can be reached at ``/scores/firstbloods?secret=<API_SECRE...
c9b973ffeb3e8e3bdfbf21999ed2306e4a9d11f0
77,492
def wave_grad(x, y, par): """ NAME: wave_grad PURPOSE: compute the deflection of an soliton+NFW tail potential USAGE: (xg, yg) = wave_grad(x, y, par) ARGUMENTS: x, y: vectors or images of coordinates; should be matching numpy ndarrays par: vector of parameters with 1 to 6 ...
26b7a23a3ba9efcb6f23f1fdcf191412c4678ebf
77,494
def generate_dates(start_date: str, last_date: str) -> list: """Generates the date strings in the date range, inclusively Arguments: start_date: the expected first date in the range last_date: the expected last date to include in the range Return: Returns a tuple of the valid dates, ...
18cd593da94bdea469c78030ac6f201c83d1db0c
77,496
def format_units(v, step, system="si"): """Format the given value in standardized units. ``system`` is either 'binary' or 'si' For more info, see: http://en.wikipedia.org/wiki/SI_prefix http://en.wikipedia.org/wiki/Binary_prefix """ for prefix, size in UnitSystems[system]: if abs(v) >= size a...
67a36538e72ac723c796a2f2defe6e46329c4c17
77,497
def order_triangles(vertices, triangles, clockwise_from_center=True): """ Order the icosahedron triangles to be in a clockwise order when viewed from the center of the sphere. Used by the 'find_rotation_interpol_coefs' for barycentric interpolation. Examples -------- >>> from surfify.utils impo...
58784b3649f199ed8d191efb8e5bdce6b53b890c
77,498
def basic_faculty_profile_data(schema): """ Gets fields on the schema that are directly stored on the profile, as opposed to many-to-many fields that are stored in other tables. """ base_fields = get_base_fields(schema) return { **base_fields, "willing_shadowing": schema.get("willin...
a4522652daf1b6ed9b97ea69aac18bae03df605c
77,500
def dummy_config(): """Returns an instance of a Config object.""" return Config(PATH_TO_DUMMY_CONFIG)
d677ba583e9ca644e501a4c7aa360b91023c01c2
77,501
def _get_peakFit_ranges(centers, half_widths, fit_window=4, merge_overlap=True): """ Parameters ---------- centers : array-like centers of peaks half_widths : array-like Full width at half maximum of peaks fit_window : int, float ranges are calculated as centers +- (FWHM ...
0389049841cdf46e66eaee01db3ec832b4516478
77,502
def map_variables(model): """ map the variables by the four types of variable bound. paras: model: the original model. returns: variable_map_dict: a dictionary contains four sub-dictionaries, each contains the replaced parameters. """ variable_map_dict = { c...
eb56c6af883f70c08364086c85ac9d951d3ad451
77,503
def append_tinfo_covered(*args): """ append_tinfo_covered(out, typid, offset) -> bool """ return _ida_typeinf.append_tinfo_covered(*args)
989d43fa6e54e4b3b394771447b86d92cc2807db
77,504
def _column_wrangler(data: pd.DataFrame) -> pd.DataFrame: """Returns DataFrame with columns transformed into a consistent format: 1. Stripped of all whitespaces at start and end 2. Any excess whitespace in between are replaced with an underscore "_" 3. All characters are lowercased """ data.colu...
fd5656d7925f7c3e604b82dfb151803804fcc739
77,505
def existing_beats(patient_id): """ checks whether there are existing heart beats for a patient :param patient_id: integer ID of patient to check if there is beat data :return: True if patient has recorded heart rates, False if not """ for user in Patient.objects.raw({"_id": patient_id}): ...
45bb0a1afa985ac00c182ad70b6911b62e00fcfe
77,506
def get_counterfactual_args(): """ Add arguments specific to the "Counterfactual" postprocessing. Return ArgParser object. """ cmd = get_general_args() cmd = get_explainer_args(cmd) cmd.add('--in_dir', type=str, default='results/temp_counterfactual/') cmd.add('--out_dir', type=str, defa...
bfe8bc8d02a8f9b614a0d03eade0ceb589371ef9
77,507
def custom_404(request, exception=None): """ Custom, 'nice' 404 page. If DJANGO_SLACK_ALERT_URL variable is setup in settings with Slack room hook URL, it will send Slack room message, but only if referrer is from the site (aka a broken link). """ referer = request.META.get('HTTP_REFERER'...
ec4d26c1c6c1921315e41816e13da7343e03dcab
77,508
def getAria2SpinSystems(ariaRestraint): """Descrn: Get the pairs of ARIA spin systems that correspond to the contributions to an ARIA restraint Inputs: Aria2 restraint object Output: List of 2-List of ARIA SpinSystem objects """ spinSystemPairs = [] for contribution in ariaRestraint.getC...
22a6d717787ec74144457451b78a4651577f9619
77,509
def out(obj, print_val=True): # !cover """ Prints out the given object in the shitty format the Windows Charmap supports. """ if isinstance(obj, str): val = str(obj.encode('ascii', 'ignore').decode('ascii')) elif isinstance(obj, (int, float, complex)): val = str(obj) else: val = str(pformat(vars(obj)).encode...
c87adeac0f863be9a6c7994cc2a67127f7a0d0d8
77,511
def find_golden_token(): """ Orientation function by side golden token Returns: Gdist(float): distance to the side nearest gold token (-1 if the gold token is found in the range 89<Grot_y<91 or -89>Grot_y>-91 Grot_y (float): the angle between the robot and the gold token (-1 if the gold t...
d685275af0ddffd3510836f1642c6c2e928f28e9
77,512
def test_implicit_optimization(): """ Checks if the optimizer works correctly in the case when the variables are not passed explicitly to the function. """ def get_implicit_loss(mean, var): def loss(): return (var() - mean) ** 2 return loss v = BoundedVariable(9, ...
09faa37bf45975def7cfe197a64cffdc538d0a12
77,513
def map_pixels_to_ascii_chars(image, range_width=25): """Maps each pixel to an ascii char based on the range in which it lies. 0-255 is divided into 11 ranges of 25 pixels each. """ pixels_in_image = list(image.getdata()) pixels_to_chars = [ASCII_CHARS[pixel_value/range_width] for pixel_value...
217971730560fcb69fa8dffca0b9de7c9c207a67
77,514
def is_attr_pattern(text): """Attribute patters are like '[title=Version \d.*]' """ return text.startswith('[')
05978edb1d6589f47a96ab6cb2da4b7f0e3f2569
77,516
def emulatescene(insig, gain, irspath): """ Emulates a scene by convolving a source input signal with em32 AIRs :param insig: (Single-channel) input signal :param gain: Gain (scalar) :param irspath: Path to the AIRs to be used :return: 32 channels of audio from an emulated em32 recording. "...
7554ea3ea03203071730136cab7615fe10fb9170
77,518
def test_input_data(): """A set of fields required to validate the company form""" return { 'DUNS Number': '123456789', 'Business Name': 'Widgets Pty', 'Secondary Name': 'Lots-a-widgets', 'National Identification System Code': '12', 'National Identification Number': '123...
34f1826119882a9fb1a8fadc40845a435bcdfb98
77,519
def _borehole_high(x, sd=0): """ High fidelity version of borehole function Reference: https://www.sfu.ca/~ssurjano/borehole.html """ numerator = 2 * np.pi * x[:, 2] * (x[:, 3] - x[:, 5]) ln_r_rw = np.log(x[:, 1] / x[:, 0]) denominator = ln_r_rw * \ (x[:, 2] / x[:, 4] + 1 + (2 ...
21d273e29c2cb85387d9f003ae94d50259a123da
77,520
def parse_args(): """Parse input arguments """ parser = ArgumentParser() parser.add_argument('--dir', help=('dir')) parser.add_argument('--keyword', help=('keyword'), default='') parser.add_argument('--filetype', help=('filetype'), defa...
56bfe9a51ac866ae80055dc86c6fb1bc9565497b
77,522
def login_view(request): """ Get: display login form Post: login user into a session """ if request.method == "POST": # Get details from form username = request.POST["username"] password = request.POST['password'] # attempt to sign in user = authentic...
b27565f9977a3c387492f4d208ad9fa896f187dc
77,523
import logging def read_hparams(filename, defaults): """Reads HParams from JSON. Args: filename: String filename. defaults: HParams containing default values. Returns: HParams. Raises: gfile.Error: If the file cannot be read. ValueError: If the JSON record cannot be parsed. """ with...
5f704eed6ade288116700f1d2c27ed104ab6ddb5
77,524
def parsecaldict(caldict,mjd): """ Small helper function for getcal() to select the entry in a calibration dictionary that is valid for a MJD.""" gd,ngd = dln.where( (mjd >= caldict['mjd1']) & (mjd <= caldict['mjd2']) ) if ngd>0: if ngd>1: gd = gd[-1] print('Multiple cal produ...
1b93096fef96e5c72fb6cb58e7711ad47eeac5ba
77,526
def sequence_nd( seq, maxlen = None, padding: str = 'post', pad_val = 0.0, dim: int = 1, return_len = False, ): """ padding sequence of nd to become (n+1)d array. Parameters ---------- seq: list of nd array maxlen: int, optional (default=None) If None, will calcu...
fafdc6ddd1415e92788d7b8bd6b331a9ac8f6c4e
77,527
def orientation_between(u, v, origin): """ Compute angle in radians between vectors u and v """ u_norm = unit_vector(u - origin) v_norm = unit_vector(v - origin) return np.sign(np.arctan2(u_norm[0] * v_norm[1] - u_norm[1] * v_norm[0], u_norm[0] * v_norm[0] + u_norm[0] * v_norm...
fd32db2b73b9305ec8d0ea9eab4addc001b7970c
77,528
def get_measurements(dataset, band_grids=None): """ Extract and return measurement paths in a dictionary: Returns { 'measurements': { 'coastal_aerosol': { 'path': path_name1, 'band': band_number, '...
af33457e8edd85f334b07c657de4dc308a140994
77,529
import re def _figure_name_filter(value): """replace characters that may cause problems for html/javascript ids""" if isinstance(value, Undefined): return value out = (value .replace('^', '-') .replace(' ', '-') .replace('.', 'dot') .replace('%', 'percen...
2d6188e958260c21620496684c7c4f2cf646c721
77,531
def validate_inputs(input_data): """Check prediction inputs against schema.""" # set many=True to allow passing in a list schema = CustomerActivityDataRequestSchema(many=True) errors = None try: schema.load(input_data) except ValidationError as exc: errors = exc.messages if...
c49721dc65e733451753e0bb8564e3560d1ff443
77,532
def shortest_path_lengths(graph, source): """ 迪克斯特拉算法 :param graph: :param source: :return: """ d = {} cloud = {} pq = AdaptableHeapPriorityQueue() pq_locator = {} for v in graph.vertices(): if v is source: d[v] = 0 else: d[v] = float...
c1f9e8a2fa9a0f1af07ee721be85c2c2f1a1f072
77,533
def restart_geoshape(*args): """ Restart GeoSHAPE instance, including Django, GeoServer, and RabbitMQ Calls ./stop_geonode and ./start_geonode, restarts tomcat7, and resets RabbitMQ """ return _run_task(_restart_geoshape, args=args)
6451b5d4f9eb00c72f121ac7ca5eb783253d9769
77,534
def add_region(request, glossid): """Add a new region to a gloss""" if request.method == "POST": # Get the data, don't use a form it just adds overhead gloss = get_object_or_404(Gloss, id=glossid) dialect = get_object_or_404(Dialect, id=request.POST['dialect']) frequency = reque...
134c7a2d719aac49cc8f139944e06d102bf17a5d
77,535
import traceback def markdown_to_safe_html(s): """ :param s: :return: """ html = s try: # Get HTML, and replace newlines with break tags html = html.replace('\n', '<br>') # Convert html to markdown html = markdown.markdown(html) except Exception as ex: ...
fa54a393988912eb2f39f900fbcb05254ecf3c92
77,536
def determine_feature_dtype(X, features): """ Determine if any features are categorical. """ feature_names = list(X.columns) non_cat_features = [] cat_features = [] for f in features: if f not in feature_names: raise KeyError(f"'{f}' is not a valid feature.") if ...
39368183612f214e9b1385be0d3bc716f7eaa950
77,537
async def docs_index() -> Response: """Documentation index static endpoint.""" return await send_from_directory(docs_dir, "index.html")
57ce7df42f563cbae2572fdc1eddb675fdd333ae
77,538
from typing import Callable from typing import Iterable from typing import Any from typing import Tuple def interactive_trace( state: 'fun_mc.State', fn: 'fun_mc.TransitionOperator', num_steps: 'fun_mc.IntTensor', trace_mask: 'fun_mc.BooleanNest' = True, iteration_axis: int = 0, block_until_re...
e826a77f5e674165f6916a277c3e575d9ad80efc
77,539
from typing import Optional from typing import Callable from typing import Dict from typing import Any from typing import Tuple def simulate_flux( alpha: npt.NDArray[np.float64], r: float, theta_0: float, n: int, m: float, objective_func: Optional[Callable] = None, root_kwargs: Optional[Di...
c9ed7a35a91319226e25544056662d8ac0922f60
77,540
def get_route(cities, network): """Return the route computed by a network.""" cities['winner'] = cities[['x', 'y']].apply( lambda c: select_closest(network, c), axis=1, raw=True) return cities.sort_values('winner').index
8baa3705a6252560edccd33642f4a996c5117c42
77,541
def shift_following_entries(entry, shift, session_=None): """Reschedule entries starting after the given entry by the given shift.""" query = entry.siblings_query.filter(TimetableEntry.start_dt >= entry.end_dt) if session_ and not entry.parent: query.filter(TimetableEntry.type == TimetableEntryType....
7324d36b1cf1d6f6aef09d6170c72c1fa0fd2ba0
77,543
def split_interval(relative_areas, radius_range): """ Split an interval by relative area. Parameters ---------- relative_area - Array The relative proportions to split the interval by. Needs to be sorted in descending order. radius_range - Tuple The min/max bounds of the int...
8a5f49696a24a15b6214debdfaedc035f0c88b85
77,545
def dT_RJ2bright(nu, T_RJ): """the frequency function for converting RJ temperature fluctuation to the brightness temperature fluctuation. ***Multiply by dT/T to get dT_RJ*** :param nu: observed frequency [GHz] :param T_RJ: RJ temperature [K] :return: dT*T_RJ/dT_RJ [K] """ x_RJ = h_ove...
1c374d57708a6fe5b42e05c4076f3b66bb756a00
77,546
def get_category_articles(request, pk, page, page_size): """Returns a paginated list of articles with the given category id.""" category_id = pk if pk is not None else request.GET["category"] articles, paginator = get_paginated_articles(category_id, page, page_size) articles_html = render_to_string("r...
e21de638689bbf9f80ee4622906048669806492b
77,547
import uuid def autoslugFromUUID(): """[Generates auto slug using UUID] """ def decorator(model): assert hasattr(model, "slug"), "Model is missing a slug field" @receiver(models.signals.pre_save, sender=model, weak=False) def generate_slug(sender, instance, *args, raw=False, **kw...
2512e1c24e0d0be0af0d418d5d7c9cbc04ef48fb
77,548
def check_small_world_bias(corr, dmin=3, dmax=30, dnum=10, randomizations=20, seed=1): """ Test to see if a method for defining edges produces networks with excess clustering This is based on Zalesky et al. Neuroimage 60:2096 2012 which demonstrated that standar...
17831a145d94adf603cde3a935aabbae2bac1f3a
77,549
def _get_corr_entropy(list_ts, log2 = True): """ Returns modified entropy to use in Gaussian correlation matrix CMI computation. H = -0.5 * sum( log(eigvals) ) where eigvals are eigenvalues of correlation matrix between time series. """ log_f = np.log2 if log2 else np.log corr_matrix =...
ad04943d7023806d2dffe1986cfc66cecb6ae601
77,552
def get_dataset(cfg): """ Get dataset. """ if cfg.dataset.name == "modelnet40": dataset = ModelNet40( cfg.dataset.root, cfg.dataset.num_points, ) else: raise NotImplementedError('Unknown cfg.dataset.name : ' + cfg.dataset.name) return dataset
e5ef2ef2cd05afd26204493f6f899d49b19d568c
77,555
def get_path(name: str) -> str: """ Get path of example data :param name: Name of test data (listed in xdem/examples.py) :return: """ if name == "longyearbyen_tba_dem_coreg": return _get_longyearbyen_tba_coreg_dem() if name in list(FILEPATHS_DATA.keys()): download_longyearby...
c2f0b4f9eb3b2de71e2a82ad1e90e790547d1fbd
77,556
from typing import Optional from typing import Callable import functools from typing import Dict import torch import time import statistics def timeit(func: Optional[Callable] = None, num_iters: Optional[int] = 100, warmup_iters: Optional[int] = None): """ A simple timeit for GPU operations....
445e8de3dd9a4b715a431317a9f2bce663528392
77,557
def dict_filter_missing(data: dict) -> dict: """ Filters out all values that are MISSING sentinel. Args: data: The dict data to filter. Returns: The filtered dict data. """ return {k: v for k, v in data.items() if v is not MISSING}
9ed466f9a7d204952e1ebe2221b42519abb326fb
77,558
def make_random_mul(kernel, n=4, concat_dim=0, dual=False): """ input is dim/n x dim output is dim x dim generalization and parameterized hypercomplex product """ dim = kernel.get_shape().as_list()[1] dim2 = kernel.get_shape().as_list()[0] kernel = tf.reshape(kernel, [dim2, 1, 1, dim]) mix = tf.split(kernel, n...
2d092ef9231590c48c2d3ecb984df6a4c180a3cf
77,559
def adadelta(lr, rho, epsilon, weight_decay): """\ Adadelta optimizer. Adadelta is a more robust extension of Adagrad that adapts learning rates based on a moving window of gradient updates, instead of accumulating all past gradients. This way, Adadelta continues learning even when many updates...
8a10c0adc6f7695c2c3cc4cc741c8667f1d03f14
77,560
def __mul__(self, other): """Computes the multiplication between two numbers. Parameters ---------- self : ee.Number Left operand. other : ee.Number | numeric Right operand. If numeric, an ee.Number is created from its value. Returns ------- ee.Number Multiplica...
6358532c6cd9e61001433f84ea77cb5e4f453e0c
77,561
import logging def upload_file(file_name, bucket, object_name=None): """Upload a file to an S3 bucket :param file_name: File to upload :param bucket: Bucket to upload to :param object_name: S3 object name. If not specified then file_name is used :return: True if file was uploaded, else False ...
b1b3ca53d65a7373257646b219ad2e1f2f9a1203
77,563
def print_stats(df): """ Print stats from a DataFrame and create a summary DataFrame that is returned """ print("{} different experiments".format(len(set(df.experiment)))) print("{} detected neurons in total".format(len(df))) print("{:.2f} neurons per experiment on average".format(len(df)/len(se...
e37335cc09e71671f33c1ffd9f5fd2fc42c0309a
77,564
def repeat_game(number, sequence): """ Apply look-and-say rule to a sequence in specified number of times Args: number (int): number of game repetitions sequence (str): initial sequence of numbers Returns: str: resulting string after applying the look-and-say rule number-times ...
35cd8f570e0025e5616f53a5a3c34b40419b8d27
77,565
def generate_ei(N, pE=0.8): """ E/I signature. Parameters ---------- N : int Number of recurrent units. pE : float, optional Fraction of units that are excitatory. Default is the usual value for cortex. """ assert 0 <= pE <= 1 Nexc = int(pE*N) Ninh = N - Nex...
1231968940fb0d913a55b84d42fc5d4eb2575427
77,566
def strip_nondigits(string): """ Return a string containing only the digits of the input string. """ return ''.join([c for c in string if c.isdigit()])
564a05de12c61a09a6d07e13b13279908128389a
77,567
def rankGraphs(graphs): """ Ranks the edges in each element of a list of graphs. Required Parameters: graphs: - a list of graphs. """ rankGraphs = {} for subj, graph in graphs.items(): rgraph = nx.Graph() edge_ar = np.asarray([x[2]["weight"] for x in graph.ed...
90580241e8e7edaba88bac37c8b46dd9875c97ff
77,568
def makeDataFrame(input_directory, filelist, **kwargs)->pd.DataFrame(): """accept a list of .fcs files and generate a tidy pandas.Dataframe""" ##Rationale users may have a single file that they want a plot from as quickly as possible. ##Converting .fcs files to pandas DataFrames allows rapid plott...
d2c79512c57a8553efd8d320f0cbd4f3533fb0e1
77,569
def default_sorted_attribute(workload_line, attr='submit_time', converter=None): """ :param workload_line: A line readed from the file. :param attr: Attribute of the line for sorting. :param converter: Converter function to cast the attribute. :return: Returns the attribute of the line....
7c9af903dfc49fd4b03bcc7602dc159f6bdc67f7
77,570
def diag(v): """ | Extracts diagonal or constructs a diagonal array. :param v: number, :ref:`scalar object<scalar_ref>`, square or one dimensional :ref:`multidimensional object<multi_ref>`. :return: number, :ref:`scalar object<scalar_ref>` o...
0665eb90fd304153365a2b64f6129061d5030d74
77,571
def feature_extractor(inputs, n_nodes, batch_size): """ Compute various features and concatenate them. Parameters ---------- morphology_input: keras layer object (batch_size x n_nodes - 1 x n_nodes) the adjacency matrix of each sample. ...
c51beba2eb40b5329e2d04f509af82c5e82067ac
77,572
def complete_remote_stage(prefix, **_): # type: (str, ...) -> t.List[str] """Return a list of supported stages matching the given prefix.""" return [stage for stage in ('prod', 'dev') if stage.startswith(prefix)]
2d927ca3550dd3f0469c3bd3e78dd15ee7d569bf
77,573
def compute_gradient_norm(output: Tensor, model: Module): """ Compute the norm of the gradient of an output (e.g a loss) with respect to a model parameters :param output: :param model: :return: """ ret = 0 output.backward(retain_graph=True) for parameter in model.parameters(): ...
7aa22db8aecd31206abe0f83ca2b86430b7a989e
77,574
import copy def extract_features(texts, tokenizer, label2id, ignore_label_id, max_length, n_jobs=-1): """Creates a dataset at inference time. Args: """ label2id = copy.deepcopy(label2id) label2...
acd126db7056cd07e756dc45720f9b9582ed1363
77,575
def pandas_dtype(dtype): """ Converts input into a pandas only dtype object or a numpy dtype object. Parameters ---------- dtype : object to be converted Returns ------- np.dtype or a pandas dtype """ if isinstance(dtype, DatetimeTZDtype): return dtype elif isinstan...
69faf0371005fa68b81265cc4f37a7939138ce39
77,576
def xcorrt(data1, data2, shift, shift_zero=0, oneside=False, demean=True, normalize=True, window=0, ndat1d=0, ndat2d=0): """ Cross-correlation of numpy arrays data1 and data2 in time domain. """ if (len(data1) - len(data2)) % 2 == 1: raise ValueError('(N1-N2)%2 has to be 0') if oneside: ...
67a9819a9a1d6f2b38dc167ab79cd20fa277fcfa
77,578
from typing import Dict from typing import List import json async def format_cookie_file(cookie_file: str): """Restore auth cookies from a file. Does not guarantee that the user is logged in afterwards. Visits the domains specified in the cookies to set them, the previous page is not restored.""" domain_c...
fda88b45fe3c31ea25a94bc17e16d56dedec522f
77,579
from typing import List def get_haso_apartment_uuids(haso_application: HasoApplication) -> List[UUID]: """ From the given Haso application, get all apartment uuids ordered by the priority of the apartment. """ return list( HasoApartmentPriority.objects.filter(haso_application=haso_applicat...
7fe65f69e370b6454094794123b4372c16246a22
77,580
def get_configuration_class(version): """ Get the appropriate config class for ``version``. :type version: str or int """ configurations_class = { 1: BuildConfigV1, 2: BuildConfigV2, } try: version = int(version) return configurations_class[version] excep...
73b17e9545c170ebc6b7d33a54c5541ece034ef8
77,581
def get_top_card_symbol(hand): """ :param hand: rankbit of a given hand without any repetition :return: the rankbit rep of the top card in the current hand """ i = 0 while hand >> i != 0: i += 1 return 1 << i
578f69f9c1b00f367670bf7d4bb95becb412cee1
77,582
def scale_min(im, targ, interpolation=cv2.INTER_AREA): """ Scales the image so that the smallest axis is of size targ. Arguments: im (array): image targ (int): target size """ r,c,*_ = im.shape ratio = targ/min(r,c) sz = (scale_to(c, ratio, targ), scale_to(r, ratio, targ)) ...
256e8000647b6e5d99e3e9de880b7e76b3b9cdb9
77,583
import io def emcee_sample_batch(sampler, ini_positions, n_step, prefix='asap', verbose=True): """Run the sampling process in batch mode.""" if verbose: print("\n# Phase: Sampling Run ...") # Number of parameters n_dim = ini_positions.shape[1] sample_results = sampler.run_mcmc( i...
4d10a45752748b7e6383bc80f895de5d6f60316a
77,584
def build(target_assigner_config, bv_range, box_coder): """Builds a tensor dictionary based on the InputReader config. Args: input_reader_config: A input_reader_pb2.InputReader object. Returns: A tensor dict based on the input_reader_config. Raises: ValueError: On invalid inpu...
3504c423472b41923718814a45f2463ae0ff28a3
77,585
def SplitImageNet(root, n_experiences=10, per_exp_classes=None, return_task_id=False, seed=0, fixed_class_order=None, train_transform=_default_train_transform, test_transform=_default_test_trans...
98ad0aca5769cc9fbbc265b3a896485b66558da1
77,586
def create_results_df(dates, station_ids, means, stds, train_time=None, params=None): """ """ df = pd.DataFrame({ 'date': dates, 'station_id': station_ids, 'mean': means, 'std': stds, 'train_time': train_time, 'params': params }) ...
e11c43077399c0b67a55f6ab61fd0c6b2c6a0bfe
77,587
def _filename(repo): """name of a tagcache file for a given repo or repoview""" filename = 'tags2' if repo.filtername: filename = '%s-%s' % (filename, repo.filtername) return filename
681f8cad850393e43eed4c3a03c53842364286f0
77,588
def measurement_schema() -> XMLSchema: """ Sets up the Measurement XML schema to validate responses from the XML API """ return XMLSchema(etree.parse(f"{current_path}/schemas/measurement.xsd"))
2851f7fa892a3e443d547f306139e5b18c8e38bc
77,589
def parse_begins(msg): """Parse the guard ID out of the "begins his shift" message.""" words = msg.split() return int(words[1][1:])
b07e3d741038365dddbacfdb70d219ef1bf007d8
77,590
def prompt_with_default(prompt: str, default: str) -> str: """Get string user input with def prompt""" prompt = prompt + f' [{default}]: ' return get_user_input(prompt, default)
994efa28a5997469122aba20d8314b799affd9d9
77,591
def make_request_for_quotation(**args): """ :param supplier_data: List containing supplier data """ args = frappe._dict(args) supplier_data = args.get("supplier_data") if args.get("supplier_data") else get_supplier_data() rfq = frappe.new_doc('Request for Quotation') rfq.transaction_date = nowdate() rfq.status ...
80a23f42bf256abec70a090c5b6a95fff1cc0adc
77,592
def index() -> flask.Response: """Let people know not to go to this site :_ :return: HTML Response :rtype: flask.Response """ return '<h1>Warning</h1>This is a malicious webserver'
319cfca2a77f1b6a93d4bc95f3db581650ecedb7
77,593
def threshold_otsu(image): """ :param image: :return: """ threshold_global_otsu = skimage.filters.threshold_otsu(image) otsu_vector = image >= threshold_global_otsu return otsu_vector
8b7c317c1a272761a0cba299915618838cb3fceb
77,594
import xarray as xr import cartopy.crs as ccrs from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER from ML_OOP_stratosphere_gases import plot_like_results def plot_figure_response_predict_maps(path=work_chaim, ncfile=None, species='H2O', ...
e70c549089131c2fe57305e996d0a48bd0a08ed4
77,595
def define_network(pretrained_model, classifier, learning_rate: float, epochs: int): """Load pre-trained network and append a custom classifier. Args: pretrained_model: pretrained model classifier: classifier appended to the pretrained model learning_rate: rate of gra...
f58b7a9f8a4acd308bb162de46bf50188a167f65
77,596
def steps_to_list(string_literal: str) -> list: """Takes a comma separated list and returns a list data type.""" new_list = [] for item in string_literal.split(','): new_list.append(item) return new_list
239beeb650df9968277eee9150cfcad27629cb75
77,597
def anchor_targets_bbox(anchors, image_group, annotations_group, num_classes, negative_overlap=0.4, positive_overlap=0.5): """Generate anchor targets for bbox detection. Args: anchors...
e9192a2589ab20b4c29bbe2215453e365ab5aa54
77,598
def lookup(address, default_port=80, format_host='{}', qname='A'): """Look up address, and return MinecraftServer instance after sucessfull lookup.""" host, port = parse_address(address) if port is None: port = default_port try: answers = dns.resolver.resolve(format_host.format(h...
a88c6dda23581f06093a596f0867824e4ea8c8ca
77,599
def posenc(x, min_deg, max_deg, legacy_posenc_order=False): """ Cat x with a positional encoding of x with scales 2^[min_deg, max_deg-1]. Instead of computing [sin(x), cos(x)], we use the trig identity cos(x) = sin(x + pi/2) and do one vectorized call to sin([x, x+pi/2]). Args: x: jnp.ndar...
aa815d1fdef875fa7a5c25cbd52d054e5ef0e389
77,600
def get_cron(id): """Return cron have id = id @param Integer id @return Cron """ cron = session.query(Cron).filter_by(Id=id).first() return cron
87c48a1fd241a2e44202df6d0cc68a672e3a81e2
77,602
from pathlib import Path def get_simulator( seed: int, x0: float, sigma: float ) -> Simulator: """ Simulatorクラスのインスタンスを作成する Parameters ---------- seed: int x0: int sigma: float Returns ------- sim: Simulator """ param = ParamSimulator( total_step=500, ...
50f65b209de3f88adddd03115458737fe60fb4f5
77,603
def set_format(): """Set output format of the instrument. Will measure its own output.""" global out_type global meas_type global format_ out = get_out_type(out_type) meas = get_out_type(meas_type) cmd = f'FORM:ELEM {out}, {meas}, TIME;' format_ = write_visa(cmd, 'FORM:ELEM?').split(','...
8f7b6957cfe3de01d55b2a2f6a1c531119dea11e
77,604