content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def validate_dtype(dtype_in):
"""
Input is an argument represention one, or more datatypes.
Per column, number of columns have to match number of columns in csv file:
dtype = [pa.int32(), pa.int32(), pa.int32(), pa.int32()]
dtype = {'__columns__': [pa.int32(), pa.int32(), pa.int32(), pa.int32()]}
... | 5,351,800 |
def get_secret(name):
"""Load a secret from file or env
Either provide ``{name}_FILE`` or ``{name}`` in the environment to
configure the value for ``{name}``.
"""
try:
with open(os.environ[name + "_FILE"]) as secret_file:
return secret_file.read().strip()
except (FileNotFoun... | 5,351,801 |
def cache(
cache_class: Callable[[], base_cache.BaseCache[T]],
serializer: Callable[[], cache_serializer.CacheSerializer],
conditional: Callable[[List[Any], Dict[str, Any]], bool] = _always_true):
"""
cache
=====
parameters:
cache_class (base_cache.BaseCache)
con... | 5,351,802 |
def words2chars(images, labels, gaplines):
""" Transform word images with gaplines into individual chars """
# Total number of chars
length = sum([len(l) for l in labels])
imgs = np.empty(length, dtype=object)
newLabels = []
height = images[0].shape[0]
idx = 0;
for i, gaps... | 5,351,803 |
def general_barplot_with_error(means, stds):
"""
Barplot, meant for fixation position and entropy. x: fixation position. y: mean (and stdev)
means: dictionary, with x labels as keys
stds: dictionary, with x labels as keys
"""
fig,ax = plt.subplots()
plt.errorbar(means.keys(), means.values(),... | 5,351,804 |
def show_all_archives():
"""Displays meta data for all archives."""
archives = Archive.select()
template = "{: <32} {: <64} {: <64} {: <32} {: <32}"
header = [
"Name",
"Source Path",
"Destination Path",
"Key Pair Name",
"Timestamp",
]
print(template.form... | 5,351,805 |
def add_custom_subparser(subparsers):
"""
Add subparser for customized stock picks
"""
custom = subparsers.add_parser(
"custom", help="Analyze set of user defined pages"
)
custom.add_argument(
"pages",
nargs="*",
help="Symbol:Wikipage to analyze, eg: AAPL:Apple_... | 5,351,806 |
def create_spark_session(spark_jars: str) -> SparkSession:
"""
Create Spark session
:param spark_jars: Hadoop-AWS JARs
:return: SparkSession
"""
spark = SparkSession \
.builder \
.config("spark.jars.packages", spark_jars) \
.appName("Sparkify ETL") \
.getOrCreate(... | 5,351,807 |
def make_expired(request, pk):
"""
将号码状态改为过号
"""
try:
reg = Registration.objects.get(pk=pk)
except Registration.DoesNotExist:
return Response('registration not found', status=status.HTTP_404_NOT_FOUND)
data = {
'status': REGISTRATION_STATUS_EXPIRED
}
serializer = ... | 5,351,808 |
def run_optimization(mesh, target_evals, out_path, params=OptimizationParams()):
"""Run the optimization."""
# Create the output directories
os.makedirs(f"{out_path}/ply", exist_ok=True)
os.makedirs(f"{out_path}/txt", exist_ok=True)
# Unpack the mesh
[
Xopt,
TRIV,
n,
... | 5,351,809 |
def register():
"""Registers all signature key managers in the Python registry."""
tink_bindings.register()
for key_type_identifier in ('EcdsaPrivateKey', 'Ed25519PrivateKey',
'RsaSsaPssPrivateKey', 'RsaSsaPkcs1PrivateKey',):
type_url = 'type.googleapis.com/google.crypto.tink.' ... | 5,351,810 |
def cmd_add(opts):
"""Add one or more existing Docker containers to a Blockade group
"""
config = load_config(opts.config)
b = get_blockade(config, opts)
b.add_container(opts.containers) | 5,351,811 |
def word2vec_similarity(segmented_topics, accumulator, with_std=False, with_support=False):
"""For each topic segmentation, compute average cosine similarity using a
:class:`~gensim.topic_coherence.text_analysis.WordVectorsAccumulator`.
Parameters
----------
segmented_topics : list of lists o... | 5,351,812 |
def remote(self, privilege, grant_target_name, user_name, node=None):
"""Check that user is only able to to create a table from a remote source when they have the necessary privilege.
"""
exitcode, message = errors.not_enough_privileges(name=user_name)
if node is None:
node = self.context.node
... | 5,351,813 |
def test_vecenv_terminal_obs(vec_env_class, vec_env_wrapper):
"""Test that 'terminal_observation' gets added to info dict upon
termination."""
step_nums = [i + 5 for i in range(N_ENVS)]
vec_env = vec_env_class([functools.partial(StepEnv, n) for n in step_nums])
if vec_env_wrapper is not None:
... | 5,351,814 |
def addGroupsToKey(server, activation_key, groups):
"""
Add server groups to a activation key
CLI Example:
.. code-block:: bash
salt-run spacewalk.addGroupsToKey spacewalk01.domain.com 1-my-key '[group1, group2]'
"""
try:
client, key = _get_session(server)
except Exceptio... | 5,351,815 |
def get_user_for_delete():
"""Query for Users table."""
delete_user = Users.query \
.get(DELETE_USER_ID)
return delete_user | 5,351,816 |
def station_code_from_duids(duids: List[str]) -> Optional[str]:
"""
Derives a station code from a list of duids
ex.
BARRON1,BARRON2 => BARRON
OSBAG,OSBAG => OSBAG
"""
if type(duids) is not list:
return None
if not duids:
return None
if len(duids) ... | 5,351,817 |
def act_mmp_3d(out_mmps, target_id):
"""Function to attribute 3D coordinates to the activity only molecule. Uses MMFF and maximises shape overlap with existing fragment.
Takes a list of mmps and a Target
Returns None"""
print "Generating 3D conformations"
# First of all make sure the protein ex... | 5,351,818 |
async def count_to(number):
""" counts to n in async manner"""
async for i in some_iter_func(number):
print(i) | 5,351,819 |
def erosion(image, selem, out=None, shift_x=False, shift_y=False):
"""Return greyscale morphological erosion of an image.
Morphological erosion sets a pixel at (i,j) to the minimum over all pixels
in the neighborhood centered at (i,j). Erosion shrinks bright regions and
enlarges dark regions.
Para... | 5,351,820 |
def NE(x=None, y=None):
"""
Compares two values and returns:
true when the values are not equivalent.
false when the values are equivalent.
See https://docs.mongodb.com/manual/reference/operator/aggregation/ne/
for more details
:param x: first value or expression
:param y: second... | 5,351,821 |
def TCPs_from_tc(type_constraint):
"""
Take type_constraint(type_param_str, allowed_type_strs) and return list of TypeConstraintParam
"""
tys = type_constraint.allowed_type_strs # Get all ONNX types
tys = set(
[onnxType_to_Type_with_mangler(ty) for ty in tys]
) # Convert to Knossos and... | 5,351,822 |
def test_phone_search(yelp_fusion, kwargs, exception_raised):
"""
test GET /businesses/search/phone
Args:
yelp_fusion (yelp.YelpFusion): a YelpFusion object
"""
if exception_raised:
with pytest.raises(RuntimeError):
yelp_fusion.phone_search(**kwargs)
else:
as... | 5,351,823 |
def builtin_unshelve(self, context, looping=False):
"""Modify the stack: ( a ... -- ... a )."""
a = context.dequeue()
context.push(a) | 5,351,824 |
def invoke_windowsError():
"""
Raised when a Windows-specific error occurs or when the error number does not correspond to an errno value.
(Only available on Windows systems)
"""
try:
a = open("unexistant.txt", 'r')
except WindowsError as e:
print("WindowsError encountered")
... | 5,351,825 |
def writeJavascriptLibrary(html):
"""Write a block of Javascript code."""
html.write("""<!-- Javascript functions to hide/display folder content -->
<script type="text/javascript">
<!-- to hide script contents from old browsers
// Pick loggraph
// Hides all loggraphs and then shows just the one of
// interest
fu... | 5,351,826 |
def _randomde(allgenes,
allfolds,
size):
"""Randomly select genes from the allgenes array and fold changes from the
allfolds array. Size argument indicates how many to draw.
Parameters
----------
allgenes : numpy array
numpy array with all the genes expressed in ... | 5,351,827 |
def add_disc_rew(seg, gamma):
"""
Discount the reward of the generated batch of trajectories.
"""
new = np.append(seg['new'], 1)
rew = seg['rew']
n_ep = len(seg['ep_rets'])
n_samp = len(rew)
seg['ep_disc_ret'] = ep_disc_ret = np.empty(n_ep, 'float32')
seg['disc_rew'] = disc_rew... | 5,351,828 |
def test_md041_good_heading_top_level_setext():
"""
Test to make sure we get the expected behavior after scanning a good file from the
test/resources/rules/md004 directory that has consistent asterisk usage on a single
level list.
"""
# Arrange
scanner = MarkdownScanner()
supplied_argum... | 5,351,829 |
def retrieve(resource_url, filename=None, verbose=True):
"""
Copy the given resource to a local file. If no filename is
specified, then use the URL's filename. If there is already a
file named C{filename}, then raise a C{ValueError}.
@type resource_url: C{str}
@param resource_url: A URL s... | 5,351,830 |
def XCor(spectra, mask_l, mask_h, mask_w, vel, lbary_ltopo, vel_width=30,\
vel_step=0.3, start_order=0, spec_order=9,iv_order=10,sn_order=8,max_vel_rough=300.):
"""
Calculates the cross-correlation function for a Coralie Spectra
"""
# speed of light, km/s
c = 2.99792458E5
# loop over orders
norder... | 5,351,831 |
def marks_details(request, pk):
"""
Display details for a given Mark
"""
# Check permission
if not has_access(request):
raise PermissionDenied
# Get context
context = get_base_context(request)
# Get object
mark = get_object_or_404(Mark, pk=pk)
mark.category_clean = mar... | 5,351,832 |
def clean_text(text):
"""
text: a string
return: modified initial string
"""
text = BeautifulSoup(text, "lxml").text # HTML decoding
text = text.lower() # lowercase text
# replace REPLACE_BY_SPACE_RE symbols by space in text
text = REPLACE_BY_SPACE_RE.sub(' ', text)
# dele... | 5,351,833 |
def get_input_device(config):
""" Create the InputDevice instance and handle errors """
dev_path = config['flirc_device_path']
logging.debug('get_input_device() dev_path: %s', dev_path)
try:
input_device = InputDevice(dev_path)
return input_device
except FileNotFoundError as excepti... | 5,351,834 |
def _simpsons_interaction(data, groups):
"""
Calculation of Simpson's Interaction index
Parameters
----------
data : a pandas DataFrame
groups : list of strings.
The variables names in data of the groups of interest of the analysis.
Returns
-------
statistic ... | 5,351,835 |
def find_includes(armnn_include_env: str = INCLUDE_ENV_NAME):
"""Searches for ArmNN includes.
Args:
armnn_include_env(str): Environmental variable to use as path.
Returns:
list: A list of paths to include.
"""
armnn_include_path = os.getenv(armnn_include_env)
if armnn_include_p... | 5,351,836 |
def read_missing_oids(oid_lines):
"""
Parse lines into oids.
>>> list(read_missing_oids([
... "!!! Users 0 ?", "POSKeyError: foo",
... "!!! Users 0 ?",
... "!!! Users 1 ?",
... "bad xref name, 1", "bad db", ]))
[0, 1]
"""
result = OidSet()
for line in oid_lines:
... | 5,351,837 |
def run(target='192.168.1.1', ports=[21,22,23,25,80,110,111,135,139,443,445,554,993,995,1433,1434,3306,3389,8000,8008,8080,8888]):
"""
Run a portscan against a target hostname/IP address
`Optional`
:param str target: Valid IPv4 address
:param list ports: Port numbers to scan on target host
:ret... | 5,351,838 |
def go():
"""サンプルを実行します."""
obj = Sample()
obj.exec() | 5,351,839 |
def check_factorial_validity(token, value):
"""
Checks whether the factorial call is in limit.
Parameters
----------
token : ``Token``
The parent token.
value : `int` or `float`
The value to use factorial on.
Raises
------
EvaluationError
- Factorial... | 5,351,840 |
def subsequent_mask(size: int):
"""
Mask out subsequent positions (to prevent attending to future positions)
Transformer helper function.
:param size: size of mask (2nd and 3rd dim)
:return: Tensor with 0s and 1s of shape (1, size, size)
"""
mask = np.triu(np.ones((1, size, size)), k=1).ast... | 5,351,841 |
def _get_dist_class(
policy: Policy, config: TrainerConfigDict, action_space: gym.spaces.Space
) -> Type[TorchDistributionWrapper]:
"""Helper function to return a dist class based on config and action space.
Args:
policy (Policy): The policy for which to return the action
dist class.
... | 5,351,842 |
def timeexec(fct, number, repeat):
"""
Measures the time for a given expression.
:param fct: function to measure (as a string)
:param number: number of time to run the expression
(and then divide by this number to get an average)
:param repeat: number of times to repeat the computation
... | 5,351,843 |
def is_bst(root):
""" checks if binary tree is binary search tree """
def is_bst_util(root, min_value, max_value):
""" binary search tree check utility function """
if root is None:
return True
if (root.data >= min_value and root.data < max_value
and is_bst_u... | 5,351,844 |
def regexify(w, tags):
"""Convert a single component of a decomposition rule
from Weizenbaum notation to regex.
Parameters
----------
w : str
Component of a decomposition rule.
tags : dict
Tags to consider when converting to regex.
Returns
-------
w : str
Co... | 5,351,845 |
def test_handling_unexpected_exception(testdata_dir: pathlib.Path, monkeypatch: MonkeyPatch) -> None:
"""Test whether a bad element string correctly errors."""
element_str = 'catalog'
full_path = testdata_dir / 'json/minimal_catalog.json'
command_str = f'trestle partial-object-validate -f {str(full_path... | 5,351,846 |
def test_subgrid_error():
"""Capture errors in the subgrid specification"""
with pytest.raises(SystemExit): # j0 outside grid
g = Grid(filename=grid_file, subgrid=(20, 150, 30, 222))
with pytest.raises(SystemExit): # i0 > i1, i0
g = Grid(filename=grid_file, subgrid=(50, 20, 30, 170)) | 5,351,847 |
def row_dot_product(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""
Returns a vectorized dot product between the rows of a and b
:param a: An array of shape (N, M) or (M, )
(or a shape that can be broadcast to (N, M))
:param b: An array of shape (N, M) or (M, )
(or a shape that can be broadcas... | 5,351,848 |
def pmg_pickle_dump(obj, filobj, **kwargs):
"""
Dump an object to a pickle file using PmgPickler.
Args:
obj : Object to dump.
fileobj: File-like object
\\*\\*kwargs: Any of the keyword arguments supported by PmgPickler
"""
return PmgPickler(filobj, **kwargs).dump(obj) | 5,351,849 |
def condition_header(header, needed_keys=None):
"""Return a dictionary of all `needed_keys` from `header` after passing
their values through the CRDS value conditioner.
"""
header = { key.upper():val for (key, val) in header.items() }
if not needed_keys:
needed_keys = header.keys()
else:... | 5,351,850 |
def check_is_proba(entry: Union[float, int], name: str = None):
"""Check whether the number is non-negative and less than or equal to 1."""
if name is None:
name = 'Probabilities'
if type(entry) not in [float, int]:
raise TypeError('{} must be floats (or ints if 0 or 1).'.format(name))
i... | 5,351,851 |
def get_generic_path_information(paths, stat_prefix=""):
"""
Get an OrderedDict with a bunch of statistic names and values.
"""
statistics = OrderedDict()
returns = [sum(path["rewards"]) for path in paths]
# rewards = np.vstack([path["rewards"] for path in paths])
rewards = np.concatenate([p... | 5,351,852 |
def pad_images(images, nlayers):
"""
In Unet, every layer the dimension gets divided by 2
in the encoder path. Therefore the image size should be divisible by 2^nlayers.
"""
import math
import numpy as np
divisor = 2**nlayers
nlayers, x, y = images.shape # essentially setting nlayers to ... | 5,351,853 |
def remove_measurements(measurements, model_dict, params=None):
"""Remove measurements from a model specification.
If provided, a params DataFrame is also reduced correspondingly.
Args:
measurements (str or list): Name(s) of the measurement(s) to remove.
model_dict (dict): The model specif... | 5,351,854 |
def make_output(platform, output):
"""Return libraries list"""
libraries = parse_libs()
# OS libs separate
_ = {"win32": ";", "linux": ":", "darwin": ":"}
out_lib = str()
# Generate libraries list
for lib in libraries:
out_lib = out_lib + "$MC_DIR/libraries/{0}".format(lib) + _[p... | 5,351,855 |
def _output(command: Sequence[str]) -> None:
"""Helper function. Prints start/finish and runs the command inbetween."""
print(f'========== {command[0]} starting ==========')
subprocess.run(command)
print(f'========== {command[0]} finished ==========') | 5,351,856 |
def good2Go(SC, L, CC, STR):
"""
Check, if all input is correct and runnable
"""
if SC == 1 and L == 1 and CC == 1 and STR == 1:
return True
else:
print(SC, L, CC, STR)
return False | 5,351,857 |
def __validate_tweet_name(tweet_name: str, error_msg: str) -> str:
"""Validate the tweet's name.
Parameters
----------
tweet_name : str
Tweet's name.
error_msg : str
Error message to display for an invalid name.
Returns
-------
str
Validated tweet name.
Rai... | 5,351,858 |
def convert_event(obj):
"""
:type obj: :class:`sir.schema.modelext.CustomEvent`
"""
event = models.event(id=obj.gid, name=obj.name)
if obj.comment:
event.set_disambiguation(obj.comment)
if obj.type is not None:
event.set_type(obj.type.name)
event.set_type_id(obj.type.gi... | 5,351,859 |
def get_pr_review_status(pr: PullRequestDetails, per_page: int = 100) -> Any:
"""
References:
https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request
"""
url = (f"https://api.github.com/repos/{pr.repo.organization}/{pr.repo.name}"
f"/pulls/{pr.pull_id}/reviews"
... | 5,351,860 |
def make_sph_model(filename):
"""reads a spherical model file text file and generates interpolated values
Args:
filename:
Returns:
model:
"""
M = np.loadtxt(filename, dtype={'names': ('rcurve', 'potcurve', 'dpotcurve'),'formats': ('f4', 'f4', 'f4')},skiprows=1)
model = ... | 5,351,861 |
def list_dir(filepath):
"""List the files in the directory"""
return sorted(list(map(lambda x: os.path.join(filepath, x), os.listdir(filepath)))) | 5,351,862 |
def minimum(x, y):
"""
Returns the min of x and y (i.e. x < y ? x : y) element-wise.
Parameters
----------
x : tensor.
Must be one of the following types: bfloat16, half, float32, float64, int32, int64.
y : A Tensor.
Must have the same type as x.
name : str
A name fo... | 5,351,863 |
def seconds_to_timestamp(seconds):
"""
Convert from seconds to a timestamp
"""
minutes, seconds = divmod(float(seconds), 60)
hours, minutes = divmod(minutes, 60)
return "%02d:%02d:%06.3f" % (hours, minutes, seconds) | 5,351,864 |
def query(querystring: str,
db: tsdb.Database,
**kwargs):
"""
Perform query *querystring* on the testsuite *ts*.
Note: currently only 'select' queries are supported.
Args:
querystring (str): TSQL query string
ts (:class:`delphin.itsdb.TestSuite`): testsuite to query... | 5,351,865 |
def rename_SI_cols(dataset, removenans=True):
"""
names columns of Spectro Inlets data like EC-Lab and PyExpLabSys+cinfdata name them.
"""
if isinstance(dataset, dict):
print("WARNGING!!! The use of dataset dictionaries is no longer suported!!!")
data = dataset
else:
data = d... | 5,351,866 |
def TTF_SizeUTF8(font, text, w, h):
"""Calculates the size of a UTF8-encoded string rendered with a given font.
See :func:`TTF_SizeText` for more info.
Args:
font (:obj:`TTF_Font`): The font object to use.
text (bytes): A UTF8-encoded bytestring of text for which the rendered
s... | 5,351,867 |
def get_mse(y_true, y_hat):
"""
Return the mean squared error between the ground truth and the prediction
:param y_true: ground truth
:param y_hat: prediction
:return: mean squared error
"""
return np.mean(np.square(y_true - y_hat)) | 5,351,868 |
def generate_v2_token(username, version, client_ip, issued_at_timestamp, email=''):
"""Creates the JSON Web Token with a new schema
:Returns: String
:param username: The name of person who the token identifies
:type username: String
:param version: The version number for the token
:type versi... | 5,351,869 |
def choose(n, k):
"""return n choose k
resilient (though not immune) to integer overflow"""
if n == 1:
# optimize by far most-common case
return 1
return fact_div(n, max(k, n - k)) / math.factorial(min(k, n - k)) | 5,351,870 |
def part_one(puzzle_input: List[str]) -> int:
"""Find the highest seat ID on the plane"""
return max(boarding_pass_to_seat_id(line) for line in puzzle_input) | 5,351,871 |
def readbit(val, bitidx):
""" Direct word value """
return int((val & (1<<bitidx))!=0) | 5,351,872 |
def main():
"""
pred_dict : dict.
{'img1.png': [array, array], ...}
array: [x1, y1, x2, y2, conf]
bordered, borderless 순
gt_dict: dict.
{{'img1.png': [array, array], ...}}
array: [x1, y1, x2, y2]
"""
with open(pred_pickle, 'rb') as f:
pred_dict = pickle.load(f)
with open(gt_pickle, 'rb') as f:
gt... | 5,351,873 |
def mdtf_rename_img(varlist,conv,img_dir):
"""Rename figure files to use variable names from settings file,
not conventions."""
for f in img_dir.iterdir():
f_name = str(f.name)
if not f_name.startswith("."):
for pod_var in varlist:
standard_name = varlist[pod_var]... | 5,351,874 |
def test_immediate_datafuture():
"""Test DataFuture string representation, for AppFutures launched with parent
"""
import time
fu = echo_slow_message("Hello world", sleep=1, outputs=["hello.1.txt"])
d_fu = fu.outputs[0]
time.sleep(0.1)
state_2 = d_fu.__str__()
print("State_2 : ", state... | 5,351,875 |
def matrix_bombing_plan(m):
""" This method calculates sum of the matrix by
trying every possible position of the bomb and
returns a dictionary. Dictionary's keys are the
positions of the bomb and values are the sums of
the matrix after the damage """
matrix = deepcopy(m)
rows = len(m)
... | 5,351,876 |
def coord_to_gtp(coord, board_size):
""" From 1d coord (0 for position 0,0 on the board) to A1 """
if coord == board_size ** 2:
return "pass"
return "{}{}".format("ABCDEFGHJKLMNOPQRSTYVWYZ"[int(coord % board_size)],\
int(board_size - coord // board_size)) | 5,351,877 |
def test_alternative_clusting_method(ClusterModel):
"""
Test that users can supply alternative clustering method as dep injection
"""
def clusterer(X: np.ndarray, k: int, another_test_arg):
"""
Function to wrap a sklearn model as a clusterer for OptimalK
First two arguments are ... | 5,351,878 |
def load_dataset(spfile, twfile):
"""Loads dataset given the span file and the tweets file
Arguments:
spfile {string} -- path to span file
twfile {string} -- path to tweets file
Returns:
dict -- dictionary of tweet-id to Tweet object
"""
tw_int_map = {}
# for filen in os.... | 5,351,879 |
def nameof(var, *more_vars,
# *, keyword only argument, supported with python3.8+
frame: int = 1,
vars_only: bool = True) -> Union[str, Tuple[str]]:
"""Get the names of the variables passed in
Examples:
>>> a = 1
>>> nameof(a) # 'a'
>>> b = 2
>>... | 5,351,880 |
def ui_save_newspaper_text_to_disk(dir_name, newspaper_text_by_date):
"""Saves data to disk at current working directory and prints UI messages.
Makes new directory named by the `dir_name` parameter, adding a suffix to
avoid naming collisions. Does not merge issues from current call into an
equally nam... | 5,351,881 |
def cache_get_filepath(key):
"""Returns cache path."""
return os.path.join(settings.CACHE_PATH, key) | 5,351,882 |
def scorer(func):
"""This function is a decorator for a scoring function.
This is hack a to get around self being passed as the first argument to the scoring function."""
def wrapped(a, b=None):
if b is not None:
return func(b)
return func(a)
return wrapped | 5,351,883 |
def print_stats(yards):
"""
This function prints the final stats after a skier has crashed.
"""
print
print "You skied a total of", yards, "yards!"
#print "Want to take another shot?"
print
return 0 | 5,351,884 |
def _calculate_risk_reduction(module):
"""
Function to calculate the risk reduction due to testing. The algorithms
used are based on the methodology presented in RL-TR-92-52, "SOFTWARE
RELIABILITY, MEASUREMENT, AND TESTING Guidebook for Software
Reliability Measurement and Testing." Rather than at... | 5,351,885 |
def run_metarl(env, test_env, seed, log_dir):
"""Create metarl model and training."""
deterministic.set_seed(seed)
snapshot_config = SnapshotConfig(snapshot_dir=log_dir,
snapshot_mode='gap',
snapshot_gap=10)
runner = LocalRunner(... | 5,351,886 |
def get_default_mutation_op(dom):
""" Returns the default mutation operator for the domain. """
if dom.get_type() == 'euclidean':
return lambda x: euclidean_gauss_mutation(x, dom.bounds)
elif dom.get_type() == 'integral':
return lambda x: integral_gauss_mutation(x, dom.bounds)
elif dom.get_type() == 'di... | 5,351,887 |
def chunked(src, size, count=None, **kw):
"""Returns a list of *count* chunks, each with *size* elements,
generated from iterable *src*. If *src* is not evenly divisible by
*size*, the final chunk will have fewer than *size* elements.
Provide the *fill* keyword argument to provide a pad value and
en... | 5,351,888 |
def doc_to_schema_fields(doc, schema_file_name='_schema.yaml'):
"""Parse a doc to retrieve the schema file."""
return doc_to_schema(doc, schema_file_name=schema_file_name)[
'schema_fields'] | 5,351,889 |
def cluster(df: pd.DataFrame, k: int, knn: int = 10, m: int = 30, alpha: float = 2.0, verbose0: bool = False,
verbose1: bool = False, verbose2: bool = True, plot: bool = True) -> Tuple[pd.DataFrame, OrderedDict]:
"""
Chameleon clustering: build the K-NN graph, partition it into m clusters
:para... | 5,351,890 |
def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000):
"""
Load the CIFAR-10 dataset from disk and perform preprocessing to prepare
it for the two-layer neural net classifier. These are the same steps as
we used for the SVM, but condensed to a single function.
"""
... | 5,351,891 |
def test_operation_populated(petstore_expanded_spec):
"""
Tests that operations are populated as expected
"""
op = petstore_expanded_spec.paths["/pets"].get
# check description and metadata populated correctly
assert op.operationId == "findPets"
assert op.description.startswith("Returns all... | 5,351,892 |
def timeframe_int_to_str(timeframe: int) -> str:
"""
Convert timeframe from integer to string
:param timeframe: minutes per candle (240)
:return: string representation for API (4h)
"""
if timeframe < 60:
return f"{timeframe}m"
elif timeframe < 1440:
return f"{int(timeframe / ... | 5,351,893 |
def FIT(individual):
"""Sphere test objective function.
F(x) = sum_{i=1}^d xi^2
d=1,2,3,...
Range: [-100,100]
Minima: 0
"""
y=sum(x**2 for x in individual)
return y | 5,351,894 |
def update_range(value):
"""
For user selections, return the relevant range
"""
global df
min, max = df.timestamp.iloc[value[0]], df.timestamp.iloc[value[-1]]
return 'timestamp slider: {} | {}'.format(min, max) | 5,351,895 |
def project_users_add(ctx, user, **kwargs):
"""
Adds new user to the project.
"""
client = api.ProjectUser(
project=ctx.obj['project'],
config=ctx.obj['config'],
user=user,
**kwargs
)
client.save()
click.echo("User '{}' added to the project.".format(user.emai... | 5,351,896 |
def wrapper_func_easy(quantity = None, food = None, express = None, is_awesome = None):
"""
wrapper_func_easy: Sample wrapper function.
"""
dict_args = {}
dict_args['quantity'] = 42 if quantity is None else quantity
if food is not None:
dict_args['food'] = food
... | 5,351,897 |
def simplify(tile):
"""
:param tile: 34 tile format
:return: tile: 0-8 presentation
"""
return tile - 9 * (tile // 9) | 5,351,898 |
def vep(dataset, config, block_size=1000, name='vep', csq=False) -> MatrixTable:
"""Annotate variants with VEP.
.. include:: ../_templates/req_tvariant.rst
:func:`.vep` runs `Variant Effect Predictor
<http://www.ensembl.org/info/docs/tools/vep/index.html>`__ with the `LOFTEE
plugin <https://github... | 5,351,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.