content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def make_wc2018_dataset(
matches_features: pd.DataFrame,
team_features: pd.DataFrame,
wc2018_qualified: pd.DataFrame):
"""
Simulating the Tournament
With a trained model at our disposal, we can now run tournament simulations on it.
For example, let's take the qualified t... | 5,314,200 |
def test_get_validator_keys(s0_validator):
"""
Note that v1 & v2 have the same responses.
Use shard 0 endpoint, NOT beacon endpoint as we are checking with `s0_validator`
"""
reference_response = [
"65f55eb3052f9e9f632b2923be594ba77c55543f5c58ee1454b9cfd658d25e06373b0f7d42a19c84768139ea294f... | 5,314,201 |
def calcular_indices(arr, clases_posibles):
"""
Calcula los indices positivos y negativos de un arreglo
En la primer posicion de cada elemento se espera la clase real.
En la segunda posicion de cada elemento se espera la clase calculada.
"""
dic = []
for clase in clases_posibles:
ind_clase = cal... | 5,314,202 |
def create_app():
"""Creating and configuring an instance of the Flask application"""
app = Flask(__name__)
@app.route('/')
def root():
"""Base view."""
return 'TODO - part 2 and beyond!'
return app | 5,314,203 |
def _box_faces(image):
""" Add borders to all detected faces """
for face in image.faces:
_box_face(image, face)
return image | 5,314,204 |
def interact_with_prescribed_behavior(agent = 'prescribed_behavior', end_time = '130000'):
"""
TODO: Please put prescribed behavior in this function.
Parameters
----------
agent: str
not important paramter just for keeping the same format with interact_with_learning_agent
end_t... | 5,314,205 |
def start_flask_gunicorn(path, app, port, workers):
"""Configures and starts gunicorn"""
stop_flask()
path = path.rstrip('/')
info = path.rsplit('/', 1)
main = info[1].split('.', 1)[0]
if os.path.exists(info[0] + '/run.py'):
os.remove(info[0] + '/run.py')
render(source='gunicorn.ws... | 5,314,206 |
def validate_parameters(value, ctx=None): # pylint: disable=unused-argument
"""Validate 'parameters' dict."""
parameters = value.get_dict() | 5,314,207 |
def get_logger(name, is_task_logger=True):
"""Return a logger with the given name.
The logger will by default be constructed as a task logger. This will
ensure it contains additional information on the current task name and task
ID, if running in a task. If executed outside of a task, the name name and... | 5,314,208 |
def get_stratified_gene_usage_frequency(ts = None, replace = True):
"""
MODIFIES A TCRsampler instance with esitmates vj_occur_freq_stratified by subject
Parameters
----------
ts : tcrsampler.sampler.TCRsampler
replace : bool
if True, ts.v_occur_freq is set to ts.v_occur_freq_stra... | 5,314,209 |
def _calculateSvalues(xarr, yarr, sigma2=1.):
"""Calculates the intermediate S values required for basic linear regression.
See, e.g., Numerical Recipes (Press et al 1992) Section 15.2.
"""
if len(xarr) != len(yarr):
raise ValueError("Input xarr and yarr differ in length!")
if len(xarr) <= ... | 5,314,210 |
def existing_deployment_openshift(
runner: Runner, deployment_arg: str, expose: PortMapping,
add_custom_nameserver: bool
) -> Tuple[str, Optional[str]]:
"""
Handle an existing deploymentconfig by doing nothing
"""
runner.show(
"Starting network proxy to cluster using the existing proxy "... | 5,314,211 |
def remove_nulls_from_dict(d):
"""
remove_nulls_from_dict function recursively remove empty or null values
from dictionary and embedded lists of dictionaries
"""
if isinstance(d, dict):
return {k: remove_nulls_from_dict(v) for k, v in six.iteritems(d) if v}
if isinstance(d, list):
... | 5,314,212 |
def test_search_intersects_and_bbox_raises(load_test_data, app_client, postgres_transactions):
"""bbox and intersects are mutually exclusive"""
item = load_test_data("test_item.json")
point = [8.4570, 56.24298]
intersects = {"type": "Point", "coordinates": point}
bbox = [8.4570, 56.24298, 8.5570, 5... | 5,314,213 |
def frame_processors(configuration, call_types, return_types):
""":type configuration: ducktest.config_reader.Configuration"""
typer = IdleProcessor()
chain(
typer,
MappingTypeProcessor(typer),
ContainerTypeProcessor(typer),
PlainTypeProcessor(),
)
call_frame_process... | 5,314,214 |
def install(target_dir): # pragma: no cover
"""
Install all the example Python files into a target directory (and create an "output" subdirectory).
If a file already exists, the script will fail. You need to copy existing files out of the way.
:param target_dir: str
:return:
"""
if not o... | 5,314,215 |
def exclude_file_from_traceback(full_path):
"""Exclude a file from appearing in a traceback generated by
Friendly-traceback. Note that this does not apply to
the true Python traceback obtained using "debug_tb".
"""
if not os.path.isfile(full_path):
raise RuntimeError(
f"{full_pa... | 5,314,216 |
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Sum Numbers',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('item',
metavar='int',
type=int,
... | 5,314,217 |
def remember_job(rj_job_dict:Dict[str,Any], rj_redis_connection) -> None:
"""
Save this outstanding job in a REDIS dict
so that we can match it when we get a callback
The REDIS dict contains a string representation of a json dict
whose entries are job ids mapped to the full job info dict.
... | 5,314,218 |
def GetLocalPackageArchiveDir(tar_dir, archive_name):
"""Returns directory where local package archive files live.
Args:
tar_dir: The tar root directory for where package archives would be found.
archive_name: The name of the archive contained within the package.
Returns:
The standard location where ... | 5,314,219 |
def StartAndRunFlow(flow_cls,
client_mock=None,
client_id=None,
check_flow_errors=True,
**kwargs):
"""Builds a test harness (client and worker), starts the flow and runs it.
Args:
flow_cls: Flow class that will be created and run.
... | 5,314,220 |
def check_dk(base: str, add: Optional[str] = None) -> str:
"""Check country specific VAT-Id"""
weights = (2, 7, 6, 5, 4, 3, 2, 1)
s = sum(int(c) * w for (c, w) in zip(base, weights))
r = s % 11
if r == 0:
return '' # check ok
else:
return 'f' | 5,314,221 |
def generate_sidepanel(spin_system, index):
"""Generate scrollable side panel listing for spin systems"""
# title
title = html.B(f"Spin system {index}", className="")
# spin system name
name = "" if "name" not in spin_system else spin_system["name"]
name = html.Div(f"Name: {name}", className=""... | 5,314,222 |
def ensure_installed(tool):
"""
Checks if a given tool is installed and in PATH
:param tool: Tool to check if installed and in PATH
:return: Full path of the tool
"""
proc = subprocess.Popen('export PATH=$PATH:/Applications/STMicroelectronics/STM32CubeMX.app/Contents/MacOs/:/usr/local/opt/arm-no... | 5,314,223 |
def clc_points(points):
"""
Args:
points (np.array|list): OpenCV cv2.boxPoints returns coordinates, order is
[right_bottom, left_bottom, left_top, right_top]
Returns:
list: reorder the coordinates, order is [left_top, right_top, right_bottom, left_bottom]
... | 5,314,224 |
def choose_til(*args):
"""
choose_til() -> bool
Choose a type library ( 'ui_choose' , 'chtype_idatil' ).
"""
return _ida_kernwin.choose_til(*args) | 5,314,225 |
def _has_child_providers(context, rp_id):
"""Returns True if the supplied resource provider has any child providers,
False otherwise
"""
child_sel = sa.select([_RP_TBL.c.id])
child_sel = child_sel.where(_RP_TBL.c.parent_provider_id == rp_id)
child_res = context.session.execute(child_sel.limit(1)... | 5,314,226 |
def is_zero(n, p=.5):
"""Return the sum of n random (-1, 1) variables divided by n.
n: number of numbers to sum
p: probability of 1 (probablity of -1 is 1-p)
"""
# This function should be about zero, but as n increases it gets better
numbers = random.choices((-1, 1), weights=(1-p, p), k=n)
... | 5,314,227 |
def reduce_loss(
sim_time: Union[float, int],
n_steps: int,
scene: JaxScene,
coordinate_init: Sequence,
velocity_init: Sequence,
target_coordinate: Sequence,
attractor: Sequence,
constants: dict,
) -> Tuple[float, List[Sequence]]:
"""
Wrapper function that reduces loss across bat... | 5,314,228 |
def lstm_ortho_initializer(scale=1.0):
"""LSTM orthogonal initializer."""
def _initializer(shape, dtype=tf.float32,
partition_info=None): # pylint: disable=unused-argument
size_x = shape[0]
size_h = shape[1] // 4 # assumes lstm.
t = np.zeros(shape)
t[:, :size_h] = orthogonal([si... | 5,314,229 |
def extract_data(loss_logs, fields, max_x=-1):
"""Extract numerical logs from loss logs.
Arguments:
loss_logs: list of text files containing numerical log data generated by
autoencoders
fields: types of values to plot (each gets its own subplot, e.g.
nonzero_mae, loss, p... | 5,314,230 |
def roc_pr_curves(xaxis, tpr_list, precision_list, model_names, model_colors=None, prc_chance=None,
prc_upper_ylim=None, figname=None, legend=True, figax=None, **kwargs):
"""Make a ROC and PR curve for each model, optionally with a SD. Compute an AUC score for each curve.
Parameters
-----... | 5,314,231 |
def safe_divide(num, denom):
"""Divides the two numbers, avoiding ZeroDivisionError.
Args:
num: numerator
denom: demoninator
Returns:
the quotient, or 0 if the demoninator is 0
"""
try:
return num / denom
except ZeroDivisionError:
return 0 | 5,314,232 |
def npSigma11( fitResult, nuisFilter="alpha_" ):
"""
Returns the block of the covariance matrix that corresponds to the main term.
"""
cov,pars = npCov( fitResult )
newPars = list( pars )
for i in reversed( range(len(pars)) ):
if nuisFilter not in pars[i]: continue
cov = np.delete( cov, i, 0 )
cov = np.del... | 5,314,233 |
def test_oauth_fail():
"""
A case when the token is missing
"""
httpretty.register_uri(httpretty.POST,
FAKE_EXCHANGE_URL,
status=401,
body="security")
connection = ExchangeOauthConnection(FAKE_EXCHANGE_URL,
... | 5,314,234 |
def test_convo_language_and_locales(
mocker, kwik_e_mart_nlp, kwik_e_mart_app_path, language, locale, expected_ser_call
):
"""Tests that the params are cleared in one trip from app to mm."""
convo = Conversation(nlp=kwik_e_mart_nlp, app_path=kwik_e_mart_app_path)
convo.params = Params(language=language,... | 5,314,235 |
def sendMessage(chat_id, text):
"""Bot sends a message to provided chat_id with the provided text"""
response = requests.post(
url='https://api.telegram.org/bot{0}/{1}'.format(BOT_TOKEN, 'sendMessage'),
data={'chat_id': chat_id, 'text': text}
).json() | 5,314,236 |
def main(args):
"""
Downloads the necessary catalogues to perform the 1- and 2-halo
conformity analysis
"""
## Reading all elements and converting to python dictionary
param_dict = vars(args)
## ---- Adding to `param_dict` ----
param_dict = add_to_dict(param_dict)
## Checking for c... | 5,314,237 |
def webpack_dev_url(request):
"""
If webpack dev server is running, add HMR context processor so template can
switch script import to HMR URL
"""
if not getattr(settings, "WEBPACK_DEV_URL", None):
return {}
data = {"host": split_domain_port(request._get_raw_host())[0]}
hmr_socket =... | 5,314,238 |
def lint(session):
"""Run linters and code formatters via pre-commit"""
cmd = 'pre-commit run --all-files'
session.run(*cmd.split(' ')) | 5,314,239 |
def parameter_symbols(val: Any) -> AbstractSet[sympy.Symbol]:
"""Returns parameter symbols for this object.
Args:
val: Object for which to find the parameter symbols.
Returns:
A set of parameter symbols if the object is parameterized. It the object
does not implement the _parameter... | 5,314,240 |
async def test_multi_start(c, s, a, b):
"""Multiple AMMs can be started in parallel"""
p2 = DemoPolicy(action="drop", key="y", n=10, candidates=None)
p3 = DemoPolicy(action="drop", key="z", n=10, candidates=None)
# policies parameter can be:
# - None: get from config
# - explicit set, which can... | 5,314,241 |
def qa_bpt(targetclass, fastspecfile=None, png=None):
"""QA of the fastspec emission-line spectra.
"""
from fastspecfit.templates.templates import remove_undetected_lines, read_stacked_fastspec
sns, _ = plot_style()
fastmeta, _fastspec = read_stacked_fastspec(fastspecfile, read_spectra=False)
... | 5,314,242 |
def sieve():
"""
Yields prime integers using Sieve of Eratosthenes.
Generates primes lazily and recursively rather than the traditional version.
"""
innersieve = sieve()
prevsq = 1
table = {}
i = 2
while True:
if i in table:
prime = table[i]
del table... | 5,314,243 |
def datetime(el, default_date=None):
"""Process dt-* properties
Args:
el (bs4.element.Tag): Tag containing the dt-value
Returns:
a tuple (string string): a tuple of two strings, (datetime, date)
"""
def try_normalize(dtstr, match=None):
"""Try to normalize a datetime string.
... | 5,314,244 |
def lexicallyRelated(word1, word2):
"""
Determine whether two words might be lexically related to one another.
"""
return any(map(lambda stem: stem(word1) == stem(word2), stemmers)
) or word1.startswith(word2) or word2.startswith(word1) | 5,314,245 |
async def playing_check(ctx: commands.Context):
"""
Checks whether we are playing audio in VC in this guild.
This doubles up as a connection check.
"""
if await connected_check(ctx) and not ctx.guild.voice_client.is_playing():
raise commands.CheckFailure("The voice client in this guild is ... | 5,314,246 |
def create_calibrated_rtl(feature_columns, config, quantiles_dir):
"""Creates a calibrated RTL estimator."""
feature_names = [fc.name for fc in feature_columns]
hparams = tfl.CalibratedRtlHParams(
feature_names=feature_names,
num_keypoints=200,
learning_rate=0.02,
lattice_l2_laplacian_reg=... | 5,314,247 |
def route_distance(df, con):
"""
Given a route's dataframe determine total distance (m) using gid
"""
dist = 0
cur = con.cursor()
for edge in df.edge[0:-1]:
query = 'SELECT length_m FROM ways WHERE gid={0}'.format(edge)
cur.execute(query)
out = cur.fetchone()
dis... | 5,314,248 |
def convert_units(P, In='cm', Out='m'):
"""
Quickly convert distance units between meters, centimeters and millimeters
"""
c = {'m':{'mm':1000.,'cm':100.,'m':1.},
'cm':{'mm':10.,'cm':1.,'m':0.01},
'mm':{'mm':1.,'cm':0.1,'m':0.001}}
return c[In][Out]*P | 5,314,249 |
def from_caffe(model_path, shapes, outputs=None, opt_model_path=None):
# type: (str, dict, List[str, ]str) -> relay.expr.Module, dict
""" Load Caffe model from file and convert to relay expression
"""
raise NotImplementedError("") | 5,314,250 |
def _nonmonotone_line_search_cheng(f, x_k, d, f_k, C, Q, eta,
gamma=1e-4, tau_min=0.1, tau_max=0.5,
nu=0.85):
"""
Nonmonotone line search from [1]
Parameters
----------
f : callable
Function returning a tuple ``(f, F)`` w... | 5,314,251 |
def course_state_editor(func):
"""
Decorator for any method that will be used to alter a Course's 'state'. It does a few useful things:
1. Clears any lingering dashboard data for a given course run to ensure that it will be in the right state
after the command.
2. Allows the user to specify a... | 5,314,252 |
def importDataFromCSV(dataType, filename):
"""
Import from a `.csv` file into a dataframe or python time/distance matrix dictionary.
Parameters
----------
dataType: string, Required
The type of data to be imported. Valid options are 'nodes', 'arcs', 'assignments', or 'matrix'.
filename: string, Required
The... | 5,314,253 |
def get_feature_from_current_buffer_and_pos(a_project):
"""
Get the name of the feature being edited in the current buffer
a_project is the current openned eiffel project
"""
pass | 5,314,254 |
def main():
"""Run the exploit and go interactive."""
args = get_parsed_args()
host = args.host
port = int(args.port)
sock = None
t = None
try:
sock = exploit(host, port)
t = Telnet()
t.sock = sock
print_info('Exploit sent, going interactive!')
t.mt_i... | 5,314,255 |
def xyz_to_str(xyz_dict: dict,
isotope_format: Optional[str] = None,
) -> str:
"""
Convert an ARC xyz dictionary format, e.g.::
{'symbols': ('C', 'N', 'H', 'H', 'H', 'H'),
'isotopes': (13, 14, 1, 1, 1, 1),
'coords': ((0.6616514836, 0.4027481525, -0.484738... | 5,314,256 |
async def _provision_nic_with_public_ip(
network_client: NetworkManagementClient,
location: str,
vm_name: str,
) -> Tuple[str, str]:
"""
Creates a public IP address and corresponding NIC. Returns (NIC id, public address
name)
"""
subnet_id = await _ensure_virtual_network_and_subnet(netw... | 5,314,257 |
def test_recursive_update_negative_different_type():
"""Test the 'recursive update' utility, when the types are different."""
# here we try to update an integer with a boolean - it raises error.
to_update = dict(subdict=dict(to_update=1))
new_values = dict(subdict=dict(to_update=False))
with pytest... | 5,314,258 |
def test_tiff_sequence_with_directory_walker(tmpdir):
"""
directory/
sequence/ # should trigger subdirectory_handler
other_stuff/ # should not
other_file1.csv # should not
other_file2.csv # should not
"""
data = numpy.random.random((100, 101))
# This directory should be d... | 5,314,259 |
def await_lifecycle_state(db_system_id, action_state, action_name, config, interactive):
"""Waits of the db_system to reach the desired lifecycle state
Args:
db_system_id (str): OCID of the DbSystem.
action_state (str): The lifecycle state to reach
action_name (str): The name of t... | 5,314,260 |
def compute_pg_vars(trajs, val_fn, gamma, gaelam):
"""
Compute variables needed for various policy gradient algorithms.
Adds advantages, values and returns to the provided trajectories.
:param trajs: An OrderedDict with observations, actions, rewards
and done flags. Assumes all have the same ba... | 5,314,261 |
def predict(event: Dict[str, Any],
context: Any) -> Dict[str, Any]:
"""
AWS lambda function, to handle incoming GET requests asking our model for predictions.
:param event: standard AWS lambda event param - it contains the query parameters for the GET call
:param context: standard AWS lambd... | 5,314,262 |
def get_simclr_transform(size, s=1):
"""Return a set of data augmentation transformations as described in the SimCLR paper."""
color_jitter = transforms.ColorJitter(0.8 * s, 0.8 * s, 0.8 * s, 0.2 * s)
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
... | 5,314,263 |
def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, indent=None, separators=None, sort_keys=False,
core: Core = None, **kw):
"""
Dumps an object into a Writer with support for HomeControl's data types
"""
return json.dump(obj, fp, skipkeys=skipk... | 5,314,264 |
def moving_slope_filter(dataframe,time,data,cutoff,time_unit=None,
log_file=os.path.join(os.getcwd(),'filter_log.txt')):
"""
Filters out datapoints based on the difference between the slope in one point
and the next (sudden changes like noise get filtered out), based on a given
c... | 5,314,265 |
async def get_sender_data(user_id: int) -> dict:
"""
Sender profile
:param user_id: User ID
:type user_id: int
:return: Sender profile
:rtype: dict
"""
return await get_sender_data_request(user_id) | 5,314,266 |
def main():
"""CLI for performing model training."""
args = docopt(__doc__, version=__version__)
args = _expand_user_path(args)
if args['--verbose']:
set_default_log_level(logging.DEBUG)
set_log_level(_LOGGER, logging.DEBUG)
if args['--log-path']:
log_path = args['--log-pat... | 5,314,267 |
def conditional_input_prediction_2d(x, y_pred, var_1_index, var_2_index, var_1_bins, var_2_bins, dependence_function=np.mean):
"""
For a given set of 2 input values, calculate a summary statistic based on all of the examples that fall within
each binned region of the input data space. The goal is to show ho... | 5,314,268 |
def plot_feature_group_importance(feature_group_df):
"""
Plot averaged feature importance of a set of models with same configs
"""
dir = '../plots/' + 'group feature importance' + '/'+ datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '/'
shutil.rmtree(dir, ignore_errors=True)
os.makedirs(dir)
... | 5,314,269 |
def remove(path):
"""Removed the passed file's containing directory."""
if not path == None and os.path.exists(path):
shutil.rmtree(os.path.dirname(path), ignore_errors=True) | 5,314,270 |
def update_model_params(params, update):
"""Updates the default parameters using supplied user arguments."""
update_dict = {}
for p in update:
m = re.match("(.*)=(.*)", p)
if not m:
LOGGER.error("Unable to parse param update '%s'", p)
sys.exit(1)
k, v = m.gr... | 5,314,271 |
def cli(ctx, opt_input, opt_output, opt_x_lim, opt_y_lim, opt_dpi, opt_figsize):
"""Plots YOLO training logfile"""
import re
import matplotlib.pyplot as plt
from pathlib import Path
from vframe.utils import log_utils, file_utils
from vframe.settings import app_cfg
from vframe.utils.draw_utils import pix... | 5,314,272 |
def fgt_get_pressureUnit(pressure_index, get_error = _get_error):
"""Get current unit on selected pressure device.
Args:
pressure_index: Index of pressure channel or unique ID
Returns:
current unit as a string
"""
pressure_index = int(pressure_index)
low_level_function = low... | 5,314,273 |
def _get_rawhide_version():
"""
Query Koji to find the rawhide version from the build target.
:return: the rawhide version (e.g. "f32")
:rtype: str
"""
koji_session = get_session(conf, login=False)
build_target = koji_session.getBuildTarget("rawhide")
if build_target:
return bui... | 5,314,274 |
def test_mixed():
"""Test positional arguments passed via keyword.
"""
class TestView(simple.SimpleView):
args = ['id']
def __call__(self, foo):
return self.request, self.id, foo
testview = create_view(TestView)
# generally is a possibility...
assert testvi... | 5,314,275 |
def fail_event_on_handler_exception(func):
"""
Decorator which marks the models.Event associated with handler by
BaseHandler.set_context() as FAILED in case the `func` raises an
exception.
The exception is re-raised by this decorator once its finished.
"""
@wraps(func)
def decorator(han... | 5,314,276 |
def draw_arc(draw, bbox, start, end, fill, width=1, segments=5000):
"""Hack that looks similar to PIL's draw.arc(), but can specify a line width.
Based on code from Pieter Ennes from
https://stackoverflow.com/questions/7070912/creating-an-arc-with-a-given-thickness-using-pils-imagedraw
"""
# radian... | 5,314,277 |
def intensityAdjustment(image, template):
"""Tune image intensity based on template
----------
images : <numpy.ndarray>
image needed to be adjusted
template : <numpy.ndarray>
Typically we use the middle image from image stack. We want to match the image
in... | 5,314,278 |
def Define_core_memesa_model():
"""\nOriginal core model + inefficient branch\n"""
model_name = 'core_model_1b'
Reactions ={'R01' : {'id' : 'R01', 'reversible' : False, 'reagents' : [(-1, 'X0'), (1, 'A')], 'SUBSYSTEM' : ''},
'R02' : {'id' : 'R02', 'reversible' : True, 'reagents' : ... | 5,314,279 |
def F16(x):
"""Rosenbrock function"""
sum = 0
for i in range(len(x)-1):
sum += 100*(x[i+1]-x[i]**2)**2+(x[i]+1)**2
return sum | 5,314,280 |
def jaccard_simple(annotation,segmentation):
""" Compute region similarity as the Jaccard Index.
Arguments:
annotation (ndarray): binary annotation map.
segmentation (ndarray): binary segmentation map.
Return:
jaccard (float): region similarity
"""
annotation = annotatio... | 5,314,281 |
def shuffle_df(df):
"""
return:
pandas.DataFrame | shuffled dataframe
params:
df: pandas.DataFrame
"""
return df.reindex(np.random.permutation(df.index)) | 5,314,282 |
def transform_from_sklearn(
idx: pd.Index,
vars_: List[str],
vals: np.array,
) -> pd.DataFrame:
"""
Add index and column names to sklearn output.
:param idx: data index
:param vars_: names of feature columns
:param vals: features data
:return: dataframe with an index an column names... | 5,314,283 |
def before_going_check_door(action, actor, direction, ctxt) :
"""Checks that the going_via is open if it is an openable door."""
if ctxt.world[IsA(action.going_via, "door")] :
if ctxt.world[Openable(action.going_via)] and not ctxt.world[IsOpen(action.going_via)] :
ctxt.actionsystem.do_first(... | 5,314,284 |
def test_ME15():
"""If the additional code type is related to a Meursing table plan then the
validity period of the additional code must span the validity period of the
measure."""
assert False | 5,314,285 |
def from_package_str(item):
"""Display name space info when it is different, then diagram's or parent's
namespace."""
subject = item.subject
diagram = item.diagram
if not (subject and diagram):
return False
namespace = subject.namespace
parent = item.parent
# if there is a par... | 5,314,286 |
def search_by_wl(target_type: str, imaging_type: str, wl: float, base_path: str) -> str:
"""Search a folder for an image of given wavelength.
A path to the image is returned.
:param target_type:
String either 'leaf' or 'reference'. Use the ones listed in constants.py.
:param imaging_type:
... | 5,314,287 |
def calculateAverageValue(faceBlob, binaryLabelVolume):
"""Deprecated."""
total = 0.0
for labeledPoint in faceBlob.points():
total += float(at(binaryLabelVolume, labeledPoint.loc))
return float(total) / float(len(faceBlob.points())) | 5,314,288 |
def calc_m_inv_m_norm_by_unit_cell_parameters(
unit_cell_parameters, flag_unit_cell_parameters: bool = False):
"""nM matrix."""
a, b = unit_cell_parameters[0], unit_cell_parameters[1]
c = unit_cell_parameters[2]
alpha, beta = unit_cell_parameters[3], unit_cell_parameters[4]
gamma = unit_cell... | 5,314,289 |
def get_m():
"""获取加密参数m"""
return subprocess.check_output(['node', 'scrapy_ddiy/scripts/js/yuanrenxue/002.js']).decode().strip() | 5,314,290 |
def init():
"""GDBINIT compatibility alias for 'start' command."""
pwndbg.commands.start.start() | 5,314,291 |
def fetch_mirchi2018(data_dir=None, resume=True, verbose=1):
"""
Downloads (and creates) dataset for replicating Mirchi et al., 2018, SCAN
Parameters
----------
data_dir : str, optional
Directory to check for existing data files (if they exist) or to save
generated data files. Files... | 5,314,292 |
def round(dt, rounding=None):
"""Round a datetime value using specified rounding method.
Args:
dt: `datetime` value to be rounded.
rounding: `DatetimeRounding` value representing rounding method.
"""
if rounding is DatetimeRounding.NEAREST_HOUR:
return round_to_hour(dt)
elif... | 5,314,293 |
def testid(prefix='',c=_default_conc,
squishy=False,squishz=False,decimate=False,substr=False,
subm=_default_subm,subr=_default_subr,subc=_default_subc,
subrho=_default_subrho,version=-1):
"""Creates a standardized string that uniquely identifies a test.
Args:
prefi... | 5,314,294 |
def calc_bearing(lat1, lon1, lat2, lon2):
"""
Calculate bearing in degrees from (lat1,lon1) towards (lat2, lon2)
"""
lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2])
dlon = lon2 - lon1
a = np.arctan2(
np.sin(dlon) * np.cos(lat2),
np.cos(lat1) * np.sin(lat2) - np... | 5,314,295 |
def Block(data, num_filter, kernel, stride=(1,1), pad=(0,0), eps=1e-3, name=None):
""" CNN block"""
conv = mx.sym.Convolution(data=data, num_filter=num_filter,
stride=stride, kernel=kernel, pad=pad, name='conv_%s' % name)
bn = mx.sym.BatchNorm(data=conv, fix_gamma=False, eps=eps,
mom... | 5,314,296 |
def flat(x, output_name="flatten"):
""" takes a tensor of rank > 2 and return a tensor of shape [?,n]"""
shape = x.get_shape().as_list()
n = np.prod(shape[1:])
x_flat = tf.reshape(x, [-1, n])
return tf.identity(x_flat, name=output_name) | 5,314,297 |
async def test_show_config_form(opp):
"""Test show configuration form."""
result = await opp.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["step_id"] == "user" | 5,314,298 |
def cli():
"""CLI for extra-pypi""" | 5,314,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.