content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def audio_process(songname: str) -> pd.DataFrame: """ :rtype: DataFrame of all the features """ y, sr = librosa.load(songname, mono=True, duration=30) rmse = librosa.feature.rms(y=y) chroma_stft = librosa.feature.chroma_stft(y=y, sr=sr) spec_cent = librosa.feature.spectral_centroid(y=y, s...
e1f517c588e42ac0381065d4fde5f331e528061d
41,315
def qg8_chunk_get_type(chunk: qg8_chunk): """ Return the chunk type as an integer """ if not isinstance(chunk, qg8_chunk): raise TypeError("Argument is not a qg8_chunk") return chunk.type
7dc2bbc77d152f4727dcf951a4ba897b0606d9ba
41,317
def agg_func(data:pd.DataFrame, object_column:str, agg_list=['nunique', 'count'])->pd.DataFrame: """ Parameters ---------- data:pd.DataFrame : object_column:str : agg_list : (Default value = ['nunique', 'count'] : Returns ------- A dataframe with...
41448ed189311bd121aac9ef37bde4ef20c47c8c
41,318
def get_audits(): """Get OS hardening login.defs audits. :returns: dictionary of audits """ audits = [TemplatedFile('/etc/login.defs', LoginContext(), template_dir=TEMPLATES_DIR, user='root', group='root', mode=0o0444)] return audits
cbc12d52fde5d9ec92536799a46d3b0a9fd0d242
41,319
def username_exists(username): """ Checks if a username aldready exists :param username: username to be checked :return: Boolean indicating whether the username exists or not :rtype: boolean """ return not User.query.filter_by( username=username).first() is None
717dc8cd2f5807c49c892ffd98e4e35f79886094
41,321
def buy_ticket(email,price,name,quantity): """ Update user balance :param email: email of user :param price: price of ticket :param name: name of ticket :param quantity: quantity to buy """ user=User.query.filter_by(email=email).first() user.balance=int(float(user.balance)-float(pric...
bf8b5378243b9c3fd8caff7e52a71c985ca47c4f
41,322
from operator import truth def test_validators(): """Tests of validatorfuncs.py that aren't covered elsewhere""" # PercentageString with raises(Invalid, match="Not a valid percentage string"): validatorfuncs.PercentageString("mess%") # ListOfType testfunc = validatorfuncs.ListOfType(int) ...
20707f0eae6491d4acd1b16c59380d5f90d54e01
41,323
import libpysal import warnings def rand_precision_mat(lat_row, lat_col, max_neighbors=8, rho=1): """Generate a random spatial precision matrix. The spatial precision matrix is generated using a rectengular lattice of dimensions `lat_row` x `lat_col`, and thus the row and colum size of the matrix is ...
8afffaee98a07a95ad6e5e0ad2f69cc9d51169ef
41,324
from typing import List def generate_df(cols_to_keep: List[str]) -> pd.DataFrame: """Generates the cleaned dataframe.""" df = pd.read_csv(CSV_URL) for col in INTEGRAL_COLS: df[col] = df[col].astype('Int64') if col.endswith('_flag'): assert get_unique_values(df[col]) == [0, 1, p...
f3c2ed950e09e2d6f52a90fd66035a6067a90a01
41,325
def get_ppm_df(): """Get a pandas dataframe containing all PPM data. Returns: pd.DataFrame: PPM Pandas dataframe """ if app.mongo is None: return None docs = app.mongo.get("PPM") if docs is None: return None ppm_dict = { "date": [], "total": [], ...
0f894522cd489b792c68d9935e4c998d08ad1b69
41,327
from datetime import datetime def utc2local(utc_dtm): """ UTC 时间转本地时间( +8:00 ) :param utc_dtm: :return: """ local_tm = datetime.fromtimestamp(0) utc_tm = datetime.utcfromtimestamp(0) offset = local_tm - utc_tm return utc_dtm + offset
0070c3ae1e37071cbf57806ca18576f81abb64e0
41,328
def make_serviceitem_servicedll(servicedll, condition='contains', negate=False, preserve_case=False): """ Create a node for ServiceItem/serviceDLL :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/serviceDLL' content_type = 'strin...
96513dafa74e7a59b602a4087528794aa540f681
41,329
import math def load_dataset_with_augmentation(source_dir, augmentation=None, min_count=None): """ Wczytanie sampli z opcjonalną augmentacją. Użyć parametru augmentation albo min_count, nie obu na raz. :param source_dir: katalog źródłowy z plikami PNG. :param augmentation: krotność augmentacji. :...
03e8487a7894a651954c2db635c337fe6e8c8c9d
41,330
def get_mse(prices, predictions): """Get the mean squared error of a network by analysing actual price and the network's corresponding predictions. :rtype: float64 :param prices: the prices that the predictions aim to mimic :param predictions: the predictions :return: the mean-squared error of the c...
ec1fbe8e053d29ea95c9ccb268e9590f1a640f45
41,331
import json def find_k_neighbors(): """Receiving input and returning closest neighbors""" input_dict = json.loads(request.get_json()) # print(pd.json_normalize(input_dict).info()) result = KNN.kneighbors( TRANSFORMER.transform(pd.json_normalize(input_dict)), return_distance=False) ...
4001322aa054c623a29fa61e60ada0e7182084d9
41,332
def get_databases(task=None): """Get list of databases Parameters ---------- task : str, optional Only returns databases providing protocols for this task. Defaults to returning every database. Returns ------- databases : list List of database, sorted in alphabetica...
a1ff0e6e6b4cf3282bcc61ff7e52538bd057c19c
41,333
def dimensions(image: np.ndarray, kernel: np.ndarray, padding:int, strides:int) -> np.ndarray: """ See https://medium.com/analytics-vidhya/2d-convolution-using-python-numpy-43442ff5f381 :param image: :param kernel: :param padding: :param strides: :return: """ x_kern_shape = kernel.sh...
007cc47f76a253adaf2f02ade01082670119ae8a
41,334
from operator import add def intcode_comp(puzzle_input, phase_setting, input_signal): """Compute based on the intcode instructions below # position mode: # 1: positional add # 2: positional multiply # 3: get input and save it at location of parameter # 4: output value located a...
dfeab35af6210994d846d1d79916700b6e0e959b
41,335
import ctypes def copy(cell: SpiceCell) -> SpiceCell: """ Copy the contents of a SpiceCell of any data type to another cell of the same type. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/copy_c.html :param cell: Cell to be copied. :return: New cell """ assert isinstance(c...
39f82d10170190b209e8a0fe5061e9aba6877317
41,336
def get_hash_hex(raw_hash): """Creates a nice hex representation of a raw req""" return raw_hash.encode('iso-8859-1').encode('hex')
a7c0e873617cae2481fecc32a2051ad1fc6a9519
41,338
from typing import Any import copy def new_document(source_path: str, settings: Any = None) -> nodes.document: """Return a new empty document object. This is an alternative of docutils'. This is a simple wrapper for ``docutils.utils.new_document()``. It caches the result of docutils' and use it on seco...
5bda163d426a9a7c2f419a282ab4c4e4907700cf
41,339
def guild_only() -> AC: """A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.ApplicationNoPrivateMessage` that is inherited from :exc:`.ApplicationC...
a61f3e0f05acfb51842982dd41cd63d82345ed0b
41,340
def importable_name(cls): """ >>> class Example(object): ... pass >>> ex = Example() >>> importable_name(ex.__class__) 'jsonpickle.util.Example' >>> importable_name(type(25)) '__builtin__.int' >>> importable_name(None.__class__) '__builtin__.NoneType' >>> importable_n...
96fe43ab1c47b506c21bcb938ea34eeefaedac5a
41,341
def gen_client(api_id: str, api_hash: str) -> Client: """Generates Client instance, nothing special Args: api_id (str): Telegram App API ID api_hash (str): Telegram App API Hash key Returns: Pyrogram::Client """ return Client( "tgresender", api_id=api_id, ...
7bd70964c3bb098cc70d2efc178cb038d04321e3
41,343
from typing import Iterable from typing import List def encode_argument_text_from_spans(arguments: Iterable[Argument], tokens: List[str]) -> str: """ Return a string for the CSV field 'answer' """ return SPAN_SEPARATOR.join([span_to_text(span, tokens) for span in arguments])
9421a6a0f9aad8f9a8c33046a207d9ae941cf218
41,344
def get_folder_size_human(path, container: DockerContainer): """disk usage in human readable format (e.g. '2,1GB')""" cmd_folder_size = "du -sh {}".format(path) result = DockerUtils.run_cmd(cmd=cmd_folder_size, container=container) return result.split()[0].decode('utf-8')
8945627c13c841ec8b42896f8285b8d600518598
41,345
def is_input_type(graphql_type: "GraphQLType") -> bool: """ Determines whether or not the "GraphQLType" is an input type. :param graphql_type: schema type to test :type graphql_type: GraphQLType :return: whether or not the "GraphQLType" is an input type. :rtype: bool """ return isinstanc...
ff21d013848159cfa9a286af991fd79267c930e7
41,346
import json def cartao_trello(request, pedido=None, desc=None): """Responsavel por enviar ao cartao trello.""" cliente = TrelloClient(api_key=API_KEY, api_secret=API_TOKEN) my_boards = cliente.get_board('kyL57xiF') lista = my_boards.all_lists() pedido = json.dumps(pedido, cls=UUIDEncoder) des...
ce558a948a747488cd6ef020e4f4e0174e2da91e
41,347
def spectral_maxpeaks(sign, FS): """Compute number of peaks along the specified axes. Parameters ---------- sig: ndarray input from histogram is computed. fs: int sampling frequency of the signal Returns ------- num_p: float total number of peaks """ f, ...
2f61e97daf08e177a13a2b98c0dec43e4ea421fb
41,350
import inspect def get_calling_module(point=2): """ Return a module at a different point in the stack. :param point: the number of calls backwards in the stack. :return: """ frm = inspect.stack()[point] function = str(frm[3]) line = str(frm[2]) modulepath = str(frm[1]).split('/') ...
638006a14fb062810db34beefcd906b898ba45a5
41,351
def _pad_keys_tabular(data, sort): """Pad only the key fields in data (i.e. the strs) in a tabular way, such that they all take the same amount of characters Args: data: list of tuples. The first member of the tuple must be str, the rest can be anything. Returns: list with the strs padded with space cha...
eba58694354a89e0a6d808c08f964755f3b11822
41,352
from typing import Optional def depth_based_median( X: FDataGrid, depth_method: Optional[Depth] = None, ) -> FDataGrid: """Compute the median based on a depth measure. The depth based median is the deepest curve given a certain depth measure. Args: X: Object containing different samp...
07025e781693c213c715aed5a8eac47fdbbb51af
41,353
def get_read_only_permission_name(model: str) -> str: """ Create read only permission human readable name. :param model: model name :type model: str :return: read only permission human readable name :rtype: str """ return f"{settings.READ_ONLY_ADMIN_PERMISSION_NAME_PREFIX.capitalize()}...
81e02b47079fc41fc5e4148a811aad12b2e5646a
41,354
from typing import OrderedDict def _determine_colnums_to_yield(colnames, fname, dtype_fname): """Return a list of integers storing the column numbers of the ASCII history file corresponding to the ordered sequence determined by the input ``colnames``. """ colnames = np.atleast_1d(colnames) colname...
6a5c9d16f64fa5b067885aff9d95b3df5eccbe27
41,355
def get_all_countries(): """Returns all countries""" url = BASE_URL + "all" return _get(url=url)
c3c6bb17e1191635a022d0a119defcaf0daff944
41,356
async def find_channel(ctx, userstr, interactive=False, collection=None, chan_type=None): """ Find a guild channel given a partial matching string, allowing custom channel collections and several behavioural switches. Parameters ---------- userstr: str String obtained from a user, expec...
c07ce7c31e7c99cce0517901dcd7d3abb18720ac
41,357
def df_params_generator(number_of_facilities, number_of_tasks, seed=0): """ Generate instance parameters for the df problem set mentioned in [1]. Parameters ---------- number_of_facilities: int the number of facilities to schedule on number_of_tasks: int the number of tasks to a...
370cba6ce19e5a5a9a556df165d554e4445da7e5
41,358
from typing import Counter def mass_timeseries(cur, facility, flux): """Returns dictionary of mass timeseries of each isotope at a facility. Parameters ---------- cur : sqlite cursor sqlite cursor facility : str name of facility flux : str direction of flux Returns...
4cd53bab4918cd3558b61b4353957da40ccf99a2
41,359
def generate_config(context): """ Creates the Cloud SQL instance, databases, and user. """ properties = context.properties res_name = properties.get('name', context.env['name']) project_id = properties.get('project', context.env['project']) instance = get_instance(res_name, project_id, properties)...
df624472b40bf983329ca8e1a58e9b9d55e95e65
41,361
def loads(strng, root_name=DEFAULT_ROOT_NAME, single_root_node=False, id_mapper=None): """load a config from a string. Args: strng: the string containing the config file root_name: the tag for the top-level node that is added implicitly single_root_node: if true, no implicit t...
0c8fdb9886b051161cdb321abbad150e453d69b2
41,363
def getLabels(kmeans, options): """@brief Labels all centroids of kmeans object to their color names @param kmeans KMeans object of the class KMeans @param options DICTIONARY options necessary for labeling @return colors LIST colors labels of centroids of kmeans object @return ind ...
8b5be98b82c0bc47369e3b980a81e512f84e31e9
41,365
def replace_surrogate_encode(mystring, exc): """ Returns a (unicode) string, not the more logical bytes, because the codecs register_error functionality expects this. """ decoded = [] for ch in mystring: # if PY3: # code = ch # else: code = ord(ch) # ...
e56d0267378ca5e29cc5ed55e359c384c84400a0
41,366
def _heom_state_dictionaries(dims, excitations): """ Return the number of states, and lookup-dictionaries for translating a state tuple to a state index, and vice versa, for a system with a given number of components and maximum number of excitations. Parameters ---------- dims: list ...
819c4e63f389ec8755e0ea92a98ee1c1e8749c08
41,367
def _get_num_els_in_scene_range(zarr_dataset: ChunkedDataset, scene_index_start: int, scene_index_end: int) -> dict: """ Get numbers of scenes, frames, agents, tl_lights in a set of scene in a zarr Args: zarr_dataset (ChunkedDataset): zarr dataset to use for computing number of elements scen...
561c9c58c9627bc56902ca6a9a904b6bfa063f22
41,369
def fill_nulls_w_own_distribution(column: Series) -> Series: """Finds the distribution of filled values in a column and fill its nulls with the same distribution :param pandas.Series column: column to fill nulls :return pandas.Series: column with nulls filled """ # Copy to avoid direct changes in ...
c1168b39b380c21758d6c1700a7d020fd1fbf008
41,370
def compute_data_term_gradient_vectorized(warped_live_field, canonical_field, live_gradient_x, live_gradient_y, scaling_factor=10.0): """ Vectorized method to compute the data term gradient :param live_gradient_x: x-component of the gradient of the warped_live_field...
42861bc4a357e533c78a397b788228eca26b216a
41,371
def pid(db, record): """File system location.""" return recid_minter(record.id, record)
5757419926629dc3862914202b2a37ff0c6777f4
41,373
from typing import Tuple def find_start_end(cus_list, pattern) -> Tuple: """ Find the start & end of pattern in cus_list. If none, return 0,0. :param cus_list: :param pattern: :return: """ for i in range(len(cus_list)): if cus_list[i] == pattern[0] and cus_list[i:i + len(pattern)] ...
e4d9c30c9050cb35a0123e7467d3c68c48c7887d
41,374
def timecoverage(): """ Time intervals of GLDAS data """ return [ ('All Available Times', 'alltimes'), (2019, 2019), (2018, 2018), (2017, 2017), (2016, 2016), (2015, 2015), (2014, 2014), (2013, 2013), (2012, 2012), (2011, 20...
f6f279c8f223a361785cc3a72cebfa02101f099f
41,375
def CDL3LINESTRIKE(data: xr.DataArray) -> xr.DataArray: """ Three-Line Strike (Pattern Recognition) Inputs: data:['open', 'high', 'low', 'close'] Outputs: double series (values are -1, 0 or 1) """ return multiple_series_call(talib.CDL3LINESTRIKE, data, ds.TIME, ds.FIELD, [f.OPEN...
e6e240952ba8e81f1c0ef3bd4e10e0b9186ca5eb
41,377
from typing import Union def check_ess_certid(cert: x509.Certificate, certid: Union[tsp.ESSCertID, tsp.ESSCertIDv2]): """ Match an ``ESSCertID`` value against a certificate. :param cert: The certificate to match against. :param certid: The ``ESSCertID`` value. ...
268af8462decec09ab2a20be14f5319439b55bb3
41,378
import bz2 import base64 def passx_decode(passx): """decode the obfuscated plain text password, returns plain text password""" return bz2.decompress(base64.b64decode(passx.encode("ascii"))).decode("ascii")
b8b2138c55dd28734661484a231128e6f3ccbbb7
41,379
def cloudfront_restriction_type(restriction_type): """ Property: GeoRestriction.RestrictionType """ valid_values = ["none", "blacklist", "whitelist"] if restriction_type not in valid_values: raise ValueError( 'RestrictionType must be one of: "%s"' % (", ".join(valid_values)) ...
d8f7a248800d0b93f0ceee60cd40227d92614341
41,380
def variance_scaling_initializer(tensor, factor=2.0): """ Variance scaling initializing using FAN_AVG, similar to the one in TF :param tensor: A tensor of arbitrary shape. :param fan_in: int :param fan_out: int :param factor: A scalar, the scaling factor. :returns: A tensor with the same shape ...
ed5b2f278cfd33858f59cd8ebdf48814426f5436
41,381
import tokenize import collections import random def convert_single_example(example, tokenizer, is_training): """Converts a single NqExample into a list of InputFeatures.""" tok_to_orig_index = [] orig_to_tok_index = [] all_doc_tokens = [] features = [] for (i, token) in enumerate(example.doc_tokens): ...
04eaa4652246803bb8a96ac2f2eac7a8b188ee92
41,382
from typing import Union from typing import Tuple def calcCog(argument: Union[str, list]) -> Tuple[float, float, float]: """ calculates the Center of Geometry of a given selection or list of atoms Args: argument (str or list): either a PyMOL-selection name or a List of atoms Returns: ...
8694f5949c21ced81b8a7d7e8dc4c89842a1ea2c
41,383
import scipy def find_peaks(signal, fs, min_separation=270, window_width=2500, noise_level=1.25): """Find peaks from pulse oximeter or ECG. Args: signal: Pulse oximeter or ECG data. fs: Sampling frequency (Hz) of the signal. min_separation: Strict minimum time between peaks (ms). ...
c892561960c5ebe299de30fa67012b12d5dcd743
41,387
def evaluate_rm_gold(prediction, ground_truth): """ Evaluation matrix. :param prediction: a dictionary of labels. e.g {0:[1,0],1:[2],2:[3,4],3:[5,6,7]} :param ground_truth: a dictionary of labels :return: """ pos_gt = 0.0 pos_pred = 0.0 true_pos = 0.0 for i in ground_truth: ...
98eeb3fa0ffe4f9b3d0863a41bd3ca5d6c4a036f
41,388
from pathlib import Path def is_git_bundle(path: Path) -> bool: """Indicate if a path is a valid git bundle.""" with TemporaryDirectory(prefix=f"{__name__}.is_git_bundle.") as dirname: with local.cwd(dirname): git("init") return bool(git["bundle", "verify", path] & TF)
b1120f27111ed4f31bb408ee31b230e6cefaa733
41,389
def checksum_file(summer, path): """ Calculates the checksum of the file 'path' using the provided hashlib digest implementation. Returns the hex form of the digest. """ with open(path, "rb") as f: # Read the file in 4KB chunks until EOF. while True: chunk = f.read(4096) if not chunk: ...
729b8f895fe74856e83046d0fd5177e584f835f2
41,391
def camel_case(value): """Convert an identifier to CamelCase""" return "".join(ele.title() for ele in value.split("_"))
e7c74ebe7611eb567f3eae8f16fb01aadd201252
41,392
def parallelize (imgs, func, cores=2): """ Execute a function for each image in parallel. This function assumes 'imgs' is multi-frames of grayscale images for the current version. Parameters ---------- imgs : numpy.ndarray (3d) or list of numpy.ndarray(2d) Input multi-frame images. ...
acd5f64501dbe13d46b7b4fafe6df4f3300c7e56
41,393
def getter_function_spectrum(filename): """ partial does not use kwargs so our options are limitted here """ return Spectrum(filename=filename, is_ucd=False)
6e3f547378cf8bbbd9b67f9031380870c23040ef
41,394
def cov_cluster_robust(jac, hess, design_info): """Cluster robust standard errors. A cluster is a group of observations that correlate amongst each other, but not between groups. Each cluster is seen as independent. As the number of clusters increase, the standard errors approach robust standard errors...
98cc96890597e336d5b43b24e8d30fd1893ae9ed
41,395
import re from datetime import datetime def fix_time_units( timeunits ): """Sometimes we get time units which aren't compatible with cdtime. This function will (try to) fix them. The input argument is a string, e.g. "months since Jan 1979" and the return value is another string, e.g. "months since 19...
64f452b35857c741a04689d670f8c3502dd2d82d
41,396
def binary_encoding(string, encoding = 'utf-8'): """ This helper function will allow compatibility with Python 2 and 3 """ try: return bytes(string, encoding) except TypeError: # We are in Python 2 return str(string)
7982f27c266479b757e3a73e9463acd88b98abcf
41,397
def get_all_overlays_config(self) -> list: """Get all configured overlays in Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - overlays - GET - /gms/overlays/config :return: Returns list of dictionaries...
3c77c14096373792bdaf5c39ffdc3f9d58b0af0d
41,398
def load_densityoperator(filename): """ Load a C++QED state vector file from the given location. Returns a tuple with a list of densityoperators and a list of times. *Usage* >>> svs,times = load_statevector("ring.sv") :param filename: Path to the C++QED state vector file that should be loade...
c1a3ba6484b86adfa76c8abd28f580f89d2103c8
41,399
import json def pending(): """ Display pending reviews. These are reviews that were submitted, but the user hasn’t responded to the confirmation email yet. They are automatically purged after 24 hours. """ if app_unavailable(): return render_template('app_unavailable.html', result=Markup(get_rea...
fa5d6ae7cc721b98bc95ad8f3eaa4832ae47dca7
41,400
def format_directory_path(path: str) -> str: """Replaces windows style path seperators to forward-slashes and adds another slash to the end of the string. """ if path == ".": return path formatted_path = path.replace('\\', '/') if formatted_path[-1] is not '/': formatted_path += ...
0daa0cc65e50bd29c76da64d302c0e01c1bb333b
41,401
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. ...
f6abd2617cb9466932aa4fdeb592971fbafb068f
41,402
def voter_count_doc_view(request): """ Show documentation about voterCount """ url_root = WE_VOTE_SERVER_ROOT_URL template_values = voter_count_doc.voter_count_doc_template_values(url_root) return render(request, 'apis_v1/api_doc_page.html', template_values)
f1ada03285333982f1b2ce219788097da0468be8
41,403
from scipy.linalg import solve_banded, solve def __lobatto__(alpha,beta,xl1,xl2): """ Compute the Lobatto nodes and weights with the preassigned node xl1,xl2 Inputs: alpha - recursion coefficients beta - recursion coefficients xl1 - assigned node location xl2 - ass...
d4eddef75bc452e84606477547003ccb3bad1647
41,406
def create_account(fullname, username, password): """ Function for creating a new user account """ new_user = User(fullname, username, password) return new_user
627efda28257d1fa56d543cd6f4564ce78c3b043
41,407
def count_futures(*args, **kwargs): """ 计数 :param args: :param kwargs: :return: """ return db_instance.count(Futures, *args, **kwargs)
477159e89a4d1c2defdf0a77531ed31f40f8bc4a
41,408
def file_attribs_get(location): """Return mode, owner, and group for remote path. Return mode, owner, and group if remote path exists, 'None' otherwise. """ if file_exists(location): fs_check = run('stat %s %s' % (location, '--format="%a %U %G"')) (mode, owner, group) = fs_check.split(' ') return {'mode': mo...
0525b500b8d6762e74c1bbb71b9abbe5612f9586
41,409
from typing import Dict from typing import Any from typing import List def upsert_sql_from_field_value_dict(schema_table: SchemaTable, field_value_dict: Dict[Field, Any], conflict_field_list: List[Field]) -> sql.Composable: """ Takes a schema table, a dict mapping Fields t...
8364a305cbf349abdd5504c94cae62341a1dcf7a
41,410
def in_date(day, *dates): """check if day is in dates list or date :param day: date :param dates: list of dates or date :return: true if in, otherwise false """ the_date = int(int_date(day) % 100) return _in_range_or_equal(the_date, dates)
9dfb64bcec9d048718edbd0dcbb23e57ced8614e
41,411
def connect_to_server(): """ Connects to the IMAP server specified in Django's settings and returns the connection object. """ c = imapclient.IMAPClient(settings.TICKETUS_MAILGW_HOST, port=getattr(settings, 'TICKETUS_MAILGW_PORT', None), us...
3dec1a1c0a2df3c2b44b12712e33ec31fdc8bbe0
41,412
import numba def jit_filter1d_function(filter_function): """Decorator for use with scipy.ndimage.generic_filter1d.""" jitted_function = numba.jit(filter_function, nopython=True) @cfunc(intc(CPointer(float64), intp, CPointer(float64), intp, voidptr)) def wrapped(in_values_ptr, len_in, out_values_ptr, ...
b1cc2a563d92cd920daa24bf0bde54002a420227
41,413
def get_metagen_search_body(self): """ Get the MetaGenSearchView view body. Attributes ---------- measure: str the genomic measure label. gene: str the gene name. Returns ------- html: str the MetaGenSearchView view body. """ # Get parameters measure...
9b1e8c6072991765cf566f1bccccb38b178141a4
41,415
import websockets import itertools def parse_websocket_frame(s): """ May raise ParseException """ try: reqs = pp.OneOrMore( websockets.WebsocketFrame.expr() ).parseString( s, parseAll=True ) except pp.ParseException as v: rais...
8342936d84adf0893b34d6e7f41cc33657f3bea6
41,416
def csnap(df, fn=lambda x: x.shape, msg=None): """ Custom Help function to print things in method chaining. Will also print a message, which helps if you're printing a bunch of these, so that you know which csnap print happens at which point. Returns back the df to further use in chaining. ...
d37e6093834db7d17664387afe871bc8e1d78c0b
41,417
import logging def start_slideshow(): """ Starting the picture frame slideshow. This starts the independent background process. :return: success """ if not process_is_running.value: # Chaning the process value process_is_running.value = True # Creating the background p...
4dfe7ac916859288303cd1a4dabff82fa1acc714
41,418
def _toCamelCase(string): """Convert a snake case string (PyTorch) to camel case (PopART)""" words = string.split("_") return words[0] + "".join(w.capitalize() for w in words[1:])
f1f21b0313c03b3d63944ee3fcbd5e16b435da6d
41,419
from datetime import datetime import re def filter_by_dates(file_list, start_date, end_date, extra_filter=None): """filter files names in 'file_list' that belongs to creation dates betweeen [start_date, end_date) start_date and end_date are given as YYYY-MM-DD""" filtered_dates = list() sd = date...
f84c53aab73d133fd0d7a1e240256937ffab357a
41,420
def pulse(x): """Return the pulse fn of the input.""" return 2*(x % 1 < .5) -1
f54f73ab6656c0242508170c16ab6ee6a0cc5b92
41,422
def instance_update(instance): """ Call update method on spanner client. Note: A ValueError exception is thrown despite the client succeeding. So, we validate the node_count and instance_display_name parameters and then ignore the ValueError exception. :param instance: a Spanner instance objec...
9d3ec54c29f482dd1290daf26b4ebed9726279f7
41,423
def nastran_tube2(DIM1: float, DIM2: float, n: float, material: pre.Material = pre.DEFAULT_MATERIAL) -> Geometry: """Constructs a circular TUBE2 section with the center at the origin *(0, 0)*, with two parameters defining dimensions. See MSC Nastran documentation [1]_ for more details. Added by JohnDN90. ...
b264c6547dc9a348fe27c909fb3fce0c190f16db
41,424
def construct_bootstrap_and_latex_commands(ids, participants, rel_existing_path, static_paths, base_cmd_fmt, to_pdf_fmt): """Construct the commands to bootstrap results and latex generati...
9876078ddef82c66162a1056417569b45d9d772f
41,425
from django.contrib import auth from django.core.urlresolvers import reverse def login(request, next_page=None, required=False, gateway=False): """Forwards to CAS login URL or verifies CAS ticket""" if not next_page: next_page = _redirect_url(request) if request.user.is_authenticated(): r...
a7cbb1a3fa4f713c9cc39ef8b77feca813b05c85
41,426
def index_singleton_clusters(clusters): """Replace cluster labels of -1 with ascending integers larger than the maximum cluster index. """ clusters = clusters.copy() filt = clusters == -1 n = clusters.max() clusters[filt] = range(n, n + len(filt)) return clusters
9cad0df27d2d99ef3a7478f3c3753cd7795beb54
41,428
def handler(event, context): """Dynamo resource""" machineTable = DynamoTable('Machines') return getMachineId(event, machineTable)
807647d225baddcfaade7b837401e4cf02dfc96f
41,429
def feature_df_to_1d(feature_df, chrom_len_s): """ Converts mulitindex feature_df (chrom,start) to single numeric index running trough all chromosomes. The column 'end' is also converted. See rod_to_1d for details. """ feature_df = feature_df.copy() feature_df.index.names = (feature_df....
34d94fa26adc399ba59020212500347a0c572f3a
41,430
def convert_wavelength_air2vacuum(wavelength_air): """ Convert air wavelength to vacuum wavelength Parameters ----------- wavelength_air: float Air wavelength in Angstroms Returns -------- float Vacuum wavelength in Angstroms """ sigma2 = (1e4/wavelength_air)**2....
919e2586c849fac9f126309ffe183160c9b3e546
41,431
def gaussian_blur(img, kernel_size=5): """Applies a Gaussian Noise kernel, blurring the original image""" return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
6613d73b6db4cf0c9cd87417a3a932d1babe3ced
41,432
def convolve_sep2(data, hx, hy, res_g=None, sub_blocks=None): """convolves 2d data with kernel h = outer(hx,hy) boundary conditions are clamping to edge. data is either np array or a gpu buffer (OCLArray) """ if isinstance(data, np.ndarray): data = np.ascontiguousarray(data) if s...
8ea0384c644c160ec31fdde5f158d2620cec801f
41,433
def gradebook_bulk_management_enabled(course_key): """ Returns whether bulk management features should be specially enabled for a given course. """ return waffle_flags()[BULK_MANAGEMENT].is_enabled(course_key)
36531886e09fa9d27e3a157b1bc4aaa76be29500
41,435
def bboxes_filter(): """ """ def _augment( image, bboxes, classes=None ): return image, bboxes, classes return _augment
deee3384f7567181eda6e6735aab01d6967787af
41,436
def kl_loss_var(prior_mu, log_var_prior, post_mu, log_var_post): """ Analytical KLD for two gaussians, taking in log_variance instead of scale ( given variance=scale**2) for more stable gradients For version using scale see https://github.com/pytorch/pytorch/blob/master/torch/distributions/kl.py#L398 "...
b52b03d44202be78683efff13896acfd83e393cf
41,437