content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def xnnpack_unit_test(name, srcs, copts = [], mingw_copts = [], msys_copts = [], deps = []):
"""Unit test binary based on Google Test.
Args:
name: The name of the test target to define.
srcs: The list of source and header files.
copts: The list of additional compiler flags for the target. -I ... | 5,339,900 |
def zscore(collection, iteratee=None):
"""Calculate the standard score assuming normal distribution. If iteratee
is passed, each element of `collection` is passed through a iteratee before
the standard score is computed.
Args:
collection (list|dict): Collection to process.
iteratee (mix... | 5,339,901 |
def AND(
*logicals: Tuple[func_xltypes.XlExpr]
) -> func_xltypes.XlBoolean:
"""Determine if all conditions in a test are TRUE
https://support.office.com/en-us/article/
and-function-5f19b2e8-e1df-4408-897a-ce285a19e9d9
"""
if not logicals:
raise xlerrors.NullExcelError('logical1 ... | 5,339,902 |
def check_mask(mask):
"""Check if mask is valid by its area"""
area_ratio = np.sum(mask) / float(mask.shape[0] * mask.shape[1])
return (area_ratio > MASK_THRES_MIN) and (area_ratio < MASK_THRES_MAX) | 5,339,903 |
def supported_estimators():
"""Return a `dict` of supported estimators."""
allowed = {
'LogisticRegression': LogisticRegression,
'RandomForestClassifier': RandomForestClassifier,
'DecisionTreeClassifier': DecisionTreeClassifier,
'KNeighborsClassifier': KNeighborsClassifier,
... | 5,339,904 |
def validate_gateway(gateway):
"""Test that a gateway is correctly set up.
Returns True if successful, or an error message."""
from hiicart.gateway.base import GatewayError
from hiicart.gateway.amazon.gateway import AmazonGateway
from hiicart.gateway.google.gateway import GoogleGateway
from hiic... | 5,339,905 |
def execute_query(db, query):
"""get data from database
"""
result = []
with closing(sqlite3.connect(db)) as conn:
conn.row_factory = sqlite3.Row
cur = conn.cursor()
for row in cur.execute(query):
result.append({name: row[name] for name in row.keys()})
return resu... | 5,339,906 |
def set_seeds(seed: int, env = None) -> None:
"""
Sets seeds for reproducibility
:param seed: Seed Value
:param env: Optionally pass gym environment to set its seed
:type seed: int
:type env: Gym Environment
"""
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
to... | 5,339,907 |
def test_get_optimal_route(get_routes_in_parts):
"""Test of the function get_optimal_route.
Args:
get_routes_in_parts (fixture): Returns each route from the list
separately. Each route is represented by a dictionary,
dictionary of the form:
{'Source': ..., 'Transfer'... | 5,339,908 |
def check_for_tool(tool_name: str) -> None:
"""Check if analysis tool is present on the file system."""
if sys.platform in ["win32", "msys", "cygwin"]:
tool_name += ".exe"
if pathlib.Path(f"./resources/ztools/{tool_name}").is_file():
return
sys.stderr.write(
colored(
... | 5,339,909 |
def module_list(path):
"""
Return the list containing the names of the modules available in
the given folder.
:param path: folder path
:type path: str
:returns: modules
:rtype: list
"""
if os.path.isdir(path):
folder_list = os.listdir(path)
elif path.endswith('.egg'):
... | 5,339,910 |
def check_weighting_input(z_matrix, c_method, w_method):
"""
Raise an exception if any argument is inappropriate for the corresponding
weighting method
"""
if w_method.upper() in {"MW", "EM", "SD", "CRITIC", "VIC"}:
if not is_normalized_matrix(z_matrix):
raise ValueError(
... | 5,339,911 |
def to_mgb_supported_dtype(dtype_):
"""get the dtype supported by megbrain nearest to given dtype"""
if (
dtype.is_lowbit(dtype_)
or dtype.is_quantize(dtype_)
or dtype.is_bfloat16(dtype_)
):
return dtype_
return _detail._to_mgb_supported_dtype(dtype_) | 5,339,912 |
def get_reset_state_name(t_fsm):
"""
Returns the name of the reset state.
If an .r keyword is specified, that is the name of the reset state.
If the .r keyword is not present, the first state defined
in the transition table is the reset state.
:param t_fsm: blifparser.BlifParser().bli... | 5,339,913 |
def gridmake(*arrays):
"""
Expands one or more vectors (or matrices) into a matrix where rows span the
cartesian product of combinations of the input arrays. Each column of the
input arrays will correspond to one column of the output matrix.
Parameters
----------
*arrays : tuple/list of np.... | 5,339,914 |
def pagerotate(document: vp.Document, clockwise: bool):
"""Rotate the page by 90 degrees.
This command rotates the page by 90 degrees counter-clockwise. If the `--clockwise` option
is passed, it rotates the page clockwise instead.
Note: if the page size is not defined, an error is printed and the page... | 5,339,915 |
def create_new_deployment(runner: Runner,
args: argparse.Namespace) -> Tuple[str, str]:
"""Create a new Deployment, return its name and Kubernetes label."""
run_id = str(uuid4())
def remove_existing_deployment():
runner.get_kubectl(
args.context, args.namespace... | 5,339,916 |
def inv_send_rheader(r):
""" Resource Header for Send """
if r.representation == "html" and r.name == "send":
record = r.record
if record:
db = current.db
s3db = current.s3db
T = current.T
s3 = current.response.s3
settings = current.de... | 5,339,917 |
def gauss_reparametrize(mu, logvar, n_sample=1):
"""Gaussian reparametrization"""
std = logvar.mul(0.5).exp_()
size = std.size()
eps = Variable(std.data.new(size[0], n_sample, size[1]).normal_())
z = eps.mul(std[:, None, :]).add_(mu[:, None, :])
z = torch.clamp(z, -4., 4.)
return z.view(z.si... | 5,339,918 |
def run_setup_py(cmd, pypath=None, path=None,
data_stream=0, env=None):
"""
Execution command for tests, separate from those used by the
code directly to prevent accidental behavior issues
"""
if env is None:
env = dict()
for envname in os.environ:
env[en... | 5,339,919 |
def test():
"""Run all the tests in the `tests/` directory using pytest """
import pytest
here = os.path.abspath(os.path.dirname(__file__))
pytest.main([os.path.join(here, 'tests')]) | 5,339,920 |
def forward_pass(img, session, images_placeholder, phase_train_placeholder, embeddings, image_size):
"""Feeds an image to the FaceNet model and returns a 128-dimension embedding for facial recognition.
Args:
img: image file (numpy array).
session: The active Tensorflow session.
images_pl... | 5,339,921 |
def restore_tf_variable(tf_sess, target_paras, model_name):
"""restore explorer variable with tf.train.checkpoint"""
reader = tf.train.NewCheckpointReader(model_name)
var_names = reader.get_variable_to_shape_map().keys()
result = dict()
for _name in var_names:
result[_name] = reader.get_tens... | 5,339,922 |
def check_url(url):
"""Returns True if the url returns a response code between 200-300,
otherwise return False.
"""
try:
req = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(req)
return response.code in range(200, 209)
except Exception:
... | 5,339,923 |
def build_permutation_importance(
data,
data_labels,
feature_names,
model,
metrics,
repeats=100,
random_seed=42
):
"""Calculates permutation feature importance."""
pi_results = {}
for metric in metrics:
pi = sklearn.inspection.permutation_i... | 5,339,924 |
def _load_parent(collection, meta):
"""Determine the parent document for the document that is to be
ingested."""
parent = ensure_dict(meta.get("parent"))
parent_id = meta.get("parent_id", parent.get("id"))
if parent_id is None:
return
parent = Document.by_id(parent_id, collection=collect... | 5,339,925 |
def get_latest_sensor_reading(sensor_serial, metric):
"""
Get latest sensor reading from MT sensor
metrics: 'temperature', 'humidity', 'water_detection' or 'door'
"""
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Cisco-Meraki-API-Key": merak... | 5,339,926 |
def border_msg(msg: str):
"""
This function creates boarders in the top and bottom of text
"""
row = len(msg)
h = ''.join(['+'] + ['-' * row] + ['+'])
return h + "\n" + msg + "\n" + h | 5,339,927 |
def test_visualization_empty_visu_file(data_file_Fujita,
condition_file_Fujita,
visu_file_Fujita_empty):
"""
Test: Empty visualization spezification file should default to routine
for no file at all
"""
plot_data_and_simul... | 5,339,928 |
def create_app(config_name='development'):
"""Returns flask app based on the configuration"""
flask_app = Flask(__name__)
flask_app.config.from_object(app_config[config_name])
flask_app.config['JSON_SORT_KEYS'] = False
flask_app.url_map.strict_slashes = False
flask_app.register_error_handler(400... | 5,339,929 |
def test_exists(keys, key, expected_result):
"""
GIVEN keys to add, key to check for and expected exists result
WHEN keys are added to the bucket and exists is called with the key
THEN the expected result is returned.
"""
test_bucket = bucket.Bucket()
for insert_key in keys:
test_buc... | 5,339,930 |
def auto_merge_paths(data, auto_merge_distance, auto_close_paths=True):
"""
This function connects all paths in the given dataset, for which the start or endpoints are closer than
auto_merge_distance.
:param data: Should be a list or tuple containing paths, attributes, svg_attributes.
:param auto_m... | 5,339,931 |
def is_authorized(secure: AccessRestriction):
"""Returns authorization status based on the given access restriction.
:param secure: access restriction
:type secure: AccessRestriction
:return: authorization status (``True`` or ``False``)
"""
if secure == AccessRestriction.ALL:
return Tru... | 5,339,932 |
def create_link_forum(**attrs):
"""Save a new link forum."""
link = build_link_forum(**attrs)
link.save()
return link | 5,339,933 |
def open_report():
"""Probe Services: Open report
---
parameters:
- in: body
name: open report data
required: true
schema:
type: object
properties:
data_format_version:
type: string
format:
type: string
... | 5,339,934 |
def prepare_scan():
"""
Returns a lexical scanner for HTSQL grammar.
"""
# Start a new grammar.
grammar = LexicalGrammar()
# Regular context.
query = grammar.add_rule('query')
# Whitespace characters and comments (discarded).
query.add_token(r'''
SPACE: [\s]+ | [#] [^\0\r... | 5,339,935 |
def check_arc(val):
"""Used to check if unlawful inverse trig function is executed by users
raise errors if happened. Cannot take inverse trig function that is not between -1 and 1
Args:
val ([int or float])
Raises:
raise error if number is not between -1 and 1
"""
if isinstanc... | 5,339,936 |
def test_s3_hook_file_delete_404(
client_hook_s3_storage_1: object, s3_client: object, s3_resource: object, s3_bucket: str
) -> None:
"""Testing DELETE resource
Args:
client_hook_s3_storage_1 (fixture): The test client.
s3_client (fixture): A S3 client object.
s3_resource (fixture):... | 5,339,937 |
def generate_question_answer(data_dir):
"""
根据三元组,生成问答数据集
:return:
"""
# 将json文件的内容导出列表
# path = '/Users/admin/Desktop/words2.json'
data = get_data()
ralations = ['审计', '子单位', '涉及', '简称', '存在', '审计日期', '篇章', '条款']
qa = []
# with open(path, 'r') as f:
# data = json.load(f... | 5,339,938 |
def get_test_server(ctxt, **kw):
"""Return a Server object with appropriate attributes.
NOTE: The object leaves the attributes marked as changed, such
that a create() could be used to commit it to the DB.
"""
kw['object_type'] = 'server'
get_db_server_checked = check_keyword_arguments(
... | 5,339,939 |
def main():
"""
Initializes and executes the program.
"""
print("%s\n\n%s %s (%s)\n" % (BANNER, NAME, VERSION, URL))
args = parse_args()
if args.update:
update()
exit()
if args.list:
representations = list_representations()
for _ in representations:
print("- %s" % _)
print("\n")
exit()
i... | 5,339,940 |
def create_songs_played_by_user(**kwargs):
"""
This function is used to create data for SongsPlayedByUser Table
Args:
**kwargs: provided kwargs
Examples:
>>> create_songs_played_by_user(song_name='this song', user_name='this user', genre='rock', date_played='2010-01-09')
"""
So... | 5,339,941 |
def keras_model(optimizer="Adamax", activation="softplus", units=32):
"""Function to create model, required for KerasClassifier"""
model = Sequential()
model.add(Dense(units, activation="relu", input_dim=2500))
model.add(Dense(2, activation=activation))
model.compile(loss="categorical_crossentropy",... | 5,339,942 |
def start_end_key(custom_cmp):
"""
Compare models with start and end dates.
"""
class K(object):
"""
Define comparison operators.
http://code.activestate.com/recipes/576653-convert-a-cmp-function-to-a-key-function/
"""
def __init__(self, obj, *args):
s... | 5,339,943 |
def get_previous_release_date():
""" Fetch the previous release date (i.e. the release date of the current live database) """
releases = Release.objects.all().order_by('-date')
return str(releases[1].date) | 5,339,944 |
def init_weather():
"""
This is called only once, when you want to enable the weather system.
"""
weather = create.create_script(WeatherScript)
weather.start() | 5,339,945 |
def readLensModeParameters(calibfiledir, lensmode='WideAngleMode'):
"""
Retrieve the calibrated lens correction parameters
"""
# For wide angle mode
if lensmode == 'WideAngleMode':
LensModeDefaults, LensParamLines = [], []
with open(calibfiledir, 'r') as fc:
# Read the... | 5,339,946 |
def scale(boxlist, y_scale, x_scale, scope=None):
"""scale box coordinates in x and y dimensions.
Args:
boxlist: BoxList holding N boxes
y_scale: (float) scalar tensor
x_scale: (float) scalar tensor
scope: name scope.
Returns:
boxlist: BoxList holding N boxes
"""
with... | 5,339,947 |
def fetch(uri: str, method: str = 'get', token: str = None):
""":rtype: (str|None, int)"""
uri = 'https://api.github.com/{0}'.format(uri)
auth = app.config['GITHUB_AUTH']
headers = {'Accept': 'application/vnd.github.mercy-preview+json'}
json = None
if token:
headers['Authorization'] = '... | 5,339,948 |
def test_branch_with_no_atoms():
"""Test SELFIES that have a branch, but the branch has no atoms in it.
Such branches should not be made in the outputted SMILES.
"""
assert is_eq(sf.decoder("[C][Branch1_1][Ring2][Branch1_1]"
"[Branch1_1][Branch1_1][F]"),
"CF... | 5,339,949 |
def nested_tuple(container):
"""Recursively transform a container structure to a nested tuple.
The function understands container types inheriting from the selected abstract base
classes in `collections.abc`, and performs the following replacements:
`Mapping`
`tuple` of key-value pair `tuple`s.... | 5,339,950 |
def _validate_args(func, args, kwargs):
"""Validate customer function args and convert them to kwargs."""
# Positional arguments validate
all_parameters = [param for _, param in signature(func).parameters.items()]
# Implicit parameter are *args and **kwargs
if any(param.kind in {param.VAR_KEYWORD, p... | 5,339,951 |
def remove_file(file):
""" Deletes file from OS if it exists
Args:
file (str, Path):
a filename or opened readable file
"""
if isinstance(file, (str, Path)) and os.path.exists(file):
os.remove(file)
elif hasattr(file, 'name') and os.path.exists(file.name):
file.... | 5,339,952 |
def _qual_arg(user_value,
python_arg_name,
gblock_arg_name,
allowable):
"""
Construct and sanity check a qualitative argument to
send to gblocks.
user_value: value to try to send to gblocks
python_arg_name: name of python argument (for error string)
gbl... | 5,339,953 |
def is_valid_ip(ip_addr):
"""
:param ip_addr:
:return:
"""
octet_ip = ip_addr.split(".")
int_octet_ip = [int(i) for i in octet_ip]
if (len(int_octet_ip) == 4) and \
(0 <= int_octet_ip[0] <= 255) and \
(0 <= int_octet_ip[1] <= 255) and \
(0 <= i... | 5,339,954 |
def make_replay_buffer(env: gym.Env, size: int) -> ReplayBuffer:
"""Make a replay buffer.
If not ShinEnv:
Returns a ReplayBuffer with ("rew", "done", "obs", "act", "log_prob", "timeout").
If ShinEnv:
Returns a ReplayBuffer with ("rew", "done", "obs", "act", "log_prob", "timeout", "state").
... | 5,339,955 |
def scale_places(places: int) -> Callable[[decimal.Decimal], decimal.Decimal]:
"""
Returns a function that shifts the decimal point of decimal values to the
right by ``places`` places.
"""
if not isinstance(places, int):
raise ValueError(
'Argument `places` must be int. Got valu... | 5,339,956 |
def format_dot_y_axis(axes: Axes, bottom: float, top: float) -> None:
"""Draw the ticks, format the labels, and adjust sizing for the day-axis.
Parameters
----------
axes: `Axes`
The Axes object describing the graph
bottom: `float`
Midnight of the earliest day
top: `float`
... | 5,339,957 |
def create_model(params : model_params):
"""
Create ReasoNet model
Args:
params (class:`model_params`): The parameters used to create the model
"""
logger.log("Create model: dropout_rate: {0}, init:{1}, embedding_init: {2}".format(params.dropout_rate, params.init, params.embedding_init))
# Query and Doc... | 5,339,958 |
def test_missing_management_form(live_server, selenium):
"""
Asserts the ConvenientFormset instantiation raises an error message when
the management form is missing.
"""
# Load webpage for test
params = {'template_name': 'initialization/missing_management_form.html'}
test_url = f'{live_serve... | 5,339,959 |
def _process_voucher_data_for_order(cart):
"""Fetch, process and return voucher/discount data from cart."""
vouchers = Voucher.objects.active(date=date.today()).select_for_update()
voucher = get_voucher_for_cart(cart, vouchers)
if cart.voucher_code and not voucher:
msg = pgettext(
'... | 5,339,960 |
def transform_batch(images,
max_rot_deg,
max_shear_deg,
max_zoom_diff_pct,
max_shift_pct,
experimental_tpu_efficiency=True):
"""Transform a batch of square images with the same randomized affine
transformation.
"""... | 5,339,961 |
def prep_seven_zip_path(path, talkative=False):
"""
Print p7zip path on POSIX, or notify if not there.
:param path: Path to use.
:type path: str
:param talkative: Whether to output to screen. False by default.
:type talkative: bool
"""
if path is None:
talkaprint("NO 7ZIP\nPLEA... | 5,339,962 |
async def root() -> Dict[str, str]:
"""
Endpoint for basic connectivity test.
"""
logger.debug('root requested')
return {'message': 'OK'} | 5,339,963 |
def detach_policy(user_name, policy_arn):
"""
Detaches a policy from a user.
:param user_name: The name of the user.
:param policy_arn: The Amazon Resource Name (ARN) of the policy.
"""
try:
iam.User(user_name).detach_policy(PolicyArn=policy_arn)
logger.info("Detached policy %s ... | 5,339,964 |
def user_create_profile(sender, instance, created, **kwargs):
"""
Depending of user_type on the User model, we want to create
a specific "type of profile"
"""
logger.info('[entities receiver]')
if created:
# Here we will put the logic of which type of user we will create.
... | 5,339,965 |
def overlapping_community(G, community):
"""Return True if community partitions G into overlapping sets.
"""
community_size = sum(len(c) for c in community)
# community size must be larger to be overlapping
if not len(G) < community_size:
return False
# check that the set of nodes in the... | 5,339,966 |
def validate_credential(zone, credential):
"""
Token is already calculated
"""
source = DataSource(DataSource.TYPE_DATABASE, CONNECTION_FILE_PATH)
canAccess = source.get_or_create_client_access_rights(credential, zone)
if canAccess:
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
... | 5,339,967 |
def test_fast_gradient_method():
"""
Fast gradient method unit test.
"""
input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)
label = np.asarray([2], np.int32)
label = np.eye(3)[label].astype(np.float32)
attack = FastGradientMethod(Net())
ms_adv_x = attack.generate(input_np, label)
... | 5,339,968 |
def test_swap_child():
""" """
for test in run_hotswap_test(DEFAULT_TIME+2,
original="""
from enaml.widgets.api import *
enamldef Main(Window): view:
Container:
Label:
text = "child 1"
... | 5,339,969 |
def gm(data,g1=0.0,g2=0.0,g3=0.0,inv=False):
"""
Lorentz-to-Gauss Apodization
Functional form:
gm(x_i) = exp(e - g*g)
Where: e = pi*i*g1
g = 0.6*pi*g2*(g3*(size-1)-i)
Parameters:
* data Array of spectral data.
* g1 Inverse exponential width.
* g2 ... | 5,339,970 |
def exp_t(u, t):
"""Compute exp_t for `u`."""
if t == 1.0:
return torch.exp(u)
else:
return torch.relu(1.0 + (1.0 - t) * u) ** (1.0 / (1.0 - t)) | 5,339,971 |
def decode_json_dict(data):
# type: (Dict) -> Dict
"""Converts str to python 2 unicodes in JSON data."""
return _strify(data) | 5,339,972 |
def linear_search(lst: list, x: Any) -> int:
"""Return the index of the first element of `lst` equal to `x`, or -1 if no
elements of `lst` are equal to `x`.
Design idea: Scan the list from start to finish.
Complexity: O(n) time, O(1) space.
For an improvement on linear search for sorted lists, se... | 5,339,973 |
def get_color_cmap(name, n_colors=6):
"""
Return discrete colors from a matplotlib palette.
:param name: Name of the palette. This should be a named matplotlib colormap.
:type: str
:param n_colors: Number of discrete colors in the palette.
:type: int
:return: List-like object of colors as h... | 5,339,974 |
def logkde2entropy(vects, logkde):
"""
computes the entropy of the kde
incorporates vects so that kde is properly normalized (transforms into a truly discrete distribution)
"""
vol = vects2vol(vects)
truth = logkde > -np.infty
return -vects2vol(vects)*np.sum(np.exp(logkde[truth])*logkde[trut... | 5,339,975 |
def issue_2021_02_16():
"""
"""
import psana.pscalib.calib.MDBWebUtils as wu
det_uniqueid = 'epix10ka_3926196238-0175152897-1157627926-0000000000-0000000000-0000000000-0000000000_3926196238-0174824449-0268435478-0000000000-0000000000-0000000000-0000000000_3926196238-0175552257-3456106518-0000000000-0000000000-0... | 5,339,976 |
def get_deployment_json(
runner: Runner,
deployment_name: str,
context: str,
namespace: str,
deployment_type: str,
run_id: Optional[str] = None,
) -> Dict:
"""Get the decoded JSON for a deployment.
If this is a Deployment we created, the run_id is also passed in - this is
the uuid w... | 5,339,977 |
def test_append_test_for_small(small_linklist):
""" tests to see if node appended to small group"""
assert len(small_linklist) == 4
small_linklist.append(1)
assert len(small_linklist) == 5 | 5,339,978 |
def generate_logo(filename):
"""
Load component images, apply a sinogram, and assemble to form the svmbir logo.
Args:
filename: Name of image file used to generate the sinogram for inclusion in the logo.
Returns:
None
"""
# Load the svmbir image, convert to negative, display, a... | 5,339,979 |
def is_admin() -> bool:
"""Check does the script has admin privileges."""
import ctypes
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except AttributeError: # Windows only
return None | 5,339,980 |
def get_firewall_status(gwMgmtIp, api_key):
"""
Reruns the status of the firewall. Calls the op command show chassis status
Requires an apikey and the IP address of the interface we send the api request
:param gwMgmtIp:
:param api_key:
:return:
"""
global gcontext
# cmd = url... | 5,339,981 |
def inferDistanceRelations(matcher, reqNode, ego, line):
"""Infer bounds on distances from a requirement."""
distMatcher = lambda node: matcher.matchUnaryFunction('DistanceFrom', node)
allBounds = matcher.matchBounds(reqNode, distMatcher)
for target, bounds in allBounds.items():
if not isinstanc... | 5,339,982 |
def test_vgp_unchanged_at_optimum(with_tf_random_seed, vgp_gpr_optim_setup):
"""Test that the update does not change sites at the optimum"""
vgp, _ = vgp_gpr_optim_setup
# ELBO at optimum
optim_elbo = vgp.elbo()
# site update step
vgp.update_sites()
# ELBO after step
new_elbo = vgp.elbo(... | 5,339,983 |
def test_get_map_data():
"""Tests that a SimilarChecker respects the MapReduceMixin interface"""
linter = PyLinter(reporter=Reporter())
# Add a parallel checker to ensure it can map and reduce
linter.register_checker(similar.SimilarChecker(linter))
source_streams = (
str(INPUT / "similar_l... | 5,339,984 |
def create_logger(name, logfile, level):
"""
Sets up file logger.
:param name: Logger name
:param logfile: Location of log file
:param level: logging level
:return: Initiated logger
"""
logger = logging.getLogger(name)
handler = logging.FileHandler(logfile)
formatter = logging.Fo... | 5,339,985 |
def restore_builtins():
"""Restore the original builtin functions."""
for k, v in builtins.items():
mod, func = k.rsplit('.', 1) # 'os.path.isdir' -> ('os.path', 'isdir')
name_elts = mod.split('.')
top = name_elts.pop(0)
module = globals()[top]
for elt in name_elts:
... | 5,339,986 |
def canonicalize_path(cwd, path, debug):
"""Given a path composed by concatenating two or more parts,
clean up and canonicalize the path."""
# // => /
# foo/bar/../whatever => foo/whatever [done]
# foo/bar/./whatever => foo/whatever [done]
# /foo/bar => /foo/bar [done]
# foo/bar... | 5,339,987 |
def context_command(func):
"""
Base options for jobs that can override context variables on the command
line.
The command receives a *context_overrides* argument, a dict ready to be
deep merged in templates contexts.
"""
@click.option('--context', '-c', 'context_vars', multiple=True,
... | 5,339,988 |
def checksum(number):
"""Calculate the checksum. A valid number should have a checksum of 1."""
check = 0
for n in number:
check = (2 * check + int(10 if n == 'X' else n)) % 11
return check | 5,339,989 |
def instanceof(value, type_):
"""Check if `value` is an instance of `type_`.
:param value: an object
:param type_: a type
"""
return isinstance(value, type_) | 5,339,990 |
def step(y, t, dt):
""" RK2 method integration"""
n = y.shape[0]
buf_f0 = np.zeros((n, ndim+1))
buf_f1 = np.zeros((n, ndim+1))
buf_y1 = np.zeros((n, ndim+1))
buf_f0 = tendencies(y)
buf_y1 = y + dt * buf_f0
buf_f1 = tendencies(buf_y1)
Y = y + 0.5 * (buf_f0 + buf_f1) * dt
retu... | 5,339,991 |
def sample_deletes(graph_, rgb_img_features, xyz,
delete_scores, num_deletes, threshold,
gc_neighbor_dist, padding_config,
**kwargs):
"""Sample Deletes.
Args:
graph_: a torch_geometric.data.Batch instance with attributes:
- rgb... | 5,339,992 |
def make_char(hex_val):
"""
Create a unicode character from a hex value
:param hex_val: Hex value of the character.
:return: Unicode character corresponding to the value.
"""
try:
return unichr(hex_val)
except NameError:
return chr(hex_val) | 5,339,993 |
def add_chemicals_from_file(filename : str):
"""Parses specified file, adding a chemical to the library for each line in the file.
Each line in the file should first contain the chemicals's molar mass, followed by a list of its names.
All words should be separated by spaces. Example file:
58.44 NaCl ta... | 5,339,994 |
def normalize(features):
"""
Normalizes data using means and stddevs
"""
means, stddevs = compute_moments(features)
normalized = (np.divide(features, 255) - means) / stddevs
return normalized | 5,339,995 |
def get_args_from_str(input: str) -> list:
"""
Get arguments from an input string.
Args:
input (`str`): The string to process.
Returns:
A list of arguments.
"""
return ARG_PARSE_REGEX.findall(input) | 5,339,996 |
def get_all_files(repo_root):
"""Get all files from in this repo."""
output = []
for root, _, files in os.walk(repo_root):
for f in files:
if f.lower().endswith(tuple(CPP_SUFFIXES + ['.py'])):
full_name = os.path.join(root, f)[len(repo_root) + 1:]
if not ... | 5,339,997 |
def simulate(school: List[int], days: int) -> int:
"""Simulates a school of fish for ``days`` and returns the number of fish."""
school = flatten_school(school)
for day in range(1, days + 1):
school = simulate_day(school)
return sum(school) | 5,339,998 |
def SPTU(input_a, input_b, n_channels: int):
"""Softplus Tanh Unit (SPTU)"""
in_act = input_a+input_b
t_act = torch.tanh(in_act[:, :n_channels, :])
s_act = torch.nn.functional.softplus(in_act[:, n_channels:, :])
acts = t_act * s_act
return acts | 5,339,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.