content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def vgg_19(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_19'): """Oxford Net VGG 19-Layers version E Example. Note: All the fully_connected layers have been transformed to conv2d layers. To use in c...
042b1f4fcb58fe64d6dd4915959e2bb53ddf72a5
53,321
import requests def get_metadata_param(param_name): """Fetch value of metadata parameter. Args: param_name: str. Name of the parameter to be fetched. """ # Send a request to get param details. resp = requests.get( '%s/%s' % (METADATA_ATTRIBUTES_URL, param_name), headers=M...
e49e4da99d87f9261a016767ad870da13be93b18
53,322
def trace_size_converter(value, params, key): """ Converts trace size from seconds to samples """ params = params[key] if value is None: return None if not value: return value if not params['frequency']: raise AttributeError('No frequency specified for trace-size argu...
87ec3707b36ee76bed365c4a91d4af829161b4b5
53,323
def get_instances_for_module(app, module, additional_xpaths=None): """ This method is used by CloudCare when filtering cases. """ modules = list(app.get_modules()) helper = DetailsHelper(app, modules) details = DetailContributor(None, app, modules).get_section_elements() detail_mapping = {de...
24558c6f22393948c7dbe5019652eab34fc9a3d9
53,324
def base_10_to_alphabet(number): """Convert a decimal number to its base alphabet representation""" return "".join(chr(A_UPPERCASE + part) for part in _decompose(number))[::-1]
3ffae0a103390c1e94ca2a40787f9a9167e39d0a
53,325
def plausibly_scopes(m: mrs.MRS) -> bool: """ Quickly test if MRS *m* can plausibly resolve a scopal reading. This tests a number of things: - Is the MRS's top qeq to a label - Do any EPs scope over themselves - Do multiple EPs use the handle constraint - Is the lo handle o...
de4a4df640a7073f95f38d22b4c2b9a1979cd5a4
53,327
def decode_chrome_leveldb_bytes(value): """ decode the encoded localstorage values from the leveldb file """ if value[0] == 0: return value[1:].decode('utf-16le') elif value[0] == 1: return value[1:].decode('utf-8') else: msg = "Unable to process Chrome LevelDB bytes in u...
e200c3da3a2f75c215fa13fc12eb12f1034b3e14
53,328
def generate_password() : """ Generate random characters to form the password. """ charSets = [ 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789', '^!\$%&/()=?{[]}+~#-_.:,;<>|\\', ] length = user_input() pwd = [] charset = cho...
12490971aba15afa8e738d47b13d251f386b869b
53,329
def generate_output_paths( output_dir: str, file_name: str, subset_name: str, extension: str ) -> list: """ Generate output paths for results files based on the given output directory, file name, subset name, and extension. :param output_dir: Output directory to which results should be output :para...
46ede2cbaa294326f6553115e883828462421dbb
53,330
def tau_screened_coulomb(energy: np.ndarray, mass_c: np.ndarray, screen_len: np.ndarray, n_imp: np.ndarray, dielectric: float) -> np.ndarray: """ Electron-ion scattering rate — Brook-Herring model Note that for highly doped semiconductors, screen length plays a significant role, ...
5ed656b4271215ef6bf5ccb154897c8fb321eebe
53,332
def primary_fuel_ferc1(fuel_df, fuel_thresh=0.5): """ Determine the primary fuel for plants listed in the PUDL fuel_ferc1 table. Given a selection of records from the PUDL fuel_ferc1 table, determine the primary fuel type for each plant (as identified by a unique combination of report_year, respond...
153a91495cfd180f9556d7cb154e761496e48e88
53,334
def simulate_SPRT_fixedtime(sigma, stop_time, true_dist=1): """ Simulate a Sequential Probability Ratio Test with fixed time stopping rule. Two observation models are 1D Gaussian distributions N(1,sigma^2) and N(-1,sigma^2). Args: sigma (float): standard deviation stop_time (int): numb...
4c63d8ee6c426ed67ca7430bdf994c37fe99bf2a
53,335
import requests import logging def get_url_descriptor(url): """ Returns an url descriptor or None on failure """ try: resp = requests.get(url) except requests.exceptions.ConnectionError: logging.error("Error connecting to {}".format(url)) return None if resp.ok: ...
8e09711e08200980c1778fd47673dcaaba67c47b
53,336
import scipy def butter_lowpass(cutoff, freq, order=5): """Butterworth lowpass filter""" nyq = 0.5 * freq normal_cutoff = cutoff / nyq numerator, denominator = scipy.signal.butter(order, normal_cutoff, btype='low', analog=False) return numerator, denominator
3fdee3e8673d87724ad8e594c93f728b422634db
53,337
def year_isnt_int(YEARS): """A funciton to test if years are integers""" return any(type(x) != int for x in YEARS)
d23d093f4655846d07228019b4110e2ef3180c69
53,338
def similarity_matrix(DAG, similarity="intersection", neighbours="successors"): """ Function to produce a similarity matrix based on neighbourhoods of nodes in DAG. Input ----- DAG - networkx directed acyclic graph similarity - type of similarity of sets. Currently only implemented for the size...
e1fb1649465173f0753332bdde49440f306e1c3e
53,339
import logging def open_mail(email: str): """Open up draft email tab in your default browser Args: email (str): email of the person Returns: bool, str: method status, empty string """ url_mail_people = f"mailto:{email}" command_success = True try: open_browser(ur...
e144751d73a3063743c94cb50b2dedca1bb54fee
53,341
import pandas def offset_to_timedelta(offset): """ Convert a pandas-compatible offset (e.g. '3H') to a Timedelta object. """ return pd.to_timedelta(pandas.tseries.frequencies.to_offset(offset))
be470852c5109ede67b2d494456fb4b1447fc2ca
53,342
import json def isJsonDict(s): """ Take a string and determine if valid JSON. """ try: data = json.loads(s) return type(data) == dict except ValueError: return False
222841fc39f78a45f0c682a83282e714a26dc0ed
53,344
from numpy import eye, hstack, ones, vstack, zeros def solve_safer_qp(P, q, G, h, sw, reg=1e-8, solver='mosek', initvals=None, sym_proj=False): """ Solve the Quadratic Program defined as: .. math:: \\begin{split}\\begin{array}{ll} \\mbox{minimize} & ...
add54dc8ea7b9c00bc25d3a57c0fbe78ea8fea0d
53,345
def get_config_constant_file(): """Contiene la obtencion del objeto config para setear datos de constantes en archivo configurador :rtype: object """ # TEST _constants_file = "constants/constants.yml" # PROD # _constants_file = "constants/constants.yml" cfg = Const...
797a0861e8e37f602dc316fe70e1c915614ff22b
53,346
def weighted_rmsd(x, y, dim=None, weights=None): """ Compute weighted root mean square deviation between two xarray DataArrays Parameters ---------- x, y : xarray.DataArray xarray DataArray for which to compute `weighted_rmsd`. dim : str or sequence of str, optional Dimension(s) ove...
a4de28d80ff40809eed130e3db5514cdf9724f5b
53,348
def pretty_color_palette(identifiers, keep_zero_black=True): """Return dictionary with pretty colors. :param identifiers: set of unique identifiers :param keep_zero_black: whether or not the background should be black :returns: dictionary """ color_dict = {} for i in identifiers: i...
ba258fe85da7d3516fc2045fffbc1d7b6876b376
53,349
def get_second_derivative_matrix(n): """ :param n: The size of the time series :return: A matrix D such that if x.size == (n,1), D * x is the second derivate of x """ m = n - 2 D = spmatrix(list(chain(*[[1, -2, 1]] * m)), list(chain(*[[i] * 3 for i in range(m)])), ...
e2346da97a073f11eab223097122d939f6813ec3
53,350
def LastIndexOf(s, substr): """Retrieve the last index of substring within a string""" ctx = None ctx = _get_ctx2(s, substr, ctx) s = _coerce_seq(s, ctx) substr = _coerce_seq(substr, ctx) return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
d560662ba3faffe44dc7fd04e5c4f783b1f2b142
53,351
from ..latent_features import LOSS_REGISTRY, REGULARIZER_REGISTRY, MODEL_REGISTRY, \ def _remove_unused_params(params): """ Removed unused parameters considering the registries. For example, if the regularization is None, there is no need for the regularization parameter lambda. Parameters -----...
a8560054bd005d1bad64ccdced99418b8d5f9931
53,352
def multi_batch_apply(f, num_batch_dims, *args, **kwargs): """Vectorized application of f on tensors with multiple batch dims. Batch dims must be the same for every tensor in args/kwargs. Args: f: Callable, needs only expect one batch dim in input tensors. num_batch_dims: Integer, the number of batch di...
da5ea73c688722e562fe0328bd4fdd351b8bafc9
53,353
import torch def get_similar_comments(embedder, dataset, corpus, sarcasm_embeddings, query, n): """ Returns the most similar comments in terms of cosine similarity of their respective embeddings Parameters: embedder (SentenceTransformer): chosen model from HuggingFace dataset (DataFrame): com...
63de8e5c5f4b0476437c68b48f30a14a28cfe452
53,354
def build_pr_review_line_comment(context, violation): """ Creates a Markdown representation of the comment to be posted to a pull request. :return: The comment """ template = env.get_template("pr_review_line_comment.txt") return template.render( violation=violation, context=context, LINT...
51f08b39077a4d97cf87a71f4e6c43802b9165eb
53,355
def fetch(table, cols="*", where=(), group=(), order=(), limit=(), **kwargs): """ Convenience wrapper for database SELECT and fetch one. Keyword arguments are added to WHERE. """ return init().fetch(table, cols, where, group, order, limit, **kwargs)
e9e3634bc71548a006f14add0a7ed3b308db9a4d
53,356
def gradient_descent(optfun, x0, iterations=100, tolerance=1e-5): """ Given an OptFunction `optfun` and a starting point `x0`, and given parameters `iterations` and `tolerance`, perform the gradient descent algorithm using backtracking line search to minimize `optfun`. This implementation should re...
45b83b31f287b2d2bf97d98a1d1f7b426607d592
53,357
from typing import Optional from typing import Set def list_files( *, storage_bucket_name: str, prefix: Optional[str] = None, ) -> Set[Blob]: """List all files in a given storage bucket.""" client = get_client() return set(client.list_blobs(storage_bucket_name, prefix=prefix))
9b1f8f6b0a3fcb5950f9f758dff7e43b22b6d590
53,358
def position_list_view(request): """ We actually don't want to see PositionForFriends entries in this view :param request: :return: """ # admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'partner_organization', 'verified_vol...
326bf422889dab0f2864bbbeaf13109d36d01753
53,359
def _transparent_cmap(cmap, n=255): """transparent heat map color map""" mycmap = cmap mycmap._init() mycmap._lut[:, -1] = np.linspace(0, 0.8, n + 4) return mycmap
90f5ec501f3b3aa9359f4b459d4c0cb533d8e9bd
53,360
import requests from bs4 import BeautifulSoup import re def scrape(): """Scrape the UD project page for metadata of the treebanks. """ session = requests.Session() retry = Retry(connect=3, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount("http://", adapter) sessio...
655a7613d97fd9a52b264efc120548a96be0a7be
53,362
from typing import List from typing import Dict def getProjectsPayload(user_id) -> List[Dict]: """ Returns a list of project information accessible to a given user. :return: list of objects containing project information """ global loadedProjects return [{ 'id': p.id, 'name': p...
f4c6bad5ac647125dba085c39c10b7eaecefa274
53,363
def QuantileMerge(feature, nan = -1, n_bins = None, q = None ,min_samples = 1): """Merge by quantile Args: feature (array-like) nan (number): value will be used to fill nan n_bins (int): n groups that will be merged into q (array-like): list of percentage split points Retur...
bab4cd0869df16c075181336dfe9b75851ced8a2
53,364
from datetime import datetime def blog(): """ The blog section will show the user an infinite cascade of blog posts that will load based on the user scroll. """ return dict( title="Blog", year=datetime.now().year )
51a6447ef8081cf8053afbbacfcd145efefca5e4
53,365
def getMediaTime(sourceName: str): """ Get the current timestamp of media in milliseconds. Supports ffmpeg and vlc media sources (as of OBS v25.0.8) :param sourceName: String - Source name. """ return __createJSON("GetMediaTime", {'sourceName': sourceName})
b28f4ce8c9c696b81fecabc7f927ed4ed6148146
53,367
import random def randbetween(ctx, bottom, top): """ Returns a random integer number between the numbers you specify """ bottom = conversions.to_integer(bottom, ctx) top = conversions.to_integer(top, ctx) return random.randint(bottom, top)
c4e5bf97ee98454aa2802826773f1431800c3f68
53,368
import json def read_dependencies(file_path): """Reads a json file and creates an iterable of unique dependencies. Args: file_path: The path to the runtime dependencies file. Returns: An iterable with unique dependencies. """ deps = None with open(file_path) as deps_file: deps = json.load(de...
52756a443b3a7b0ee6ed1a932b3d1b7984fe4189
53,369
from datetime import datetime def is_inactive( person_data: dict, keyword: str = COMPANIES_HOUSE_RESIGNATION_KEYWORD, date_format: str = COMPANIES_HOUSE_DATE_FORMAT, ) -> bool: """Tests whether board members (default) or controllers are inactive.""" return ( keyword in person_data ...
b2037de136debeca92d7024fd1319ca2d5709bed
53,370
def get_day_menu(which, url): """Parses the day menu from the given url.""" # Assumptions: # - The #content-core contains only <li> items belonging to the menu and <h3> elements that indicate a type. # - All menu items have a price, except vegetables. # - Priced items are of the form "NAME - € X,XX"...
d1f3cc3135e45c3811e8cf1f5f20faa48920dae5
53,371
def _create_heatmap(image_shape, heatmap_shape, annotation_points, kernel): """ Creates density map. annotation_points : ndarray Nx2, annotation_points[:, 0] -> x coordinate annotation_points[:, 1] -> y coordinate """ assert (kernel....
2887102ebb9733d7698fa415f96eedae4c2bb59e
53,372
import random def LabelList(ratio=1, root='~/.mxnet/datasets', name='market1501'): """Load the Label List for Market 1501 dataset. Parameters ---------- ratio : float, default 1 Split label into train and test. root : str, default '~/.mxnet/datasets' Path to the folder stored the ...
382008e530980c279b67e9ad98bb5b6588d1c366
53,373
def get_tags_by_month_for_users(data , usernames): """ initialize list of months and sets for each list of data in data slice out twitter information if username in username list for each tag in hashtags in tweet add hashtag to set in data list :param data - l...
ca2fbfb2137b47fe23c7d113f002e528cb55b3ae
53,374
def customer_edit(request, cid): """ 新增客户 :return: """ obj = models.Customer.objects.get(id=cid) if request.method == 'GET': form = CustomerForm(instance=obj) return render(request, 'customer_add.html', {'form': form}) form = CustomerForm(data=request.POST, instance=obj) ...
bdd4013fae723fc0839451f61d4bf547a65c83ae
53,375
def dynamic_pricing(tfr_dfs): """ Transform the EIA 861 Dynamic Pricing table. Args: tfr_dfs (dict): A dictionary of transformed EIA 861 DataFrames, keyed by table name. It will be mutated by this function. Returns: dict: A dictionary of transformed EIA 861 dataframes, keye...
3898ddbc8cbb1714524bf1f2d5e6307e49fb964c
53,376
def get_annotation(annotation_file, annotation_name, sampling_freq=64): """ Extract annotation from an EDF file annotation_file : EDF handle annotation_name :(str) name of the annoation to get sampling_freq : (int) sampling freq to use to build the event binary representation """ annotation...
b8a75ea245434314162d60fb9a0a471c5bfe4f4e
53,377
def set_header_path(*args): """ set_header_path(path, add) -> bool Set or append a header path. IDA looks for the include files in the appended header paths, then in the ida executable directory. @param path: list of directories to add (separated by ';') may be NULL, in this case nothing i...
7e21d368728720e1150821bbc2895dc9896df72e
53,379
import random def randomString(stringLength=10): """Generate a random string of fixed length """ letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!" return ''.join(random.choice(letters) for i in range(stringLength))
778b7ac606286877eb9f8757d2ad4138bbf1a87e
53,380
def color_balance (input: Tensor, weight: Tensor) -> Tensor: """ Apply color balance adjustment (temperature and tint) on an RGB image. Parameters: input (Tensor): Input RGB image with shape (N,3,H,W) in range [-1., 1.]. weight (Tensor): Scalar weight with shape (N,2) in range [-1., 1.]. ...
98023baa37e84f56d066bcb0fc0973567f2fa0b1
53,381
import json def sort_num(request): """ Sort some numbers from Request """ num_str = request.GET["numbers"] num_lst = [int(n) for n in num_str.split(",")] data = { "num": sorted(num_lst), "status": "ok", "msg": "Integer soarted Succesfully!" } return HttpResponse(json.du...
e39e69403e419e6f98dd182179e7b01f6f5d8edf
53,382
from typing import Dict from typing import Any async def async_setup(hass: HomeAssistant, config: Dict[str, Any]): """Import integration from config.""" if DOMAIN in config: for entry in config[DOMAIN]: hass.async_create_task( hass.config_entries.flow.async_init( ...
c7c4269577b7ab9c9169bbb0ec390bc21e2ae948
53,384
def get_cephfs_data_pool_name(): """ Fetches ceph fs datapool name from Ceph Returns: str: fs datapool name """ ct_pod = pod.get_ceph_tools_pod() out = ct_pod.exec_ceph_cmd('ceph fs ls') return out[0]['data_pools'][0]
5344974df8cb23c45bd9696abef6f5c7ae3f19e0
53,385
def no_identical_digits_in_same_block(): """Returns a list of clauses, stating that if a digit appears in a cell, the same digit cannot appear elsewhere in the same row, column, or 3x3 square.""" bigi = 0 bigj = 0 list = [] for big in range(9):# The 9 big boxes if (bigj > 2): ...
16a47e272e256bc0b0eac20d301d8271e4421e28
53,386
def xgb_average_recalln_curve_score(n): """evaluate average recall-n curve score for xgb""" def feval(preds, labels): labels = labels.get_label() trials = np.argsort(preds)[::-1] ranks = get_rank(labels[trials]) curve = recall_curve(ranks) return "a-recall@%d" % n, np.su...
111de0aa1e50f1b46a4d05cfde9e69271010dd3a
53,387
def view_organization(organization_id): """ Function enables user to view an Organization from the database. """ try: organization_id = int(organization_id) if not organization_controller.query_organization(organization_id): return jsonify({ 'message': 'Organi...
625621e3bd881cdac7408291490bfc6db2ab6494
53,388
def get_face_rectangles(azure_response): """ Returns the rectangles corresponding to the faces detected by Azure :param azure_response: Response from Azure Face request as dictionary. :return: The rectangles of any detected face with the format: (width, height, left, top) """ result = [] for...
d07e40f1b4c648c52ea660179f8d8c1f4957f0db
53,389
import math def SchaffersF7(arr: np.ndarray, seed: int = 0) -> float: """Implementation for BBOB Weierstrass function.""" dim = len(arr) arr.shape = (dim, 1) if dim == 1: return 0.0 z = np.matmul(_R(dim, seed, b"R"), arr) z = Tasy(z, 0.5) z = np.matmul(_R(dim, seed, b"Q"), z) z = np.matmul(LambdaA...
997c6d34e3dafb1151399d03f8aee59469761785
53,390
def retr_spacegroup_number(xtalstr,ini0): """ Retrieve the space group number. When choosing real space grids some space groups imply restrictions on the number of points along the different lattice vectors. To impose the correct restrictions we need to know the space group number of the curren...
f86827aa089b79c054fe8c4d78c5a6da48f0463e
53,391
def GetLocationFlag(): """Anthos location flag.""" return base.Argument( '--location', required=False, help='Specifies the Google Cloud location to use. If not' 'specified will use the current compute/zone property.')
db4754bbb31429e2e743d48eabffcff60d68076a
53,392
def get_user_credentials(env_ctx, upgrades): """ Prompt for snaplogic user credentials. If upgrades required then ask for admin user. """ credentials = None print "" user = 'admin' password = input_value("Please specify the SnapLogic admin Password:", "", False, True) env_ctx['SNAPLOGIC_...
d693c4001688166095a6531e96bf6ec3418ef5f8
53,393
def rmse(y_true, y_pred): """ Calculates the RMSE value for forecast Values Args: y_true: True time series type: np.array y_pred: Predicted time series type: np.array Return: score: RMSE value for forecast values ...
f7702f3638482fcb8a2d638f942ab12d244e105d
53,394
def build_yolo_augmentation(cfg, is_train): """ Train Augmentations: - YOLOFJitterCrop - YOLOFResize - YOLOFRandomDistortion - RandomFlip Test: - YOLOFResize """ augmentation = [] if is_train: if cfg.INPUT.JITTER_CROP.ENABLED: augmentat...
b8ef6bbd4068131d37d736d065b94d2c2a5b68b9
53,395
def get_mean_expression(fnames, name, sep="\t", gene_set=[]): """Get mean expression for replicates of one time point.""" dfs = [get_expression(fname, sep=sep, gene_set=gene_set) for fname in fnames] joined = pd.concat(dfs, axis=1, join="inner") return joined.mean(axis=1).rename(name)
2ead6d81fa378b091dbb96aeffec769856ee8146
53,396
def find_random_monster(min_cr=None, max_cr=None, environment=None): """ Find a random monster """ filters = [ {'$sample': {'size': 1}} ] if min_cr: query = {'$match': {'challenge_rating': {"$gte": float(min_cr)}}} filters.insert(0, query) if max_cr: query ...
a1a9560cc3702c867bffb19e662079b2a795ec08
53,397
import re def make_vowelify(words): """Chop off consonant ala nautica if second to last letter is a vowel.""" new_arr = [] for word in words: if re.search(_regexes['all_vowels'], word[:-2]): new_arr.append(word[:-1]) return new_arr
4d674bd9b031720768d6109a3ca8f864a6d7788b
53,398
def sketch_by_name(sketches: adsk.fusion.Sketches, name: str) -> adsk.fusion.Sketch: """ Finds a sketch by name in a list of sketches Useful for parsing a collection of sketches such as DXF import results. :param sketches: A list of sketches. :type sketches: adsk.fusion.Sketches :param name: Th...
1051785c48aaad0833c7786d5a9152c716e18cd2
53,399
def LoadFinalCircuit(Parasitics=False,LoopgainMag=True,LoopgainPhs=True): """ Returns the Loop Gain symbolic analysis estimation of the final circuit Select Parasitcs=True for symbolic estimations considering the parasitics after extraction in Cadence. """ #Frequency limits to be plot f_check_...
95108e0219381c396e10602bcb467c6ff758ca4f
53,400
def get_conformer(species, name): """ Generate a conformer of a species given a new name but with the same atoms Arguments: species (autode.species.Species): name (str): Returns: (autode.conformers.Conformer): Conformer """ conformer = Conformer(name=name, atoms=spe...
25d071d3a48942856edcb7f5156a2b85b1fe8cd4
53,401
import requests import json def _get_stream_with_params_and_return_list_of_ads(filter_params): """ This function handles: http GET request check that no http error is returned converting the bytestring in the response to a list of ads """ response = requests.get(url_for_stream,...
3d3c5db65efc05270e3ea24bdac354baa3c80f6d
53,403
import requests import numpy as np from requests.exceptions import ReadTimeout def post_nadlan_sviva_rest(body, only_neighborhoods=True, subject=None, add_coords=True): """take body from request and post to nadlan.gov.il deals REST API, Sviva=other parameters, demographics, etc, ...
c659b5ac32b6b5317d614460def207fe9fc20820
53,405
def make_export(objects, exportable_objects=None): """Make export""" query_helper = QueryHelper(objects) ids_by_type = query_helper.get_ids() converter = ExportConverter( ids_by_type=ids_by_type, exportable_queries=exportable_objects, ) csv_data = converter.export_csv_data() object_names = "_"...
4fdaa37b84371cc6926dcb4eb5a5880e1bb53990
53,406
from operator import ne def grad(fld, bnd=True): """2nd order centeral diff, 1st order @ boundaries if bnd""" # vx, vy, vz = fld.component_views() if bnd: fld = viscid.extend_boundaries(fld, order=0, crd_order=0) if fld.iscentered("Cell"): crdx, crdy, crdz = fld.get_crds_cc(shaped=Tru...
5196dd3a6d92839ae83ccfd503ddb08a98aad17f
53,407
def profile(request): """displays profile page""" current_user = request.user user_id = current_user.id return render(request, 'profile/profile.html', { 'account': get_object_or_404(Account, acc_id=user_id), 'dj_name': current_user.username })
0801d99ebdeae1ff14a449ab1c91f3ddf66828ec
53,408
import numpy def positions_join(positions_sequence): """Return concatenated positions arrays.""" return numpy.concatenate(positions_sequence)
f2743b00ac6b3c19e2c8efe0209e8a3f938389b7
53,409
def build_optimizer(model, args): """ helper to build the optimizer and wrap model :param model: the model to wrap :returns: optimizer wrapping model provided :rtype: nn.Optim """ optim_map = { "rmsprop": optim.RMSprop, "adam": optim.Adam, "adadelta": optim.Adadelta, ...
8f5233a0b3f264d56307550e2c38f445381acbec
53,411
def callback_on_failure(): """Simple callback on failure""" return False
98fcb160561ff4c6c25f49e95610394b56580a04
53,412
def _reconstitute(cls, dict_, items): """ Reconstitute an ``OrderingList``. This is the adjoint to ``OrderingList.__reduce__()``. It is used for unpickling ``OrderingList``\\s """ obj = cls.__new__(cls) obj.__dict__.update(dict_) list.extend(obj, items) return obj
2fb4d4bafba99da0a4bcdc4348b7e0f75aa78895
53,413
def id_attributes_map(dataset_path, id_field_names, field_names, **kwargs): """Return dictionary mapping of field attribute for each feature ID. Note: There is no guarantee that the ID field(s) are unique. Use ArcPy cursor token names for object IDs and geometry objects/ properties. ...
8c654542434f81b2b8ac94de54ece3880abd8e34
53,414
def modify_attack_types(id_, attack_types, user, **kwargs): """ Set the Indicator attack type. :param indicator_id: The ObjectId of the indicator to update. :type indicator_id: str :param attack_types: The new indicator attack types. :type attack_type: list,str :param user: The user updatin...
5df8efb8b3f36d70a303a145f28587dec485332e
53,415
def mdotvpw(M, v, w): """ M.v + w """ return vaddw(mdotv(M, v), w)
c5fbd96c6cbd4f6fe2b93a287b4ef02397464817
53,417
def get_ip(device): """ Return first ip on an interface """ cmd = "ip addr show dev %s" % device for i in execute(cmd): vals = i.lstrip().split() if (vals[0] == 'inet'): return vals[1] return ""
87da98e037b74de3686e3e2f3919327a6df8130c
53,418
def index2int(index): """Helper function to convert timeindexes to ints""" return index.view(np.int64).reshape(-1,1)
6a56d04fc5d43e54262ec804ec538c62f4294a44
53,419
def fetch_documents_front(document_id): """ Obtém o JSON do Document do Kernel com base no parametro 'document_id' """ return fetch_data("/documents/%s/front" % (document_id))
e1fd02859332cc9947b9a14ea2cd4ed4bfdb0de4
53,420
from typing import List from typing import Optional from typing import Any import glob def get_positions( topology: PathLike, trajectory: List[str], *, mask: str = "all", stride: Optional[int] = None, ) -> NDArray[(Any, ...), Float]: """Read a molecular dynamics trajectory and retrieve the coo...
30b0374187088f56e48b1756b475a55785fde373
53,421
def snd(pair): """Return the second element of pair """ return pair[1]
a7893d60324ebdd358a0a0bb86bd2842d2617629
53,422
def create_swagger_spec(): """ Swagger API definition. """ return jsonify(spec.to_dict())
26354017e8403107873e9fc543488e9a4ace98b6
53,423
def quicksort_hoare(a): """Quicksorts a list, using Hoare partitioning.""" def partition(low, high): swap_center_to_front(low, high) pivot = a[low] low -= 1 high += 1 while True: low += 1 while a[low] < pivot: low += 1 ...
46b1ce7568b519df932a17a0903ca3814a1e3c7e
53,424
import inspect def trimArgsKwargs(fn, givenArgs, givenKwargs=None): """ given function, and tuple and dict of args and kwargs, trim args to accepted length, and remove all but given kwargs from dict for use in signals - some functions just need to trigger on specific signals, while others may need more detail inf...
02ae5865f519052bc56f178d79626d1145889c75
53,425
def norm_hue_channel(value): """Normalize hex channel.""" return norm_angle(value)
1612b10e790a1f179ef168501ea83e421eee275a
53,427
def _add_common_cc_options(version, **kwargs): """Add common C++ defines, compiler and linker options. This function will add common Xykivo C++ options to the given cc_library or cc_binary optional arguments. :param version: The version of the of the C++ target :param kwargs: Optional C++ target a...
be9dc753106c69a3baf5af4bf51de2846a36b01a
53,429
def ServiceAccountCredentials(email, key_file=None, key_data=None): """Configure OAuth2 credentials for a Google Service Account. Args: email: The email address of the account for which to configure credentials. key_file: The path to a file containing the private key associated with the service acc...
6e6e30262b065ec279955ba1a3ba89a2217bb068
53,430
def get_prop_type(value, key=None): """ Performs typing and value conversion for the graph_tool PropertyMap class. If a key is provided, it also ensures the key is in a format that can be used with the PropertyMap. Returns a tuple, (type name, value, key) """ if isinstance(key, unicode): ...
41805f689d76e0f8103a9ede42eea93b91fea542
53,431
def get_pb_by_name(xml_parent, name): """ Searches for a pb_type with the given name inside a parent pb_type. Returns either a child or the parent. The provided parent may be a mode but a pb_type is always returned. """ assert xml_parent.tag in ["pb_type", "mode"], xml_parent.tag # Check t...
aa8a55d0af07ff30ffd9a27556ec50480c6ccde0
53,432
def getTimeframe(start: date, stop: date) -> str: """Given two dates, returns a stringified version of the interval between the two dates which is used to retrieve data for a specific time frame from Google Trends. """ return f"{start.strftime('%Y-%m-%d')} {stop.strftime('%Y-%m-%d')}"
3099cc6c3ae19dd737df5d5bac4527e6ef430bb7
53,433
def set_val(request): """AJAX POST for setting arbitrary values to an object.""" user = request.user msg = "fail" instance = None if request.method == 'POST': cid = request.POST.get('cid') oid = request.POST.get('oid') field = request.POST.get('field') instance_value ...
b18cb0afd01f689f53064ca9e9be1945ddec1200
53,434
def h3_to_parent(h, res=None): """ Get parent of arrays of cells. Parameters ---------- h : array of H3Cells res: int or None, optional The resolution for the parent If `None`, then `res = resolution(h) - 1` Returns ------- array of H3Cells """ h = np.array(...
e45316b21a6f90d26ec7bd79d02c44b1b1fd1597
53,435
import struct def packFileInfo(file, byte_order='<'): """ packs FileInfo object into bytearray b """ if file.address is None: raise ValueError('FileInfo object does not have an address') if (byte_order != '<') and (byte_order != '>'): raise ValueError('unknown byte_order: '+str(byte_order))...
7c18a200f0571470224d7f253014460ce913bf54
53,436