content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def build_asignar_anexos_query(filters, request): """ Construye el query de búsqueda a partir de los filtros. """ return filters.buildQuery().filter(ambito__path__istartswith=request.get_perfil().ambito.path).order_by('nombre')
1a176182fa0559bac56df17f32345d2c4c22b1f1
16,900
import os def validate_paths(paths_A, paths_B, strict=True, keys_ds=None): """ Validate the constructed images path lists are consistent. Can allow using B/HR and A/LR folders with different amount of images Parameters: paths_A (str): the path to domain A paths_B (str): the path to domain...
71d7bb123524196618f9e743ad2ceb0d696e7ea3
16,901
def _median(data): """Return the median (middle value) of numeric data. When the number of data points is odd, return the middle data point. When the number of data points is even, the median is interpolated by taking the average of the two middle values: >>> median([1, 3, 5]) 3 >>> median...
f05a6b067f95fc9e3fc9350b163b3e89c0792814
16,902
def num_translate(value: str) -> str: """переводит числительное с английского на русский """ str_out = NUM_DICT.get(value) return str_out
8555556843ea5235f462dbb7b092eaa09168ab0e
16,903
def get_patch_shape(corpus_file): """Gets the patch shape (height, width) from the corpus file. Args: corpus_file: Path to a TFRecords file. Returns: A tuple (height, width), extracted from the first record. Raises: ValueError: if the corpus_file is empty. """ example = tf.train.Example() t...
054a43d1aa7809b55c57fa0e7574dd43273f4bae
16,904
import re def _TopologicallySortedEnvVarKeys(env): """Takes a dict |env| whose values are strings that can refer to other keys, for example env['foo'] = '$(bar) and $(baz)'. Returns a list L of all keys of env such that key2 is after key1 in L if env[key2] refers to env[key1]. Throws an Exception in case of ...
78ee345ed67d61994245efff8b103d908aa1a7a4
16,905
def get_children_as_dict(parent): """For a given parent object, return all children as a dictionary with the childs tag as key""" child_list = getChildElementsListWithSpecificXpath(parent, "*") child_dict = {} for child in child_list: value = get_children_as_dict(child) if child.tag not ...
054d3591a34536c79e0e5b3715dad6e414d29d46
16,906
from sys import path def load_ascii_font(font_name): """ Load ascii font from a txt file. Parameter --------- font_name: name of the font (str). Return ------ font: font face from the file (dic). Version ------- Specification: Nicolas Van Bossuyt (v1. 27/02/17) Note...
bdf91ce0ccdb574587d71ec9283d15cde09f0f0f
16,907
import itertools import six def get_multi_tower_fn(num_gpus, variable_strategy, model_fn, device_setter_fn, lr_provider): """Returns a function that will build the resnet model. Args: num_gpus: number of GPUs to use (obviously) variable_strategy: "GPU" or "CPU" m...
72e149d25cc6c80a8ea4c5f35f9215cb71aa2a65
16,908
from typing import Union def extract_by_css( content: str, selector: str, *, first: bool = True ) -> Union[str, list]: """Extract values from HTML content using CSS selector. :param content: HTML content :param selector: CSS selector :param first: (optional) return first found element or all of t...
b03d76c893c0f23da332c9978bedc5c9c408e840
16,909
def generate_styles(): """ Create custom style rules """ # Set navbar so it's always at the top css_string = "#navbar-top{background-color: white; z-index: 100;}" # Set glossdef tip css_string += "a.tip{text-decoration:none; font-weight:bold; cursor:pointer; color:#2196F3;}" css_string += "a.ti...
44b36321dedba352c6aa30a352c7cd65cca1f79a
16,910
from pathlib import Path def get_config_file() -> Path: """ Get default config file. """ return get_project_root()/'data/config/config.yaml'
92bc2af7e55b424bcf10355790f377c90a73cf9b
16,911
def kilometers_to_miles(dist_km): """Converts km distance to miles PARAMETERS ---------- dist_km : float Scalar distance in kilometers RETURNS ------- dist_mi : float Scalar distance in kilometers """ return dist_km / 1.609344
61707d483961e92dcd290c7b0cd8ba8f650c7b5b
16,912
def _objc_provider_framework_name(path): """Returns the name of the framework from an `objc` provider path. Args: path: A path that came from an `objc` provider. Returns: A string containing the name of the framework (e.g., `Foo` for `Foo.framework`). """ return path.rpartition("/"...
607c040a9a9c56a793473ffcba779fc7d7a64ed5
16,913
import os def create(rosdistro_index_url, extend_path, dir, name, build_tool, verbose): """Creates a new workspace, saves it, and switches to it if it is the first workspace. :param rosdistro_index_url: The rosdistro to use :param extend_path: Parent workspace to use. :param dir: Where to create ...
68b00ed62012331893f387a04d83adb6664a8827
16,914
def sample_publisher(name='EA'): """Create and return a sample publisher""" return Publisher.objects.create(name=name)
da3d859897c9c3a6f98aa9a7950d77d1390a7527
16,915
def AddGlobalFile(gfile): """ Add a global file to the cmd string. @return string containing knob """ string = '' if gfile: string = ' --global_file ' + gfile return string
70c4bee610766bbea4faf4e463f88ee65f8804f5
16,916
def get_scale_sequence(scale_0, v_init, a, n_frames): """ simulates an object's size change from an initial velocity and an acceleration type """ scale = scale_0 sequence = [scale] # TODO # friction, sinusoidal for i in range(n_frames-1): scale = max(0.05, scale + v_init) if ...
d559672cd2e7b9fa0ff94fb537c48510319a7d53
16,917
def read_file(filename): """Opens the file with the given filename and creates the puzzle in it. Returns a pair consisting of the puzzle grid and the list of clues. Assumes that the first line gives the size. Afterwards, the rows and clues are given. The description of the rows and clues may interleave ...
332ea941aef3b484e2083bfcc734d4bc9fd7f62c
16,918
def login_user(request): """View to login a new user""" user = authenticate(username=request.POST['EMail'][:30], password=request.POST['Password']) if user is not None: if user.is_active: login(request, user) send_email("ROCK ON!!!", "User login - " + user.first_name + " " + ...
ce3c126192df1aeab171438587cdc78a51ebda77
16,919
def gdf_convex_hull(gdf): """ Creates a convex hull around the total extent of a GeoDataFrame. Used to define a polygon for retrieving geometries within. When calculating densities for urban blocks we need to retrieve the full extent of e.g. buildings within the blocks, not crop them to an arbitrar...
c636e67b77ed312a952e7f4af3b3535c983417e3
16,920
from typing import Dict from typing import Any def room_operating_mode(mode: str) -> Dict[str, Any]: """Payload to set operating mode for :class:`~pymultimatic.model.component.Room`. """ return {"operationMode": mode}
df5d1434d5994eca266a3fd06b6a742710bad0eb
16,921
from typing import Dict from typing import Any def _validate_options(data: Dict[str, Any]) -> Dict[str, Any]: """ Looks up the exporter_type from the data, selects the correct export options serializer based on the exporter_type and finally validates the data using that serializer. :param data: A...
8d380d3052c3e1cd4d859fa46829034ba1cf6860
16,922
def householder_name (name, rank): """Returns if the name conforms to Householder notation. >>> householder_name('A_1', 2) True >>> householder_name('foobar', 1) False """ base, _, _ = split_name(name) if base in ['0', '1']: return True elif rank == 0: if base in...
63ff3395e065a79b4d5ee76fb3092efa0cb32b2b
16,923
def calculateDerivatives(x,t,id): """ dxdt, x0, id_, x_mean = calculateDerivatives(x,t,id) Missing data is assumed to be encoded as np.nan """ nm = ~np.isnan(t) & ~np.isnan(x) # not missing id_u = np.unique(id) id_ = [] dxdt = [] x0 = [] x_mean = [] for k in range(0...
86a6e2fc3e50e65ffd162728b79b50ab6ee09a81
16,924
import requests import time def SolveCaptcha(api_key, site_key, url): """ Uses the 2Captcha service to solve Captcha's for you. Captcha's are held in iframes; to solve the captcha, you need a part of the url of the iframe. The iframe is usually inside a div with id=gRecaptcha. The part of the url we ...
e610a265d03be65bfd6321a266776a8102c227d0
16,925
import os import mimetypes def send_asset(asset_file_name): """Return an asset. Args: asset_file_name: The path of the asset file relative to the assets folder. Returns: The asset specified in the URL. """ asset_path = f"assets/{asset_file_name}" asset_size = os.path.getsize(...
f259a03d5a579d07a8110656ad5e5f50a533b9ce
16,926
def clean_crn(crn, duplicates = True, trivial = True, inter = None): """Takes a crn and removes trivial / duplicate reactions. """ new = [] seen = set() for [R, P] in crn: lR = sorted(interpret(R, inter)) if inter else sorted(R) lP = sorted(interpret(P, inter)) if inter else sorted(P) ...
28f4e8eac7b6aea0505491ef55ce54d8d05f0069
16,927
def get_db_mapping(mesh_id): """Return mapping to another name space for a MeSH ID, if it exists. Parameters ---------- mesh_id : str The MeSH ID whose mappings is to be returned. Returns ------- tuple or None A tuple consisting of a DB namespace and ID for the mapping or N...
ae3f8de5c93ab0230a7c87edfa2d3996a9c8667b
16,928
def MC_dBESQ_gateway(N = 10**6, t = 0, n0 = 0, test = 'laguerre', method = 'laguerre', args = [], num_decimal = 4): """ Monte Carlo estimator of expected dBESQ using birth-death simulation, exact BESQ solution, dLaguerre simulation or PDE systems. :param N: int, Number of simulations :param T: posi...
6d09ca8ef2f772e194c7ae656ec4bf9e8a2b6948
16,929
import sys def locate_app(app_id): """Attempts to locate the application.""" if app_id is None: return find_app_in_cwd() if ':' in app_id: module, app_obj = app_id.split(':', 1) else: module = app_id app_obj = None __import__(module) mod = sys.modules[module] ...
027b199a602fb81950cd10eea52276035ac9a045
16,930
def resolve_image(image): """ Resolve an informal image tag into a full Docker image tag. Any tag available on Docker Hub for Neo4j can be used, and if no 'neo4j:' prefix exists, this will be added automatically. The default edition is Community, unless a cluster is being created in which case Enterpris...
7d03b936f90c459a2dade179d9e38bd17c8c1af8
16,931
def _cifar_meanstd_normalize(image): """Mean + stddev whitening for CIFAR-10 used in ResNets. Args: image: Numpy array or TF Tensor, with values in [0, 255] Returns: image: Numpy array or TF Tensor, shifted and scaled by mean/stdev on CIFAR-10 dataset. """ # Channel-wise means and std devs cal...
286ab555d30fd779c093e3b8801821f8370e1ca8
16,932
def get_value_counts_and_frequencies(elem: Variable, data: pd.DataFrame) -> Categories: """Call function to generate frequencies depending on the variable type Input: elem: dict data: pandas DataFrame Output: statistics: OrderedDict """ statistics: Categories = Categories() _scale...
7afe35dc605c1eb25158c8a948eeabcfb0027dc6
16,933
def determineLinearRegions(data, minLength=.1, minR2=.96, maxSlopeInterceptDiff=.75): """ Determine regions of a plot that are approximately linear by performing linear least-squares on a rolling window. Parameters ---------- data : array_like Data within which linear regions a...
318672634082ae87b18f087e8aee65efc1da3f59
16,934
def compute_dispersion(aperture, beam, dispersion_type, dispersion_start, mean_dispersion_delta, num_pixels, redshift, aperture_low, aperture_high, weight=1, offset=0, function_type=None, order=None, Pmin=None, Pmax=None, *coefficients): """ Compute a dispersion mapping from a IRAF multi-spec descri...
94fcb70652bad0f2fa26cf73981129f3ae949d8b
16,935
def normalize_pcp_area(pcp): """ Normalizes a pcp so that the sum of its content is 1, outputting a pcp with up to 3 decimal points. """ pcp = np.divide(pcp, np.sum(pcp)) new_format = [] for item in pcp: new_format.append(item) return np.array(new_format)
ea0feeda3f8515b538ae62b08aad09a16ddb2a73
16,936
def calc_line_flux(spec, ws, ivar, w0, w1, u_flux): """ calculate the flux and flux error of the line within the range w0 and w1 using trapz rule""" u_spec = spec.unit u_ws = ws.unit ivar = ivar.to(1./(u_spec**2)) spec_uless = np.array(spec) ws_uless = np.array(ws) ivar_uless = np.array(ivar) if ivar.unit != ...
78206ce98025ead64e207bd69a8adf1a31178744
16,937
def boolean(entry, option_key="True/False", **kwargs): """ Simplest check in computer logic, right? This will take user input to flick the switch on or off Args: entry (str): A value such as True, On, Enabled, Disabled, False, 0, or 1. option_key (str): What kind of Boolean we are setting. W...
d62b36d08651d02719b5866b7798c36efd2a018f
16,938
import tqdm import copy def edge_preserving_filter(ref_map: np.ndarray, guided_image: np.ndarray, window_size: int, epsilon: float = 1e-10) -> np.ndarray: """ Perform edge - preserving filtering on the newly created reference map. :param ref_map: Classification reference map. ...
1ca88240c26fd4eae67f869bc95a8b0ce885260b
16,939
from typing import List def preprocess_annotated_utterance( annotated_utterance: str, not_entity: str = NOT_ENTITY, ) -> List[str]: """Character Level Entity Label Producer Named-entity of each character is extracted by XML-like annotation. Also, they would be collected in a l...
b148f19017b97a0f4859abc129cdca50fd187c15
16,940
from typing import List from typing import Tuple import jinja2 def generate_constant_table( name: str, constants: List[Constant], *, data_type: str = "LREAL", guid: str = "", lookup_by_key: bool = False, **kwargs ) -> Tuple[str, str]: """ Generate a GVL constant table, with no inte...
54b491ac3673c68a0e7ef819389e393e921d841f
16,941
def filter_stop_words(text): """ Filter all stop words from a string to reduce headline size. :param text: text to filter :return: shortened headline """ words = filter(lambda w: not w in s, text.split()) line = "" l = 0 for w in words: if l < 20: line += w + " "...
d27b63018fa8f7b2d072e768c54ce4a056c58ff1
16,942
def importPublicKey(publickey): """ Cette fonction permet de exporter la clé public, elle prend en paramètre use clé public """ return RSA.importKey(publickey)
b744efc95fc154edcf4149134b7b307e75a0bb17
16,943
def _format_contact(resource, key): """ Return the contact field with the correct values. This is mainly stripping out the unecessary fields from the telecom part of the response. """ contacts = resource.pop(key) resource[key] = [] for contact in contacts: contact["telecom"] = _...
57291dfdf2a724df2cd2342891aa96309648a9c1
16,944
from datetime import datetime def get_day_type(date): """ Returns if a date is a weeday or weekend :param date datetime: :return string: """ # check if date is a datetime.date if not isinstance(date, datetime.date): raise TypeError('date is not a datetime.date') day_type = "" ...
72d74746a7782e0f45b3b7d0292b4cbd4ad9f167
16,945
def case_insensitive_equals(name1: str, name2: str) -> bool: """ Convenience method to check whether two strings match, irrespective of their case and any surrounding whitespace. """ return name1.strip().lower() == name2.strip().lower()
28b7e5bfb5e69cf425e1e8983895f1ad42b59342
16,946
def get_access_token(cmd, subscription=None, resource=None, scopes=None, resource_type=None, tenant=None): """ get AAD token to access to a specified resource. Use 'az cloud show' command for other Azure resources """ if resource is None and resource_type: endpoints_attr_name = cloud_resourc...
9a5190db41e4061698ead3846a6e53f42e64deed
16,947
def ensure_listable(obj): """Ensures obj is a list-like container type""" return obj if isinstance(obj, (list, tuple, set)) else [obj]
bdc5dbe7e06c1cc13afde28762043ac3fb65e5ac
16,948
def merge_dicts(*dicts: dict) -> dict: """Merge dictionaries into first one.""" merged_dict = dicts[0].copy() for dict_to_merge in dicts[1:]: for key, value in dict_to_merge.items(): if key not in merged_dict or value == merged_dict[key]: merged_dict[key] = value ...
b32a9f4bed149144a3f75b43ed45c8de4351f3d1
16,949
from re import X def winner(board): """ Returns the winner of the game, if there is one. """ for moves in _winner_moves(): if all(board[i][j] is X for (i, j) in moves): return X elif all(board[i][j] is O for (i, j) in moves): return O return None
c6e3b35b2cf37ff3da4fe5cd306f7a6f78603f16
16,950
def specified_kwargs(draw, *keys_values_defaults: KVD): """Generates valid kwargs given expected defaults. When we can't realistically use hh.kwargs() and thus test whether xp infact defaults correctly, this strategy lets us remove generated arguments if they are of the default value anyway. """ ...
bd3dfdcbb084a87b0c60d9221692f8fbd3e70333
16,951
def add_image(): """User uploads a new landmark image, and inserts into db.""" imageURL = request.form.get("imageURL") landmark_id = request.form.get("landmark_id") new_image = LandmarkImage(landmark_id=landmark_id, imageurl=imageURL) db.session.add(new_image) d...
dce5f9c21daef67b1a13b1d590fe027213c408e0
16,952
def merge(link1: Node, link2: Node) -> Node: """ Merge two linklists. Parameters ----------- link1: Node link2: Node Returns --------- out: Node Notes ------ """ link = Node(None) ptr = link while link1 and link2: if link1.val <= link2.val: ...
5d40acbd1ffb595a7f4605c3181ede19fb4adbb3
16,953
def l1_norm_optimization(a_i, b_i, c_i, w_i=None): """Solve l1-norm optimization problem.""" cvx.solvers.options['show_progress'] = not CVX_SUPRESS_PRINT # Non-Weighted optimization: if w_i is None: # Problem must be formulated as sum |P*x - q| P = cvx.matrix([[cvx.matrix(a_i)], [cvx.ma...
0966516185c99b936a1fcc8b3d4c74e67587bc63
16,954
def set_order(market, order_type, amount, price, keys, stop_price=None): """ Create an order Arguments: market (str) : market name, order_type (str) : may be "limit", "market", "market_by_quote", "limit_stop_loss" amount (float) : positive if BUY order, and negative for SELL ...
8f9823be8a39d404062114432604c8480aed20c6
16,955
import calendar def convert_ts(tt): """ tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1) >>> tt = time.strptime("23.10.2012", "%d.%m.%Y") >>> convert_ts(tt) 1350950400 tt: time.struct_time(tm_year=1513, tm_mon=1...
a3c2f5ae3d556290b6124d60fd4f84c1c2685195
16,956
def data_context_path_computation_context_path_comp_serviceuuid_optimization_constraint_name_post(uuid, tapi_common_name_and_value=None): # noqa: E501 """data_context_path_computation_context_path_comp_serviceuuid_optimization_constraint_name_post creates tapi.common.NameAndValue # noqa: E501 :param uuid...
fef62699a5a16385ffeeb47f252c1a3142fa9c96
16,957
import re import json def receive_github_hook(request): """a hook is sent on some set of events, specifically: push/deploy: indicates that the content for the repository changed pull_request: there is an update to a pull request. This function checks that (globally) the event is val...
874a71c3c9c002f3714ce0b4bb80586e8d67d7e8
16,958
import torch def dice(y, t, normalize=True, class_weight=None, ignore_label=-1, reduce='mean', eps=1e-08): """ Differentable Dice coefficient. See: https://arxiv.org/pdf/1606.04797.pdf Args: y (~torch.Tensor): Probability t (~torch.Tensor): Ground-truth label normalize (b...
dd0b6fb75688ed0579a3bf9a513f73d0b785e57e
16,959
def read_start_params(path_or_database): """Load the start parameters DataFrame. Args: path_or_database (pathlib.Path, str or sqlalchemy.MetaData) Returns: params (pd.DataFrame): see :ref:`params`. """ database = load_database(**_process_path_or_database(path_or_database)) opt...
31cc6d5f538a8616f9eda676e4bf8757f02f1cb3
16,960
def load_single_rec_into_tables_obj(src_dbreq, schema_engine, psql_schema, rec_id): """ Return Tables obj loaded from postgres. """ if len(psql_schema): psql_schema += '.' tables = create_tabl...
bba0f407b2b406ff454b00e4647b6cb29dd000fd
16,961
def calcCovariance(modes): """Return covariance matrix calculated for given *modes*.""" if isinstance(modes, Mode): array = modes._getArray() return np.outer(array, array) * modes.getVariance() elif isinstance(modes, ModeSet): array = modes._getArray() return np.dot(arra...
7803e765dcf4ad40158040013691bd0f3d7775be
16,962
def sparse_tensor_value_to_texts(value): """ Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings representing its values. This function has been modified from Mozilla DeepSpeech: https://github.com/mozilla/DeepSpeech/blob/master/util/text.py # This Source Code Form is...
e1133532ecd88478d9a5a96773e413992e6566f8
16,963
def coding_problem_45(rand5): """ Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, implement a function rand7() that returns an integer from 1 to 7 (inclusive). Note: for n >= 24, rand5() ** n is a multiple of 7 and therefore rand5() ** 24 % 7 is an unb...
8e26c6f95d953e0a8b3d8a33232c886742a535ce
16,964
def handle_rss_api(output, kwargs): """ Special handler for API-call 'set_config' [rss] """ name = kwargs.get('keyword') if not name: name = kwargs.get('name') if not name: return None feed = config.get_config('rss', name) if feed: feed.set_dict(kwargs) else: ...
73bd10dc2a40cc1648423372e8fcae065e83dbce
16,965
def progress(job_id, user: User = Depends(auth_user), db: Session = Depends(get_db)): """ Get a user's progress on a specific job. """ job = _job(db, job_id) check_job_user(db, user, job) progress = rules.get_progress_report(db, job, user) return progress
fc581297463bc46ce461811d7f675cc99ee63b65
16,966
import json def getRoom(borough): """Return a JSON dataset for property type of airbnb listing""" prpt = db.session.query(data.Borough, data.Room_Type, data.Price, data.Review_Rating, data.review_scores_cleanliness, data.review_scores_value, data.host_r...
2ae05f1f5a501b0a8e25dfc7b212cb0aeecbc0f1
16,967
def get_info(name_file, what='V', parent_folder='txt_files'): """Get data from txt file and convert to data list :param name_file : name of the file, without txt extension :param what : V = vertices, E = edges, R = pose :param parent_folder""" file_path = get_file_path(name_file, parent_folder) ...
f06608340622c7173dffabb6c08f178b9e887e73
16,968
def receive_message( sock, operation, request_id, max_message_size=MAX_MESSAGE_SIZE): """Receive a raw BSON message or raise socket.error.""" header = _receive_data_on_socket(sock, 16) length = _UNPACK_INT(header[:4])[0] actual_op = _UNPACK_INT(header[12:])[0] if operation != actual_op: ...
0c1cd762a2a0889d2894993e0f5362e0acdaee36
16,969
def cycle_interval(starting_value, num_frames, min_val, max_val): """Cycles through the state space in a single cycle.""" starting_in_01 = (starting_value - min_val) / (max_val - min_val) grid = np.linspace(starting_in_01, starting_in_01 + 2., num=num_frames, endpoint=False) grid ...
34fa0d60b9d5d99eee9666d70c77e4375d37ace8
16,970
def commit_ref_info(repos, skip_invalid=False): """ Returns a dict of information about what commit should be tagged in each repo. If the information in the passed-in dictionary is invalid in any way, this function will throw an error unless `skip_invalid` is set to True, in which case the invalid ...
86425248cd4a90aa75d03c2965d63aba3a38e81d
16,971
def function(x, axis=0, fast=False): """ Estimate the autocorrelation function of a time series using the FFT. :param x: The time series. If multidimensional, set the time axis using the ``axis`` keyword argument and the function will be computed for every other axis. :param ax...
cb71d63ee35adde701eba91e068b0f6898005f04
16,972
def find_binaries(*args, **kwargs): """Given images data, return a list of dicts containing details of all binaries in the image which can be identified with image_id or image_tag. One of image_id or image_tag must be specified. :params: See `find_image` :exception: exceptions.ImageNotFound ...
0bc4345279f11cc751f4aee62a7773f0fa21643a
16,973
import copy def solve_version(d): """ solve version difference, argument map d is deepcopied. """ # make copy d = copy.deepcopy(d) v = d.get('version', 0) # functions in _update for f in _update_chain[v:]: d = f(d) return d
ce6a412cc2350a3f6c97c7e1f649a537c35f6722
16,974
from localstack.services.es import es_api def start_elasticsearch_service(port=None, asynchronous=False): """ Starts the ElasticSearch management API (not the actual elasticsearch process. """ port = port or config.PORT_ES return start_local_api("ES", port, api="es", method=es_api.serve, asynchro...
0af83d283735ad1bfdd0684bf1bc1ff36e42d727
16,975
def regexp_ilike(expr, pattern): """ --------------------------------------------------------------------------- Returns true if the string contains a match for the regular expression. Parameters ---------- expr: object Expression. pattern: object A string containing the regular expression to match against...
fe8e7c9a38b5379d265651d60d80bd8804219842
16,976
import os def extract_frames(width, height, video_filename, video_path, frames_dir, overwrite=False, start=-1, end=-1, every=1): """ Extract frames from a video using decord's VideoReader :param video_path: path of the video :param frames_dir: the directory to save the frames :param overwrite: to ...
64ffb491c7d5f07fa95c05086422d6b3d0f4c927
16,977
def make_tree(path): """Higher level function to be used with cache.""" return _make_tree(path)
26919144c49f238c78a29ff4c2ce91d5da939484
16,978
def cmd(f): """Decorator to declare class method as a command""" f.__command__ = True return f
3bdc82f0c83b0a4c0a0dd6a9629e7e2af489f0ae
16,979
def small_prior(): """Give string format of small uniform distribution prior""" return "uniform(0, 10)"
fb636b564b238e22262b906a8e0626a5dff305d1
16,980
from typing import List from typing import Dict from typing import OrderedDict def retrieve_panelist_ranks(panelist_id: int, database_connection: mysql.connector.connect ) -> List[Dict]: """Retrieve a list of show dates and the panelist rank for the reque...
0560a4f0d2c11f9dbd56d25c63d70fc29ed4292d
16,981
def maxPixel(rpl): """maxPixel(rpl) Computes the max pixel spectrum for the specified ripple/raw spectrum object.""" xs = epq.ExtremumSpectrum() for r in xrange(0, rpl.getRows()): dt2.StdOut.append(".") if dt2.terminated: break for c in xrange(0, rpl.getColumns()): ...
9cb40df8a02e7c861aebedb7d2e13c3fac04d024
16,982
def skip_device(name): """ Decorator to mark a test to only run on certain devices Takes single device name or list of names as argument """ def decorator(function): name_list = name if type(name) == list else [name] function.__dict__['skip_device'] = name_list return functio...
1bacdce5396ada5e2ba7a8ca70a8dfb273016323
16,983
def conv1d(inputs, filters, kernel_size, strides=1, padding='valid', data_format='channels_last', dilation_rate=1, activation=None, use_bias=True, kernel_initializer=None, bias_initializer=init_ops.zeros_initia...
f3e9dc40d7da6a9bc7a55ec8b13c91a4ac8ba2c3
16,984
def _transform(ctx): """Implementation for the transform rule.""" if ctx.attr.command and not ctx.attr.transform: fail(("Target '%s' specifies 'command = ...', but this attribute is ignored when no pattern" + " is supplied with the 'transform' attribute") % (ctx.label.name)) lines = [...
062e2f8ec7bfe751f0525e7279e5930b21409f28
16,985
from typing import List from typing import Union def check_constraints( df: pd.DataFrame, schema: dict ) -> List[Union[ConstraintError, ConstraintTypeError]]: """ Check table field constraints. Arguments: df: Table. schema: Table schema (https://specs.frictionlessdata.io/table-schema)...
bd6569932b2eb6e4510b7a5e8e6b22e92ddaa1e5
16,986
from typing import Iterable from typing import Tuple from typing import Optional from typing import Mapping from typing import Any import textwrap def consolidate_fully( inputs: Iterable[Tuple[core.Key, xarray.Dataset]], *, merge_kwargs: Optional[Mapping[str, Any]] = None, combine_kwargs: Optional[Map...
240f2579f97ed1b2eaef2d4d7e9e35ed17dbacdf
16,987
from typing import Iterator from re import T from typing import Optional def first(items: Iterator[T]) -> Optional[T]: """Return the first item of the iterator.""" return next(items, None)
5571c8d1541ce2cb3f49da736f92e17fe6326e6d
16,988
from typing import Sequence def plot_precision_recall_curve( precisions: Sequence[float], recalls: Sequence[float], title: str = 'Precision/Recall curve' ) -> matplotlib.figure.Figure: """ Plots the precision recall curve given lists of (ordered) precision and recall values. A...
d71220b71dfe26aae949676105ba643e249f1c69
16,989
import json def Serialize(obj): """Return a binary serialized version of object. Depending on the serialization method, some complex objects or input formats may not be serializable. UTF-8 strings (by themselves or in other structures e.g. lists) are always supported. Args: obj: any object Return...
d9632f0104c69bfb38396f47f5813fd9a87d6361
16,990
from typing import Union def getDragObject(parent: QWidget, item: Union['SourceListWidgetItem', 'DestTreeWidgetItem']) -> QDrag: """Instantiate QDrag of type application/draggerItem with corresponding QMimeData Parameters ---------- parent: QWidget item: Union['SourceListWidgetItem', 'DestTreeWid...
a6990e9f1a95632d25e15d993d0117cdb911cf7b
16,991
import requests from bs4 import BeautifulSoup def get_soup(url): """ Makes a request to the given url and returns a BeautifulSoup instance of Soup """ res = requests.get(url) if not res.content: return None soup = BeautifulSoup(res.content, "lxml") return soup
bc4e79f4e2313e3c3edc6f6f123b6d13f71c0075
16,992
def _grow_segment(segment, addition): """Combine two segments into one, if possible.""" if _eq(segment[-1], addition[0]): # append addition return segment + addition[1:] elif _eq(segment[-1], addition[-1]): # append reversed addition return segment + list(reversed(addition[:-1])) elif ...
12f48ec2efbd74ac09f9277f2769a4b35030a425
16,993
def dsmoothlist_by_deform_exp(deform_exp, ag_mode): """ Automatically extract the selected artificial generations for training and validation set: 'Resp': ['respiratory_motion', 'single_frequency', 'mixed_frequency', 'zero'], 'NoResp': ['single_frequency', 'mixed_frequency', 'zero'], 'Si...
965ecf7373c313dccd290fb8a7c6c2075645a16a
16,994
from typing import Callable from typing import BinaryIO from typing import Tuple def get_data_reader(header: Header) -> Callable[[BinaryIO], Tuple]: """Make a binary reader function for data.""" names = get_data_names(header) format_ = "" for name in names: if "CH" in name: forma...
c243d5d50ec8738f8f8673fd9bf40b9d26cad69b
16,995
def test_api_mediawiki(monkeypatch): """The api_mediawiki test using mocks.""" result = "OpenClassrooms est une école en ligne..." def mock_summary(*args, **kwargs): return result monkeypatch.setattr( MediawikiApi, 'search', mock_summary) wikipedia = MediawikiApi() assert wiki...
28b22d4acf195dee3d1e7f10688610fea71fea3f
16,996
from typing import Callable def check_fnr(fnr: str, d_numbers=True, h_numbers=False, logger: Callable = lambda _x: None) -> bool: """ Check if a number is a valid fødselsnumber. Args: fnr: A string containing the fodselsnummer to check h_numbers: False (the default) if h-numbers should be ...
2d5af194f1a69a093c6bf69b2cd42537d2dd32b0
16,997
import unittest def get_case_list_from_cls(test_cls_list): """ 将测试类转化为测试用例 :return: """ test_list = [] for test_cls in test_cls_list: test_cases = unittest.TestLoader().loadTestsFromTestCase(test_cls) test_list.append(test_cases) return test_list
3f7ed0c7ed0b9110a9cb11579087712321ec868e
16,998
from sklearn.metrics import r2_score from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split def align_times(sync_behavioral, sync_neural, score_thresh=0.9999, ignore_poor_alignment=False, return_model=False, verbose=False): """Align times across diff...
8bc8ad2a92267a0c1c5e8a4c6a71494910df8b7f
16,999