content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from .record import decode def get_flatten_name(fea): """ Get names of feature after flatten. Parameters ---------- fea: list or str return value of get_itervar_feature or a line of logfile Returns ------- feature_names: Array of str """ feature_name = { "_attr_"...
102bc6e780f0312f22e812b47ed4c76c6d940140
49,200
def change_style(style, representer): """ Change the style of a particular YAML representer. """ def new_representer(dumper, data): scalar = representer(dumper, data) scalar.style = style return scalar return new_representer
1365e8ed6ad8a237404aa3bc2274ab7e8137e50b
49,201
import copy def move_piece(board, player, piece, initial, final, jumpFlag=False, jumpPosition = None): """ Moves a piece on the board and modifies the cell values as required. """ assert ((jumpFlag) and (jumpPosition != None)) or ((not jumpFlag) and (jumpPosition == None)), "Jump position not passed b...
9f1e546e4b27034a4c26e6456be8ba69685532e2
49,202
def sponge(N:bytearray, d:int): """ Sponge construction for hash functions. N: Thing to hash \n d: size of hash wanted \n return bytearray """ def pad(N, r): iN = bm.bytes_to_int(N) lN = int.bit_length(iN) # Number of 0 to add b = (r - ((lN + 3) % r)) % r ...
0e9a9e03b52fcc2838cdc638948722a82213c08a
49,203
import threading def track_event(tracking_id, category, action, uid=None, label=None, value=0, software_version=None, timeout=2, thread=True): """ Record an event with Google Analytics Parameters ---------- tracking_id : str Google Analytics tracking ID. category : str...
8fb4df7da593abe296c0b524b1ab18c3df460b46
49,204
from typing import List def get_expected_calls(mocker: MockerFixture, file_name: str) -> List: """List of the first 20 expected open calls for the write_nexus_corp method with default args.""" expected_calls = [ mocker.call(file_name, 'w'), mocker.call().__enter__(), mocker.call().writ...
f8c15b409ae91819224d333d358888e71bb36461
49,205
def scanD(d, ck, minSupport): """ 计算候选数据集CK在数据集D中的支持度, 并返回支持度大于最小支持度 minSupport 的数据 Args: D 数据集 Ck 候选项集列表 minSupport 最小支持度 Returns: retList 支持度大于 minSupport 的集合 supportData 候选项集支持度数据 """ # ssCnt 临时存放选数据集 Ck 的频率. 例如: a->10, b->5, c->8 ssCnt = {...
a37fccca461774777bf082ca1b1e2bf3528cc220
49,206
import itertools def accountNames(): """ invert the accountfields list so we can use it to look up user input. """ return dict( itertools.chain.from_iterable( ((alias.lower(), k.lower()) for alias in aliases) for k, aliases in accountFields.items() ) )
357916b52c6156ae8acfc6ea45e5ce9bb604929a
49,207
import codecs def _readfile(fname, strip="\n"): """Shortcut for reading a text file.""" with codecs.open(fname, 'r', 'UTF8') as fp: content = fp.read() return content.strip(strip) if strip else content
5708a91ed7ceb8743bf0e6a40962c80e74996368
49,208
def part1and2(data): """ >>> part1and2(read_input()) (266, 19242) """ grid = defaultdict(int) length = defaultdict(int) for wire in data: wire_grid = process_instructions(wire) for location in wire_grid: grid[location] += 1 length[location] += wire_...
5bf4a67a18472ad0e3d736998d6d363f92a2ba78
49,209
from typing import Optional from typing import Tuple import sys def create_operon_figure(operon: Operon, plot_ignored: bool, feature_colors: Optional[dict] = {}, bounds: Optional[Tuple[int, int]] = None, existing_ax: O...
90f505af32a0762d4ed44ab0e6ebdae5ead07e42
49,210
def functions_str(graph, examples: bool = True, add_count: bool = True, **kwargs) -> str: """Make a summary string of the functions in the graph.""" df = function_table_df(graph, examples=examples) headers = list(df.columns) if add_count: headers[0] += ' ({})'.format(len(df.index)) return ta...
34dc7e2d91dce30eda60cb013d26919907f86f73
49,211
import numba def duffing(n_points: int = 10**6, x_0: float = 0.1, y_0: float = 0.1, a: float = 2.75, b: float = 0.15) -> PlotData: """ Calculates a list of (x, y) points according to the Duffing Map https://en.wikipedia.org/wiki/Duffing_map :param n_points: The number of (x, y) plot points to calculat...
971208bf9dbb44fd02fdab474397069129604986
49,212
def _sliding_attacks(square, occupied, deltas, limit=_default_limit): """ 计算棋子的攻击范围 :param square: :param occupied: :param deltas: :param limit: :return: """ attacks = 0 for delta in deltas: sq = square while True: sq += delta if not limit(...
d0d6841a77d3dcd48d60fbf6a8c8969705688e7b
49,213
def get_github_repo_url(): """ Build URL to github repo """ return 'git://github.com/%s/%s.git' % (MOZILLA_GITHUB_ACCOUNT, DEEPSPEECH_GITHUB_PROJ)
bf8cf954bade35d6ade834d45cfc48a8c71bcfcf
49,214
import re def vnpy_opt_DAY_IN_2(opt): """ vnpy 优化结果清洗, 针对 DAY_IN_2 :param opt: :return: """ data = re.compile(r'DAY_IN_2\':\s(\d+)\}"\]:\s([\d\.]+)').findall(opt) data = np.array(data).T dic = { "DAY_IN_2": pd.Series(data[0], dtype=np.int), "capital": pd.Series(data[1],...
0e428a91f4198fb81041710ec7a49259efdf32c8
49,215
import pathlib import logging def check_stages(start_from, stages): """ Trigger stages rerun """ # nothing to do if no stage passed on cmd line if not start_from: return def tryint(i): # we usually expect int, can be also single char like 'a' or 'b' try: return in...
b2f787549b04dc752b4b17655943a685a7bab99a
49,216
def get_request(url: str) -> HTMLResponse: """Makes a http requests to the server. :param url: The url to send the get requests. returns: The html response from the server. """ session = HTMLSession() return session.get(url)
8c8d0d958c96fd96605444c7bce358d5afc96e76
49,217
from typing import Union import httpx def sync_detailed( *, client: AuthenticatedClient, json_body: SearchEventIn, ) -> Response[Union[ErrorResponse, SearchEventOut]]: """Search Event Dado um Trecho, uma lista de Grupos que resultam da pesquisa por esse Trecho e um price token, atualiza os p...
9a076d45545912da5d854b9cd6056151a6aa183d
49,218
def add(lhs, rhs): """Elementwise addition. Parameters ---------- lhs : relay.Expr The left hand side input data rhs : relay.Expr The right hand side input data Returns ------- result : relay.Expr The computed result. """ return _make.add(lhs, rhs)
21a0599e8746c88c53b63218aa32e904599ee095
49,219
def view_url(context): """Last part of the url for viewing this context. By default: for Images and Files, redirect to .../view Code taken from CMFPlone/skins/plone_scripts/livesearch_reply.py """ portalProperties = getToolByName(context, 'portal_properties') siteProperties = getattr(portalPro...
42c8430e99fb0638fe4664d357e74502e0564fd3
49,220
from typing import Set from typing import List def track_state_update( self, update_task: DatabaseTask, session, track_factory_txs, block_number, block_timestamp, block_hash, ): """Return int representing number of Track model state changes found in transaction.""" num_total_change...
2195003e463604f8d3473bb67d1b9b26908702bd
49,221
def ignore(x): """Method to indicate bypassing property validation""" return x
cc9ae3c1e15fab3e7f55190278356c11d87d9744
49,222
import os def get_alembic_config(db_url: str) -> Config: """ Создает объект конфигурации alembic, чтобы программно вызывать команды alembic """ cmd_options = SimpleNamespace( config=os.path.join(MODULE_PATH, 'alembic.ini'), db_url=db_url, raiseerr=False, rev_range=N...
b479bbc0af174c569e0b11a8efb0816ae7d06a60
49,223
def _time_bb_splits(games): """ This function plots the time it takes for the spy to leave the CC after the most recent BB. If the spy fails to leave after the BB (shot, timeout, etc.), then it is the time from BB to game end. If the spy BBs multiple times in the same convo without leaving, it wil...
5cbf507d4b1f84055c8444a6106a24a34076ba21
49,224
import numpy def alpha(freqs, cfc_mat, qfc_mat=None): """ calculate alpha from expansion """ # Obtain the imaginary frequency and sort other freqs ridxs = tuple(idx for idx, freq in enumerate(freqs) if freq < 0.0) assert len(ridxs) == 1, ('Freqs should only have one imag') ridx = ridxs[0] ...
30fd3aa3bbf8e1ec5464233813d0b4c41ad6c9b4
49,225
def capture_with_stderr(command, cwd=None, env=None, timeout=0, pgrp=0): """Run a program in the background and capture its output. stdout and stderr are captured independently. :Parameters: - `command`: The command to execute. If it is a string, it will be parsed for command-line argum...
2cd8b6d8c3106d110f23b8a38305a86dd83a67c6
49,226
def to_rad(pseudo_dms): """ convert pseudo DMS string (DDD.MMSS) to radians """ w = pseudo_dms.split('.') # separate degree and MMSS degree = int(w[0]) minute = int(w[1][:2]) second = int(w[1][2:]) return (degree + minute / 60 + second / 3600) / 180 * pi
96704b6201e7f5129ea162eee8a67bf8a9e91336
49,227
def default_for_key(key, *args, **kwargs): """The :func:`default_for_key` decorator will register the given metric in the global metric dict (`metrics.DEFAULT_METRICS`) so that it can be referenced by name in instances of :class:`.MetricList` such as in the list given to the :class:`.torchbearer.Model`. ...
f8c790341135f6124304c75ab74e4d6d53ceea5b
49,228
def website_create(request): """ хендлер для запроса, создать сайт создает и возвращает сайт, или ошибка :param request: :return: """ if request.method != 'POST': return HttpResponseNotAllowed(['POST']) req = json_request(request) name = req['name'] ip_address = req['ip...
65d5c1b164da4d4e74051df4118be9f1f837bbba
49,229
from pytest_localserver import http def httpserver(request): """The returned ``httpserver`` provides a threaded HTTP server instance running on a randomly assigned port on localhost. It can be taught which content (i.e. string) to serve with which response code and comes with following attributes: ...
fce6aef741c936b5d826857d9feb9d56402a66b4
49,230
def eval_request_bool(val, default=False): """ Evaluates the boolean value of a request parameter. :param val: the value to check :param default: bool to return by default :return: Boolean """ assert isinstance(default, bool) if val is not None: val = val.lower() if val...
99909909846f3194abc8c83ad84411c3ccd1245c
49,231
def _drop_constant_dims(ys): """Returns a view of the matrix `ys` with dropped constant rows.""" ys = np.asarray(ys) if ys.ndim != 2: raise ValueError("Expecting a matrix.") variances = ys.var(axis=1) active_mask = variances > 0. return ys[active_mask, :]
dd57aecc89d13bf19353a7e7488c8bcfb15044cc
49,232
def correlateToOBTmissionEpoch(pyUTCtime): """correlate the local time to OBT mission epoch time""" return pyUTCtime - s_obtMissionEpochWithLeapSeconds
8a02e3dd31c76298bd1c0c3eac383dc27ded5d56
49,233
def applicationNavigation(ctx, translator, navigation): """ Horizontal, primary-only navigation view. For the navigation element currently being viewed, copies of the I{selected-app-tab} and I{selected-tab-contents} patterns will be loaded from the tag. For all other navigation elements, copies of...
5158b37c4644ba1e8fabbf186786d3fef8215af9
49,234
from datetime import datetime def update_notice(): """ Update a row in notice table. :return: """ error = None # Initialize form doc_change_notice_form = DocChangeNoticeForm(request.form, csrf_enabled=False) doc_change_id = doc_change_notice_form.doc_change_id.data # Get Users f...
8153b26695aec9c3d2b22e17254d444e77bbf1a9
49,235
def by_priority(feedback): """ Converts a feedback into a numeric representation for sorting. Args: feedback (Feedback): The feedback object to convert Returns: float: A decimal number representing the feedback's relative priority. """ category = Feedback.CATEGORIES.UNKNOWN ...
264493ca79a2d260df1f16c5aa0a7ed35b14fa62
49,236
def get_feature_2(sentence: str, index: int) -> str: """Token to the right.""" tokens = tok(sentence) return tokens[index + 1].lower() if index < len(tokens) - 1 else ""
3361cf0c21bd468eac6469a3c3f65ab4c0b8d503
49,237
def split_by_gaps(vec,num_gaps = 1,index = None): """ Aggregates the indices of a vector based on gaps between index values. The number of gaps is specified by num_gaps, and the largest num_gaps gaps in the sorted array are used to cluster values. Arguments --------- vec : A one-d...
f5250f11dfefb06bdfc70f97175576c8a4b2ebaa
49,238
def is_hashable(obj): """Returns true if *obj* can be hashed""" try: hash(obj) except TypeError: return False return True
01be0946922e6e5cfaf21b32642f367f3690e91d
49,239
def checkout_confirm(request): """View for confirming the users order, if he confirms it saves the order to the database and does all appropriate actions as well.""" order = get_order(request) cart = request.session.get("cart") # If the user has no order, no cart or has not chosen an # address...
a45d3ecb0f2a8d31a46f5364b011fe34b2e5547b
49,240
import torch def point_form(boxes): """ Convert prior_boxes to (xmin, ymin, xmax, ymax) representation for comparison to point form ground truth data. Args: boxes: (tensor) center-size default boxes from priorbox layers. Return: boxes: (tensor) Converted xmin, ymin, xmax, ymax form of ...
14560aee2b168d1c0b1020867158a2e99be1f9b8
49,241
import array import itertools def stim_data(elec, max_spk=1024): """ retrieve segment data containing stim waveforms Args: elec: max_spk: Returns: tuple counts, events - count, the number of spikes events - list of SegmentDataPacket classes """ c_spikes = _c.Se...
6797d5a48307d5edc8c7b5d89df3c09f70ad91fa
49,242
def is_valid(number, table=None): """Checks to see if the number provided passes the Damm algorithm.""" try: return bool(validate(number), table=table) except ValidationError: return False
8fc0386c2d7aff6293cca3e0ba4702bce048be81
49,243
def dbscan(points, eps, minpts): """ Implementation of [DBSCAN]_ (*A density-based algorithm for discovering clusters in large spatial databases with noise*). It accepts a list of points (lat, lon) and returns the labels associated with the points. References ---------- .. [DBSCAN] Ester, M...
d77106fc2cddb2447440014172fee127462eb9c3
49,244
def line_search(f, x_k, g_k, p_k, ls_method='back_tracking', ls_params={'alf': 1, 'rho': 0.3, 'mu': 1e-4, 'iter_lim': 1000}): """ This function performs line search for an objective function "f" using pytorch ie. at x_k, find an alf for which x_k + alf*p_k decreases the objective function INPUTS: ...
70fff57b4813c2778d5dd92b44f89764382dec8a
49,245
def analytical_leg_jacobian(leg_angles, sign): """ Computes the analytical Jacobian. Args: ` leg_angles: a list of 3 numbers for current abduction, hip and knee angle. sign: whether it's a left (1) or right(-1) leg. """ l_up = 0.2 l_low = 0.2 l_hip = HIP_COEFFICIENT* (-1)**(sign + 1)...
090736207207a96d484bd8d028b89418936d73a1
49,246
def create_widget(rig, bone_name, bone_transform_name=None): """ Creates an empty widget object for a bone, and returns the object. """ obj_name = WGT_PREFIX + rig.name + '_' + bone_name scene = bpy.context.scene collection = ensure_widget_collection(bpy.context) # Check if it already exists in...
e97514310f0f73e5bcc19595b7a12b4b74d162b3
49,247
from datetime import datetime def make_context(asset_depth=0): """ Create a base-context for rendering views. Includes app_config and JS/CSS includers. `asset_depth` indicates how far into the url hierarchy the assets are hosted. If 0, then they are at the root. If 1 then at /foo/, etc. """ context = flatten_...
7d94f4d66143220eea6d276efaa1126aa37a1fc4
49,248
def process_categorical_data(df): """Splits categories and converts categories to numbers Args: df: Pandas DataFrame Return categories: Pandas DataFrame """ # create a dataframe of the 36 individual category columns categories = df['categories'].str.split(pat = ';', expand = T...
b329e44a486206c5a750341b611b77a8cd35e586
49,249
def mean_time_weekday_view(user_id): """ Returns mean presence time of given user grouped by weekday. """ data = get_data() if user_id not in data: log.debug('User %s not found!', user_id) abort(404) weekdays = group_by_weekday(data[user_id]) return [ (day_abbr[week...
02b7248ac439803e32eaed9ba15d31a3b7f0937d
49,250
def next_vol_pred(model, data_generator, verbose=False): """ get the next batch, predict model output returns (input_vol, y_true, y_pred, <prior>) """ # batch to input, output and prediction sample = next(data_generator) with timer.Timer('prediction', verbose): pred = model.predict...
6bdfe28a5f3498900e0fbebd18f5ec2abda1354d
49,251
from typing import Iterable from typing import Optional from typing import List def marshal_bson( obj: object, types: Iterable=BSON_TYPES, fields: Optional[List[str]]=None, ) -> dict: """ Recursively marshal a Python object to a BSON-compatible dict that can be passed to PyMongo, Motor, etc......
cebd51004799fc229159847e00bd9ce8146dc8f6
49,252
def api_get_all_sysrepo_modules(): """ Returns all Sysrepo module names """ return json_resp(sr_model.get_modules_names())
75c37d52e18cce3f1e37145bd083b66f58d51eb2
49,253
def get_category_index_from_categories(categories, category): """ Gets the index of a category from the categories dictionary. If the category doesn't exist, it creates a new entry for that category name and returns the new index number. """ if category not in categories: categories[cat...
94ce8e2926c1de55383d5fd11e531d9c81792f9c
49,254
def next_wangib(date): """Waning gibbous.""" return find_moon_phase(date, pi * 2.0, pi + (pi / 4.0))
3b7e05102ca409c76b13fe8eb2583be226eca4d9
49,255
def create_repas_noel_column(X): """Crée la variable pour le repas de Noël""" X["repas_noel"] = X["repas_noel"] * X["effectif"] return X
adfd6d07007d8e0f30903e16ed43f37dd55d92a2
49,256
def intervalLength(aa, wrapAt=360.): """Returns the length of an interval.""" if wrapAt is None: return (aa[1] - aa[0]) else: return (aa[1] - aa[0]) % wrapAt
dbceac2d1606d1bedf7c12b4114c17b70db78a86
49,257
import re def is_valid_ordering(ordering): """checks if an ordering is valid Args: ordering (str): The ordering of a note Returns: bool: True if the ordering is valid """ if re.match(r'^[0-9_]+$', ordering): return True else: return False
306d618fb0af6793c474d0cf96d9a5182a15ed23
49,258
def translateDNA_6Frames(sequence) : """returns 6 translation of sequence. One for each reading frame""" trans = ( translateDNA(sequence, 'f1'), translateDNA(sequence, 'f2'), translateDNA(sequence, 'f3'), translateDNA(sequence, 'r1'), translateDNA(sequence, 'r2'), translateDNA(sequence, 'r3')...
691b5828a394c15213b6bb2e6bf97735c7de8715
49,259
def dataset_to_dataframe(ds: xr.Dataset, dim_order: t.List[str] = None): """Convert an xarray Dataset to a pandas DataFrame. Stores Dataset attributes and fixes the merged/expand_dims dimension names bug. Parameters ---------- ds : xr.Dataset The Dataset to convert. dim_order : lis...
e82b8a8e4cf588eb94e59d9736742604c59fc222
49,260
def load(f, where=None): """Read Amiga disk font file.""" # read & ignore header _read_header(f) hunk_id = _read_ulong(f) if hunk_id != _HUNK_CODE: raise FileFormatError('Not an Amiga font data file: no code hunk found (id %04x)' % hunk_id) glyphs, props = _read_font_hunk(f) return F...
1fb0c3ed81ebb5d6f9f99666ef0cf28873cbcc52
49,261
import requests def block(self, hash_or_number: str, **kwargs): """ Return the content of a requested block. https://docs.blockfrost.io/#tag/Cardano-Blocks/paths/~1blocks~1{hash_or_number}/get :param hash_or_number: Hash or number of the requested block. :type hash_or_number: str :param retu...
c6a79e379f52fa72bf22b911f69e9a530eb568e4
49,262
def sql_from_one_hot_encoder( X: list, categories: list, drop_first: bool = False, column_naming: str = None ) -> list: """ --------------------------------------------------------------------------- Returns the SQL code needed to deploy a one-hot encoder model using its attributes. Parameters...
8568f633de60785238307224c71794be99f51668
49,263
def load(trange=['2013-11-5', '2013-11-6'], probe='15', instrument='fgm', datatype='1min', suffix='', downloadonly=False, no_update=False, time_clip=False): """ This function loads data from the GOES mission; this function is not meant to be...
106b469e871b5c2eca6f396ed7d943218e4acb65
49,264
def map_data_ea(*args): """ map_data_ea(insn, addr, opnum=-1) -> ea_t map_data_ea(insn, op) -> ea_t Map a data address. @param insn: the current instruction (C++: const insn_t &) @param addr: the referenced address to map (C++: ea_t) @param opnum: operand number (C++: int) """ return _ida...
9641d4c32bd014ab1835c94ad264fac4eb8c1d7d
49,265
from operator import invert def act(q, v): """ Returns the transformation (rotation) of a vector v by a unit-quaternion q. """ return compose(compose(q, np.insert(v, 0, 0)), invert(q))[1:]
dd29a2aaab7bfb1d5173695ccd8346d50b916d15
49,266
def untile_data3D(data,(lentZ,lentY,lentX),(lenZ,lenY,lenX)): """ Reorganize tiled sparky data into 3D data Parameters: * data 1D numpy array of tile data * lentZ size of tile in Z (w1) dim * lentY size of tile in Y (w2) dim * lentX size of tile in X (w3) dim * lenZ size o...
61e3087a35148c025384b0f5b41175de5e404933
49,267
def evenly_combine(objects, select=None): """ Evenly combine multiple objects into a single object. Parameters ----------- values: list of objects A list of objects to combine, the objects can be of any type as long as the selected object is either an iterable or a dict. select: fun...
4b9a57768a46a2ee1ba6570e2ed600ba334b3398
49,268
def list_flavors(as_list=False): """ Print `openstack` server size (flavor) options. Set ``as_list`` to return a python list object. Usage: fab provider.list_flavors Flavors: +----+-------------------------+-----------+------+----------+-------+-------------+ | ID | ...
9414d8db196c36f19412975b069328821693aea6
49,269
def shark_saved_queries(): """ Retrieve saved queries for a user/account GetParams: account: an account user: a user Returns: A json object conatining a list of saved queries """ error, user, account, _, handle = getRequestParameters(forceCluster=False) if error is ...
98f2c976133d870bd66fb7b969ae31988bee4b9b
49,270
def is_remote_a_wordpress(base_url, error_page, downloader): """ This functions checks if remote host contains a WordPress installation. :param base_url: Base url :type base_url: basestring :param error_page: error page content :type error_page: basestring :param downloader: download func...
d26c1a2f49a9522fe590ba315af90a17c592419f
49,271
from re import X def CNOT(control: int, target: int) -> QCircuit: """ Convenience CNOT initialization Parameters ---------- control: int control qubit target: int target qubit Returns ------- QCircuit object """ return X(target=target, control=control)
1d259a19f1c0cdb5fce5319889fa65c85173c7b1
49,272
import platform def get_python_version(): """ A convenience function to get the python version used to run this tutorial. This ensures that the conda environment is created with an available version of python. """ versions = {'3': '3.8'} return versions[platform.python_version_tuple()[0]]
f34439a174862cf5c4958baca217c0fb149c887a
49,273
import json def read_json(file_path: str) -> dict: """Reads json file from the given path. Args: file_path (str): Location of the file Returns: dict: Json content formatted as python dictionary in most cases """ with open(file_path, "r") as f: return json.load(f)
251c0ad8597ca2819727f95e7e52aa062444cba2
49,274
from typing import List def join_stmts( stmts: List[str], opts: PrintOptions, delimiter: str = "," ) -> str: """A convenience method for joining statements when the entire stmt list is already known""" return JoinPrinter(delimiter=delimiter, stmt_list=stmts).to_string(opts)
e7fa6b460584c4b3d327031881c1b6e832330b3f
49,275
def str_is_none(source): """ 判断字符串不为空 """ if source == '' or source == 'NULL' or source == 'None' or source is None: return True return False
e99d4bf0cae1e0a92cf51a133280a823fc354b31
49,276
def atttyp(att: str) -> str: """ Helper function to return attribute type as string :param str: attribute type e.g. 'U002' :return type of attribute as string e.g. 'U' :rtype str """ return att[0:1]
ff6b4dd284c235db8a12591f78ce276bc73dd6ce
49,277
def lin2freq(n_lin): """Compatibility hack to allow for linearly spaced cosine filters with `make_erb_cos_filters_nx`; intended to generalize the functionality of `make_lin_cos_filters`. """ return _identity(n_lin)
6001e24f133f3bd0d2c2d1627516f93e3c09c4db
49,278
def lower_confidence_bound(num_class_A: int, num_samples: int, alpha: float) -> float: """ Computes a lower bound on the probability of the event occuring in a Bernoulli distribution. Parameters ---------- num_class_A: int The number of times the event occured in the samples. num_samples...
fddb252d21782f876fd804949e236915260a994a
49,279
def get_weather_units(units): """returns a str representation of units of measurement that corresponds to given system of units. if units is 'metric' return °C if units is 'kelvin' return K by default if units is 'imperial' return °F Parameters ---------- :param str units: the system of un...
6a12cb96e98f6ccf95927a79a5e9ffaa0a31d4ab
49,280
def trca_feature(W: ndarray, X: ndarray, n_components: int = 1) -> ndarray: """Return trca features. Modified from https://github.com/mnakanishi/TRCA-SSVEP/blob/master/src/test_trca.m Parameters ---------- W : ndarray spatial filters from csp_kernel, shape (n_channels, n_filters) ...
a5e746dbe200c606a1856d8fc741cabc8b38f807
49,281
def get_data(flist): """ Extract data to pandas dataframes from all files in flist. All coordinates should be same within all phi files in this directory. Parameters ---------- flist - list of phi file names to read from CHARMM PBEQ output Returns ------- crds - X Y Z coordinates f...
da4d5a5064a10e16ae5aa780bef130a300360d2e
49,282
def unescaper(msg): """ unescape message this function undoes any escape sequences in a received message @param msg: the message to unescape @return: the unescaped message """ out = [] escape = False for x in msg: if x == 0x5c: escape = True continue ...
e5e440269426784a7317860ac67133d61d7db7b0
49,283
def squarest_of(c, sort_key=None, reverse_on_key=False): """Returns the :term:`squarest` member of `c`, a collection of numbers. If there are multiple perfect squares, `sort_key` is used to pick a single one. Parameters ---------- c : iterable of int A collection of integers. so...
8f5c38f415b41de763973398ffa23354af22e563
49,284
def compute_curvature(point1: geom.Point, point2: geom.Point, point3: geom.Point) -> float: """ Estimate signed curvature along the three points. :param point1: First point of a circle. :param point2: Second point of a circle. :param point3: Third point of a circle. :return signed curvature of t...
49fa7865fb57399201b79badcccbe30e8f440d06
49,285
from typing import Callable from typing import Iterable from typing import Dict from typing import Any def groupby_many_reduce(key: Callable, reducer: Callable, seq: Iterable): """Group a collection by a key function, when the value is given by a reducer function. Parameters: key (Callable): Key function...
7d08325206bfb78cfe421244af6d91b4cd3ceb56
49,286
def compare_modules(file_, imports): """Compare modules in a file to imported modules in a project. Args: file_ (str): File to parse for modules to be compared. imports (tuple): Modules being imported in the project. Returns: tuple: The modules not imported in the project, but do e...
3085d16b0b92153711868aed615611a481ed6fa0
49,287
def categorize(state): """ Given a state, categorize it as winning(good)=0/ losing(bad)=1/ tie=2 or incomplete game=3 state""" if (state[0][0] == 2 and state[0][1] == 2 and state[0][2] == 2) or ( state[1][0] == 2 and state[1][1] == 2 and state[1][2] == 2) or ( state[2][0] == 2 and state[2][1] == 2 and state[2][2]...
20e8931b8204ad360afcb9521c3a375c07a5aecd
49,288
import os import subprocess def run_command(cmd, cwd=os.getcwd(), stdout=False, stderr=False): """Execute a single command and return STDOUT and STDERR.""" stdout, stdout_str = output_handler(stdout) stderr, stderr_str = output_handler(stderr, redirect='2>') p = subprocess.Popen(cmd, stdout=stdout, s...
598046666538be44a6e92c1bb6ca3cd854e23691
49,289
def _FetchAllFiles(input_api, white_list, black_list): """Hack to fetch all files.""" # We cannot use AffectedFiles here because we want to test every python # file on each single python change. It's because a change in a python file # can break another unmodified file. # Use code similar to InputApi.FilterSo...
99f3a88be278af877ab4dec2a164ce4093a16e82
49,290
def __split2contiguous(levels): """ Function __split2contiguous(levels) takes list of split intervals and make it contiguous if possible """ tmplevs = [] for il in range(len(levels)): lv = levels[il] if not (isinstance(lv, list) or isinstance(lv, tuple)): raise VCSUtilsEr...
590f62a295fda41a2849f6e14719165f4f54ad2f
49,291
from . import api import requests import os def create_app(): """Create and configure an instance of the Flask application.""" app = Flask(__name__, static_folder='react') app.secret_key = b'cs3235privatepartsyo' # Initialize firebase # register api commands app.register_blueprint(api.bp) ...
a63565cab39ca934566a6d71e0291fcd1a042dee
49,292
def _programs_with_attribute(attr): """ get a list of modules with a given attribute """ progs = [] for prog in PROGRAM_MODULE_NAMES.keys(): module = _import_module(prog) if hasattr(module, attr): progs.append(prog) return progs
24347e2d07876108f0a31821e16840f007149708
49,293
import base64 def recursive_decode(s:str, level=9, method=[]) -> str: """ Recursive decode `s`(encoded by `recursive_encode`) using base64, `level` is depth of recursive, the max value is 32 """ assert 0 < level <= 32 if not isinstance(s, (bytearray, bytes)): s = bytes(s, 'utf-8') if m...
49614a7c13126eb4c620a4527302809de6c88393
49,294
import data_augmentation as aug import features import os import pickle def _load_data(dataset, is_training=False): """Load input data, target values and file names for a dataset. The input data is assumed to be a dataset of feature vectors. These feature vectors are standardized using a scaler that is e...
37a0167585dba4d3591f80eb0e90c1ddfbb8f991
49,295
def get_envelope(t_note_length, t_attack=0.010, t_release=0.3, sr=16000): """Create an attack sustain release amplitude envelope.""" t_note_length = min(t_note_length, 3.0) i_attack = int(sr * t_attack) i_sustain = int(sr * t_note_length) i_release = int(sr * t_release) i_tot = i_sustain + i_release # atta...
5547855641c49d733dddd19c2a8065ffbb52d31e
49,296
def create_update(table, columns: dict, filters: dict): """ :param table: :param columns: dict: :param filters: dict: """ table = Table(table) query = Query.update(table) for k, v in columns.items(): query = query.set(k, v) query = set_query_filters(filters, query, table) ...
7e95532c05c07d436c851899ed6545df5bd00da0
49,297
def new_recipe(request): """Создание рецепта '/new' """ user = User.objects.get(username=request.user) form = RecipeForm(request.POST or None, files=request.FILES or None) ingredients = get_ingredients(request) if not form.is_valid(): return render( request, 'new_re...
ee08c4357932cdc2ea0e731a56a5c0597a8c6c6d
49,298
import requests def get_nameservers(): """Returns the available nameservers.""" return requests.get( 'https://api.cloudns.net/dns/available-name-servers.json', params=get_auth_params())
654233d6ef13f518a63c1dcf60ff8c8026872593
49,299