content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def template(m1, m2): """ :param m1: :param m2: :return: """ c_mass = chirp_mass(m1, m2) B = 16.6 # In seconds to - 5/8 t = np.linspace(0, 0.45, 10000) tc = 0.48 gw_frequency = B * c_mass ** (-5 / 8) * (tc - t) ** (-3 / 8) t_h = np.linspace(-450, 0, 10000) t_merge_...
64e81538e8b37472c7142e9c21d047bf10a19bc7
27,158
def _como_hasheable(matriz): """Retorna una copia hasheable (y por tanto inmutable) de `matriz`.""" return tuple(tuple(fila) for fila in matriz)
a6a1c4371536636d45cfabaf0e2d6938b26a8e08
27,159
def diff(*args, **kwargs): """ Return a diff between two hex list :param args: :param kwargs: :return: """ skip_if_same = True if kwargs.get("skip_if_same", False): skip_if_same = kwargs["skip_if_same"] if len(args) != 2: raise NotImplementedError("Only comparison of ...
c7ec1cc92ef3143798e675576dcc2924e24159bb
27,160
def gravity_effect(position, other_position): """Return effect other_position has on position.""" if position == other_position: return 0 elif position > other_position: return -1 return 1
25130c253cb888057e9b52817cac9cf3778a4c69
27,161
from operator import mul def rots(n_phi_pairs): """ From the provided list of (axis,angle) pairs, construct the product of rotations roti(axis0,angle0) *** roti(axis1,angle1) ... Because rotation of q by A is achieved through A***q***conj(A), rotate( A *** B, q ) is the same as ...
743ebb3a7a8a68f1178ef4f9116607f33dcdb9cf
27,163
def n_cr_shell( thickness, radius, length ): """ Critical compressive load for cylindrical shell. Calculates the critical load for a cylindrical shell under pure compression and assumes uniform stress distribution. Calculation according to EN1993-1-6 [1], Annex D. Param...
1210c3f19a801a7ddf3bae7b478c47732c701433
27,164
def unique_slug(s, model, num_chars=50): """ Return slug of num_chars length unique to model `s` is the string to turn into a slug `model` is the model we need to use to check for uniqueness """ slug = slugify(s) slug = slug[:num_chars].strip('-') while True: dup = model.objects...
ef34215722cca23417c9e944f6320dba79188c8c
27,165
def _to_vertexes(data): """create points at every vertex, incl holes""" # create new file outfile = GeoTable() outfile.fields = list(data.fields) # loop points if "LineString" in data.type: for feat in data: if "Multi" in feat.geometry["type"]: for l...
8c82eac68399e10b1cf87155f6c2b9e8318a8205
27,166
import pickle def _load(fname) : """ Load a cached file and return the resulting object @param fname: file name """ try : f = open(fname) return pickle.load(f) finally : f.close()
5fd5496d226c2ff8265b3dafa0b038bb8015ec5d
27,167
import warnings def reale(x, com="error", tol=None, msg=None, xp=None): """Return real part of complex data (with error checking). Parameters ---------- x : array-like The data to check. com : {'warn', 'error', 'display', 'report'} Control rather to raise a warning, an error, or t...
0823cdc3cb989f7b29dc70e010ad0ae0d2132fbd
27,168
def find_less_than_or_equal(series_key, value): """Find the largest value less-than or equal-to the given value. Args: series_key: An E-Series key such as E24. value: The query value. Returns: The largest value from the specified series which is less-than or equal-to the qu...
4bc6f00910c8d5453d7db82869fe37cd3244cd45
27,169
def GetCommentsByMigration(migration): """Get the comments for a migration""" q = db.Query(models.Comment).filter('migration =', migration) return list(q.fetch(1000))
555f5c8d2df5b05c579b8e20d30e54a035056081
27,170
def get_proxy_list(html_response): """ Returns list of proxies scraped from html_response. :param html_response: Raw HTML text :type html_response: unicode :rtype: list[unicode] """ try: tmp = IPS_REGEXP.findall(html_response.replace("\n", ","))[0] proxies = tmp.split("</tex...
38978d1c65022f2575fd9ce94cddb02782fb82fd
27,171
import fnmatch def ignore_paths(path_list, ignore_patterns, process=str): """ Go through the `path_list` and ignore any paths that match the patterns in `ignore_patterns` :param path_list: List of file/directory paths. :param ignore_patterns: List of nukeignore patterns. :param process: Function t...
63196e54eb4505cbe12ebf77d2a42fede68c1d0b
27,172
import requests def check_static(url): """ Check viability of static links on cf.gov home page and sub-pages. Example call to check static assets in production: ./cfgov/scripts/static_asset_smoke_test.py -v /ask-cfpb/ /owning-a-home/ Example of local check of home page: ./cfgov/scripts/stati...
bccc85254c21471447c15c6fd6a9f2aaaa6ce10d
27,173
def validation_error_handler(err): """ Used to parse use_kwargs validation errors """ headers = err.data.get("headers", None) messages = err.data.get("messages", ["Invalid request."]) schema = ResponseWrapper() data = messages.get("json", None) error_msg = "Sorry validation errors occurr...
3b7ef977b0cf4ec892314923e988509f17e7f49c
27,174
def is_element(a, symbol="C"): """ Is the atom of a given element """ return element(a) == symbol
a04068346d8872f2f3d6228c0f862bcc11d0ff1b
27,175
def create_call_status(job, internal_storage): """ Creates a call status class based on the monitoring backend""" monitoring_backend = job.config['lithops']['monitoring'] Status = getattr(lithops.worker.status, '{}CallStatus' .format(monitoring_backend.capitalize())) return Status(j...
63c9903d5facff8512c40b2838b0796869cdb9ff
27,176
from pathlib import Path import logging def file_handler() -> RotatingFileHandler: """Create a file-based error handler.""" handler = RotatingFileHandler( Path("log") / "error.log", maxBytes=50_000, backupCount=5, delay=True, ) handler.setLevel(logging.ERROR) handle...
62de46cf48e99dabc04a0f3c5ed7083f9261ed6a
27,177
def get_additional_node_groups(node_name, deployment_id): """This enables users to reuse hosts in multiple groups.""" groups = [] try: client = get_rest_client() except KeyError: return groups deployment = client.deployments.get(deployment_id) for group_name, group in deployment....
76cc8f8b98adde91a75c6ab6f39fa6ca17ceabe0
27,178
def is_requirement(line): """ Return True if the requirement line is a package requirement. Returns: bool: True if the line is not blank, a comment, a URL, or an included file """ return line and not line.startswith(('-r', '#', '-e', 'git+', '-c'))
2b89ced1920ac136e9437fda2fd2f8841debf847
27,179
def pden(s, t, p, pr=0): """ Calculates potential density of water mass relative to the specified reference pressure by pden = dens(S, ptmp, PR). Parameters ---------- s(p) : array_like salinity [psu (PSS-78)] t(p) : array_like temperature [℃ (ITS-90)] p : array_li...
c2b64dbfc3ed554a8929f420792ea56df3858cc0
27,180
import typing def SWAP(first: int, second: int, control: typing.Union[int, list] = None, power: float = None) -> QCircuit: """ Notes ---------- SWAP gate, order of targets does not matter Parameters ---------- first: int target qubit second: int target qubit contro...
f5a7af3cc4c9618a17465c3890be81d3251750da
27,181
def stable_normalize(x, etha=1.0e-8): """ Numerically stable vector normalization """ n = np.linalg.norm(x, axis=-1, keepdims=True) if n < etha: n = etha return x / n
36428ecde3993c225b19ccc19278d34c4d9bac36
27,182
import time from functools import reduce def Word2VecFeatureGenerator(df): """ Finds and returns word embedding for the head and body and computes cosine similarity. Input: DataFrame Returns list(headlineVec, bodyVec, simVec)""" t0 = time() print("\n---Generating Word2Vector Features...
0ff2c339ed953592173c0d5afafc72daeeef86a2
27,183
def reachable(Adj, s, t): """ Adj is adjacency list rep of graph Return True if edges in Adj have directed path from s to t. Note that this routine is one of the most-used and most time-consuming of this whole procedure, which is why it is passed an adjacency list rep rather than a list of ver...
dc0ea0c6d2314fa1c40c3f3aa257a1c77892141f
27,184
def remove_links( actor: Actor, company: Company, *, facebook=False, linkedin=False, twitter=False ) -> Response: """Remove links to all existing Online Profiles.""" response, _ = update_profiles( actor, company, facebook=facebook, linkedin=linkedin, twitter=twitter, ...
bdfeefa8366031022a3a108c385f244e6fd740bf
27,185
def get_basis_psd(psd_array, notes): """Get avg psd from the training set (will serve as a basis)""" psd_dict = {} psd_basis_list = [] syl_basis_list = [] unique_note = unique(notes) # convert note string into a list of unique syllables # Remove unidentifiable note (e.g., '0' or 'x') if '...
f8b1e596fdda1125159a963d3362e87abe7b4bfe
27,186
def _get_columns(statement): """Get the available columns in the query `statement`. :param statement: A SQL SELECT statement. :returns: A list of columns that are being selected. """ expecting_columns = False for token in statement.tokens: if token.is_whitespace(): pass ...
49db28bd92d05f4d6e35c32f87e0be4a04e80a92
27,187
def create_conv(in_channels, out_channels, kernel_size, order, num_groups, padding=1): """ Create a list of modules with together constitute a single conv layer with non-linearity and optional batchnorm/groupnorm. Args: in_channels (int): number of input channels out_channels (int): numb...
43ccd6342b0598ab0715960cbae8ad9efb7e29ce
27,189
def expand_json(metadata, context=DEFAULT_CONTEXT): """ Expand json, but be sure to use our documentLoader. By default this expands with DEFAULT_CONTEXT, but if you do not need this, you can safely set this to None. # @@: Is the above a good idea? Maybe it should be set to None by # default...
6fa1f5c4f93f75e45c9a535fe56190ea869dfaa0
27,190
def parsemsg(s, encoding="utf-8"): """Parse an IRC Message from s :param s bytes: bytes to parse :param encoding str: encoding to use (Default: utf-8) :returns tuple: parsed message in the form of (prefix, command, args) """ s = s.decode(encoding, 'replace') prefix = u("") trailing =...
b0205609724eb91d6b53fe37cc9be508a640a95a
27,195
def concatenate_unique(la, lb): """Add all the elements of `lb` to `la` if they are not there already. The elements added to `la` maintain ordering with respect to `lb`. Args: la: List of Python objects. lb: List of Python objects. Returns: `la`: The list `la` with missing elements from `lb`. ""...
307fde291233727c59e2211afc3e0eed7c8ea092
27,196
from datetime import datetime def email_last_send_for_sub(sub_id): """Return when an email was last sent for a subscription, or None.""" last_sent = db.get('email_sub_last_sent:{}'.format(sub_id)) if last_sent is not None: return datetime.datetime.strptime(last_sent, '%Y-%m-%dT%H:%M:%SZ')
e44740a38a2af35c92474aa8da92481d439cc94c
27,197
def is_output_op(node): """Return true when the node is the output of the graph.""" return node.WhichOneof("op_type") == "output_conf"
9a20a471a397a480cc2b295cc96961e030f71e43
27,198
import torchvision def plot_samples_close_to_score(ood_dict: dict, dataset_name: str, min_score: float, max_score: float, n: int = 32, do_lesional: bool = True, show_ground_truth: bool = False, print_score: bool = False) -> None: """Arrange slices in...
33149237d3d36cbae04a1902994487107447a5e5
27,199
from salt.cloud.exceptions import SaltCloudException def avail_images(call=None): """ REturns available upcloud templates """ if call == 'action': raise SaltCloudException( 'The avail_locations function must be called with -f or --function.' ) manager = _get_manager()...
8adf233a1c1bfeef23b94689c0ccb4230fc2b5b5
27,200
import requests def _verify_email_upload(transfer_id: str, session: requests.Session) -> str: """Given a transfer_id, read the code from standard input. Return the parsed JSON response. """ code = input('Code:') j = { "code": code, "expire_in": WETRANSFER_EXPIRE_IN, } r ...
d46610f4dc7582df68fc82654de167a43729d8af
27,202
def envelope_generic(pshape, *args, **kwargs): """ Envelope for a given pulse shape at a given time or times. Parameters ---------- pshape : str or function object Pulse shape type or user-provided function. Allowed string values are 'square', 'gauss', 'cos', 'flattop_gauss'...
6e6d007a6602c90c1d39b4749442b910d90f9cf1
27,204
def sdb_longitude(longitude): """Return an 8 character, zero padded string version of the longitude parameter. **Arguments:** * *longitude* -- Longitude. """ adjusted = (180 + float(longitude)) * 100000 return str(int(adjusted)).zfill(8)
b7b82819952d30ea58dc9dc08e0c4ab63d92743e
27,205
def is_allowed_location(location, allowed_location): """" Returns true if the location is allowed_location Args: location: location id allowed_location: allowed_location Returns: is_allowed(bool): Is location allowed. """ if allowed_location == 1: return True ...
e16b8bb15827b34c65b3ee6aa36f710ad2aaeea5
27,207
def gsl_isinf(*args, **kwargs): """gsl_isinf(double x) -> int""" return _gslwrap.gsl_isinf(*args, **kwargs)
71b1a114cdb581721eaafc442a038b8183a056d1
27,208
def abstract_clone(__call__, self, x, *args): """Clone an abstract value.""" def proceed(): if isinstance(x, AbstractValue) and x in cache: return cache[x] result = __call__(self, x, *args) if not isinstance(result, GeneratorType): return result cls = resu...
4c5f85a710d29f751adb7b2a5cd37ca33136e227
27,209
from typing import Union from typing import Dict from typing import Any import typing def Layout( align_baseline: bool = None, align_center: bool = None, align_content_center: bool = None, align_content_end: bool = None, align_content_space_around: bool = None, align_content_space_between: boo...
b20157e22d69e32fc89d5abda243b5e967d1eefe
27,210
def paint_hull(inputfile, hull={}): """Launches the emergency hull painting robot with the specified Intcode source file Parameters ---------- inputfile: str Path/Filename of Intcode source code hull : dict<(int,int): int> Initial state of the hull """ robot_pos = (0, 0) ...
a781aca8f946cc6931b310848064df93ce888012
27,211
from typing import Tuple from datetime import datetime def get_token_expiration(parser: ConfigParser, profile: str) -> Tuple[str, str]: """Return token expiration date and whether it is expired. Parameters ---------- parser : ConfigParser Parser with all configuration files. profile : str...
0ec467b5c1455784f28b1529e82116e1dbc0dde6
27,212
def ensure_format(s: str, n_chars: int = None) -> str: """ Removes spaces within a string and ensures proper format ------ PARAMS ------ 1. 's' -> input string 2. 'n_chars' -> Num characters the string should consist of. Defaults to None. """ assert isinstance(s, str), "Input...
646faf1f155fdd2023ea711adfe62d6e13dd0954
27,213
def gamma_boundary_condition(gamma=-3): """ Defines boundary condition parameterized by either a scalar or list/iterable. In the latter case, piecewise-interpolation on an equispaced grid over the interior of (0, 1). In the former, the scalar defines the minimum displacement value of the boundary co...
acdfe4e311361c27ef0cec4dbebb2fb51d180683
27,214
def toggleDateSyncButton(click): """Change the color of on/off date syncing button - for css.""" if not click: click = 0 if click % 2 == 0: children = "Date Syncing: On" style = {**on_button_style, **{"margin-right": "15px"}} else: children = "Date Syncing: Off" ...
f8d74feb690044c96d41d83802f791f54f3f6ab8
27,215
def _opt(spc_info, mod_thy_info, geo, run_fs, script_str, opt_cart=True, **kwargs): """ Run an optimization """ # Optimize displaced geometry geom = geo if opt_cart else automol.geom.zmatrix(geo) success, ret = es_runner.execute_job( job=elstruct.Job.OPTIMIZATION, script_st...
b06a97dd33d66a3bc6dc755f48e010f03eb96832
27,218
def fi(x, y, z, i): """The f1, f2, f3, f4, and f5 functions from the specification.""" if i == 0: return x ^ y ^ z elif i == 1: return (x & y) | (~x & z) elif i == 2: return (x | ~y) ^ z elif i == 3: return (x & z) | (y & ~z) elif i == 4: return x ^ (y | ~...
af30fff4cfc2036eb2b7d3e6b33d365b8d64404a
27,219
import torch def th_accuracy(pad_outputs, pad_targets, ignore_label): """Calculate accuracy. Args: pad_outputs (Tensor): Prediction tensors (B * Lmax, D). pad_targets (LongTensor): Target label tensors (B, Lmax, D). ignore_label (int): Ignore label id. Returns: float: Acc...
31b89a949a6c2cfa7e9dd2dddc8e0f25d148d5e9
27,220
def staff_level(): """ Staff Levels Controller """ mode = session.s3.hrm.mode def prep(r): if mode is not None: auth.permission.fail() return True s3.prep = prep output = s3_rest_controller() return output
f665c822c002a9b27e2f8132213c7c2b8841611d
27,221
def aa_status_string (status): """usage: str return = aa_status_string(int status)""" if not AA_LIBRARY_LOADED: return AA_INCOMPATIBLE_LIBRARY # Call API function return api.py_aa_status_string(status)
eabe0b6016b269a749e86e88e3eb5aab8e844215
27,222
def echo(context, args): """ echo text Echo back the following text.""" info(args) return context
887e49ce9ff95c7eabf0499756e1cfce418ccd59
27,223
import time def wait_for_visibility(element, wait_time=1): """Wait until an element is visible before scrolling. Args: element (ElementAPI): The splinter element to be waited on. wait_time (int): The time in seconds to wait. """ end_time = time.time() + wait_time while time.time...
b3e4ed391098131bc62bad4277f8ef163e129d20
27,224
import asyncio async def meta(request): """Return ffprobe metadata""" async def stream_fn(response): async with sem: cmd = ['ffprobe', '-v', 'quiet', '-i', request.args.get('url'), '-print_format...
65bbedf428196ac8317716287550ee868bb6b99e
27,225
from typing import Tuple import ctypes def tpictr( sample: str, lenout: int = _default_len_out, lenerr: int = _default_len_out ) -> Tuple[str, int, str]: """ Given a sample time string, create a time format picture suitable for use by the routine timout. https://naif.jpl.nasa.gov/pub/naif/toolkit...
73f098aa71b796d1a586f9e8666e4277339b7c0d
27,226
def survey_page(request): """View extracts the data that a volunteer fills out from the monthly survey and updates the data on app side accordingly""" if request.method == 'GET': request.session['vol_id'] = request.GET.get('id') request.session['vol_email'] = request.GET.get('email') ...
fa9ac1a31782c0a5639d0d20d98cc41772b1ce09
27,227
def chebyu(n, monic=0): """Return nth order Chebyshev polynomial of second kind, Un(x). Orthogonal over [-1,1] with weight function (1-x**2)**(1/2). """ base = jacobi(n,0.5,0.5,monic=monic) if monic: return base factor = sqrt(pi)/2.0*_gam(n+2) / _gam(n+1.5) base._scale(factor) r...
b71c947e8f988fe3500339a10bd783ed8561da77
27,228
def spm(name, path, size, bos= -1, eos= -1, unk= 0, coverage= 0.9995): """-> SentencePieceProcessor trains a sentence piece model of `size` from text file on `path` and saves with `name`. """ SentencePieceTrainer.train( "--model_prefix={name} \ --input={path} \ --vocab_size...
df22367462839192bcd55093ddf8a2c5b15085f6
27,229
def list_reshape_bywindow(longlist, windowlen, step=1): """ A function to use window intercept long list into several component A list could like below, [a, b, c, d, e] Output could be [[a,b], [c,d]] where windowlen as 2, step as 2 Parameters: ------------ longlist: ...
ee501b49c34656f4c0a1353d36f542b231b3a925
27,230
def generate_test_repo() -> Repository: """ gets you a test repo """ test_requester = Requester( login_or_token="", retry=False, password=None, jwt=None, base_url="https://github.com/yaleman/github_linter/", timeout=30, pool_size=10, per_page=100, ...
56ed5de055e0437bb00630f4cdb71e4547868e64
27,231
from ucsmsdk.mometa.comm.CommSyslogConsole import \ def syslog_local_console_exists(handle, **kwargs): """ Checks if the syslog local console already exists Args: handle (UcsHandle) **kwargs: key-value pair of managed object(MO) property and value, Use 'print(ucscoreutil...
f4f0b1c50dd29fdf8d574ff4bd5b3f4b33b522f5
27,232
import numpy def filter_inputs(inputlist, minimum_members, number_of_families): """ Removes functions that have fewer than minimum_members different hashes, and returns a subset (number_of_families) different ones. """ temp = defaultdict(list) for i in inputlist: temp[i[1]].append((i[0], i[2])) ...
a92d37a20964b543bbd89dd86b0a93166ffe0130
27,233
def is_phone_in_call_video_tx_enabled(log, ad): """Return if phone in tx_enabled video call. Args: log: log object. ad: android device object Returns: True if phone in tx_enabled video call. """ return is_phone_in_call_video_tx_enabled_for_subscription( log, ad, get...
ec51a84c43a808b1e5f750eddf1eedcc4f050158
27,235
def find_mapping_net_assn(context, network_id, host_id): """ Takes in a network id and the host id to return an SEA that creates that mapping. If there's no association found, a None is returned :context: The context used to call the dom API :network_id: The neutron network id. :host_id: The Ho...
543516722a3011d7d859f8f46ae62fd2823989e0
27,237
def bubble_sort(seq): """Inefficiently sort the mutable sequence (list) in place. seq MUST BE A MUTABLE SEQUENCE. As with list.sort() and random.shuffle this does NOT return """ changed = True while changed: changed = False for i in xrange(len(seq) - 1): if seq...
be8c8b4dea93fb91f0ed9397dcd3a9fb9c5d4703
27,239
def numba_cuda_DeviceNDArray(xd_arr): """Return cupy.ndarray view of a xnd.xnd in CUDA device. """ cbuf = pyarrow_cuda_buffer(xd_arr) # DERIVED return pyarrow_cuda_buffer_as.numba_cuda_DeviceNDArray(cbuf)
80f820ac589434f407a1e05954cb59c308882540
27,240
def deg2rad(dd): """Convertit un angle "degrés décimaux" en "radians" """ return dd/180*pi
cba29769452ed971a9934cae4f072724caf9a8d8
27,241
def createView(database, view_name, map_func): """ Creates and returns a Cloudant view. """ my_design_document = design_document.DesignDocument(database, "_design/names") my_design_document.add_view(view_name, map_func) return view.View(my_design_document, view_name, map_func)
77b8fbcbe33c8ae08605f4dff8dc7379dd686329
27,242
def find_modifiable_states(state_data): """ Find indices into the state_data array, Args: state_data (ndarray): States array, in the form returned by cmd_states.get_cmd_states.fetch_states Returns: (ndarray): Numeric index of states that represent dwells with modifiable chip counts ...
61dc59766deb0b6b2c238fe4ce20fe819ef8c7d3
27,243
def get_datasource_bounding_box(datasource_uri): """Get datasource bounding box where coordinates are in projected units. Args: dataset_uri (string): a uri to a GDAL dataset Returns: bounding_box (list): [upper_left_x, upper_left_y, lower_right_x, lower_right_y] in ...
0d262eafb535807c9f6ce38ca3485f731cc95c97
27,246
def distributions_to_lower_upper_bounds(model, negative_allowed=[], ppf=(0.05,0.95), save_to_model=False): """ Converts distributions to uniform distributions by taking specified ppf Args: model: The model object negative_allowed: list of params which are allowed to be negative ppf:...
c86b53802e34ec71a9a72d498278900a36420f37
27,248
def create_feature_indices(header): """ Function to return unique features along with respective column indices for each feature in the final numpy array Args: header (list[str]): description of each feature's possible values Returns: feature_indices (dict): unique feature names as...
a29d8c4c8f3a31ad516216756b7eba7eb4110946
27,250
def lower(word): """Sets all characters in a word to their lowercase value""" return word.lower()
f96b1470b3ab1e31cd1875ad9cbf9ed017aa0158
27,251
def band_pass(data, scale_one, scale_two): """ Band pass filter Difference of two gaussians G(data, s1) - G(data, s2) """ bp = gaussian(data, scale=scale_one) - gaussian(data, scale=scale_two) return bp
140074b49dc589641380a830b1cce8edb6445a45
27,252
def _in_dir(obj, attr): """Simpler hasattr() function without side effects.""" return attr in dir(obj)
f95e265d278e3014e8e683a872cd3b70ef6133c9
27,253
def load_stat_features_others_windows(patient_list, data_path="statistic_features.csv", statistics_list=["std_x", "std_y", "std_z"], n_others_windows=40): """ Returns: X_all_data - ndarray of shape(n_records, n_new_features), feature-vector consist of features of curre...
71de81b25740479f6fc1bc270cff35f33a70b357
27,256
def map_format(value, pattern): """ Apply python string formatting on an object: .. sourcecode:: jinja {{ "%s - %s"|format("Hello?", "Foo!") }} -> Hello? - Foo! """ return soft_unicode(pattern) % (value)
53273dd29d7d0a0e11981fc7de948e930e966fc4
27,257
def Cadzow(Xk, K, N, tol_ratio=10000, max_iter=10): """ Implement Cadzow denoising Parameters ---------- Xk : signal to denoise K : number of most significant members to take N : number of samples in the signal tol_ratio : min ratio of (K+1)th singular value / Kth singular value ...
3dfffcf4eeb0b9765059f327b327375378007825
27,258
def toposortGroup(candidateIrefs): """Given a set of IRefs, returns a list of irefs toposorted based on the include graph.""" graph = {} for iRef in candidateIrefs: graph[iRef] = set(includePaths(iRef)) candidateSet = set(candidateIrefs) output = [] for group in toposort.toposort(graph):...
48166f439a5a9c4ad6ef8abd5c9b9e8dd6559888
27,259
def make_template(template): """Given an OpenSearch template, return a Template instance for it. >>> template = make_template('http://localhost/search?q={term}') >>> template.substitute(term='opensearch syntax') 'http://localhost/search?q=opensearch+syntax' >>> """ terms = decompose_templat...
ad6729cf5c4c2d9cf2198781e4566809d2a8f2b9
27,260
def search(T, dist, w, i=0): """Searches for w[i:] in trie T with distance at most dist """ if i == len(w): if T is not None and T.is_word and dist == 0: return "" else: return None if T is None: return None f = search(T.s[w[i]], dist, w, i + 1) ...
926a0c3e50d38ed1ad7b6e66e8e0a85e24716d89
27,261
def get_weighted_embeddings(embeddings, weights): """Multiply a sequence of word embeddings with their weights :param embeddings: a sequence of word embeddings got from embedding_lookup, size of [batch_size, seq_len, embed_dim] :param weights: a sequence of weights for each word, size of [batch_size,...
741d68036cc7df4060403f3bf9f2acd08b16466c
27,262
def _adjust_values(females, males): """ Adjusting the values as the man moves in with the woman """ females = females.copy() males = males.copy() males.loc[:,"hid"] = females["hid"].tolist() males.loc[:,"east"] = females["east"].tolist() males.loc[:,"hhweight"] = females["hhweight"].tol...
d139869b73e06fb917f843e86d135d1d9db3f4e3
27,263
def create_other_features(data): """Create columns for each other feature extracted.""" # Features list features_list = ['Fibra_ottica', 'Cancello_elettrico', 'Cantina', 'Impianto_di_allarme', 'Mansarda', 'Taverna', 'Cablato', 'Idromassaggio', 'Piscina'] # Crea...
20d2f7e71c06952f2604004224fa113ab9ec88bb
27,264
def handler_good(): """Return True for a good event handler.""" return True
302ea021276cb9be2d5e98c2a09776f4ee53cc97
27,265
def form_gov(): """ Collects the data from the government form and redirects them to the appropriate results page to report the final results """ collected_data = [] form_gov = InputData_gov() if request.method == "POST": try: collected_data.append("Government") ...
483a3ae4746a555bf1ab80252659606bca1b5447
27,266
from io import StringIO def convert_to_grayscale(buffer): """Converts the image in the given StringIO object to grayscale. Args: buffer (StringIO): The original image to convert. Must be in RGB mode. Returns: StringIO: The grayscale version of the original image. Raises: ValueError: If the prov...
8aa632768da7c49e82923074c3057cffe3ed4d51
27,267
def line_visible(plaza_geometry, line, delta_m): """ check if the line is "visible", i.e. unobstructed through the plaza""" intersection_line = plaza_geometry.intersection(line) # a line is visible if the intersection has the same length as the line itself, within a given delta delta = meters_to_degree...
aadc340eddb5f4036af1e8131ced244aa081c75d
27,268
def bad_gateway(message="Bad gateway"): """ A shortcut for creating a :class:`~aiohttp.web.Response` object with a ``502`` status and the JSON body ``{"message": "Bad gateway"}``. :param message: text to send instead of 'Bad gateway' :type message: str :return: the response :rtype: :class:...
9f9592b53b4e08b5c089ed2ad32754b95b8dcdb9
27,269
def chromatic_induction_factors(n: FloatingOrArrayLike) -> NDArray: """ Return the chromatic induction factors :math:`N_{bb}` and :math:`N_{cb}`. Parameters ---------- n Function of the luminance factor of the background :math:`n`. Returns ------- :class:`numpy.ndarray` ...
14f43cbc64aa1904eb38fa2442b33c840aad7275
27,270
def get_correctly_labeled_entries(all_entries): """Get entries that are labeled and evaluated as correct.""" return [ entry for entry in all_entries if convert_to_bool(entry[9]) and convert_to_bool(entry[10]) ]
a61251165629c9bfff3d412c8f4be10eb5b8a5ac
27,271
def data_context_connectivity_context_connectivity_serviceuuid_latency_characteristictraffic_property_name_delete(uuid, traffic_property_name): # noqa: E501 """data_context_connectivity_context_connectivity_serviceuuid_latency_characteristictraffic_property_name_delete removes tapi.topology.LatencyCharacteris...
f8409c09d84ac223f8b3081e4396bc9af86c31c0
27,272
def tag_state_quantities(blocks, attributes, labels, exception=False): """ Take a stream states dictionary, and return a tag dictionary for stream quantities. This takes a dictionary (blk) that has state block labels as keys and state blocks as values. The attributes are a list of attributes to tag. ...
74df558808c1db1e59f27ebe320e8931c291eb28
27,273
def instancesUserLookup(query=None, query_type=None): """ Return a list of sites to which the requested user belongs Display on /search """ if query_type == 'username': kwargs = {'$or': [{'users.username.site_owner': {'$regex': query, '$options': 'i'}}, {'users.username.site_editor': {'$re...
27b778fb1d199497c5529754bf0cbbe99357ddcb
27,276
def volume_kerucut_melingkar(radius: float, tinggi: float) -> float: """ referensi dari kerucut melingkar https://en.wikipedia.org/wiki/Cone >>> volume_kerucut_melingkar(2, 3) 12.566370614359172 """ return pi * pow(radius, 2) * tinggi / 3.0
2f0ddb7b1bd75ec1ee637135f4d5741fda8af328
27,277
def vgg19(pretrained=False, **kwargs): """VGG 19-layer model (configuration "E") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfg['E']), **kwargs) if pretrained: model....
2ff08d30dc82297d5d497f55894e62766dd35019
27,278
def xmprv_from_seed(seed: Octets, version: Octets, decode: bool = True) -> bytes: """derive the master extended private key from the seed""" if isinstance(version, str): # hex string version = bytes.fromhex(version) if version not in PRV: m = f"invalid private version ({version})" ...
f7fb2a06d3e812e24b18453304c9a10476bda31d
27,279