content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def normalize_dates(df,col):
"""Normalize the DF using min/max"""
scaler = MinMaxScaler(feature_range=(-1, 1))
df_values= df[col].values.reshape(-1,1)
dates_scaled = scaler.fit_transform(df_values)
return pd.DataFrame(dates_scaled) | 017e643c1536cb7b39546515aed7d5a303614a7f | 3,619,900 |
def discretize_instationary_cg(analytical_problem, diameter=None, domain_discretizer=None, grid_type=None,
grid=None, boundary_info=None, num_values=None, time_stepper=None, nt=None,
preassemble=True):
"""Discretizes an |InstationaryProblem| with an |Sta... | db6c1bab4fc592e628e5059333d1bea061f98d62 | 3,619,901 |
import os
import pathlib
def getFile(path):
"""
Retrieve the path to one of the reference or example files
Relies on the environment variable ``SERPENT_TOOLS_DATA``
to find the data files.
Parameters
----------
path : str
The name of the file without any additional directory
... | 09fba05e5be7fbb6bb6c8d40acafa71d2018cf29 | 3,619,902 |
def index():
"""List parties."""
parties = party_service.get_all_parties_with_brands()
parties.sort(key=lambda party: party.starts_at, reverse=True)
active_parties, archived_parties = partition(
parties, lambda party: not party.archived
)
brands = brand_service.get_all_brands()
bra... | fd95b27dcc32021239ca8320382bf9c8518e234a | 3,619,903 |
def parse_doi(iso_xml):
"""Get the DOI from an ISO XML doc"""
tree = ET.parse('iso.xml')
root = tree.getroot()
doi_el = root.findall(
'.gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/'
'gmd:CI_Citation/gmd:identifier/gmd:MD_Identifier/gmd:code/'
'gco:CharacterString', NS_DICT
)[0]
... | dcd322984f0cd1fda7ddf6e8763251e92e1856d6 | 3,619,904 |
def ajax_instagram_confirm(request):
"""
View called by an ajax function, it confirms that a user saw the Instagram modal.
"""
user = request.user
user.instagram = False
user.save()
return JsonResponse({"ok", True}) | 1c1a52034c3f3ae35327496bb959936dea59a253 | 3,619,905 |
from typing import Optional
def get_migration_from_new_config_key(new_config_key: str) -> Optional[AbstractPropertyMigration]:
"""
Get a migration from new config key.
"""
return _history_from_new_config_key_dict.get(new_config_key) | bfd0252c98bcf82d4d4dcefbaa2ad85d2a4db703 | 3,619,906 |
def _build_array_type(var, property_path=None):
""" Builds schema definitions for array type values.
:param var: The array type value
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:param property_path: [type], optional
:return: The built s... | e7c4de84e7410010c1e9ff799e46f644a1be9ef7 | 3,619,907 |
def td_processor(df):
""" Process dataframe for TD trial types """
onset_new, duration_orig, trial_type, delay, response, rt, onset_orig = [
df[name].copy() for name in
['onset', 'duration', 'trial_type',
'delay_time_days',
'response_button',
'reaction_time',
... | 5dda7c2281be12accee7db028521906073fa703a | 3,619,908 |
import binascii
def des_descrypt(s):
"""
DES 解密
:param s: 加密后的字符串,16进制
:return: 解密后的字符串
"""
secret_key = '20171117'
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
return de | 67eb89af8eb47a7d735aa054770797a2386b9ec6 | 3,619,909 |
def _kirkwood_muller_dispersion_ads(p_ads, m_ads):
"""Calculate the dispersion constant for the adsorbate.
p and m stand for polarizability and magnetic susceptibility
"""
return (1.5 * constants.electron_mass * constants.speed_of_light**2 * p_ads * m_ads) | 58766d18dcd5eb82e14751f2dbbc15ad57c947f9 | 3,619,910 |
from typing import List
def connect_mol_from_frags(frags: List[Chem.rdchem.Mol], fragmentor: FragmentorBase) -> Chem.rdchem.Mol:
"""
Given a list of fragments (RDKit mol objects) with attachment points [*] marked by integer pairs (attachment_idx)
Return a new mol object
Atom properties are maintained... | b3215551122603e5a1f56cd0131b1bc4c980fcfa | 3,619,911 |
from typing import Sequence
from typing import List
def get_all_lists() -> Sequence[List]:
"""Return all lists."""
lists = db.session.query(DbList).all()
return [_db_entity_to_list(list_) for list_ in lists] | 71f5360f6a2c47811eea03f03b8def984d6f70d0 | 3,619,912 |
def annotate_FayAndWusH(T, lineage_uid, df_seqs, fit_params_kingman, fit_params_BSC, seq_string_uid_to_uid):
""" Traverse tree, calculate Fay and Wu's H for each node, and calculate significance """
annotations = []
# Condition for stopping traversal
def stop(node):
if node.name == "germli... | 54605d0cfdc23a598e8310b0019a4e339cdfecf1 | 3,619,913 |
def include_jquery():
"""
Return whether to include jquery
Setting could be False, True|'full', or 'slim'
"""
return get_bootstrap_setting("include_jquery") | a9bfcf07ee9f9523721561e50dd14821df4852fb | 3,619,914 |
import torch
def isample_from_lineseg(z_vals, weights, N_importance,
det=False, pytest=False, is_only=False,
alpha_base=0.01):
"""
Importance sampling on the line segments
--
z_vals: original sample points to center on
weights: weighted distributio... | 72a92e023bde4a6bb83a06041c206b7fab1b5861 | 3,619,915 |
import itertools
def read_mf_scans(filename_list=None, # type: ['str']
ub_matrix=None, intensity_matrix=None, processes=1, a3_offset=None, a4_offset=None):
"""
# type: (...) -> ['Scan']
Reads TASMAD scan files.
:param filename_list: A list of TASMAD file names to read. User will be ... | 3f818e91747631a51677f04d2a6533cf3c653876 | 3,619,916 |
def get_current_tpc():
"""
Returns: The current TargetPlatformCapabilities that is being used and accessed.
"""
return _current_tpc.get() | ee9a074982fe67eed85abc3d4cbf123b50b03f96 | 3,619,917 |
from libensemble.libE_fields import libE_fields
import sys
def check_inputs(libE_specs, alloc_specs, sim_specs, gen_specs, exit_criteria, H0):
"""
Check if the libEnsemble arguments are of the correct data type contain
sufficient information to perform a run.
"""
if 'comm' not in libE_specs:
... | 1adb8b92b2874c09a48dce58134ef25b77cefcf2 | 3,619,918 |
def check_rwp_calibration(spectrum_rwp, spectrum_broad):
"""
check the rwp calibration by comparing with a broadened cloud radar spectrum
based on different criteria it is decided if the calibration in trustworthy
(``unsecure_calibration``) and correctable (``mod_calibration``)
Args:
spect... | e61788f61e88c10a2130bf17e11fa604d76d1e5d | 3,619,919 |
def concatenate_state_matrices(G):
"""
Takes a State() model as input and returns the A, B, C, D matrices
combined into a full matrix. For static gain models, the feedthrough
matrix D is returned.
Parameters
----------
G : State
Returns
-------
M : ndarray
"""
if not is... | 5c260fe0d97b8472a7aa3925f922854fc80eb654 | 3,619,920 |
def load_fossil():
"""Fossil"""
return _load_local('fossil') | 0922049db08170082b97c0ecc0d0e34f287d8557 | 3,619,921 |
import argparse
def parse_args():
"""parse args for binlog2sql"""
parser = argparse.ArgumentParser(description='Parse MySQL binlog to SQL you want', add_help=False)
connect_setting = parser.add_argument_group('connect setting')
connect_setting.add_argument('-h', '--host', dest='host', type=str,
... | 8ade98cd269c737fb3ba8daed9c5d64d4b20a6ec | 3,619,922 |
from typing import Counter
def main(args=None, **kwargs):
"""Main function of the Counter module."""
# PROTECTED REGION ID(Counter.main) ENABLED START #
return run((Counter,), args=args, **kwargs)
# PROTECTED REGION END # // Counter.main | 03011ff55cc179fbdf2e63e8f4d2300045f55947 | 3,619,923 |
import numpy
def _link_local_maxima_by_velocity(
current_local_max_dict, previous_local_max_dict,
max_velocity_diff_m_s01):
"""Does velocity-matching for local maxima at successive times.
N_c = number of maxima at current time
N_p = number of maxima at previous time
:param current_lo... | e36e914588a60d012fa4a1ddf47c1f13cfe29e62 | 3,619,924 |
import os
def icontrol_rest_folder(method):
"""
Returns iControl REST folder + object name if
a kwarg name is 'name' or else ends in '_name'.
The folder and the name will be prefixed with the global
prefix OBJ_PREFIX.
"""
def wrapper(*args, **kwargs):
""" Necessary wrapper """
... | ee48e2c4ef39eeb396c0fb5e27471b0974771612 | 3,619,925 |
def exp(x : float,iterations : int = 100,taylor_exapnsion=False):
"""Calulates the exponential function,\n
if taylor_exapnsion is set to True it will do what it says,\n
use the taylor expansion of the exp function for calculations,\n
else it will use the stored constant e and raise it to the... | 7bc57ad994ef3f6adafd0c12c902660ea2f59a4b | 3,619,926 |
def numPointsInSpans(spans):
"""
ARC112B
>>> numPointsInSpans([(1, 3)])
3
>>> numPointsInSpans([(1, 3), (5, 7)])
6
>>> numPointsInSpans([(1, 3), (3, 5)])
5
>>> numPointsInSpans([(1, 3), (2, 5)])
5
"""
timeline = []
for start, end in spans:
assert start <= end
... | e1ffecb3a1d4147f4b15256278f398c5213df200 | 3,619,927 |
def load_notebook_template(**kwargs):
"""
kwargs: the parameters to be replaced in the yaml
Reads the yaml for the web app's custom resource, replaces the variables
and returns it as a python dict.
"""
return helpers.load_param_yaml(NOTEBOOK_TEMPLATE_YAML, **kwargs) | a33d1616064f9385e010a9d496635fd4e3a7f2b8 | 3,619,928 |
def grab_data(conn, schema, table, columns):
""" Obtain data from Postgres.
:param schema: name of schema in db
:param table: name of table in schema
:param columns: list of column names (not working yet)
:type schema: str
:type table: str
:return: data from data
:rtype: two-dimensional... | 1d4aae5ef1cc1446215165cefb532a42b0f9e6ba | 3,619,929 |
def merge_import_policies(value, order=""):
"""
Merges and returns policy list for import.
If duplicates are found, only the most specific one will be kept.
"""
if not hasattr(value, "merged_import_policies"):
raise AttributeError("{value} has not merged import policies")
return value.... | adaaf5626e09022b36b69b332fb85788665c114e | 3,619,930 |
import copy
def _fix_xlink_ns(tree):
"""Fix xlink namespace problems.
If there are xlink temps, add namespace and fix temps.
If we declare xlink but don't use it then remove it.
"""
xlink_nsmap = {"xlink": xlinkns()}
if "xlink" in tree.nsmap and not len(
tree.xpath("//*[@xlink:href]",... | 0df54d7c6e12f4ef9afb3cde356a8528d45c1a1b | 3,619,931 |
def run_ldd(ldd, binary):
"""Runs `ldd` and gets the combined stdout/stderr output as a list of lines."""
if not detect_elf_binary(resolve_binary(binary)):
raise InvalidElfBinaryError('The "%s" file is not a binary ELF file.' % binary)
process = Popen([ldd, binary], stdout=PIPE, stderr=PIPE)
st... | 7a3ee428941d0f4594b1b2bff6b71ce74a4944ee | 3,619,932 |
def wind_ms(wind_ms):
"""Checks units for wind_ms"""
return check_array_bounds(
arr=wind_ms, lims=(0, 50), action="warn", name="Wind speed (m/s)"
) | 9829892705177f4bb0ff2f43ca335ffbf757e155 | 3,619,933 |
def disqus_dev(context):
"""
No longer supported by Disqus
"""
return {} | 9d823582b4ddc4e3bed992ef203642641ef83486 | 3,619,934 |
def multivariableode(t,x):
"""Function containing the ODE x_1' = -x_1 + x_2
x_2' = -x_2 .
"""
xprime = np.empty([2], float);
xprime[0] = -x[0] + x[1];
xprime[1] = -x[1];
return xprime; | d80958809a5c493566e84f0dcf19bbeb48ffb0b8 | 3,619,935 |
def plot_factor_contribution_to_perf(
perf_attrib_data,
ax=None,
title="Cumulative common returns attribution",
):
"""
Plot each factor's contribution to performance.
Parameters
----------
perf_attrib_data : pd.DataFrame
df with factors, common returns, and specific returns as c... | c2f063e0dddb6ffde568d53048034d6a8341ac0b | 3,619,936 |
from typing import Dict
def dict_to_nice_string(control_dict: Dict) -> str:
"""
Converts a dictionary of options (like template_control_dict)
to a more human readable format. Which can then be printed to a text file,
which can be manually modified before submiting analysis jobs.
Parameters
... | 10d09f0468356f0c0252e58c98efcfad39a243e4 | 3,619,937 |
def min_sentence_set():
""" minimum query """
return {'hello', 'world'} | 6ec3b76f47c9596422c473b4401ce4124806ec1c | 3,619,938 |
def _sort_student(name: str) -> str:
"""
Return the given student name in a sortable format.
Students are sorted by last name (i.e., last space-split chunk).
"""
return name.lower().split()[-1] | 92747346e0e6ded9715761b8907ccb8ab33da742 | 3,619,939 |
def XYZ_to_Hunter_Lab(
XYZ: ArrayLike,
XYZ_n: ArrayLike = TVS_ILLUMINANTS_HUNTERLAB[
"CIE 1931 2 Degree Standard Observer"
]["D65"].XYZ_n,
K_ab: ArrayLike = TVS_ILLUMINANTS_HUNTERLAB[
"CIE 1931 2 Degree Standard Observer"
]["D65"].K_ab,
) -> NDArray:
"""
Converts from *CIE XY... | 28c9260e32effd24703f36d372a171a47549e819 | 3,619,940 |
def inverse_transform(w, Jmin=2):
"""
Compute the wavelet inverse transform of w
"""
return perform_wavelet_transf(w, Jmin, -1) | 6e364c774aa08c2feb2694440817ac0d5a940f38 | 3,619,941 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Airly as config entry."""
api_key = entry.data[CONF_API_KEY]
latitude = entry.data[CONF_LATITUDE]
longitude = entry.data[CONF_LONGITUDE]
use_nearest = entry.data.get(CONF_USE_NEAREST, False)
# For backwards ... | 18543b48cf92589dae0bba3f4056d301e214a9ed | 3,619,942 |
from typing import Union
from typing import Tuple
def split_element_id(element_id: Union[str, bytes]) -> Tuple[str, int]:
"""
Splits a combined element_id into the collection_string and the id.
"""
if isinstance(element_id, bytes):
element_id = element_id.decode()
collection_str, id = elem... | 9f94dc6d5e2f7eadca0d069987321039def2fcc0 | 3,619,943 |
import re
def is_gcd_file(filename: str) -> bool:
"""Checks whether `filename` is a GCD file."""
if re.search('(gcd|geo)', filename.lower()):
return True
return False | 3022bd165683cde609d1f866c3ce655e84561dc4 | 3,619,944 |
def create_connection(log, mydb):
"""creates a connection to the SQLite db
"""
log.debug("Creating db connection...")
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName(mydb)
if not db.open():
lasterr = db.lastError()
if lasterr.isValid():
log.error("QS... | d59e34d1d9a2848816834ed9a450e10535dfe66d | 3,619,945 |
def overlap_coeff(arr1, arr2):
"""
This function computes the overlap coefficient between the two input
lists/sets.
Args:
arr1,arr2 (list or set): The input lists or sets for which the overlap
coefficient should be computed.
Returns:
The overlap coefficient if both the ... | 3396f28f2e6b21af5dd7bcb00fc07632181c5346 | 3,619,946 |
def _clean_to_gce_name(identifier):
"""
GCE requires the names of all resources to comply with RFC1035. This
function takes an identifier which might not comply with RFC1035 and
attempts to map it into the logical equivalent identifier that does match
RFC1035.
:param unicode identifier: The inp... | b9ffe1a83abe3206b1d57c726f6eb8e95397fc28 | 3,619,947 |
def get_incompatible_fields(ga_ads_service):
"""
Return list of incompatible fields for the metrics and segments
here - we can't directly get incompatible fields, we received list of selectable fields for each fields.
- Hence, to get incompatible fields, we remove selectable from all_fields.
""... | 00752e4b0ae3704fc88e602bb354aba7895501c0 | 3,619,948 |
def update_user(username, infos):
""" Update a user by its username
arg infos: Dict
return True if deleted or False if not found
"""
with session_scope() as session:
user = session.query(User)
ret = user.filter_by(username=username).update(infos)
return bool(ret) | f763a9c75df45b163a3fe72e1b96e1e867d7b74b | 3,619,949 |
def rectplot(x,xpos,ylim=[],**kwargs):
""" plot rectangles on an axis
Parameters
----------
x : ndarray
range of x
xpos : ndarray (nbrect,2)
[[start indice in x rectangle 1, end indice in x rectangle 1],
[start indice in x rectangle 2, end indice in x rectangle 2],
... | ae9f6f1f2d96d3d3e31e4a3c32dec1ddbc940b40 | 3,619,950 |
def del_course_package():
"""
swagger-doc: 'schedule'
required: []
req:
course_id:
description: '课程id'
type: 'string'
type:
description: '1:一级,2:二级,3:三级,4:课包'
type: 'string'
res:
verify_code:
description: 'id'
type: ''
"""
cou... | 4f3dddb610b4b12d606535b983bb0d0e8b47f882 | 3,619,951 |
def run_isfa(img_X, img_Y):
"""
Wrapper of the Slow Feature Analysis algorithm.
:param img_X: First image.
:param img_Y: Second image.
:return:
bcm: Binary change matrix between both images
"""
channel, img_height, img_width = img_X.shape
sfa = ISFA(img_X, img_Y)
# when max... | 7fe37d68d311e523d7b7534044cdad2f71905d7d | 3,619,952 |
def uniform_bar_modes(n=10, bctype=3, npoints=2001,
barparams=np.array([7.31e10, 2747.0, 0.4]),
kl_over_EA = 1000, m_over_rhoAL = 1000):
"""Mode shapes and natural frequencies of Uniform bar/rod.
Parameters
----------
n: int, numpy array
highest mode ... | 90e5205e520a1587733d77ec3e0eb6ba89fc99b7 | 3,619,953 |
import requests
import json
def polling_locations_import_from_master_server(request, state_code):
"""
Get the json data, and either create new entries or update existing
:return:
"""
# Request json file from We Vote servers
messages.add_message(request, messages.INFO, "Loading Polling Location... | 7be3f8acb609103c43591cfbdd40ee231075b28f | 3,619,954 |
def pactfile() -> str:
"""
A sample Pact file as a string.
"""
with open(
PROJECT_ROOT / "test_app" / "pactfiles" / "LibraryClient-Library-pact.json",
"r",
) as f:
return f.read() | c0281fbf065d783f26c63592eb66a8be980056a1 | 3,619,955 |
def grig2dataset(grbs, params_of_interest):
"""
Parameters
----------
grbs : TYPE
DESCRIPTION.
params_of_interest : TYPE
DESCRIPTION.
Returns
-------
ds : TYPE
DESCRIPTION.
"""
params_df = params_of_interest.copy()
# get lat and lon
grb = g... | 4befc23501cb9e0c44dfb8e777f933899524dc08 | 3,619,956 |
import re
def search_song(df, query):
"""
search_song: Fetches the closest matching song from the database
- If multiple are found, return a list of potential songs
:param df: DataFrame object to obtain info of search result
:param query: A query in string format, usually the name ... | cd072523c965dd187c04d2f4901a82dd491c1b75 | 3,619,957 |
from pathlib import Path
def _test_path(fn):
"""Leads to files saved in the data folder
Parameters
----------
fn: str
The whole filename.
Returns
-------
The path of the file in the current working system.
"""
return Path(__file__).parent / "data" / fn | 2f6d7e6b952c40e8fe8cefd1c0c8f0c000e02fdd | 3,619,958 |
def mirror_axis(cube,axis=-2):
"""Mirror one axis of an n-cube.
Parameters
----------
cube : array
Expected shape of cube: (...,nx,...).
axis : int
axis index to be mirrored. Default: -2. Mirroring assumes a
central columns of elements. See 'Returns' section.
Returns
... | dd6519ac49e05d90e58eceb99827c6ac6c044bb9 | 3,619,959 |
def lw(W, Wref=1.0e-12):
"""
Sound power level :math:`L_{w}` for sound power :math:`W` and reference power :math:`W_{ref}`.
:param W: Sound power :math:`W`.
:param Wref: Reference power :math:`W_{ref}`. Default value is :math:`10^{12}` watt.
"""
if type(W) is list:
W = np.array(W)
... | 88b0f41aaccd39629f5cff9a2b825f857b37a9de | 3,619,960 |
def calc_hydrogen_bond_interactions(protein, mol, key_inters_defs, mol_key_inters,
filter_strict=False, exact_protein=False, exact_ligand=False):
""" Calculate H-bond interactions
Parameters:
protein (Molecule): The protein
mol (Molecule): The ligand to test
key_... | 3c6dbfddc631dbbd6f02a57c928bfaaec5ed5ae3 | 3,619,961 |
def yes_or_no(msg, *params, yes=True, certain=False, third_choice=False):
"""Query yes, no or display with message.
Args:
msg (str): Message to be printed out.
yes (bool): Indicates whether the default answer is yes or no.
"""
choices = " [Y/n]?" if yes else " [yes/N]" if certain else ... | 42058dd0ed2fb606444233e13551d6d5f11a90a7 | 3,619,962 |
import pyhees.section4_1_Q
def calc_Q_T_H_rad_d_t_i(Q_max_H_d_t_i, L_H_d_t_i):
"""1時間当たりの暖冷房区画iに設置された放熱器の処理暖房負荷
Args:
Q_max_H_d_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの1時間当たりの暖冷房区画𝑖に設置された放熱器の最大暖房出力
L_H_d_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの1時間当たりの暖房負荷(MJ/h)
Returns:
ndarray: 1時間当たりの暖冷房区画iに設置された放熱... | 2f5bb796ee3c002684db4ab6da225e33cd890e65 | 3,619,963 |
def fetch_all_issue_by_entity_type(project_id,entity_type, entity_id):
"""
find all the issue in a project by entity type and entity id
"""
issues = Issue.query.filter_by(project_id=project_id, entity_type=entity_type,entity_id=entity_id).all()
return list(map(lambda issue: to_json(issue), issues)) | dd7e50136b229b1d7a3569789af5f60d22006d08 | 3,619,964 |
def bivariate_gaussian(true, pred):
"""
Stabilized rank-agnostic bivariate gaussian probability function (pdf)
Returns results of eq # 24 of http://arxiv.org/abs/1308.0850
:param true: truth values with at least [mu1, mu2]
:param pred: values predicted with at least [mu1, mu2, sigma1, sigma2, rho]
... | f1ae2de6e21d24636bbd38b9c0a7212997f81e39 | 3,619,965 |
import base64
def gen_counters_and_filters_from_strategy(s, dimension, before_sleep, trigger_variable_name):
"""
生成counter列表,以及每个counter列表相关联的条件
:return: (counters, filters)
"""
counters = []
collect_counters = []
filters = []
sleep_found = False
for tid, t in enumerate(s.terms)... | e343998a183d7c9201f9c16e499fda7f1b6dcbd0 | 3,619,966 |
def connect():
"""
connect to libvirt
must be called before any other calls in this library!
:return: boolean
"""
global is_init
global conn
if is_init is True:
return True
else:
conn = libvirt.open(None)
if conn is None:
raise Exception("Could not... | 247aeebd77a14fea49e56b02670c596d9b47f64e | 3,619,967 |
def lemmatizeAndStem(word):
"""
Lemmatize and stem a word. Change a verb to its present tense, and reduce the word to its root forms.
Parameters:
word: string
The word the user wants to lemmatize and stem
Returns:
The lemmatized and stemmed word
"""
stemmer = Sno... | ee1da2ccbb1199d4fa8a120cbeba909302fe58c0 | 3,619,968 |
def _magni_test_var_in_globals_func(*args, **kwargs):
"""Test function used in some tests."""
return 'magni_test_var' in globals() | c4209abbc865e65644df919678dd11ddbad24e7e | 3,619,969 |
def overlap(layer, interval):
"""
calculate the thickness for a layer that overlapping with an interval
:param layer: (from_depth, to_depth)
:param interval: (from_depth, to_depth)
:return: the overlapping thickness
"""
res = 0
if layer[0] >= interval[0] and layer[1] <= interval[1]: # c... | f77fdc433f79cf7990416a97cc9edfcbcc860585 | 3,619,970 |
from typing import Callable
from typing import Any
import inspect
from typing import get_type_hints
import functools
def wrap_class_callback(cls: type[ClassCallback]) -> Callable[..., Any]:
"""Function to wrap class callbacks in a function callback equivalent to:
1. Creating an instance of the class
2. Ad... | 765421d3fded62b0ddb64902299d1d8f413500e0 | 3,619,971 |
import zipfile
def _extract_info(archive, info):
"""
Extracts the contents of an archive info object
;param archive:
An archive from _open_archive()
:param info:
An info object from _list_archive_members()
:return:
None, or a byte string of the file contents
"""
... | 3014a9e85077f33522aaf466c9bef3bd020d252b | 3,619,972 |
def _space_all_but_first(s: str, n_spaces: int) -> str:
"""Pad all lines except the first with n_spaces spaces"""
lines = s.splitlines()
for i in range(1, len(lines)):
lines[i] = " " * n_spaces + lines[i]
return "\n".join(lines) | 36da5eb15a9ab5fa473831b5440ffa88495f6cac | 3,619,973 |
import signal
def filter_signal(
x: np.ndarray,
fs: float,
min_freq: float,
max_freq: float,
notch_freqs: list[float],
order: int = 5
) -> np.ndarray:
"""Filter sEMG signal with a Butterworth bandpass filter.
Parameters
----------
x: np.ndarray
sEMG data with shape (n_... | 498129c3231da755e593a7e84e636023ff75d58a | 3,619,974 |
from datetime import datetime
def get_colour(duration, duration_in_traffic):
"""Return a colour to provide an idea of the current traffic.
Gives a visual representation of the amount of traffic on route.
:param duration: A duration string, like "4 mins"
:param duration_in_traffic: A duration in traf... | e6e2f10046d9c08c9480ae38638b304258aab600 | 3,619,975 |
def get_all_translations(rna_sequence, genetic_code):
"""Get a list of all amino acid sequences encoded by an RNA sequence.
All three reading frames of `rna_sequence` are scanned from 'left' to
'right', and the generation of a sequence of amino acids is started
whenever the start codon 'AUG' is found. ... | e5e3fa652f5f170f71d1574465c8d23cc8170013 | 3,619,976 |
from dacy.datasets import female_names, male_names
from dfm.description.match_counter import MatchCounter
from typing import List
from typing import Dict
def get_gender_name_patterns() -> List[Dict[str, list]]:
"""Gets a list of all gendered first names in Denmark from DaCy, and converts to a list of lowercase sp... | aa6c5847be19fb2a51fad7631bf66a1ecf47ed76 | 3,619,977 |
def _transform_coord_to_ref(cubes, ref_coord):
"""Transform coordinates of cubes to reference."""
try:
# Convert AuxCoord to DimCoord if necessary and possible
ref_coord = iris.coords.DimCoord.from_coord(ref_coord)
except ValueError:
pass
if not np.array_equal(np.unique(ref_coord... | b92d73184ee2862196634fd3c630d3c42df89532 | 3,619,978 |
def parse_hue_api_response(response):
"""Take in the Hue API json response."""
data_dict = {} # The list of sensors, referenced by their hue_id.
# Loop over all keys (1,2 etc) to identify sensors and get data.
for key in response.keys():
sensor = response[key]
modelid = sensor['model... | 2e16ae3ded2182f8914dca36f599dcb801b6c286 | 3,619,979 |
def fix_and_score_evidence(validated_evs, datasources_to_datatypes, evidence_manager):
"""take line as a dict, convert into an evidence object and apply a list of modifiers:
fix_evidence, and if valid then score_evidence, extend data and inject loci
"""
left, right = None, None
ev = Evidence(validat... | 2f71e226553bbed4eb801990034cf66e71060c3e | 3,619,980 |
import argparse
import sys
def parse_args():
""" Parse command-line arguments."""
parser = argparse.ArgumentParser(description='''Identify family distribution with unmasked Ensembl ID''')
parser.add_argument(
'-i','--input', nargs='?', type=argparse.FileType('r'),
default=sys.stdin, help='... | 54de56cab2708bb82c32808e7961295f3e427ba4 | 3,619,981 |
def fix_brackets(placeholder: str) -> str:
"""Fix the imbalanced brackets in placeholder.
When ptype is not null, regex matching might grab a placeholder with }
missing. This function fix the missing bracket.
Args:
placeholder: string placeholder of RuntimeParameter
Returns:
Placeholder with re-bal... | 5fa4a83eeca676c58c33038add62a0c5bed7fe8b | 3,619,982 |
def _generate_upsert_sql(mon_loc):
"""
Generate SQL to insert/update for Oracle.
"""
mon_loc_db = [(k, _manipulate_values(v, k in TIME_COLUMNS)) for k, v in mon_loc.items()]
all_columns = ','.join(col for (col, _) in mon_loc_db)
all_values = ','.join(value for (_, value) in mon_loc_db)
updat... | 67e2f91d208ac91d31346b82769f070375ba5c38 | 3,619,983 |
def make_sparse(arr, kind='block', fill_value=nan):
"""
Convert ndarray to sparse format
Parameters
----------
arr : ndarray
kind : {'block', 'integer'}
fill_value : NaN or another value
Returns
-------
(sparse_values, index) : (ndarray, SparseIndex)
"""
arr = np.asarra... | b42e403c91d166732154cf16ea697358389db297 | 3,619,984 |
def preprocess_image(image, labels, prediction=False):
"""
format for tf model + open image and prepare it for resnet
"""
if prediction==False:
image = tf.io.read_file(image)
image = tf.io.decode_image(image, channels=3,expand_animations = False)
image = tf.cast(image, tf.float32) / ... | 204dc32dd9d4b6288382c4bfb67e1ae3511e51a6 | 3,619,985 |
def application(environ, start_response):
"""Do something fun"""
form = parse_formvars(environ)
huc12 = form.get("huc12", "000000000000")[:12]
scenario = int(form.get("scenario", 0))
start_response("200 OK", [("Content-type", "image/png")])
return [make_plot(huc12, scenario)] | ff35c425e43bef3527416f2e6781af0c91fde48b | 3,619,986 |
import logging
def all_peaks (timelags, std_score_dict, structural_delay_dict=None, minimal_synapse_delay=0):
"""
Return the largest standard score peak for each functional connection, rejecting false positives.
Implemented is the forward direction, that is looking for peaks at post-synaptic time lags
... | 032d9f7922a53d158857215dd506d17a1489e32a | 3,619,987 |
from pathlib import Path
def run(args):
"""
Run GPROF-NN algorithm.
Args:
args: The namespace object provided by the top-level parser.
"""
mp.set_start_method("spawn")
#
# Check and load inputs.
#
model = Path(args.model)
if not model.exists():
LOGGER.error("... | 2ef3f90e797aaf52fc22a59e62357ac22c3c9426 | 3,619,988 |
def create_primitive_set(lib):
"""Create a DEAP primitive set from a dso.libraryLibrary."""
pset = gp.PrimitiveSet("MAIN", len(lib.input_tokens))
rename_kwargs = {"ARG{}".format(i): i for i in range(len(lib.input_tokens))}
for k, v in rename_kwargs.items():
# pset.renameArguments doesn't actua... | 0c1a74b590b1421c49e55d672acdba3a6576a52c | 3,619,989 |
def segmentation_to_rgb(seg_im, N, colors=None):
"""
Helper function to visualize segmentations as RGB frames.
NOTE: assumes that geom IDs go up to N at most - if not,
multiple geoms might be assigned to the same color.
"""
# ensure all values lie within [0, N]
seg_im = np.mod(seg_im, N)
... | 6381af3b0760a045ef7a0d913e9427b60323bb3c | 3,619,990 |
def a_1d_worse(a_1d):
"""a_1d worsened by constant offset."""
return a_1d + OFFSET | 899b57007f0a939d380d6e5bd9f2d3e2ef4dffaf | 3,619,991 |
def ParseRangeHeader(range_header):
"""Parse HTTP Range header.
Args:
range_header: A str representing the value of a range header as retrived
from Range or X-AppEngine-BlobRange.
Returns:
Tuple (start, end):
start: Start index of blob to retrieve. May be negative index.
end: None or ... | ad37fd1532edd9519073c93aa73402b3c7d0a404 | 3,619,992 |
from pathlib import Path
import os
def separate_cifs(filePath: str):
"""
Separate catenated CIF into individual datablocks within a temporary
directory.
Args
----
filePath: str
path to input file.
"""
fp = Path(filePath)
# create a temporary dictionary.
if no... | 829a4e20ae34bccab0caac341f5d601939d10ddd | 3,619,993 |
def create_router_ospf(tgen, topo=None, input_dict=None, build=False, load_config=True):
"""
API to configure ospf on router.
Parameters
----------
* `tgen` : Topogen object
* `topo` : json file data
* `input_dict` : Input dict data, required when configuring from testcase
* `build` : O... | c85dd365dfa48c61d7c9e7e57dcd3dac7d598f6d | 3,619,994 |
def _get_required_consent_subjects() -> set[Subject]:
"""Return the consent subjects required for this brand."""
return consent_subject_service.get_subjects_required_for_brand(g.brand_id) | f330ab6abee82e3c0b88a723155a8e30355f31ed | 3,619,995 |
from typing import Any
from typing import List
def init_args(
cls: Any,
) -> List[str]:
""" Return the __init__ args (minus 'self') for @cls
Args:
cls: class, instance or callable
Returns:
The arguments minus 'self'
"""
# This looks insanely goofy, but seems to literally be th... | 2d867049f3c1f4937d0d8a7042315644cef219ae | 3,619,996 |
def analyse_start(deal: Deal, declarer_is_first: bool = False) -> int:
"""
Calculate the most tricks declarer can make.
:param deal: The deal to analyse
:param declarer_is_first: The algorithm assumes that the person who leads is to the left
of the declarer (as would be the case with the first card led
to a ha... | 7391fd3482c673d019318a3f9f61342784911526 | 3,619,997 |
import re
def create_url(url):
"""
modifying the given url so that it returns JSON data when
we do a GET requests later in this script
"""
# extract the branch name from the given url (e.g master)
branch = re.findall(r"\/tree\/(.*?)\/", url)[0]
api_url = url.replace("https://github.com", "https://api.githu... | 682343d1e7462ef224865b659357716e55cd22cd | 3,619,998 |
import secrets
def generate_token_urlsafe(unique=False, nbytes=32):
"""Generate an URL-safe random token."""
return secrets.token_urlsafe(nbytes=nbytes) | 5bdab6879f241a7459653e5ec363110263f0c171 | 3,619,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.