content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calculate_dvdt(v, t, filter=None):
"""Low-pass filters (if requested) and differentiates voltage by time.
Parameters
----------
v : numpy array of voltage time series in mV
t : numpy array of times in seconds
filter : cutoff frequency for 4-pole low-pass Bessel filter in kHz (optional, defa... | 63,300 |
def test_run_pipeline_steps_complex_with_multistep_all_skip(mock_invoke_step,
mock_module):
"""Multiple steps and none run."""
# None of these should run - various shades of python true
steps = [{
'name': 'step1',
'skip': [1, 2, 3]
... | 63,301 |
def f_to_ppm(f, larmor):
""" Converts frequency (Hz) to ppm
Parameters:
f (float): frequency or array in Hz
larmor (float): Larmor frequency (in Hz)
Returns:
ppm (float)
"""
ppm = f/larmor*1.0e6 + PPM_OFFSET
return(ppm) | 63,302 |
def allreduce_hook(
process_group: dist.ProcessGroup, bucket: dist.GradBucket
) -> torch.futures.Future:
"""
This DDP communication hook just calls ``allreduce`` using ``GradBucket``
tensors. Once gradient tensors are aggregated across all workers, its ``then``
callback takes the mean and returns th... | 63,303 |
def submit_apbs_json():
"""
Handles APBS job submissions.
Runs the APBS main function originally from 'apbs_cgi.py'.
"""
json_response = None
http_status_response = None
if request.method == 'POST':
form = loads(request.data)['form']
for key in form.keys():
if k... | 63,304 |
def check_coverage(vocab, embeddings_index):
"""
:param vocab: the output Counter from the count method
:param embeddings_index: embedding loaded from files
:return: those words:their count that not find in word-embedding
"""
a = []
oov = {}
find_amount = 0
not_find_amount = 0
f... | 63,305 |
def my_rbf(x, y=None, gamma=1.0/(2.1)**2, withnorm=False):
"""
"""
if y is None:
y = x
if withnorm:
xn = x/np.linalg.norm(x)
yn = y/np.linalg.norm(y)
else:
xn = x
yn = y
dist = np.linalg.norm(xn - yn)
return np.exp(-gamma*(dist**2)) | 63,306 |
def pareto_dominates(u, v, tolerance=None):
""" Returns true if u >= v elementwise, and at least
one of the elements is not an equality.
"""
u = np.asarray(u, dtype=np.float32)
v = np.asarray(v, dtype=np.float32)
if tolerance is None:
return np.all(u >= v) and not np.all(u == v)
else:
return n... | 63,307 |
def hashing(file,pp):
""" Map an input file and a postprocessing config to an unique hash.
The hash is used to store the item in the database. It
needs to be persistent across different python implementations
and platforms, so we implement the hashing manually.
"""
def myhash(instring):
... | 63,308 |
def from_arrow_to_python_class(type: pa.DataType) -> DTypeLike:
"""Convert an Arrow type to an (almost) equivalent Python class.
For now, Arrowbic is using Numpy dtype for timestamp and duration conversion, to keep
the proper time unit information.
"""
return _base_from_arrow_to_python_mapping[type... | 63,309 |
def pie(
sizes: list,
labels: list[str],
title: Optional[str] = None,
explode: Optional[Sequence] = None,
exportfile: Optional[Path] = None,
gzipped: bool = False,
show: bool = True,
) -> None:
"""Produce, show and optionally save a pie plot.
:param sizes... | 63,310 |
def convert_sequence_to_actions(sequence: Sequence,
agent_start_dir: Direction) -> Sequence:
"""
Converts a sequence containing East, West, North, South
to a sequence of actions from an agents perspective
:param sequence: a sequence of steps in the form of East, South, No... | 63,311 |
def create_contig_and_fragments(contig, overlap_size, fragment_size):
"""
Creates a contig and overlapping fragments
:param str contig: original sequence to create test data from
:param int overlap_size: number of bases fragments should overlap
:param int fragment_size: length of bases
note:: ... | 63,312 |
def test_connection_refused():
"""Test sending data when server is not listening."""
data = nuke_tools.send_data(LOCALHOST, FREE_PORT, 'hello')
assert 'ConnectionRefusedError. {}:{}'.format(LOCALHOST, FREE_PORT) in data | 63,313 |
def get_all_accounts():
"""
Get all member accounts of the organization.
"""
accounts=[]
token_tracker = {}
while True:
members = session.client('organizations').list_accounts(
**token_tracker
)
accounts.extend(members['Accounts'])
if 'NextTo... | 63,314 |
def field_set_multi_field_defaults(parent_field):
"""Sets defaults for each nested field in the multi_fields array"""
for mf in parent_field['multi_fields']:
dict_set_default(mf, 'name', mf['type'])
mf['flat_name'] = parent_field['flat_name'] + '.' + mf['name'] | 63,315 |
def resolve_ctx(cli, prog_name, args):
"""
Parse into a hierarchy of contexts. Contexts are connected through the parent variable.
:param cli: command definition
:param prog_name: the program that is running
:param args: full list of args
:return: the final context/command parsed
"""
ctx... | 63,316 |
def dump_db(curr_time, settings_dic, log):
"""saves a copy of data.db as _data.db before starting the app
"""
log.debug("Saving a copy of the SQLite database...")
db_file = os.path.join(settings_dic["login_dir"], settings_dic["db_filename"])
db_file_temp = os.path.join(settings_dic["recovery_dir"], ... | 63,317 |
def SetFUFONT():
""" set font """
fontsize=8
FUFONT=wx.Font(fontsize,wx.FONTFAMILY_DEFAULT,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_NORMAL) | 63,318 |
def main():
"""Simple Login App"""
menu = ["Home","Login","SignUp"]
choice = st.sidebar.selectbox("Menu",menu)
if choice == "Home":
Jobs = pd.read_csv('Resume_data_fordebug.csv')
#jds = pd.read_csv('jobdesc.csv')
st.markdown("<h1 style='text-align:center;'>Welcome to ScreenRes</h1>", unsafe_allow_html... | 63,319 |
def _apache_ssl_context(
*, apache_cacerts_list: List[Path], scale_factor: int
) -> List[SSLContext]:
"""
Provides an SSLContext referencing the temporary CA certificate trust store that contains the certificate of the
secure apache service.
"""
cache_key = _apache_ssl_context.__name__
resul... | 63,320 |
def display_map(energy_type, year, scope):
"""
Docs
"""
# scope = "Africa"
df = df_notna.query("Year==@year & energy_type==@energy_type")
fig = px.choropleth(
df,
locations="Code",
color="percentage",
hover_name="Entity",
hover_data={
"Year": ... | 63,321 |
def build_indicator_module_from_yaml(
filename: PathLike,
name: str | None = None,
indices: Mapping[str, Callable] | ModuleType | PathLike | None = None,
translations: dict[str, dict | PathLike] | None = None,
mode: str = "raise",
encoding: str = "UTF8",
) -> ModuleType:
"""Build or extend a... | 63,322 |
def getnameinfo(sockaddr, flags):
"""
getnameinfo(sockaddr, flags) -> (host, port)
Get host and port for a sockaddr.
.. seealso:: :doc:`/dns`
"""
return get_hub().resolver.getnameinfo(sockaddr, flags) | 63,323 |
def configOpt():
"""Init for option
"""
usage = 'Usage: %prog [-f] [other option] [-h]'
p = OptionParser(usage)
# basic options
p.add_option('-t', '--totalsj', dest='totalsj',
action='store', type='string', help='totalsj file')
p.add_option('-b', '--bed', dest='bed',... | 63,324 |
def meta_track_name(txt):
"""
Creates a track name meta message.
Parameters
----------
txt : string
The track name for the message.
"""
return text_meta_message(kTrackName, txt) | 63,325 |
def model_path(base_path: Path, training_run):
"""Returns the path of the model of a given training run.
Arguments:
base_path: A Path object pointing to the base directory where the training run is located.
training_run: The name of the directory of the training run.
Returns:
The P... | 63,326 |
def process_images():
"""
新增实现:
1. 记录每个图像样本包含的caption出现的concept词,按照dict_concept_to_index编码记录
2. 如果是origin模式,则直接将karpathy的划分方案继承下来,不做改动
3. 如果是fewshot模式,则按照我们希望的,按照BaseTrain、BaseVal、BaseTest、Support、Test的方式进行划分
4. 划分的修改结果返回到下一步处理
"""
# 记录每个图像中所有caption出现的concept
print('... | 63,327 |
def plot_mcdwin(histogramme_mcdwin, filename):
"""
plot the mcdwin 2d histogram to eps and pdf
:param histogramme_mcdwin:
:param filename:
:return: None
"""
c = TCanvas('c', 'mcdwin data', 200, 10, 700, 500)
histogramme_mcdwin.SetXTitle("Time Of Flight")
histogramme_mcdwin.SetYTitle(... | 63,328 |
def countLinkCheckThreads():
"""
Count LinkCheckThread threads.
@return: number of LinkCheckThread threads
@rtype: int
"""
i = 0
for thread in threading.enumerate():
if isinstance(thread, LinkCheckThread):
i += 1
return i | 63,329 |
def predict_class_name_and_confidence(img, model, input_size):
"""predict image class and confidence according to trained model
Args:
img: image to predict
model: pytorch model
Returns:
class_name: class index
confidence: class confidence
"""
class_idx, confidence = ... | 63,330 |
def test_stm32cubeprogrammer_create(
check_call, require, path_exists, path_home, system, tc, runner_config
):
"""Tests that ``STM32CubeProgrammerBinaryRunner`` class can be created using
the ``create`` factory method and that ``flash`` command works as expected.
"""
system.return_value = tc["syste... | 63,331 |
def get_overview_of_data(subject_data, layout, b0_threshold):
"""
Gather data from dwi and fmaps into a dictionary
"""
data = {}
data['dwi'] = []
data['fmap'] = []
data['sbref'] = []
# dwi data
data_types = ['dwi','fmap','sbref']
for data_type in data_types:
for filenam... | 63,332 |
def laplace(arr):
"""Laplace filtered signal as features.
Parameters
----------
arr : ndarray, shape (n_channels, n_times)
Returns
-------
output : (n_channels * n_times,)
"""
c4 = 4 * arr[8] - (arr[2] + arr[7] + arr[14] + arr[9])
c3 = 4 * arr[4] - (arr[0] + arr[3] + arr[10] + ... | 63,333 |
def plot_block_diffs(
blocks,
truths,
title=None,
active_label=1,
fig_fname=None):
"""
Show percent of datapoints in each block where truth value is equal
to active_label
:param blocks: array of block or meta-values
:type blocks: np.array with shape (num_samples,)
... | 63,334 |
def assign_road_name(x):
"""Assign road conditions as paved or unpaved to Province roads
Parameters
x - Pandas DataFrame of values
- code - Numeric code for type of asset
- level - Numeric code for level of asset
Returns
String value as paved or unpaved
"""
... | 63,335 |
def create_icon_node(node, params):
"""
Alters the params dict with the values suitable for creation of the nodes with icons and
creates additional parameters dict storing the information about the icon node
:params:
:param node: dict containing the node data
:param params: dict containing basel... | 63,336 |
def configureAgent(server_hostname):
""" Configure the agent so that it has all the configs knobs properly installed """
osCommand = ["sed", "-i.bak", "s/hostname=localhost/hostname=" + server_hostname +
"/g", "/etc/ambari-agent/conf/ambari-agent.ini"]
execOsCommand(osCommand)
re... | 63,337 |
def _check_fm(fm):
"""Check Field Index map value types"""
if not isinstance(fm, dict): return False
for f in fm:
if not isinstance(f, basestring): return False
if not isinstance(fm[f], set): return False
for m in fm[f]:
if not isinstance(m, fm[f]): return False
retur... | 63,338 |
def fixed_param_names_from_stragegy(config: model.ModelConfig,
params: Union[Dict, mx.gluon.ParameterDict],
strategy: str) -> List[str]:
"""
Generate a fixed parameter list given a list of all parameter names and
a strategy.
"""
... | 63,339 |
def toDrive(collection, folder, namePattern='{id}', scale=30,
dataType="float", region=None, datePattern=None, **kwargs):
""" Upload all images from one collection to Google Drive. You can use
the same arguments as the original function
ee.batch.export.image.toDrive
:param collection: Colle... | 63,340 |
def valid_publish_topic(value: Any) -> str:
"""Validate that we can publish using this MQTT topic."""
value = valid_topic(value)
if "+" in value or "#" in value:
raise vol.Invalid("Wildcards can not be used in topic names")
return value | 63,341 |
def get_ownership_filter(filter_str: str) -> Filter:
"""Get an OwnershipFilter from its id string."""
filter_dict = {
UNOWNED_FILTER: UnownedFilter(),
OWNED_FILTER: OwnedFilter(),
ALL_FILTER: None,
}
return _get_filter(filter_dict=filter_dict, filter_str=filter_str) | 63,342 |
def forgot_password_request():
"""Respond to existing user's request to reset their password."""
if not current_user.is_anonymous:
return redirect(url_for('main.index'))
form = RequestResetPasswordForm()
if form.validate_on_submit():
user = User.objects(email=form.email.data).first()
... | 63,343 |
def get_cached_bc_file_path(
project: Project,
binary: ProjectBinaryWrapper,
required_bc_file_extensions: tp.Optional[tp.List[BCFileExtensions]] = None,
) -> Path:
"""
Look up the path to a BC file from the BC cache.
Args:
project: the project
binary: which corresponds to the BC... | 63,344 |
def handle_request_data_before_send_request(teststep, config, testcase_variables):
"""
测试步骤发起请求前,对数据进行处理
@param testcase_variables:
@param teststep:
@param config:
@return:
"""
# 全局函数
testcase_id = teststep.testcase_id
testsuite_id = TestCase.objects.get(id=testcase_id).testsuit... | 63,345 |
def get_data(parts_of_interest):
"""
Given a dictionary of classes with sub-dicts of required properties, returns a dictionary keyed
first by class and then by instance_id of those extracted properties.
"""
component_dict = defaultdict(dict)
## verbose log entry detailing what the compon... | 63,346 |
def buildClassifier(input_shape=(100, 100, 3)):
"""
This creates the CNN algorithm.
Args:
input_shape(tuple): This is the image shape of (100,100,3)
Returns:
classifier(sequential): This is the sequential model.
"""
# Initialising the CNN
classifier = Sequential()
classif... | 63,347 |
def exp_categorical_crossentropy_Im_mc(exp=1.0, class_weights=[],nclass=2,ncluster=[]):
"""
:param exp: exponent. 1.0 for no exponential effect.
"""
def inner(y_true, y_pred):
# sz=y_pred.shape
mv=tf.reduce_max(y_true)
I_weight = tf.cond(tf.greater(mv,50), lambda: tf.add(1.0,0.0... | 63,348 |
def cubic_approx_quadratic(cubic, tolerance, _2_3=2/3):
"""Approximate a cubic Bezier with a single quadratic within a given tolerance.
Args:
cubic (sequence): Four complex numbers representing control points of
the cubic Bezier curve.
tolerance (double): Permitted deviation from th... | 63,349 |
def test_euler_tour():
"""
グラフの画像: https://atcoder.jp/contests/abc202/editorial/1864
1
╱ ╲
2 3
╱│╲
4 5 7
│
6
"""
from align import Align
print(test_euler_tour.__doc__)
# prepare testcase
N = 7
P = [0, 0, 1, 1, 3, 1]
adj: List[Lis... | 63,350 |
def teardown_deployer_network(config_path=None):
"""Teardown the network elements on the deployer.
This function is idempotent.
"""
cfg = Config(config_path)
global LOG
LOG = logger.getlogger()
LOG.debug('----------------------------------------')
LOG.info('Teardown Docker networks')
... | 63,351 |
def skip_description(session, context, poll):
"""Skip description creation step."""
if len(poll.options) == 0:
context.user.expected_input = ExpectedInput.options.name
session.commit()
context.query.message.edit_text(
i18n.t("creation.option.first", locale=context.user.locale... | 63,352 |
def get_labeled_filelist(json_file_list_path):
"""
Get a list of raw image files and mask files.
Parameters
----------
json_file_list_path : str
Path to a json file which contains a list of dictionaries with the
keys 'raw' and 'mask'
Returns
-------
list
List of... | 63,353 |
def colorwheel_plot(head_grid, occ_grid=None, m_occ_grid=None,
title="", show=True, save=False):
"""Create velocity plot of grid with color wheel overlay.
INPUTS:
head_grid - (np.matrix) Grid of the heading angles (rad)
occ_grid - (opt)(np.matrix) Grid of occupancy statu... | 63,354 |
def test_open_netcdf():
"""Test xroms.open_netcdf()."""
file = os.path.join(xroms.__path__[0], "tests", "input", "ocean_his_0001.nc")
ds = xroms.open_netcdf(file) # , Vtransform=2)
assert ds | 63,355 |
def __substituteGamma(expr, *args, gamma=IndexedBase('\gamma', integer=True, shape=1)):
"""
Substitute gamma[i] by args[i] in expression.
:param Expr expr: expression
:param args: entries of the gamma vector
:param Expr gamma: optional symbol to use for gamma
:return: expr with gamma[i] substit... | 63,356 |
def generate_password():
"""Funtion that generates random password for the user"""
gen_password = Credentials.generate_password()
return gen_password | 63,357 |
def hyphenation(word):
"""
Split word in syllables
:param word: input string
:return: a list containing syllables of the word
"""
if not word or word == '':
return []
# elif len(word) == 3 and (is_vowel(word[1]) and is_vowel(word[2]) and not is_toned_vowel(word[2]) and (
# no... | 63,358 |
def main():
"""
Close an open Trade in an Account
"""
parser = argparse.ArgumentParser()
#
# Add the command line argument to parse to the v20 config
#
common.config.add_argument(parser)
parser.add_argument(
"tradeid",
help=(
"The ID of the Trade to clo... | 63,359 |
def create_dictionary(generator):
"""
Creates dictionary
(key=CVE id, value=list of links)
<class 'generator'> -> dict
"""
cves = dict()
for item in generator:
if item.startswith('CVE'):
header = item
links = list()
else:
links.append(item... | 63,360 |
def GetBusNumberToDeviceTreeMap(fast=True):
"""Gets devices currently attached.
Args:
fast [bool]: whether to do it fast (only get description, not
the whole dictionary, from lsusb)
Returns:
map of {bus number: bus object}
where the bus object has all the devices attached to it in a tree.
"""
... | 63,361 |
def logprob_angle(xa, ya, xb, yb,ha,measured_angle, std):
"""logprob that a, b and c are in (xa,ya),(xb,yb),(xc,yc) under the measured angle.
Args:
xa: abscissa of point a
ya: ordinate of point a
xb: abscissa of point b
yb: ordinate of point b
measured_dist: measured... | 63,362 |
def get_partype(cdragon_bin, ddragon_language):
"""
Gets partype in the requested language.
This is a backup to relying on ddragon, still not pretty, could use improvement
"""
if 'arType' not in cdragon_bin['primaryAbilityResource']:
return translate.t(ddragon_language, "game_ability_resourc... | 63,363 |
def GetGap ( classes, gap_list ):
"""
Input
classes: {课号:{教师姓名:[完成课时,完成课时比例,完成业绩]}} (dict)
Output
availableT: available teacher list,在职教师名及其完成业绩(tuple)
unavailableT: unavailable teacher list,离职 & 管理岗教师名及其完成业绩(tuple)
gap:由离职 & 管理岗教师产生的业绩缺口(float)
"""
gap = 0
availableT = []
... | 63,364 |
def filter_exists(name):
"""
Check whether a filter named "name" exists.
"""
hdata = weechat.hdata_get("filter")
filters = weechat.hdata_get_list(hdata, "gui_filters")
filter = weechat.hdata_search(hdata, filters, "${filter.name} == %s" % name, 1)
return bool(filter) | 63,365 |
def normalize_image(image,
mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225)):
"""Normalize the input image.
Parameters
----------
image : numpy.ndarray
Input image.
mean : tuple, optional
Mean values for each of the three RGB channels w... | 63,366 |
def indel_equivalence_solver(df, genome, refgene, chr_prefixed):
"""Solve indel equivalence and calculates
indels_per_gene (ipg)
Args:
df (pandas.DataFrame)
genome (pysam.FastaFile): reference genome
refgene (str): path to refCodingExon.bed.gz
chr_prefixed (bool): True ... | 63,367 |
def link_annotation(uniprot_id, p_type, p_load, preferential=False):
"""
Links a uniprot node to an annotation node
:param uniprot_id: uniprot/swissprot ID
:param p_type: type of the annotation
:param p_load: content of the annotation
:param preferential: if the annotation is preferrential refe... | 63,368 |
def strain(transport: Transport):
"""Assume total recrystallization during transport."""
return 0 | 63,369 |
def test_remove_insert_fan_and_check_fan_info(duthosts, enum_rand_one_per_hwsku_hostname, localhost, creds_all_duts,
mocker_factory):
"""
:param duthost: DUT host object
:param localhost: localhost object
:param creds_all_duts: Credential for snmp
:para... | 63,370 |
def generateMessage(estopState, enable, right_vel, left_vel):
"""
Accepts an input of two bools for estop and enable.
Then two velocities for right and left wheels between -100 and 100
"""
# Empty list to fill with our message
messageToSend = []
# Check the directions of the motors, False =... | 63,371 |
def editItem(category_name, item_id):
"""Item edit page handler, retrieves item from database
and renders the edit item page"""
# Get item from the database
item = session.query(Product).filter_by(id=item_id).one()
if "username" not in login_session:
# If user not logged in, redirect to lo... | 63,372 |
def atom_periodic_number_convert(coord_input):
"""
Add a new column contain periodic number of the corresponding atom
:param coord_input: coordinate dataframe of 2D or 3D data
:type: pandas.DataFrame
:return coord: same dataframe with added column of periodic number
"""
# check in... | 63,373 |
def response_md5_is_valid(response):
"""Checks the MD5 hash of ``response.content`` against that response's
"content-md5" header. Returns ``True`` if they match, else ``False``.
If the response does not include a ``content-md5`` header, we can't verify it,
but we should not hold up that response. Thus,... | 63,374 |
def test_high_order_forward(thr, ho_order, ho_shape):
"""
Checks that if we change the mode space while keeping mode population the same,
the result of forward transformation for orders higher than 1 do not change.
"""
dtype = numpy.float32
modes = FunctionHelper.generate_modes((ho_shape,), dt... | 63,375 |
def unpatch_task(task):
"""Deprecated API. The new API uses signals that can be deactivated
via unpatch() API. This API is now a no-op implementation so it doesn't
affect instrumented tasks.
"""
deprecation(
name='ddtrace.contrib.celery.patch_task',
message='Use `unpatch()` instead',... | 63,376 |
def cost_deriv(a, y):
"""Mean squared error derivative"""
return a - y | 63,377 |
def hsvColor(hue, sat=1.0, val=1.0, alpha=1.0):
"""Generate a QColor from HSVa values. (all arguments are float 0.0-1.0)"""
c = QtGui.QColor()
c.setHsvF(hue, sat, val, alpha)
return c | 63,378 |
def create_project_directories(project_path, project_name):
"""
Create patient data and log directories for a project
:param project_path: pathway to project
:param project_name: project name
:return:
"""
# Create New Project Directory
if not os.path.exists(project_path):
os.mkdi... | 63,379 |
def choose_shift(count_data, min_shift=2, max_shift=12):
"""
Helper function to choose the best shift to apply to the data before applying mixture model.
This helps automatically pick a shift vs. just having a fixed
"""
best_fit = None
best_shift = None
for count_shift in range(min_shift, m... | 63,380 |
def general_pdist(points, distance_function = haversine):
"""
Calculate the distance bewteen each pair in a set of points given a distance function.
Author: Piotr Sapiezynski
Source: https://github.com/sapiezynski/haversinevec
Input
-----
points : array-like (shape=(N, 2))
... | 63,381 |
def get_conf_option(cfp,sec):
"""
读取监控配置文件(nmshosts.conf)中某部分的选项
"""
adict = {}
#print(sec)
#print('---------------')
global V3OPTIONS
for o in V3OPTIONS:
try:
adict[o] = cfp.get(sec,o)
except:
print("%s:exception!!"%o)
adict[o]= None
... | 63,382 |
def get_interface_name():
"""
Returns the interface name of the first not link_local and not loopback interface.
"""
interface_name = ''
interfaces = psutil.net_if_addrs()
for name, details in interfaces.items():
for detail in details:
if detail.family == socket.AF_INET:
... | 63,383 |
def difference(seq1, seq2):
"""
Return all items in seq1 only
"""
return [item for item in seq1 if item not in seq2] | 63,384 |
def get_training_data():
"""
Return python dict of data and its paths
"""
train_and_validation_data = {}
image_id_and_path = {}
datasets = {"validation": VALIDATION_DATASETS, "training": TRAINING_DATASETS}
for training_data_type, training_data in datasets.items():
for imagery_datase... | 63,385 |
def generate_node(mcr, x, y, z, first_wait, second_wait, player):
"""
Generate a node using the coordinates and angles. Take in the
Minecraft RCON object, the coordinates, the primary and secondary
wait times, and the player object.
"""
send_tp(mcr, x, y, z, -90, 20, player)
sleep(fir... | 63,386 |
def pair_all_images(rootdir: pathlib.Path,
detector: str = None,
overwrite: bool = OVERWRITE,
reverse: bool = False,
suffix: str = SUFFIX):
""" Pair all the images from a nested dataset
:param Path rootdir:
The path to the ... | 63,387 |
def update_query_string(context, **kwargs):
"""Return the current query string updated with the provided kwargs."""
parameters = dict(context["request"].GET.items())
parameters.update(kwargs)
return "?" + urlencode(parameters) | 63,388 |
def default_pim_interface_policies(existing, jp_bidir):
"""Generates command list that will be used default interface
policies used for PIM such as neighbor and join-prune policies
Args:
existing (dict): key/values of the existing config
jp_bidir (bool): flag to detrmine if join-prune po... | 63,389 |
def test_catalog_register():
"""
Test consul catalog register
"""
consul_url = "http://localhost:1313"
token = "randomtoken"
node = "node1"
address = "addres1"
nodemeta = {
"Cpu": "blah",
"Cpu_num": "8",
"Memory": "1024",
"Os": "rhel8",
"Osarch": "... | 63,390 |
def setMainModule(main_module):
"""Call this before using other methods of this module."""
# Technically required.
assert main_module.isCompiledPythonModule()
# Singleton and to avoid passing this one all the time, pylint: disable=global-statement
global _main_module
_main_module = main_module | 63,391 |
def _get_cuda_arch_flags(cflags=None):
"""Return the CUDA arch flags."""
if cflags is not None:
for flag in cflags:
if 'arch' in flag:
return []
supported_arches = ['3.5', '3.7',
'5.0', '5.2', '5.3',
'6.0', '6.1', '6.2',
... | 63,392 |
def get_payload_for_v36_cluster_upgrade(params):
"""Construct telemetry payload of v35 cluster upgrade.
:param dict params: defined entity instance, telemetry source_description
:return: json telemetry data for the operation
:type: dict
"""
def_entity = params.get(CLUSTER_ENTITY)
native_e... | 63,393 |
def fetch_desikan_killiany(*args, **kwargs):
"""
Fetches Desikan-Killiany atlas shipped with `abagen`
Returns
-------
atlas : dict
Dictionary with keys ['image', 'info'] pointing to atlas image
(.nii.gz) and information (.csv) files
References
----------
Desikan, R. S.,... | 63,394 |
def conditional_cov_full(X1, X2, X, mu_ell_X1, mu_ell_X2, mu_ell_X, mu_ss_X1, mu_ss_X2, mu_ss_X, nonstat, V):
"""
part of the conditional post cov matrix.
"""
num_func = 1 # Fixed for one latent function
num_data = tf.shape(X)[0] ... | 63,395 |
def ReplaceEntries(image_fname, input_fname, indir, entry_paths,
do_compress=True, allow_resize=True, write_map=False):
"""Replace the data from one or more entries from input files
Args:
image_fname: Image filename to process
input_fname: Single input ilename to use if repla... | 63,396 |
def ratio(matrix, objectives, weights):
"""Execute ratio MOORA without any validation."""
# change the sign the minimization criteria
# If we multiply by -1 (min) the weights,
# when we multipliying this weights by the matrix we emulate
# the -+ ratio mora strategy
objective_x_weights = weights ... | 63,397 |
def get_ssh_config(hostname):
"""Get SSH config for given hostname
:param: hostname: hostname
:return: dict
"""
ssh_config_file = path.abspath(path.expanduser('~/.ssh/config'))
if path.exists(ssh_config_file):
ssh_config = SSHConfig()
with open(ssh_config_file) as f:
... | 63,398 |
def choose_profile(config_files):
"""Show brief info on each Okta environment found in loaded configuration profiles"""
click.echo("[*] Choose a configuration profile to load. E.g. 1")
while True:
choice = click.prompt("[*] Enter the number of the configuration profile to load", type=int)
... | 63,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.