content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def is_num(a: Any) -> bool:
"""Checks if the specified Python object is a number (int, float, long, etc)."""
return isinstance(a, numbers.Number) | 5,291,900 |
def format_docstring(obj: ObjType) -> Optional[str]:
"""Format the docstring with bold docstring sections.
Parameters:
- `obj`: The python object to get the docstring from.
Returns:
- Bold formatted docstring sections of docstring or `None`.
"""
docstring = inspect.getdoc(obj)
if docstring:
docs... | 5,291,901 |
def get_branch() -> OneOf[Issue, str]:
"""Return a `OneOf` object containing the branch name."""
return subprocess.eval_cmd('git rev-parse --abbrev-ref HEAD') | 5,291,902 |
def test_scalar_likelihood_quadrature_variational_expectation(likelihood_setup, mu, var):
"""
Where quadrature methods have been overwritten, make sure the new code
does something close to the quadrature.
"""
likelihood, y = likelihood_setup.likelihood, likelihood_setup.Y
F1 = likelihood.variati... | 5,291,903 |
def spectrum_process(
data,
sfreq,
cfreq,
toffset,
modulus,
integration,
bins,
log_scale,
zscale,
detrend,
title,
clr,
):
"""
Process data into a form useable for spectrum and spectrogram graphs.
Break spectrum by modulus and display each blo... | 5,291,904 |
def _resnet_cifar10(name, block, layers, pretrained, **kwargs):
"""Constructs a ResNet model for CIFAR-10 classification.
Args:
name: A string. Name of the ResNet model. Choose from 'resnet20', 'resnet32', 'resnet44', 'resnet56', 'resnet110', 'resnet1202'
block: The building block class.
... | 5,291,905 |
def cmd_project_build_stat(mixcli: MixCli, latest: bool = False, version: bool = False, **kwargs: str):
"""
Default function when MixCli project get command is called. Processing concept list command.
:param version: Only include the build version(s)
:param mixcli: MixCli, a MixCli instance
:param ... | 5,291,906 |
def cli(config):
"""
Management gitlab namespaces.
"""
click.entry("Calling sub user") | 5,291,907 |
def get_all_users():
""" For example:
>>> get_all_users()
[<User 1>, <User 2>, <User 3>, <User 4>, <User 5>, <User 6>,
<User 7>, <User 8>, <User 9>, <User 10>,<User 12>, <User 12>]
"""
return User.query.all() | 5,291,908 |
def run(ctx, module, interface, list, help):
"""Run a Nipype Interface.
Examples:\n
nipypecli run nipype.interfaces.nipy --list\n
nipypecli run nipype.interfaces.nipy ComputeMask --help
"""
import argparse
from .utils import add_args_options
from ..utils.nipype_cmd import run_instance
... | 5,291,909 |
def strftime(dt, *args, **kwargs):
"""Version of datetime.strftime that always uses the C locale.
This is because date strings are used internally in the database, and
should not be localized.
"""
if hasattr(dt, 'strftime'):
return dt.strftime(*args, **kwargs)
else:
return time.... | 5,291,910 |
def create_swag_from_ctx(ctx):
"""Creates SWAG client from the current context."""
swag_opts = {}
if ctx.type == 'file':
swag_opts = {
'swag.type': 'file',
'swag.data_dir': ctx.data_dir,
'swag.data_file': ctx.data_file
}
elif ctx.type == 's3':
... | 5,291,911 |
def main():
"""
Synthesize a program and then try it on BarrelfishOS.
"""
# load arguments from CLI
args = parse_args()
# tag synthesizer version
version = '%s_%s' % (args.synth.lower(), int(time.time()))
print log('Starting synthesizer test version=%s' % version)
msg = 'Loading s... | 5,291,912 |
def install_libuca(path: str, verbose: bool = True) -> dict:
"""
Installs the libuca repository into the given *path*. Returns a dict which contains some information about
the installation process.
The returned dict contains the following items:
- success: boolean value of whether or not the instal... | 5,291,913 |
def _Case0_(start, end):
""" Case0 experiment code """
def _set_(key, val, desc, units, format="f8", shape=("ntimes","nalts")):
p = rootgrp.createVariable(key,format, shape)
p.description = desc
p.uints = units
p[:] = val
return
fname = "data/sim/case0.nc.gz"
ev,... | 5,291,914 |
async def test_import_single_instance(hass, discovery_flow_conf):
"""Test import doesn't create second instance."""
flow = config_entries.HANDLERS["test"]()
flow.hass = hass
flow.context = {}
discovery_flow_conf["discovered"] = True
MockConfigEntry(domain="test").add_to_hass(hass)
result = ... | 5,291,915 |
def indent_empty_lines(s: str, compiler: CommandCompiler) -> str:
"""Indents blank lines that would otherwise cause early compilation
Only really works if starting on a new line"""
initial_lines = s.split("\n")
ends_with_newline = False
if initial_lines and not initial_lines[-1]:
ends_with_... | 5,291,916 |
def _get_config_kwargs(**kwargs):
"""Get the subset of kwargs which pertain the config object"""
valid_config_kwargs = ["websockets", "cipher", "proxy_options", "keep_alive"]
config_kwargs = {}
for kwarg in kwargs:
if kwarg in valid_config_kwargs:
config_kwargs[kwarg] = kwargs[kwarg... | 5,291,917 |
def test_main_info_with_tcp_interface(capsys):
"""Test --info"""
sys.argv = ['', '--info', '--host', 'meshtastic.local']
Globals.getInstance().set_args(sys.argv)
iface = MagicMock(autospec=TCPInterface)
def mock_showInfo():
print('inside mocked showInfo')
iface.showInfo.side_effect = mo... | 5,291,918 |
def test_parcel_parcel_density_pseudoadiabatic_initially_saturated():
"""Test Parcel.parcel_density, saturated parcel, pseudoadiabatic."""
height = [2000, 1000, 0]*units.meter
z_init = 3000*units.meter
t_initial = -2*units.celsius
q_initial = 0.004751707262581661*units.dimensionless
l_initial = ... | 5,291,919 |
def _configure_logging(config):
"""Configure the message broker's logging system interface.
:param config: Nowcast system configuration.
:type config: :py:class:`nemo_nowcast.config.Config`
"""
# Initialize exception logging to Sentry with client DSN URL from SENTRY_DSN envvar;
# does nothing i... | 5,291,920 |
def get_test_lines(test_case, test_params):
"""
Create a list of strings corresponding to the lines in a single test case.
Uses TensorFlow to compute the expected results for the given parameters,
and provides the code to call the test fixture to run the test.
"""
channel_idx = -1 if test_param... | 5,291,921 |
def _g1(x,f1,a,f2,b):
"""g1: exponential decay"""
return a * (b*np.exp(-f1*x) + (1-b) * np.exp(-f2*x)) | 5,291,922 |
def mos():
"""Margin of Safety"""
a = float(input("Please Enter Sales Price Per Unit: "))
b = float(input("Please Enter Variable Cost Per Unit: "))
bb = float(input("Please Enter Total Fixed Cost: "))
c = float(input("Please Enter Expected Sales: "))
d = float(a)-float(b)
e = float(bb... | 5,291,923 |
def getLocationInfo(field, response={}):
""" Get location info from field
:param field: field row data from influxdb
:param response: initial response body
:return: location info response
"""
coords = pgh.decode(field['geo'])
response['locationID'] = field['time']
response['georeferencedBy'] = 'CanAirIO... | 5,291,924 |
def alpha(flux1, flux2, freq1=ufloat(144e6, 24e6),
freq2=ufloat(1400e6, 0)):
"""Get spectral index with error. Default is LDR2 and FIRST.
"""
return log(flux1 / flux2) / log(freq1 / freq2) | 5,291,925 |
def iter_all_files(data_dir, extensions=None, hidden=False):
"""Scan all files with some extensions."""
if extensions is not None:
extensions = [e.lower() for e in extensions]
for root, _, files in os.walk(data_dir, topdown=False, followlinks=True):
if not hidden and is_hidden(root):
... | 5,291,926 |
def decline_pr(script, project_key, repo_slug, pr_id, pr_version=0):
"""
Decline a PR
:param script: a TestScript instance
:type script: TestScript
:param project_key: The project key
:type project_key: str
:param repo_slug: The repo slug
:type repo_slug: str
:param pr_id: The PR id ... | 5,291,927 |
def test_selector_with_cuts () :
"""Use selector-with-cuts to loop over good entries in the chain
- loop over the good entries in the chain using selector
- fill dataset
"""
logger = getLogger("test_selector_with_cuts")
from ostap.fitting.pyselectors import SelectorWithCuts
... | 5,291,928 |
async def test_component_platform_not_found_2(hass):
"""Test errors if component or platform not found."""
# Make sure they don't exist
files = {YAML_CONFIG_FILE: BASE_CONFIG + "light:\n platform: beer"}
with patch("os.path.isfile", return_value=True), patch_yaml_files(files):
res = await async... | 5,291,929 |
def register(fixed=None, moving=None, dim=None, lam=1., loss='mse',
optim='ogm', hilbert=None, max_iter=500, sub_iter=16,
lr=1, ls=6, steps=8, plot=False, klosure=RegisterStep,
velocity=None, kernel=None, verbose=True, **prm):
"""Diffeomorphic registration between two images u... | 5,291,930 |
def geocode_addr(in_path, type, start, end, geo_coords):
""" geocode_addr
Input:
<str> in_path, relative path to data file
<str> type, "AG" for allGas, otherwise gasBuddy
<int> start, line number of data file to start reading from
<df> geo_coords, ge... | 5,291,931 |
def get_nodes(api_url=None, verify=False, cert=list()):
"""
Returns info for all Nodes
:param api_url: Base PuppetDB API url
"""
return utils._make_api_request(api_url, '/nodes', verify, cert) | 5,291,932 |
def git_untracked_files(path='', debug=False, timeout=None, exception=True,
show=False):
"""Return a list of any local files that are not tracked in the git repo
- path: path to git repo, if not using current working directory
- debug: if True, insert breakpoint right before subproc... | 5,291,933 |
def main():
"""Will ask you about yellow and green letters"""
# query yellow letters and their positions
yel = {}
for i in range(1, 6):
if input(f"Yellow letter(s) on position {i}? y/n ").lower() == "y":
yel[i] = cln(input(f"Which letter(s)? "))
# query green letters and their ... | 5,291,934 |
def read_sm_def (
sm_def_file: str
) -> dict:
"""
Reads state machine definition from a file and returns it as a dictionary.
Parameters:
sm_def_file (str) = the name of the state machine definition file.
Returns:
sm_def_dict (dict) = the state machine definition as a dictionary.
... | 5,291,935 |
def exec_cmd(ctx: Context, user: str, container: str, command: tuple, tty: bool):
"""See command Help."""
ctx.obj['STAKKR'].init_project()
ctx.obj['CTS'] = get_running_containers_names(ctx.obj['STAKKR'].project_name)
if ctx.obj['CTS']:
click.Choice(ctx.obj['CTS']).convert(container, None, ctx)
... | 5,291,936 |
def print_version_and_exit():
"""Print version and copyright info to stderr and exit with 0."""
sys.stderr.write(
"logtailor version {}. Copyright 2018 Stefan Braun.\n".format(__version__)
)
sys.exit(0) | 5,291,937 |
def _fit_coil_order_dev_head_trans(dev_pnts, head_pnts):
"""Compute Device to Head transform allowing for permutiatons of points."""
id_quat = np.concatenate([rot_to_quat(np.eye(3)), [0.0, 0.0, 0.0]])
best_order = None
best_g = -999
best_quat = id_quat
for this_order in itertools.permutations(np... | 5,291,938 |
def test_eap_proto_gpsk(dev, apdev):
"""EAP-GPSK protocol tests"""
def gpsk_handler(ctx, req):
logger.info("gpsk_handler - RX " + req.encode("hex"))
if 'num' not in ctx:
ctx['num'] = 0
ctx['num'] = ctx['num'] + 1
if 'id' not in ctx:
ctx['id'] = 1
c... | 5,291,939 |
def test_group_options_are_passed_to_the_installer(
tester: "CommandTester", mocker: "MockerFixture"
):
"""
Group options are passed properly to the installer.
"""
mocker.patch.object(tester.command.installer, "run", return_value=1)
tester.execute("--with foo,bar --without baz --without bim --o... | 5,291,940 |
def render_into_template(
screenshots: Dict[str, Image.Image],
template: Image.Image,
) -> Image.Image:
"""Place all the screenshots, into the correct place."""
# Place all the screenshots
for device, screenshot in screenshots.items():
template.paste(screenshot, SCREENSHOT_OFFSETS[device])
... | 5,291,941 |
def _process_text(text):
"""
Pre-process Text
"""
text = unicodedata.normalize("NFKD", text) # Normalize
text = '\n'.join(text.splitlines()) # Let python take care of unicode break lines
# Take care of breaklines & whitespaces combinations due to beautifulsoup parsing
text = r... | 5,291,942 |
def get_model_effectors(file_path, sheet_name):
"""
Gets the effectors and respective references for each reaction on the kinetics1 sheet and returns a dictionary
{rxn_id : ([effector_list], [effector_references])}. Entry i in effector_references contains all references as a
string for effector i in... | 5,291,943 |
def account(request, user_id):
"""
:param request:
:return:
"""
if not request.user.is_superuser:
return HttpResponseRedirect(reverse('index'))
error_messages = []
user = User.objects.get(id=user_id)
user_insts = UserInstance.objects.filter(user_id=user_id)
instances = Inst... | 5,291,944 |
def create_hash_key(index: str, params: str) -> str:
"""
:param index: индекс в elasticsearch
:param params: параметры запроса
:return: хешированый ключ в md5
"""
hash_key = hashlib.md5(params.encode()).hexdigest()
return f"{index}:{hash_key}" | 5,291,945 |
def create_keywords(client, customer_id, ad_group, keywords_to_add):
"""Creates new keywords on a given ad group.
Args:
client: A google.ads.google_ads.client.GoogleAdsClient instance.
customer_id: (str) Customer ID associated with the account.
ad_group: A google.ads.google_ads.v4.types... | 5,291,946 |
def _estimate_mmd2_linear_time(latent, i1, i2, sigma=None):
"""From Gretton et. al. 2012"""
if sigma is None:
sigma = estimate_median_sigma(latent)
A = -0.5 / sigma
n = min(len(i1), len(i2))
m = n // 2
assert m > 0
k = lambda x,y: np.exp(A * np.sum(np.power(x-y,2)))
h = lambda x1,y1,x2,y2: k(x1,x2)+k(y1,y2)-k... | 5,291,947 |
def CreateVotes(blockable, count, **kwargs):
"""Creates multiple Vote entites for the given Blockable.
Args:
blockable: The Blockable to create Votes for.
count: int, The number of Votes to create.
**kwargs: dict, Any Vote properties to customize.
Returns:
The newly-created Vote entities.
"""
... | 5,291,948 |
def check_paths(import_path, export_path):
"""
Inspects for file errors in import and export paths.
Args:
import_path (string): path to input file.
export_path (string): path to output file.
Returns:
None.
Raises:
FileNotFoundError: file does not exist on input pat... | 5,291,949 |
def compute_codes_requiring_type(handle_data, types_to_codes, registry=None):
"""Compute a DictOfStringSets of return codes to a set of input types able
to provide the ability to generate that code.
handle_data is a HandleData instance.
d is a dictionary of input types to associated return codes(same f... | 5,291,950 |
def delta_disk_neighbors(
poses: np.ndarray,
agent: int,
delta: float) -> np.ndarray:
"""Return the agents within the 2-norm of the supplied agent.
NOTE: The does not including the agent itself!
Parameters
----------
poses : np.ndarray
A `3xN` numpy array representi... | 5,291,951 |
def categorize_answers(df, question, answer_column):
""" Extract a question answered and count different answers.
Parameters
----------
df : Pandas Dataframe
Dataframe containing questionnaire data
question : str
question id
answer_column : str
column containing the an... | 5,291,952 |
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry) -> bool:
"""Set up Verisure from a config entry."""
coordinator = VerisureDataUpdateCoordinator(opp, entry=entry)
if not await coordinator.async_login():
raise ConfigEntryAuthFailed
entry.async_on_unload(
opp.bus.async... | 5,291,953 |
def get_config_path():
"""
Return the full path to the config file.
"""
# first priority: config file at ~/cadgan_resources/settings.ini
home_dir = os.path.expanduser("~")
config_dir = os.path.join(home_dir, 'cadgan_resources')
at_home_config = os.path.join(config_dir, "settings.ini")
if... | 5,291,954 |
def p_effect_def(p):
"""effect_def : ACT_EFF mixed_predicate_list"""
p[0] = p[2] | 5,291,955 |
def get_spreadsheet(user, spreadsheet_id):
"""
Get spreadsheet
:type user: django.contrib.auth.models.User
:param user: User of spreadsheet
:type spreadsheet_id: str
:param spreadsheet_id: Spreadsheet ID of spreadsheet to get
:rtype: Google `Spreadsheet` resource, int
:return: Spread sh... | 5,291,956 |
def GetFileSha1(file_path):
"""Returns the SHA1 checksum of the file given (base64 encoded)."""
return base64.b64encode(GetFileHashes(file_path, do_sha1=True)['sha1']) | 5,291,957 |
def test_scm_extended(dut):
"""
Read the 5 additional registers of the SCM and compares the response
with the desired value
"""
access = RegAccess(dut)
yield _init_dut(dut)
dut._log.info("Check contents of SYSTEM_VENDOR_ID")
yield access.assert_reg_value(MODULE_DI_ADDRESS, SENDER_DI_AD... | 5,291,958 |
def quarterly_visits(customer_logins):
"""
Small subroutine to return quarterly visits from an amount of
customer login data.
"""
visits = np.zeros(4)
customer_visits = len(customer_logins.index)
# 6 is the size of a part of day, integer division gives a
# number between 0 and 3
vi... | 5,291,959 |
def connect_UDP(host, port, waitTimeout=None):
"""
Connect RPC server via UDP. Returns C{t.i.d.Deferred} that will
callback with C{protocol.MsgpackDatagramProtocol} object.
@param host: IP address of host.
@type host: C{str}
@param port: port number.
@type port: C{int}
@param waitTimeou... | 5,291,960 |
def get_root_url():
"""Return the root URL for this resource."""
# path = request.path
# path = path[1:].split('/')
# path = '/'.join(path[:2])
# return request.url_root + path
return request.url_root | 5,291,961 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/2017-07-01<br/>"
f"/api/v1.0/2017-07-01/2017-07-10<br/>"
) | 5,291,962 |
def HashFileContents(filename):
"""Return the hash (sha1) of tthe contents of a file.
Args:
filename: Filename to read.
Returns:
The sha1 of a file.
"""
hasher = hashlib.sha1()
fh = open(filename, 'rb')
try:
while True:
data = fh.read(4096)
if not data:
break
hasher.... | 5,291,963 |
def hello_airflow(execution_date: dt.datetime, argument=None, **kwargs):
"""
Print the execution date (and other variables passed from airflow).
Args:
execution_date (dt.datetime): the time of the dag's execution (passed by airflow)
argument: an example argument
**kwargs: other vari... | 5,291,964 |
def get_moyenne(points_3D, indice):
"""Calcul la moyenne d'une coordonnée des points,
la profondeur est le 3 ème = z, le y est la verticale
indice = 0 pour x, 1 pour y, 2 pour z
"""
somme = 0
n = 0
for i in range(17):
if points_3D[i]:
n += 1
somme += points_3... | 5,291,965 |
def simplify_list_item_mathematical(list_item_mathematical: list) -> Real:
"""
Apply mathematical operations on the operands and reduce to 1 value
Not Used
:param list_item_mathematical: list of mathematical items
:return: value
"""
# Current value
value = None
# Current Operator... | 5,291,966 |
def load(whitelist: Optional[Set[str]] = None) -> None:
"""Load the database.
:param whitelist: If specified, only load ontologies with this set of prefixes
"""
drop_all()
create_all()
mr = registries.get_metaregistry()
prefix_to_resource: Dict[str, Resource] = {}
for _, entry in sort... | 5,291,967 |
def assert_almost_equal(actual: numpy.float64, desired: float, decimal: int):
"""
usage.matplotlib: 3
usage.networkx: 8
usage.scipy: 164
usage.skimage: 35
usage.sklearn: 109
usage.statsmodels: 286
"""
... | 5,291,968 |
def ca_authorize_key(h_session, h_object, auth_data):
"""
User authorizes key within session or access for use
:param h_session: session handle
:param object: key handle to authorize
:param auth_data: authorization byte list, e.g. [11, 12, 13, ..]
:return: Ret code
"""
if auth_data is n... | 5,291,969 |
def code_to_md(source, metadata, language):
"""
Represent a code cell with given source and metadata as a md cell
:param source:
:param metadata:
:param language:
:return:
"""
options = []
if language:
options.append(language)
if 'name' in metadata:
options.append... | 5,291,970 |
def get_schema(is_ipv6, octet):
"""Get the template with word slots"""
new_line = '\n'
period = '.'
space = ' '
non_words = [new_line, period, space]
if is_ipv6:
schema = [octet, octet, 'and', octet, octet, new_line, octet, octet,
octet, octet, octet, octet, octet, peri... | 5,291,971 |
def zone_from_longitude(phi):
"""Return the difference between UT and local mean time at longitude
'phi' as a fraction of a day."""
return phi / deg(360) | 5,291,972 |
def get_version(arg):
""" Get version.
"""
if isinstance(arg, pymongo.MongoClient):
return arg.server_info()['version']
elif isinstance(arg, str) or isinstance(arg, unicode):
host, port = parse_hostportstr(arg)
with pymongo.MongoClient(host, port, connect=True, serverSelectionTim... | 5,291,973 |
def impute_features(feature_df):
"""Imputes data using the following methods:
- `smoothed_ssn`: forward fill
- `solar_wind`: interpolation
"""
# forward fill sunspot data for the rest of the month
feature_df.smoothed_ssn = feature_df.smoothed_ssn.fillna(method="ffill")
# interpolate between ... | 5,291,974 |
def module_fixture():
"""Mock a module."""
return MockModule("test") | 5,291,975 |
def visualize(model, # type: thelper.typedefs.ModelType
task, # type: thelper.typedefs.TaskType
loader, # type: thelper.typedefs.LoaderType
draw=False, # type: bool
color_map=None, # type: Optional[Dict[int, np.nd... | 5,291,976 |
def update_user(username):
""" Update attributes for a single user. Only users with 'role' admin
can update users.
Args:
password(str): user's password
role(int): user's role
Returns:
success(bool): successfully updated
"""
if not g.user.is_authe... | 5,291,977 |
def dprint(*args):
"""Print to both stdout and stderr at the same time to allow for stdout redirection while still seeing the output in real time, rather than buffered like with tee"""
print(*args)
print(*args, file=sys.stderr
) | 5,291,978 |
def loss_calc_pose(out, label, gpu0):
"""
This function returns loss for the pose auxilary task
"""
# out shape batch_size x channels x h x w -> batch_size x channels x h x w
# label shape h x w x 1 x batch_size -> batch_size x 1 x h x w
label = torch.from_numpy(label).long()
label = Variab... | 5,291,979 |
def get_user_input() -> Tuple[str, float]:
"""Ask the user for a ticker and the number of years backward to go, then
return the user's answers.
Returns:
Tuple[str, float]: the ticker and number of years backward to go
"""
ticker = input('Ticker: ').upper()
years_backward = float(input(... | 5,291,980 |
def test_pop_empty_stack():
"""Test that pop on a empty stack throws an IndexError."""
from stack import Stack
s = Stack()
with pytest.raises(IndexError):
s.pop() | 5,291,981 |
async def test_setup_oppio_no_additional_data(opp, aioclient_mock):
"""Test setup with API push default data."""
with patch.dict(os.environ, MOCK_ENVIRON), patch.dict(
os.environ, {"OPPIO_TOKEN": "123456"}
):
result = await async_setup_component(opp, "oppio", {"oppio": {}})
assert re... | 5,291,982 |
def retrieve_text_document(image, default_lang=ALL_LANGUAGE) -> TextDocument:
"""
Retrieves text with all possible languages, detects the exact language and retrieves the
text again, but with the correct language.
Should only be used for medium or large images
"""
text = pytesseract.image_to_s... | 5,291,983 |
def test_extract_json_object():
"""It should remove all the characters after the last }"""
assert extract_json_object(' ^[0m {"key1": true } ^[0m') == '{"key1": true }'
assert extract_json_object('{"key1": true }') == '{"key1": true }' | 5,291,984 |
def flow_convolve_nearest(data, flow_func, structure=None, wrap=False, function=None, dtype=None, debug=False, **kwargs):
"""
A function to compute a Semi-Lagrangian convolution using the nearest neighbour method. This can be performed
faster as no interpolation is required.
Input:
data:
... | 5,291,985 |
def get_tests(suite):
"""Generates a sequence of tests from a test suite
"""
for item in suite:
try:
# TODO: This could be "yield from..." with Python 3.3+
for i in get_tests(item):
yield i
except TypeError:
yield item | 5,291,986 |
def login_view(request):
"""Provide the login view and functionality."""
if request.user.is_authenticated():
return redirect(reverse('index'))
form = UserLoginForm(request.POST or None, request=request)
next_page = request.GET.get('next', reverse('index'))
if form.is_valid():
if re... | 5,291,987 |
def chi2_bin(df: pd.DataFrame, x: str, y: str, bins=5, init_bins=100, init_method='qcut', init_precision=3,
print_process=True):
"""
卡方分箱
:param df: 数据集
:param x: 待分箱特征名称
:param y: 目标变量的名称
:param bins: 最终的分箱数量
:param init_bins: 初始化分箱的数量,若为空则钚进行初始化的分箱
:param init_method: 初始化... | 5,291,988 |
def test_board_group_iteration():
"""Test that we can iterate over a BoardGroup."""
board_group = BoardGroup(MockBoard, TwoBoardsMockBackend())
count = 0
for b in board_group:
assert type(b) == MockBoard
count += 1
assert count == 2 | 5,291,989 |
def cache_control_expires(num_hours):
"""
Set the appropriate Cache-Control and Expires headers for the given
number of hours.
"""
num_seconds = int(num_hours * 60 * 60)
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
response = func(request, *... | 5,291,990 |
def critical_struct(obj, label="Object"):
"""Critical level dict log."""
if wx.Log.GetLogLevel() <= wx.LOG_FatalError:
_log_struct(obj, critical, label) | 5,291,991 |
def get_widget_at_mouse():
"""
Get the widget under the mouse
:return: variant, QWidget || None
"""
current_pos = QtGui.QCursor().pos()
widget = QApplication.widgetAt(current_pos)
return widget | 5,291,992 |
def load_multitracks(track_list):
"""Load a list of multitracks.
Parameters
----------
track_list : list
List of track ids in format 'Artist_Title'
Returns
-------
multitracks : dict
List of multitrack objects.
Examples
--------
>>> track_list = ['ArtistName1_T... | 5,291,993 |
def build_can_scraper_dataframe(
data_by_variable: Dict[ccd_helpers.ScraperVariable, List[float]],
location=DEFAULT_LOCATION,
location_type=DEFAULT_LOCATION_TYPE,
location_id=DEFAULT_LOCATION_ID,
start_date=DEFAULT_START_DATE,
source_url: Union[None, str, Iterable[str]] = None,
source_name: ... | 5,291,994 |
def getNetWorkTXRXValue(networkCardNum, valueType):
"""
function : Check Bond mode
input : int, String
output : int
"""
cmd = "/sbin/ethtool -g %s | grep '%s:' | tail -n 2" % (networkCardNum,
valueType)
(status, output) = subproces... | 5,291,995 |
def process_text():
"""Remove emoticons, numbers etc. and returns list of cleaned tweets."""
data = pull_tweets()
regex_remove = "(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)|^RT|http.+?"
stripped_text = [
re.sub(regex_remove, '',
tweets).strip() for tweets in data
]
re... | 5,291,996 |
def one_gate_range(min_qubits, max_qubits, num_threads):
"""Execute test_gates_static once for each posible number in range."""
for nq in range(min_qubits, max_qubits + 1):
test_gates_static(nq, num_threads) | 5,291,997 |
async def reload(ctx):
"""Reloads all modules.
This command requires the Manage Server permission.
"""
# ctx.bot.unload_extension('music')
ctx.bot.unload_extension('chatbot')
# ctx.bot.load_extension('music')
ctx.bot.load_extension('chatbot')
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
print(... | 5,291,998 |
def concat(input_op_nodes: list, output_name: str, column_names: [list, None] = None):
"""
Define Concat operation.
:param input_op_nodes: List of parent nodes for the node returned by this method.
:param output_name: Name of returned Concat node.
:param column_names: List of output relation column... | 5,291,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.