content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def scale_intensity(data, out_min=0, out_max=255): """Scale intensity of data in a range defined by [out_min, out_max], based on the 2nd and 98th percentiles.""" p2, p98 = np.percentile(data, (2, 98)) return rescale_intensity(data, in_range=(p2, p98), out_range=(out_min, out_max))
57df2200fbefa4ab6f1c91f46063b1b1f147301e
23,078
def raises_regex_op(exc_cls, regex, *args): """ self.assertRaisesRegex( ValueError, "invalid literal for.*XYZ'$", int, "XYZ" ) asserts.assert_fails(lambda: int("XYZ"), ".*?ValueError.*izznvalid literal for.*XYZ'$") """ # print(args) # assert...
9b0e6aa0692d2285467578083f76c888de9874c1
23,079
def getParInfo(sourceOp, pattern='*', names=None, includeCustom=True, includeNonCustom=True): """ Returns parInfo dict for sourceOp. Filtered in the following order: pattern is a pattern match string names can be a list of names to include, default None includes all includeCustom to include custom parame...
01eafb065ef98e1fd4676898aeb8d0c5a7a74b9d
23,080
def generate_crontab(config): """Generate a crontab entry for running backup job""" command = config.cron_command.strip() schedule = config.cron_schedule if schedule: schedule = schedule.strip() schedule = strip_quotes(schedule) if not validate_schedule(schedule): sc...
d958c47e0673d19dbd8d8eb2493995cdc2ada7ff
23,081
import attr def to_dict(observation: Observation): """Convert an Observation object back to dict format""" return _unprefix_attrs(attr.asdict(observation))
4ffd5ad24fee6bd983d7cb85ac7d1b9eeb56e751
23,085
def _consolidate_extrapolated(candidates): """Get the best possible derivative estimate, given an error estimate. Going through ``candidates`` select the best derivative estimate element-wise using the estimated candidates, where best is defined as minimizing the error estimate from the Richardson extr...
2641a56d852ed9e4065c7dfad4b1fd51ef581b91
23,086
import torch def build_wideresnet_hub( num_class: int, name='wide_resnet50_2', pretrained=True): """[summary] Normalized mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] Args: name (str, optional): [description]. Defaults to 'wide_resnet50_2'. pretr...
39f977a9ab368bd9fa15fb36c600c350afca7f53
23,088
def get_phoenix_model_wavelengths(cache=True): """ Return the wavelength grid that the PHOENIX models were computed on, transformed into wavelength units in air (not vacuum). """ wavelength_url = ('ftp://phoenix.astro.physik.uni-goettingen.de/v2.0/' 'HiResFITS/WAVE_PHOENIX-ACES...
ff5632086ffb3aa3eb6655c3ba18e182f0724bc4
23,089
def accuracy_boundingbox(data, annotation, method, instance): ## NOT IMPLEMENTED """ Calculate how far off each bounding box was Parameters ---------- data: color_image, depth_image annotation: pascal voc annotation method: function(instance, *data) instance: instance of object ...
78fa63d5e2cbdad843feaddd277b98886789a517
23,091
import logging def test_kbd_gpios(): """Test keyboard row & column GPIOs. Note, test only necessary on 50pin -> 50pin flex These must be tested differently than average GPIOs as the servo side logic, a 4to1 mux, is responsible for shorting colX to rowY where X == 1|2 and Y = 1|2|3. To test the ...
237f26a5da5711c480ef9dadbaa46170ca97c884
23,093
def fields_for_model(model): """ This function returns the fields for a schema that matches the provided nautilus model. Args: model (nautilus.model.BaseModel): The model to base the field list on Returns: (dict<field_name: str, graphqlType>): A mapping of f...
9eb6f1a51513ff6b42ab720a1196cea1402cac23
23,094
def _landstat(landscape, updated_model, in_coords): """ Compute the statistic for transforming coordinates onto an existing "landscape" of "mountains" representing source positions. Since the landscape is an array and therefore pixellated, the precision is limited. Parameters ---------- lan...
0205654ef8580a0d6731155d7d0c2b2c1a360e9c
23,095
def presence(label): """Higher-order function to test presence of a given label """ return lambda x, y: 1.0 * ((label in x) == (label in y))
49c7e0b4b7af69c808917af7ab4d6b56a7a4ef89
23,096
def make_formula(formula_str, row, col, first_data_row=None): # noinspection SpellCheckingInspection """ A cell will be written as a formula if the HTML tag has the attribute "data-excel" set. Note that this function is called when the spreadsheet is being created. The cell it applies to knows ...
d9a41a2906151a050afa78e099278b7d5462faa9
23,098
def select(population, to_retain): """Go through all of the warroirs and check which ones are best fit to breed and move on.""" #This starts off by sorting the population then gets all of the population dived by 2 using floor divison I think #that just makes sure it doesn't output as a pesky decimal. Then i...
4dc1251f09e6bd976d170017bbd328563e9ef786
23,099
import numpy def normal_function( sigma, width ): """ Defaulf fitting function, it returns values from a normal distribution """ log2 = log(2) sigma2 = float(sigma)**2 lo, hi = width, width+1 def normal_func(value, index): return value * exp( -index*index/sigma2 * log2 ) ...
797b4eb00db5a0d4675b547664982f537da9e6ab
23,100
def remove_duplicates(l): """ Remove any duplicates from the original list. Return a list without duplicates. """ new_l = l[:] tmp_l = new_l[:] for e in l: tmp_l.remove(e) if e in tmp_l: new_l.remove(e) return new_l
81132e3b23592589c19ddb11f661e80be6984782
23,102
import functools def in_boudoir(callback): """Décorateur : commande utilisable dans un boudoir uniquement. Lors d'une invocation de la commande décorée hors d'un boudoir (enregistré dans :class:`.bdd.Boudoir`), affiche un message d'erreur. Ce décorateur n'est utilisable que sur une commande définie ...
ed086805f2d865331f559406218f9a9ecd4a7194
23,103
def xyz_to_pix(position, bounds, pixel_size): """Convert from 3D position to pixel location on heightmap.""" u = int(np.round((position[1] - bounds[1, 0]) / pixel_size)) v = int(np.round((position[0] - bounds[0, 0]) / pixel_size)) return (u, v)
d38b45d573a689f72fda4a7ed477be831bea26a8
23,105
import random def get_random_lb(): """ Selects a random location from the load balancers file. Returns: A string specifying a load balancer IP. """ with open(LOAD_BALANCERS_FILE) as lb_file: return random.choice([':'.join([line.strip(), str(PROXY_PORT)]) for line in lb_file]...
2f8620a213bfc87dd3eae662ace409a31597931b
23,106
def enlarge(n): """ Multiplies a number by 100 Param: n (numeric) the number to enlarge Return the enlarged number(numeric) """ return n * 100
6685af169c8e321ceabc0086d1835d459a627a59
23,107
import re def ResolveWikiLinks(html): """Given an html file, convert [[WikiLinks]] into links to the personal wiki: <a href="https://z3.ca/WikiLinks">WikiLinks</a>""" wikilink = re.compile(r'\[\[(?:[^|\]]*\|)?([^\]]+)\]\]') def linkify(match): wiki_root = 'https://z3.ca' wiki_name = match.group(1).rep...
bef3e309aa2489e720a1742e327e9dd4edf6d720
23,108
def handle_new_favorite(query_dict): """Does not handle multi-part data properly. Also, posts don't quite exist as they should.""" for required in POST_REQUIRED_PARAMS: if required not in query_dict: return False # not yet safe to use. post_id = str(string_from_interwe...
7caed7d280870cb7a67b1bfd53200ec3486a4f41
23,109
def steam_ratings(html_text): """Tries to get both 'all' and 'recent' ratings.""" return { "overall": steam_all_app_rating(html_text), "recent": steam_recent_app_rating(html_text), }
71cb3e85e9a1f01e5d4b080372b24c2f848bf7cf
23,110
def separation_cos_angle(lon0, lat0, lon1, lat1): """Evaluate the cosine of the angular separation between two direction vectors.""" return (np.sin(lat1) * np.sin(lat0) + np.cos(lat1) * np.cos(lat0) * np.cos(lon1 - lon0))
a7e1a7ecdfd0ab7f1dc58b99190cc9eeab7fcf20
23,111
def get_band_params(meta, fmt='presto'): """ Returns (fmin, fmax, nchans) given a metadata dictionary loaded from a specific file format. """ if fmt == 'presto': fbot = meta['fbot'] nchans = meta['nchan'] ftop = fbot + nchans * meta['cbw'] fmin = min(fbot, ftop) ...
61e9b0781559de431e5189b89f69a0763b039d8f
23,113
import functools def logging(f): """Decorate a function to log its calls.""" @functools.wraps(f) def decorated(*args, **kwargs): sargs = map(str, args) skwargs = (f'{key}={value}' for key, value in kwargs.items()) print(f'{f.__name__}({", ".join([*sargs, *skwargs])})...') ...
25822434fe331c59ce64b6f9cd5ec89b70b2542a
23,114
def yandex_mean_encoder(columns=None, n_jobs=1, alpha=100, true_label=None): """ Smoothed mean-encoding with custom smoothing strength (alpha) http://learningsys.org/nips17/assets/papers/paper_11.pdf """ buider = partial( build_yandex_mean_encoder, alpha=alpha, ) return Tar...
b38ac44cb2ff12c33f415d716cc4e13006eabf0b
23,115
from typing import Optional import math from typing import Counter def cure_sample_part( X: np.ndarray, k: int, c: int = 3, alpha: float = 0.3, u_min: Optional[int] = None, f: float = 0.3, d: float = 0.02, p: Optional[int] = None, q: Optional[int] = None, n_rep_finalclust: Opti...
b85d2f23bd1b64a0f17abc5178cfc25e442419b5
23,116
from typing import Optional import pickle def deserialize_result(r: bytes, *, deserializer: Optional[Deserializer] = None) -> JobResult: """Given bytes, deserializes them into a JobResult object. :param r: bytes to deserialize. :param deserializer: Optional serializer to use for deserialization. If not ...
049a453a7277f30a38019ca59bedbc458fbaf84c
23,118
def form_symb_dCdU(): """Form a symbolic version of dCdU""" dCdU = form_nd_array("dCdU",[3,3,8*12]) for I in range(3): for J in range(3): for K in range(3,8*12): dCdU[I,J,K] = 0 return dCdU
ec802da453dd7c522bf5725fd70fd16a2406c12e
23,119
import torch def predict(X, y, clf, onehot_encoder, params): """ Runs a forward pass for a SINGLE sample and returns the output prediction. Arguments: X (list[int]) : a list of integers with each integer an input class of step y (list[int]) : a list of integers with each integer an output ...
8e0aa3c687a3ad24e02f730a5dca31f4fd36c6ad
23,120
def parse_modules_and_elabs(raw_netlist, net_manager): """ Parses a raw netlist into its IvlModule and IvlElab objects. Returns a tuple: (modules, elabs) modules is a list of IvlModule objects. elabs is a list of IvlElab objects. """ sections = parse_netlist_to_sections(raw_netlist) mod...
029d5a86de450eb6c104cc2582e21fe854c557e7
23,121
def scrub_dt_dn(dt, dn): """Returns in lowercase and code friendly names of doctype and name for certain types""" ndt, ndn = dt, dn if dt in lower_case_files_for: ndt, ndn = scrub(dt), scrub(dn) return ndt, ndn
853959c073f45be0ffc97dfd8733d2b10a837a32
23,122
def by_uri(uri): """A LicenseSelector-less means of picking a License from a URI.""" if _BY_URI_CACHE.has_key(uri): return _BY_URI_CACHE[uri] for key, selector in cc.license.selectors.SELECTORS.items(): if selector.has_license(uri): license = selector.by_uri(uri) _B...
1dc3dfe4070857984768e1af6462927fd08daf77
23,123
def read_S(nameIMGxml): """ This function extract the images's center from the xml file. Parameters ---------- nameIMGxml : str the name of the file generated by MM3D. Usually, it is "Orientation-Im[n°i].JPG.xml" Returns ------- numpy.ndarray: the center of the IMG ...
f4054827c8ecfa6d81ac752e8ac46e4cccbc5245
23,124
def AddBatchJob(client): """Add a new BatchJob to upload operations to. Args: client: an instantiated AdWordsClient used to retrieve the BatchJob. Returns: The new BatchJob created by the request. """ # Initialize appropriate service. batch_job_service = client.GetService('BatchJobService', versio...
6c48997e4739f05fe6df826654a45b6f7deafc1b
23,125
def bellmanFord(obj,source): """Determination of minimum distance between vertices using Bellman Ford Algorithm.""" validatePositiveWeight(obj) n = CountVertices(obj) minDist = dict() for vertex in obj.vertexList: if vertex == source: minDist[vertex] = 0 else: ...
83cdbab547741a070ef694b4cea8f16355eb4af5
23,126
from typing import Callable import inspect import click def auto_default_option(*param_decls, **attrs) -> Callable[[_C], _C]: """ Attaches an option to the command, with a default value determined from the decorated function's signature. All positional arguments are passed as parameter declarations to :class:`cli...
e1813faf2c0d936333edf4d2a1b111dec6c7a376
23,127
def zCurve(seq): """Return 3-dimensional Z curve corresponding to sequence. zcurve[n] = zcurve[n-1] + zShift[n] """ zcurve = np.zeros((len(seq), 3), dtype=int) zcurve[0] = zShift(seq, 0) for pos in range(1, len(seq)): zcurve[pos] = np.add(zcurve[pos - 1], zShift(seq, pos)) return zc...
4118274fc3bee084777847553dcfa9c4dc92c6c9
23,129
def getgeo(): """ Grabbing and returning the zones """ data = request.args.get('zone_name', None) print data #Check if data is null - get all zones out = [] if data: rec = mongo.db.zones.find({'zone_name':data}) else: rec = mongo.db.zones.find() for r in rec: r.p...
822e8e995ae47d887340a2750eeda5646dfa9d5b
23,130
def photo_upload(request): """AJAX POST for uploading a photo for any given application.""" response = None if request.is_ajax() and request.method == 'POST': form = PhotoForm( data=request.POST, files=request.FILES, use_required_attribute=False, ) if form.is_valid(): ...
e760570d07f43800c05f4d1d8b36b9cb84804003
23,131
def table_str(bq_target): # type: (BigqueryTarget) -> str """Given a BigqueryTarget returns a string table reference.""" t = bq_target.table return "%s.%s.%s" % (t.project_id, t.dataset_id, t.table_id)
95053c839d2bc1e4d628261d669a73a6b9dcb309
23,132
def any_to_any_translate_back(content, from_='zh-CN', to_='en'): """ 中英,英中回译 :param content:str, 4891个字, 用户输入 :param from_: str, original language :param to_: str, target language :return: str, result of translate """ translate_content = any_to_any_translate(content, from_=from_, to...
def5100d73712fd1f244913aca725328cbe02b4d
23,133
def to_short_site_cname(user, site): """ 订阅源显示名称,最多 10 个汉字,支持用户自定义名称 """ if isinstance(site, dict): site_id = site['id'] site_cname = site['cname'] else: site_id = site.id site_cname = site.cname if user: cname = get_user_site_cname(user.oauth_id, site_id...
70b4874af06e4185a72a45ff82838b2d00cdcec6
23,134
def load_roed_data(full_output=False): """ Load master table with all labels """ mtab = load_master_table() df1 = table.Table.read("roed14_stars.fits").to_pandas() def renamer(x): """ match master table Star with Name """ x = x.strip() if x.startswith("BD") or x.startswith("CD"):...
8698b478abb9a3e617ce9a23feb89fecf220e341
23,135
import math def calculate_distance(p1, p2): """ Calculate distance between two points param p1: tuple (x,y) point1 param p2: tuple (x,y) point2 return: distance between two points """ x1, y1 = p1 x2, y2 = p2 d = math.sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)) return d
756b609a91e17299eb879e27e83cd663800e46dd
23,136
def statistics(request, network): """ some nice statistics for the whole pool """ # some basic statistics days = 1 current_height, all_blocks, pool_blocks, pool_blocks_percent, bbp_mined = get_basic_statistics(network, days) miners_count = get_miner_count(network, days) graph_days = 7 t...
d44033323bfe041ee53109a9274ff2fd9c9d9df3
23,137
from textwrap import dedent def package_load_instructions(inst_distributions): """Load instructions, displayed in the package notes""" per_package_inst = '' for dist in inst_distributions: if dist.type == 'zip': per_package_inst += dedent( """ # Loadi...
321a7486f27a3cb327ae7556e317bc53c24726ac
23,138
def specialize_transform(graph, args): """Specialize on provided non-None args. Parameters that are specialized on are removed. """ mng = graph.manager graph = transformable_clone(graph, relation=f'sp') mng.add_graph(graph) for p, arg in zip(graph.parameters, args): if arg is not No...
44b892312ff677bdc5bee84bf5df1e1dc4bd5ba5
23,139
from functools import reduce import operator import itertools def Multiplication(k): """ Generate a function that performs a polynomial multiplication and return coefficients up to degree k """ assert isinstance(k, int) and k > 0 def isum(factors): init = next(factors) return redu...
23a663231e44b09cd446e9ba1d269e7b123efc1d
23,140
def safe_divide(a, b): """ Avoid divide by zero http://stackoverflow.com/questions/26248654/numpy-return-0-with-divide-by-zero """ with np.errstate(divide='ignore', invalid='ignore'): c = np.true_divide(a, b) c[c == np.inf] = 0 c = np.nan_to_num(c) return c
104970a64f5d77f674a46f9da08b039345fa546a
23,141
def read_image(filepath, gray=False): """ read image :param filepath: :param gray: :return: """ if gray: return cv2.cvtColor(cv2.imread(filepath), cv2.COLOR_BGR2GRAY) else: return cv2.cvtColor(cv2.imread(filepath), cv2.COLOR_BGR2RGB)
d5743c8ad517f5c274e3ac64d6082ea36539cfe3
23,143
from ...hubble.helper import parse_hub_uri def mixin_hub_pull_parser(parser): """Add the arguments for hub pull to the parser :param parser: the parser configure """ def hub_uri(uri: str) -> str: parse_hub_uri(uri) return uri parser.add_argument( 'uri', type=hub_...
9f62462baecc744ab7b7e3e78b5446a3d5347569
23,144
from typing import Tuple from typing import List import yaml from typing import Dict def load_config() -> Tuple[List, List]: """Get configuration from config file. Returns repo_paths and bare_repo_dicts. """ if config_file.exists(): with open(config_file, "r") as ymlfile: config =...
e9f483c6cc3ff1335a5d9866cc577e72a9a8084f
23,145
def deindented_source(src): """De-indent source if all lines indented. This is necessary before parsing with ast.parse to avoid "unexpected indent" syntax errors if the function is not module-scope in its original implementation (e.g., staticmethods encapsulated in classes). Parameters -------...
227d5e8e35b251f02ce5e9237f8120d2dd9c7e4b
23,146
def home(): """Render the home page.""" form = SearchForm() search_results = None if form.validate_on_submit(): search_term = form.username.data cur = conn.cursor() cur.execute(f"SELECT * FROM student WHERE name = '{search_term}';") search_results = cur.fetchall() ...
d578e4ba95af57828dfa6f483ad9aa0aeac8ea92
23,147
def capacity(): """ Returns the raw capacity of the filesystem Returns: filesystem capacity (int) """ return hdfs.capacity()
c9e220b19a1a1a200d2393bb98116be1767370b9
23,148
async def deploy(current_user: User = Depends(auth.get_current_user)): """ This function is used to deploy the model of the currently trained chatbot """ response = mongo_processor.deploy_model(bot=current_user.get_bot(), user=current_user.get_user()) return {"message": response}
cb7d53f605616e8a979dd144b786313c99f7a244
23,149
def find_rocks(img,rgb_thresh=(100, 100, 60)): """ Find rock in given image frame""" color_select = np.zeros_like(img[:,:,0]) # Require that each pixel be above all three threshold values in RGB # above_thresh will now contain a boolean array with "True" # where threshold was met above_thresh = ...
f0bffadfdf826f1f649029f3aaf224d07681589e
23,150
from pathlib import Path def maybe_start_with_home_prefix(p: Path) -> Path: """ If the input path starts with the home directory path string, then return a path that starts with the home directory and points to the same location. Otherwise, return the path unchanged. """ try: return Pa...
6ee4e49e8dfb9bc68a1c10f5ea792715fb5d5336
23,151
def parse_nrc_lexicon(): """Extract National Resource Council Canada emotion lexicon from http://saifmohammad.com/WebPages/lexicons.html Returns: {str: [str]} A defaultdict of emotion to list of associated words """ emotion2words = defaultdict(list) with open(NRC_LEXICON) as lexicon_file: ...
869988934a7ab6a1b0b601f96472ff85a2686975
23,152
def rouge_2_fscore(predictions, labels, **unused_kwargs): """ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor,...
1c0ab9b514c36cf9947b31624e8a2cf308cdfe6b
23,153
def enhancedFeatureExtractorDigit(datum): """ Your feature extraction playground. You should return a util.Counter() of features for this datum (datum is of type samples.Datum). ## DESCRIBE YOUR ENHANCED FEATURES HERE... ## """ features = basicFeatureExtractorDigit(datum) "*** YOUR CODE HERE ***"...
564e324cd12b2cb98bd65cb053b5acea2f4d5831
23,155
def tested_function(x): """ Testovana funkce Da se sem napsat vselijaka cunarna """ freq = 1 damp_fac = 0.1 val = np.sin(freq * x) damp = np.exp(-1 * damp_fac * abs(x)) return val * damp
95808b55ace5b0536104f02de874344aa02d7033
23,157
def parse_line(line): """ Parses a (non-comment) line of a GFF3 file. The attribute field is parsed into a dict. :param line: line to parse as string :return: dict with for each column (key) the corresponding value """ parts = line.strip().split('\t') output = {} if len(parts) != len(...
0ea071c5a4165fd2bbbe77798bec09b033250c72
23,158
import requests from datetime import datetime def get_time_string(place: str = "Europe/Moscow"): """ Get time data from worldtimeapi.org and return simple string Parameters ---------- place : str Location, i.e. 'Europe/Moscow'. Returns ------- string Time in format '%...
f15ef5a843317c55d3c60bf2ee8c029258e1cd78
23,159
from typing import Type from typing import Dict from typing import Callable def new_worker_qthread( Worker: Type[WorkerProtocol], *args, _start_thread: bool = False, _connect: Dict[str, Callable] = None, **kwargs, ): """This is a convenience function to start a worker in a Qthread. In mos...
f607799bd7abf4b275d90bc4523dc9f0e8d2d200
23,160
import fnmatch def contains(filename, value=None, fnvalue=None): """ If a string is contained within a yaml (and is not a comment or key), return where we found it """ if filename in ALL_STRINGS: for el in ALL_STRINGS[filename]: if (value and value in el[0]) or (fnvalue and fnmatch.fnmatch...
2c21aee4fe7121ad26e588b33dfa2f09f1d4066b
23,161
def plot_with_overview( ds, tn, forcing_vars=["dqdt_adv", "dtdt_adv"], domain_var="q", overview_window_width=4, ): """ Produce a forcing plot with timestep `tn` highlighted together with overview plots of domain data variable `domain_var`. The width over the overview plot is set with...
e02be6157853b5a0a409fe45a02f52d685913e22
23,162
def optimize(nn_last_layer, correct_label, learning_rate, num_classes): """ Build the TensorFLow loss and optimizer operations. :param nn_last_layer: TF Tensor of the last layer in the neural network :param correct_label: TF Placeholder for the correct label image :param learning_rate: TF Placeholde...
b618626f7e458e1ef3ffda74af7532d93668a9cb
23,163
def expanded_indexer(key, ndim): """Given a key for indexing an ndarray, return an equivalent key which is a tuple with length equal to the number of dimensions. The expansion is done by replacing all `Ellipsis` items with the right number of full slices and then padding the key with full slices so tha...
a4fa3b1e4a106350348c128ef5ce8b86dac1f0c0
23,164
def downsample( data, sampling_freq=None, target=None, target_type="samples", method="mean" ): """Downsample pandas to a new target frequency or number of samples using averaging. Args: data: (pd.DataFrame, pd.Series) data to downsample sampling_freq: (float) Sampling frequency of data...
4dca048a77ac1f20d0ee1bac702c48e4311f8900
23,165
def available_commands(mod, ending="_command"): """Just returns the available commands, rather than the whole long list.""" commands = [] for key in mod.__dict__: if key.endswith(ending): commands.append(key.split(ending)[0]) return commands
38a96ca9485e9814ba161550613d3d96db126693
23,166
def retrieve_browse(browse_location, config): """ Retrieve browse image and get the local path to it. If location is a URL perform download. """ # if file_name is a URL download browse first and store it locally validate = URLValidator() try: validate(browse_location) input_filen...
6c5b5e916542db20584205588e5e2929df692b38
23,167
def add_suffix(input_dict, suffix): """Add suffix to dict keys.""" return dict((k + suffix, v) for k,v in input_dict.items())
7dbedd523d24bfdf194c999b8927a27b110aad3e
23,168
from autots.tools.transform import GeneralTransformer from autots.tools.transform import simple_context_slicer from datetime import datetime def ModelPrediction( df_train, forecast_length: int, transformation_dict: dict, model_str: str, parameter_dict: dict, frequency: str = 'infer', predi...
afb3dccc20c2399a50c2564aeb0d1f214d80dd6a
23,169
def make_year_key(year): """A key generator for sorting years.""" if year is None: return (LATEST_YEAR, 12) year = str(year) if len(year) == 4: return (int(year), 12) if len(year) == 6: return (int(year[:4]), int(year[4:])) raise ValueError('invalid year %s' % year)
ced5617772af14a3e438cb268f58ceee3895083d
23,170
def set_stereo_from_geometry(gra, geo, geo_idx_dct=None): """ set graph stereo from a geometry (coordinate distances need not match connectivity -- what matters is the relative positions at stereo sites) """ gra = without_stereo_parities(gra) last_gra = None atm_keys = sorted(atom_keys(gra...
d26248883b90a561c8d70bb8a12be68affe40c2a
23,171
def multiply_MPOs(op0, op1): """Multiply two MPOs (composition along physical dimension).""" # number of lattice sites must agree assert op0.nsites == op1.nsites L = op0.nsites # physical quantum numbers must agree assert np.array_equal(op0.qd, op1.qd) # initialize with dummy tensors and bo...
62e9e250c46d281ccbb39c0ddf1082d45386a1d3
23,172
import json from typing import OrderedDict def build_list_of_dicts(val): """ Converts a value that can be presented as a list of dict. In case top level item is not a list, it is wrapped with a list Valid values examples: - Valid dict: {"k": "v", "k2","v2"} - List of dict: [{"k": "v"...
dfd92f619ff1ec3ca5cab737c74af45c86a263e0
23,173
def add_borders_to_DataArray_U_points(da_u, da_v): """ A routine that adds a column to the "right" of the 'u' point DataArray da_u so that every tracer point in the tile will have a 'u' point to the "west" and "east" After appending the border the length of da_u in x will be +1 (one new colu...
e9b3e057fb56a998821e84a96b77e00bac4e0923
23,174
def arg(prevs, newarg): """ Joins arguments to list """ retval = prevs if not isinstance(retval, list): retval = [retval] return retval + [newarg]
8d591595add095542ad697b4bd54642a4a14a17c
23,175
def quote_plus(s, safe='', encoding=None, errors=None): """Quote the query fragment of a URL; replacing ' ' with '+'""" if ' ' in s: s = quote(s, safe + ' ', encoding, errors) return s.replace(' ', '+') return quote(s, safe, encoding, errors)
e0a5ba9237550856b695e236e7a457c34f053ba0
23,176
def mod(x, y): """Implement `mod`.""" return x % y
f19c019ed3cf072b1b5d3ec851c14a824c14edb5
23,177
from typing import List def _lower_batch_matmul(op: relay.Call, inputs: List[te.Tensor]) -> te.Tensor: """Lower a batch_matmul using cuBLAS.""" return cublas.batch_matmul( inputs[0], inputs[1], transa=op.attrs["transpose_a"], transb=op.attrs["transpose_b"], dtype=op.che...
2fa7be16c558e0edf9233d699139c004b44a93c2
23,178
from re import S def cross_entropy_loss(inputs, labels, rescale_loss=1): """ cross entropy loss with a mask """ criterion = mx.gluon.loss.SoftmaxCrossEntropyLoss(weight=rescale_loss) loss = criterion(inputs, labels) mask = S.var('mask') loss = loss * S.reshape(mask, shape=(-1,)) return S.make_...
7151ace5b1ac93439defe93a4d6e45002cbfb8a6
23,179
def as_wrapping_formatters(objs, fields, field_labels, formatters, no_wrap=None, no_wrap_fields=[]): """This function is the entry point for building the "best guess" word wrapping formatters. A best guess formatter guesses what the best columns widths should be for the table celldata. It does this ...
1f60c9ebaebb919ab8d4478e029aed649931df8a
23,180
import torch def classification_metrics(n_classes: int = 2): """Function to set up the classification metrics""" logger.info(f"Setting up metrics for: {n_classes}") metrics_dict_train = torch.nn.ModuleDict( { "accuracy": Accuracy(), "recall": Recall(), "precisio...
b876c7ac3da006cf54bc04e91f13de5a35103dab
23,181
def ping(device, address, ttl=None, timeout=None, tos=None, dscp=None, size=None, count=None, source=None, rapid=False, do_not_fragment=False, validate=False, vrf=None, command=None, output=None...
1e13d1af7e9678bc8650bc3173858b148fbedc86
23,182
import numpy import scipy def _subSquare(vectors, var, full=False): """ given a series of vectors, this function calculates: (variances,vectors)=numpy.linalg.eigh(vectors.H*vectors) it's a seperate function because if there are less vectors than dimensions the process can be accelerated, it j...
8f588d3f64eaf892a1481983436c13d7c5010f12
23,184
def to_pickle(data): """ This prepares data on arbitrary form to be pickled. It handles any nested structure and returns data on a form that is safe to pickle (including having converted any database models to their internal representation). We also convert any Saver*-type objects back to their norm...
e52dddec911b0ac548daed81452d041aee41f548
23,185
import requests def spot_silver_benchmark_sge() -> pd.DataFrame: """ 上海黄金交易所-数据资讯-上海银基准价-历史数据 https://www.sge.com.cn/sjzx/mrhq :return: 历史数据 :rtype: pandas.DataFrame """ url = "https://www.sge.com.cn/graph/DayilyShsilverJzj" payload = {} r = requests.post(url, data=payload) dat...
8bfcc5d24116231835a41447fb284f346586628e
23,186
def requires_all_permissions(permission, login_url=None, raise_exception=False): """ Decorator for views that defines what permissions are required, and also adds the required permissions as a property to that view function. The permissions added to the view function can then be used by the sidebar ...
e2368c7f32185ebe1ee7cec50625a72b0fe9ec03
23,187
def hasTable(cur, table): """checks to make sure this sql database has a specific table""" cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='table_name'") rows = cur.fetchall() if table in rows: return True else: return False
dfdb3db0901832330083da8b645ae90e28cfb26d
23,188
def _check_wkt_load(x): """Check if an object is a loaded polygon or not. If not, load it.""" if isinstance(x, str): try: x = loads(x) except WKTReadingError: warn('{} is not a WKT-formatted string.'.format(x)) return x
457a02cffa7f56e05ad7ca3a8df83f5f719346b7
23,189
def _yielddefer(function, *args, **kwargs): """ Called if a function decorated with :func:`yieldefer` is invoked. """ try: retval = function(*args, **kwargs) except: return defer.fail() if isinstance(retval, defer.Deferred): return retval if not (hasattr(ret...
b226984e1b4845783dc47f187d24482e040cc6c0
23,190
import scipy import warnings def dimension_parameters(time_series, nr_steps=100, literature_value=None, plot=False, r_minmin=None, r_maxmax=None, shortness_weight=0.5, literature_weight=1.): """ Estimates parameters r_min and r_max for calculation of correlation ...
abec1b064b42083b9e60bb2cb4827d7fe8f7b2e9
23,191
def seir_model_with_soc_dist(init_vals, params, t): """ SEIR infection model with social distancing. rho = social distancing factor. """ S_0, E_0, I_0, R_0 = init_vals S, E, I, R = [S_0], [E_0], [I_0], [R_0] alpha, beta, gamma, rho = params dt = t[1] - t[0] for _ in t[1:]: ...
dae5ace760055f5bbb78f079b660e8d55587b2fe
23,193
import torch def greeq(data, transmit=None, receive=None, opt=None, **kwopt): """Fit a non-linear relaxometry model to multi-echo Gradient-Echo data. Parameters ---------- data : sequence[GradientEchoMulti] Observed GRE data. transmit : sequence[PrecomputedFieldMap], optional Map(...
4190b82de68f6362bf6cec48e4e88419bab7b0da
23,194