content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load_webcat_data(webcat_csv):
""" Create a dictionary that maps from eids to lists with webcat data"""
table = generate_form.csv_to_numpy(webcat_csv, FIRST_ROW)
data = {}
for i in range(table.shape[0]):
eid = table[i, USER].strip().lower()
data[eid] = list(table[i, :])
return da... | 66,200 |
def get_pbo_pe_comparisons(
outcome_X,
train_comps,
problem,
utils,
init_round,
total_training_round,
comp_noise_type,
comp_noise,
pe_strategy,
):
"""
Generate TS-based comparisons on previously observed points
Args:
outcome_X ([type]): [description]
trai... | 66,201 |
async def _named_spooled_temporary_file(max_size=0, mode='w+b', buffering=-1,
encoding=None, newline=None,
suffix=None, prefix=None, dir=None,
loop=None, executor=None):
"""Open a spooled temporar... | 66,202 |
def test_flags_cfg_init(flag_data_file, default_flag_data, monkeypatch):
"""Ensure the flag manager is using the flag data over the default_config"""
flag_data = {
'UST_EXTENSION': '0',
}
flag_file = flag_data_file('flags.cfg', flag_data)
default_file = flag_data_file('default_flags.cfg', de... | 66,203 |
def kill_children():
"""Kill debugger processes"""
global CHILDREN_PID # pylint: disable=global-statement
for child in CHILDREN_PID:
child.kill()
CHILDREN_PID = [] | 66,204 |
def Covariance4D2Correlation4D(Cov_MPMB):
"""It normalizes each element of the 4-D Multi-Polarimetric Multi-Baseline
with respect to the corresponding diagonal terms.
INPUT
Cov_MPMB: [Nimm*Npol x Nimm*Npol x Nr x Na] Covariance matrices
OUTPUT
Corr_MPMB: [Nimm*Npol x Ni... | 66,205 |
def run(total_workers=1, chunk_size=100, threads_per_worker=None, once=False, greedy=False, rses=[], scheme=None, exclude_rses=None, include_rses=None, delay_seconds=0):
"""
Starts up the reaper threads.
:param total_workers: The total number of workers.
:param chunk_size: the size of chunk for deletio... | 66,206 |
def header(
term: Terminal,
ui: UI,
*,
host: Host,
dbinfo: DBInfo,
tps: int,
active_connections: int,
system_info: Optional[SystemInfo] = None,
) -> Iterator[str]:
"""Return window header lines."""
pg_host = f"{host.user}@{host.host}:{host.port}/{host.dbname}"
yield (
... | 66,207 |
def get_stats_intraday(**kwargs):
"""
MOVED to iexfinance.iexdata.get_stats_intraday
"""
raise ImmediateDeprecationError("get_stats_intraday") | 66,208 |
def text_pos(text: Union[StringView, str],
line: int, column: int,
lbreaks: List[int] = []) -> int:
"""
Returns the text-position for a given line and column or -1 if the line
and column exceed the size of the text.
"""
if lbreaks:
try:
return lbreaks[li... | 66,209 |
def formatList(inputList):
"""
Formats a list of items to html unordered list
:param inputList: list of items to be formatted
"""
report = HTML()
htmlList = report.ul
for val in inputList:
val = str(val)
htmlList.li(val)
return report | 66,210 |
def _plot_annotations(raw, params):
"""Set up annotations for plotting in raw browser."""
while len(params['ax_hscroll'].collections) > 0:
params['ax_hscroll'].collections.pop()
segments = list()
_setup_annotation_colors(params)
for idx, annot in enumerate(raw.annotations):
annot_sta... | 66,211 |
def multi_maps_dfs(job_func, dfs_chunks, rou, reduce_num=1):
"""
执行与文件chunk数相同数量的map
:param job_func: 全部slave统一的默认的job python脚本位置
:param dfs_chunks:所有的文件chunk 编号list
:param admm_para_path: ADMM 的本地参数路径
:param reduce_num: partition中需要reduce的数量
:return:
"""
# 执行map时,触发一个异步的执行chunk检查
... | 66,212 |
async def get_images_list(
request: Request,
page: schemas.PageRequest,
):
"""
According to params to get images list
:param request: pony ORM
:param page: page_num page_size To decide how many images return
:return: List[image_url]
"""
with request.pony_session:
imag... | 66,213 |
def test_noschedule_first(testloop):
"""Non-scheduled coro funcs run first before scheduling tasks"""
event = LoadLimitEvent()
val = []
@event
async def one(result):
"""one"""
val.append(1)
@event
async def two(result):
"""two"""
val.append(2)
@event
... | 66,214 |
def test__conformer():
""" test autofile.fs.conformer
"""
prefix = os.path.join(PREFIX, 'conformer')
os.mkdir(prefix)
locs = [autofile.system.generate_new_conformer_id()]
cnf_fs = autofile.fs.conformer(prefix)
print(cnf_fs.leaf.path(locs))
assert not cnf_fs.leaf.exists(locs)
cnf_fs... | 66,215 |
def _get_det_bboxes(
pred: List[dict], labels: List[str], im_path: str = None
) -> List[DetectionBbox]:
""" Gets the bounding boxes and labels from the prediction object
Args:
pred: the output of passing in an image to torchvision's FasterRCNN
model
labels: list of labels
im... | 66,216 |
def test_net(
args,
dataset_name,
proposal_file,
output_dir,
ind_range=None,
gpu_id=0,
include_feat=False):
"""Run inference on all images in a dataset or over an index range of images
in a dataset using a single GPU.
"""
assert not cfg.MODEL.RPN_O... | 66,217 |
def main():
"""Run main function."""
data = json.loads(sys.stdin.read())
# Prepare the node data by adjoining a key value equal to each record's
# index in the original data.
nodes = [add_key(record, index) for (index, record) in enumerate(data["nodes"])]
# Convert the link data to Multinet f... | 66,218 |
def contrastive_loss_test(y_true, dist):
"""Test function above using implementation with numpy instead tensors."""
margin = P.margin
return y_true * np.square(dist) + (1 - y_true) * np.square(np.max(margin - dist, 0)) | 66,219 |
def verify_password_hash(password: str, password_hash: str) -> bool:
"""
Helper function for verifying hashed password against
plain password.
Args
----
password: str
password_hash: str
Returns
-------
bool (Confirming if password is same as ... | 66,220 |
def test_xhmm_extract_ped_step_part_get_output_files(targeted_seq_cnv_calling_workflow):
"""Tests XhmmStepPart::_get_output_files_genotype()"""
# Define expected
base_out = "work/{mapper}.xhmm.{library_name}/out/{mapper}.xhmm.{library_name}"
expected = get_expected_output_vcf_files_dict(base_out=base_ou... | 66,221 |
def _get_project_results_for_jobs(jobs):
"""Return projects for jobs."""
projects = {}
for job in sorted(jobs, key=lambda j: j.name):
project_name = job.get_environment().get('PROJECT_NAME', job.name)
if project_name not in projects:
projects[project_name] = {'name': project_name, 'jobs': []}
i... | 66,222 |
def untex(s):
"""Replace tex constructs with unicode"""
s = s.replace('$^{\circ}$', degree)
s = re.sub(emph, '<i>\g<emph_text></i>', s)
s = s.replace('\&', '&')
s = s.replace(r'$\beta$', beta)
s = s.replace(r'{\AE}', 'Æ')
s = s.replace(r'{\O}', 'Ø')
s = s.replace(r'{\AA}', 'Å')
s = s... | 66,223 |
def _clean(arr):
"""Convert ratio values for missing pieces of the tax into "unclassified"
and remove empty entries.
Rules:
- if all the cols are unclassified then remove row.
- if there is no classification for either genus, subfamily or family then remove row.
- collapse unclassifi... | 66,224 |
def to_categorical(batch, num_classes):
"""
Converts a batch of length-padded integer sequences to a one-hot encoded sequence
:param batch:
:param num_classes:
:return:
"""
b, l = batch.shape
out = np.zeros((b, l, num_classes))
for i in range(b):
seq = batch[0, :]
... | 66,225 |
def unixgetaddr(program):
"""Get the hardware address on a Unix machine."""
from os import popen
for line in popen(program):
words = line.lower().split()
if 'hwaddr' in words:
addr = words[words.index('hwaddr') + 1]
return int(addr.replace(':', ''), 16)
if 'et... | 66,226 |
def set_console_cursor_position(handle, coord: COORD):
"""
Sets the cursor position in console.
:param windll.kernel32.GetStdHandle handle: A handle.
"""
windll.kernel32.SetConsoleCursorPosition(handle, coord) | 66,227 |
def format_summary(translation):
""" Transforms the output of the `from_batch` function
into nicely formatted summaries.
"""
raw_summary, _, _ = translation
summary = (
raw_summary.replace("[unused0]", "")
.replace("[unused3]", "")
.replace("[PAD]", "")
.replace("[unu... | 66,228 |
def splitintopolygons(polygons,d):
"""
Give a 1d array of length (N*(d*(d+1))), consisting of a series of N simplexes. Each simplex
has d+1 locations, each location is d long. For example, for 2d:
[(x1,y1),(x2,y2),(x3,y3)][(x1,y1),(x2,y2),(x3,y3)]...
d = dimensions
... | 66,229 |
def pwbs_execute_scommand(command, vdm, special):
"""Funkcja wykonująca zadanie specjalne"""
verbose_debug_mode = vdm
if command == "--new-config":
print("PWBS: Generowanie Pustego Pliku Komend")
dane = []
if not special: # pragma: no cover
write_json(config_file, dane)
... | 66,230 |
def test_get_recipe_tags():
"""
Test for get_recipe_tags method.
Test is passed only if the provided recipe is classified correctly.
This means that all the ingredients of the recipe must be classified correctly.
"""
assert recipe_tagger.get_recipe_tags(["aubergine"]) == ["vegetable"]
assert... | 66,231 |
def read_image(filename):
"""
Reads a filename of an image as PIL pytorch format image. Returns the image
:param filename: Path to image
:return: PIL Image
"""
return Image.open(filename) | 66,232 |
def normalise(x):
"""
Normalises a given 3D vector.
Parameter:
x - a 3D vector that is an array.
"""
if x is not None and len(x) == 3:
return x/np.sqrt(np.dot(x,x))
else:
raise Exception("Three coordinates are required in the array.")
return No... | 66,233 |
def sequence_id(sqlite_connection):
"""
Функция возвращает список из id всех остановок
"""
try:
cur = sqlite_connection.cursor()
cur.execute("SELECT _id FROM stopsker")
seq = list()
for elem in cur.fetchall():
seq.append(int(elem[0]))
except Exception a... | 66,234 |
def asin(x):
"""
Computes inverse sine element-wise.
:param x: y-coordinate on the unit circle.
:type x: array
:return: The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2].
"""
return _cur_framework(x).asin(x) | 66,235 |
def sockaddr_from_tupe(addr):
"""
Converts a socket address tuple (host, port) to a proper socketaddr_*
C struct.
@param addr:
@return:
"""
if ":" in addr[0]:
family = socket.AF_INET6
if len(addr) == 4:
addr, port, flowinfo, scope_id = addr
else:
... | 66,236 |
def get_annotation_output(annotation_id: Optional[pulumi.Input[str]] = None,
annotation_store_id: Optional[pulumi.Input[str]] = None,
dataset_id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
... | 66,237 |
def add_matches(flight_matches, flight_ids):
"""
Add new matches to the flight_ids dict.
Returns the number of newly matched flights.
"""
matches = 0
for i in flight_matches.index:
prev_id = flight_matches.loc[i, 'FLIGHT_ID_x']
next_id = flight_matches.loc[i, 'FLIGHT_ID_y']
... | 66,238 |
async def handle_command(
request: Request,
response: Response,
background_tasks: BackgroundTasks,
x_slack_request_timestamp: int = Header(None),
x_slack_signature: str = Header(None),
db_session: Session = Depends(get_db),
):
"""Handle all incomming Slack commands."""
raw_request_body =... | 66,239 |
def inference(request):
""" Function: inference
* inference top
"""
def _get_selected_object():
project_name = request.session.get('inference_view_selected_project', None)
selected_project = Project.objects.get(name=project_name)
model_name = request.session.get('infere... | 66,240 |
def parse_registry_url(registry_url):
"""
Given an AWS ECR registry URL, parses out the AWS Account ID and Region
>>> aid, region = parse_registry_url('http://12345.dkr.ecr.us-west-2.amazonaws.com')
('12345', 'us-west-2')
>>> aid, region = parse_registry_url('12345.dkr.ecr.us-west-2.amazonaws.com'... | 66,241 |
def add_repository_to_path(repo, rev="HEAD", in_repo_path=""):
"""
Adds a repository reference to sys.path. If gitimporter is not initialized yet, it will also be added to
sys.path_hooks
:param repo: a pygit2 repository object or a path to a git repository
:param rev: the revision which should be u... | 66,242 |
def test_for_Si_substrate(
model,
): # TODO test fit on spectrum to decide wether Si substrate is required or not
"""make test fit for only slice 900-1000""" | 66,243 |
def add_zone_ideal_loads_energy(idf):
"""add fmu output of
- Zone Ideal Loads Zone Total Heating Energy
- Zone Ideal Loads Zone Total Cooling Energy
"""
idf = ensure_contains(
idf,
'EnergyManagementSystem:GlobalVariable',
'gv_the')
idf = ensure_contains(
... | 66,244 |
def _entropy(data, group_pop_var, total_pop_var):
"""Calculate Entropy index.
Parameters
----------
data : pandas.DataFrame or geopandas.GeoDataFrame
Dataframe or geodataframe if spatial index holding data for location of interest
group_pop_var : string
Variable containing the popul... | 66,245 |
def main():
"""
Main service for transport module
"""
parse = ParserHelper(
description="Wirepas Gateway Transport service arguments",
version=transport_version,
)
parse.add_file_settings()
parse.add_mqtt()
parse.add_gateway_config()
parse.add_filtering_config()... | 66,246 |
def procemIOTTicketWriterThread(iott_buffer, iott_c, counter, item_counter):
"""This is a spawnable thread that sends one HTTP packet to IoTTicket and dies after success.
It measures how long it takes from here until we get a response."""
# print(common_utils.getTimeString(), threading.current_thread().n... | 66,247 |
def Delta_calc(airtemp=scipy.array([])):
"""
Function to calculate the slope of the temperature - vapour pressure curve
(Delta) from air temperature T:
.. math::
\\Delta = 1000 \\cdot \\frac{e_s \\cdot 4098}{(T + 237.3)^2}
where es is the saturated vapour pressure at temperature T.
Pa... | 66,248 |
def determineRotation(steroid_orientation,reference_orientation,cutoff=1e-2):
"""
Only does rotation if angle differs significantly from 0 or pi. This
minimizes the number of transformations that are done. At the end, we
then decide the correct way to describe the signs of each flip.
"""
... | 66,249 |
async def log_redis_info(redis: Redis, log_func: Callable[[str], Any]) -> None:
"""Log information about redis status."""
with await redis as r:
info, key_count = await asyncio.gather(r.info(), r.dbsize())
log_func(
f'redis_version={info["server"]["redis_version"]} '
f'mem_usage={inf... | 66,250 |
def test_rename_model_aggregation_folder(composite_resource, aggr_cls, mock_irods):
""" test that we can rename a model program/instance aggregation folder"""
res, user = composite_resource
file_path = 'pytest/assets/generic_file.txt'
mp_mi_folder = 'mp_mi_folder'
ResourceFile.create_folder(res, mp... | 66,251 |
def make_survey_and_score(theta,args):
"""
Wrapper for score_survey. Makes a new field_list, then scores the stars in star_list.
Parameter
---------
theta : list
Should be a list of length N_fieldx2, with first N_field entries being RAs, next
N_field entries being Decs.
arg... | 66,252 |
def crawler1(request):
"""
Hello world
"""
# 方案一的代码
code_crawler1_1_path = crawler_code_dir / 'crawler1_1.py'
code_crawler1_1 = open(code_crawler1_1_path).read()
# 方案二的代码
code_crawler1_2_path = crawler_code_dir / 'crawler1_2.py'
code_crawler1_2 = open(code_crawler1_2_path).read()
... | 66,253 |
def saveaveraged(basedir, ptcode, ctcode, cropname, phases):
""" Step C: Save average of a number of volumes (phases in cardiac cycle)
Load ssdf containing all phases and save averaged volume as new ssdf
"""
filename = '%s_%s_%s_phases.ssdf' % (ptcode, ctcode, cropname)
file_in = os.path.join(based... | 66,254 |
def create_user_profile(sender, **kwargs):
"""When creating a new user, make a profile for him."""
user = kwargs["instance"]
if not UserProfile.objects.filter(user=user):
UserProfile(user=user).save() | 66,255 |
def test_sample_independent_int_loguniform_distributions() -> None:
"""Test sampling from int distribution returns integer."""
study = optuna.create_study()
def int_value_fn(idx: int) -> float:
random.seed(idx)
return random.randint(0, 100)
intlog_dist = optuna.distributions.IntLogUni... | 66,256 |
def get_annotmatch_rowids_from_aid2(ibs, aid2_list, eager=True, nInput=None,
force_method=None):
"""
# This one is slow because aid2 is the second part of the index
Returns a list of the aids that were reviewed as candidate matches to the input aid
"""
from ibeis.... | 66,257 |
def test_bad_markdown_metadata():
"""Test exception raised if markdown metadata cannot be parsed."""
with pytest.raises(MystMetadataParsingError):
myst_to_notebook(
dedent(
"""\
+++ {{a
"""
)
) | 66,258 |
def pause(
subparser: argparse._SubParsersAction = None
):
"""Forward to /pause
Args:
subparser (argparse._SubParsersAction, optional):
Parser for command 'pause'. Defaults to None.
"""
name = 'pause'
if subparser is None:
make_request(f'{_API}/{name}', True)
... | 66,259 |
def import_data():
"""Import data from given folder into ctdcal for processing"""
# something like this?
# ctdcal import _path_
# TODO: smart imports based on file ext? .hex, .xmlcon, .cap
# NOTE: ODF file types vs. others (oxygen, salt)
pass | 66,260 |
def get_data_source_dropdown_options(dataSource, dataType, language):
"""Creates and returns the dropdown options for each data source.
The dropdown options include the label, the value and the title
for each dropdown item.
Parameters
----------
dataSource : str
The name of the data so... | 66,261 |
def Run(args):
"""Adds a binding to the IAM policy for a Google Cloud Function.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated IAM policy.
"""
function_ref = args.CONCEPTS.name.Parse()
return util.AddFunctionIamPolicyB... | 66,262 |
def cifar10_resnet23_prediction(image, maps=64,
test=False):
"""
Construct Resnet23 as reference.
"""
# Residual Unit
def res_unit(x, scope_name, dn=False):
C = x.shape[1]
with nn.parameter_scope(scope_name):
# Conv -> BN -> Relu
... | 66,263 |
def dshape_to_alchemy(dshape, primary_key=frozenset()):
"""
>>> dshape_to_alchemy('int')
<class 'sqlalchemy.sql.sqltypes.Integer'>
>>> dshape_to_alchemy('string')
<class 'sqlalchemy.sql.sqltypes.Text'>
>>> dshape_to_alchemy('{name: string, amount: int}')
[Column('name', Text(), table=None... | 66,264 |
def parse_percentiles(percentiles):
"""Parse lists of percentile values in (0,100) range.
Examples:
.2
10,15,99.9
"""
def parse_percentile(val):
try:
result = float(val)
if result <= 0 or result >= 100:
raise ValueError()
except ValueError:
raise ArgumentTypeEr... | 66,265 |
def lightcurve_from_alert(
alert: list,
# figsize: list=[6.47, 4],
figsize: list = [8, 5],
title: str = None,
include_ulims: bool = True,
include_cutouts: bool = True,
include_crossmatch: bool = True,
mag_range: list = None,
z: float = None,
legend: bool = False,
grid_interva... | 66,266 |
def dump_json(data, pretty=False):
"""Dump JSON, with optional prettification, to stdout"""
print(
json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')) if pretty
else json.dumps(data)
) | 66,267 |
def _clean_data_header(newhdu, oldhdu, data, oldindex):
"""
Updates the min and max values in the new header.
"""
newheader = newhdu.header
oldheader = oldhdu.header
oldnames = oldhdu.columns.names
newindex = newhdu.columns.names.index(oldnames[oldindex - 1]) + 1
newheader['TDMIN' + str(... | 66,268 |
def get_requirements_from_file(requirements_file):
"""
Get requirements from file.
:param str req_file: Name of file to parse for requirements.
:return: List of requirements
:rtype: list(str)
"""
requirements = []
with open(requirements_file) as f:
for line in f:
lin... | 66,269 |
def trajectory_fast_scan(test, test_brick, n_axes, cs='CS3', millisecs=5000):
"""
Do a fast scan involving n_axes motors
:param n_axes: no. of axes to include in trajectory
:param test_brick: the test brick instance to run against
:param (TestCase) test: the calling test object, used to make asserti... | 66,270 |
def extract_encoded_headers(payload: bytes) -> Tuple[str, bytes]:
"""This function's purpose is to extract lines that can be decoded using the UTF-8 decoder.
>>> extract_encoded_headers("Host: developer.mozilla.org\\r\\nX-Hello-World: 死の漢字\\r\\n\\r\\n".encode("utf-8"))
('Host: developer.mozilla.org\\r\\nX-H... | 66,271 |
def RunRevision(context, revision, zip_file, profile, num_runs, command, args):
"""Given a zipped revision, unzip it and run the test."""
print('Trying revision %s...' % str(revision))
# Create a temp directory and unzip the revision into it.
cwd = os.getcwd()
tempdir = tempfile.mkdtemp(prefix='bisect_tmp')
... | 66,272 |
def test_neighbors_no_gpu():
"""This test doesn't check accuracy of the neighbor graph, just that it
runs and adds the correct fields"""
adata = make_test_features_anndata()
compute_neighbor_graph(adata, use_gpu=False)
assert "neighbors" in adata.uns
assert "connectivities" in adata.obsp.keys() | 66,273 |
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Rock the Casbah',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('items',
metavar='str',
nargs='+', # one or more
... | 66,274 |
def formatted_loss_components_string(components: dict) -> str:
"""
Formats the components returned by calc_LV_Lbeta
"""
total_loss = components['L_V']+components['L_beta']
fractions = { k : v/total_loss for k, v in components.items() }
fkey = lambda key: f'{components[key]:+.4f} ({100.*fractions... | 66,275 |
def teardown_cluster(cluster_config: Union[dict, str]) -> None:
"""Destroys all nodes of a Ray cluster described by a config json.
Args:
cluster_config (Union[str, dict]): Either the config dict of the
cluster, or a path pointing to a file containing the config.
"""
with _as_config_... | 66,276 |
def _get_placeholders():
"""Returns placeholders for the image and segmentation."""
img = tf.placeholder(dtype=tf.float32, shape=_IMAGE_SHAPE)
seg = tf.placeholder(dtype=tf.float32, shape=_SEGMENTATION_SHAPE)
return img, seg | 66,277 |
def _get_mult_function(mt: sparse.COO):
"""
Get a function similar to `` lambda a, b: np.einsum('i,ijk,k->j', a, mt, b)``
Returns
-------
func : function (array_like (n_dims,), array_like (n_dims,)) -> array_like (n_dims,)
A function that computes the appropriate multiplication
"""
... | 66,278 |
def add_sb_to_sb(G, make_clique = False):
"""Assigns track drivers to the SB muxes. Each mux gets driven from
all the tracks entering the same BLE section, apart from those
coming from the direction of the wire it drives. This creates a
reasonably flexible and very straight-forward to implement switch,
... | 66,279 |
def submission_target_buffer(self,
description,
analysis_mode,
tool,
tool_instance,
type,
event_time,
tags,
... | 66,280 |
def autoreturn(tree, *, syntax, **kw):
"""[syntax, block] Implicit "return" in tail position, like in Lisps.
Each ``def`` function definition lexically within the ``with autoreturn``
block is examined, and if the last item within the body is an expression
``expr``, it is transformed into ``return expr`... | 66,281 |
def filter_ignore(annotations, filter_fns):
""" Set the ``ignore`` attribute of the annotations to **True** when they do not pass the provided filter functions.
Args:
annotations (dict or list): Dictionary containing box objects per image ``{"image_id": [box, box, ...], ...}`` or list of annotations
... | 66,282 |
def area(location):
"""This function takes in a location as argument, checks the list of locations available and returns the formatted time to the user."""
location = format_location(location)
for areas in pytz.all_timezones:
if location.lower() in areas.lower():
location = areas
... | 66,283 |
def load_image_stack(topdir, filename):
"""
Load ome.tif image stack of either 1,2,3 images
Differenciates layers of images as either "left" or "right" image
Rotates images 90 degrees and stiches left and right side together
Returns the loaded left, right and stiched images.
"""
fulldatap... | 66,284 |
def update_dict_params_for_calibration(params):
"""
Update some specific parameters that are stored in a dictionary but are updated during calibration.
For example, we may want to update params['default']['compartment_periods']['incubation'] using the parameter
['default']['compartment_periods_incubatio... | 66,285 |
def mk_lt(ctx, x, y):
"""
mk_lt(Int_ctx ctx, Int_net x, Int_net y) -> Int_net
Parameters
----------
ctx: Int_ctx
x: Int_net
y: Int_net
"""
return _api.mk_lt(ctx, x, y) | 66,286 |
def test__check_format():
"""Test the _check_format method"""
logger = Logger("test")
# Check the default
assert logger._console_format == '%a[{levelname}]% [{logger}]', "Should be %a[{levelname}]% [{logger}]"
assert logger._file_format == "[{levelname}] [{time}] [{filename}]", "Should be [{levelna... | 66,287 |
def webServerDetection():
"""
webServerDetection works like this:
-First, program asks user to give IP addresses of web servers ten times.
-Then,it scans them via nmap.
-It writes details of each web server to a file called web.dat
"""
web = []
try:
# Take 10 input... | 66,288 |
def test_subscriptions_uninstall(aws_credentials, cli_runner):
"""
Assert that 'newrelic-lambda subscriptions uninstall' attempts to uninstall the
New Relic log subscription on a function.
"""
register_groups(cli)
result = cli_runner.invoke(
cli,
[
"subscriptions",
... | 66,289 |
def counting_sort(numbers):
"""Sort given numbers (integers) by counting occurrences of each number,
then looping over counts and copying that many numbers into output list.
Running time: O(n + k) where k is the range of numbers, because if k is really high then affects the run time significantly.
Memo... | 66,290 |
def brightness(n):
"""
Set the screen brightness between 0 and 255
:param n: value of brightness between 0 and 255
:type n: int
"""
n = int(n)
if 0 <= n <= 255:
termux_brightness(n)
else:
raise ValueError('Value must be between 0 and 255') | 66,291 |
def get_payment_balance() -> float:
""" Payment balance """
output = 0
payment_dicts = get_payments()
for payment_dict in payment_dicts["payments"]:
payment = Payment(payment_dict)
direction = payment.direction
if direction == DIRECTION_TRANSFER:
continue
op... | 66,292 |
def round_to(value: float, target: float):
"""
Round price to price tick value.
"""
rounded = int(round(value / target)) * target
return rounded | 66,293 |
def g_data(rgb_data, dim=ArrayDim.TWO):
"""
功能:获取一个 RGB 图像的 G 分量\n
参数:\n
rgb_data:一个图像的 rgb 数据(3维数组)\n
dim:指明返回值是2维数组还是3维数组\n
返回值:图像的 R 分量数组(是一个2维数组 or 3维数组)\n
"""
return _rgb_component_data(rgb_data, RGBComponent.G, dim) | 66,294 |
def self_replicator(params,
time,
gamma_max,
nu_max,
omega,
phi_Rb,
phi_Mb,
Kd_cpc=0.025,
Kd_cnt=5E-4,
phi_O = 0,
dil_ap... | 66,295 |
def imei_get_subscribers_api(imei, **kwargs):
"""IMEI Subscribers API (version 2.0) GET route."""
return ImeiApi().get_subscribers(imei, **kwargs) | 66,296 |
def AvailableAccounts():
"""Get all accounts that have credentials stored for the CloudSDK.
This function will also ping the GCE metadata server to see if GCE credentials
are available.
Returns:
[str], List of the accounts.
"""
store = c_creds.GetCredentialStore()
accounts = store.GetAccounts() | S... | 66,297 |
def open(format, **kwargs):
"""
writer.open('.eps') will create a sl.writer instance
"""
if format not in known_formats:
raise WriterFormatError(format, known_formats)
return known_formats[format].open(kwargs) | 66,298 |
def smart_post_expression():
"""
This is the function to be called as the first argument for the AddKnobChanged callback later on.
Sets its context to nuke.thisNode() and picks up the changing knob by the nuke.thisKnob() command.
@return: None
"""
n = nuke.thisNode()
k = nuke.thisKnob()
... | 66,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.