content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def testIBP():
""" Plot matrices generated by an IBP, for a few different settings. """
from pybrain.tools.plotting.colormaps import ColorMap
import pylab
# always 50 customers
n = 50
# define parameter settings
ps = [(10, 0.1),
(10,), (50,),
(50, 0.5),
]
... | 5,328,700 |
def rel_error(model, X, Y, meanY =0):
"""function to compute the relative error
model : trained neural network to compute the predicted data
X : input data
Y : reference output data
meanY : the mean of the of the untreated Y """
Yhat = model.predict(X)
dY = Yhat - Y
axis = tuple(... | 5,328,701 |
def read_data(vocab, path):
"""Reads a bAbI dataset.
Args:
vocab (collections.defaultdict): A dictionary storing word IDs.
path (str): Path to bAbI data file.
Returns:
list of Query of Sentence: Parsed lines.
"""
data = []
all_data = []
with open(path) as f:
... | 5,328,702 |
def get_dataset(cfg: DatasetConfig,
shard_id: int,
num_shards: int,
feature_converter_cls: Type[seqio.FeatureConverter],
num_epochs: Optional[int] = None,
continue_from_last_checkpoint: bool = False) -> tf.data.Dataset:
"""Returns a datas... | 5,328,703 |
def contour_distances_2d(image1, image2, dx=1):
"""
Calculate contour distances between binary masks.
The region of interest must be encoded by 1
Args:
image1: 2D binary mask 1
image2: 2D binary mask 2
dx: physical size of a pixel (e.g. 1.8 (mm) for UKBB)
Returns:
mea... | 5,328,704 |
def weighted_sequence_identity(a, b, weights, gaps='y'):
"""Compute the sequence identity between two sequences, different positions differently
The definition of sequence_identity is ambyguous as it depends on how gaps are treated,
here defined by the *gaps* argument. For details and examples, see
`... | 5,328,705 |
def loss_fd(batch,model,reconv_psf_image,step=0.01):
"""
Defines a loss respective to unit shear response
Args:
batch: tf batch
Image stamps as ['obs_image'] and psf models as ['psf_image']
reconv_psf_image: tf tensor
Synthetic reconvolution psf
step: float
Step size for the f... | 5,328,706 |
def batch_tokenize(sentences: List[str],
tokenizer: yttm.BPE,
batch_size: int = 256,
bos: bool = True,
eos: bool = True) -> List[List[int]]:
"""
Tokenize input sentences in batches.
:param sentences: sentences to tokenize
:param... | 5,328,707 |
def blog_index(request):
"""The index of all blog posts"""
ctx = {}
entries = Page.objects.filter(blog_entry=True).order_by(
'-pinned', '-date_created')
paginator = Paginator(entries, 10)
page_num = request.GET.get('page')
ctx['BASE_URL'] = settings.BASE_URL
try:
entries = ... | 5,328,708 |
def read_ini_file(file_path):
"""Read an ini file and return the profile data.
If the profile name begins with 'profile ', remove it.
Parameters
----------
- file_path - the path to the file to read
Returns
-------
The profile data.
"""
LOG.info('Reading ini file from %s', file... | 5,328,709 |
def pair_time(pos_k, pos_l, vel_k, vel_l, radius):
""" pos_k, pos_l, vel_k, vel_l all have two elements as a list """
t_0=0.0
pos_x=pos_l[0]-pos_k[0]
pos_y=pos_l[1]-pos_k[1]
Delta_pos=np.array([pos_x, pos_y])
vel_x=vel_l[0]-vel_k[0]
vel_y=vel_l[1]-vel_k[1... | 5,328,710 |
def test_systeminit():
"""
Test that initializing a ``System`` class produces a list of ``Prior``
objects of the correct length when:
- parallax and total mass are fixed
- parallax and total mass errors are given
- parallax is fixed, total mass error is given
- parallax error... | 5,328,711 |
def replace_version(search_dir: Path = _DEFAULT_SEARCH_DIR, *, old: str, new: str):
"""Replaces the current version number with a new version number.
Args:
search_dir: the search directory for modules.
old: the current version number.
new: the new version number.
Raises:
Val... | 5,328,712 |
def coco_to_shapely(inpath_json: Union[Path, str],
categories: List[int] = None) -> Dict:
"""Transforms COCO annotations to shapely geometry format.
Args:
inpath_json: Input filepath coco json file.
categories: Categories will filter to specific categories and images that co... | 5,328,713 |
def test_ssl_configuration():
"""
Given:
- Kafka initialization parameters
When:
- Initializing KafkaCommunicator object
Then:
- Assert initialization is as expected.
"""
kafka = KafkaCommunicator(brokers='brokers',
ca_cert='ca_cert',
... | 5,328,714 |
def create_activity_specific_breathing_rate_df(
person_breathing_in,
time,
event,
breathing_rate_key,
rounding=5
):
"""
Generate breathing rates taking into account age and activity intensity.
Parameters:
person_breathing_in: string
E.g. "person 1"
time: stri... | 5,328,715 |
def find_valid_imported_name(name):
"""return a name preceding an import op, or False if there isn't one"""
return name.endswith(MARKER) and remove_import_op(name) | 5,328,716 |
def parseText(text1, nlp):
"""Run the Spacy parser on the input text that is converted to unicode."""
doc = nlp(text1)
return doc | 5,328,717 |
def read_rc(rcpath):
"""Retrieve color values from the rc file.
Arguments:
rcpath (str): path to the rc file.
Returns:
3-tuple of integers representing R,G,B.
"""
if not os.path.exists(rcpath):
return None
with open(rcpath) as rc:
colors = [int(ln) for ln in rc.... | 5,328,718 |
def load_gij_coeff_matrix(friction_coeffs_root, translation, order_g12, eps=1e-8):
"""
Load Fourier expansion coefficients of friction coefficients gii and gij.
Represent result as a matrix (numpy.array)
:param translation: means relative position of the second oscillator
"""
# Determine if tra... | 5,328,719 |
def view_pebbles_home(request):
"""Serve up the workspace, the current home page.
Include global js settings"""
app_config = AppConfiguration.get_config()
if app_config is None:
return HttpResponseRedirect(reverse('view_no_domain_config_error'))
# Is this D3M Mode? If so, make sure:
# ... | 5,328,720 |
def save_to_pickle(value, path, file_name):
"""saves a value into a pickle file"""
if not os.path.exists(path):
os.mkdir(path)
with open(os.path.join(path, file_name), 'wb') as handle:
pickle.dump(value, handle, protocol=pickle.HIGHEST_PROTOCOL) | 5,328,721 |
def multi_pretty(request):
""" 批量添加(Excel文件)"""
from openpyxl import load_workbook
if request.method == "GET":
return render(request, 'multi_pretty.html')
file_object = request.FILES.get("exc")
wb = load_workbook(file_object)
sheet = wb.worksheets[0]
for row in sheet.iter_rows(min_ro... | 5,328,722 |
def is_port_open(host, port, timeout=5):
"""
verifies if a port is open in a remote host
:param host: IP of the remote host
:type host: str
:param port: port to check
:type port: int
:param timeout: timeout max to check
:type timeout: int
:return: True if the port is open
:rt... | 5,328,723 |
def check_transport_reaction_gpr_presence(model):
"""Return the list of transport reactions that have no associated gpr."""
return [
rxn
for rxn in helpers.find_transport_reactions(model)
if not rxn.gene_reaction_rule
] | 5,328,724 |
def get_RSA_modulus(b, num):
"""
Generates a list of RSA modulus' of bit length b
such that each modulus, n = pq, where p and q are
both primes.
:param b: bit length of the modulus
:param num: number of modulus' you want
:returns: a list of RSA modulus'
"""
p_lst = []
# genera... | 5,328,725 |
def generate_single_color_images(width, height, destination_dir):
""" Generates and saves to disk about 1000 single-color rectangle-shaped images """
light_values = range(69, 231, 3)
medium_values = range(46, 154, 2)
dark_values = range(23, 78, 1)
index = 1
# Generate light coloured images
... | 5,328,726 |
def reset_data():
"""Reset the datastore to a known state, populated with test data."""
setup.reset_datastore()
db.put([
Authorization.create(
'haiti', 'test_key', domain_write_permission='test.google.com'),
Authorization.create(
'haiti', 'domain_test_key',
... | 5,328,727 |
def use_processors(n_processes):
"""
This routine finds the number of available processors in your machine
"""
from multiprocessing import cpu_count
available_processors = cpu_count()
n_processes = n_processes % (available_processors+1)
if n_processes == 0:
n_processes = 1
print... | 5,328,728 |
def test_gauge_absolute_negative_rate_tcp(mock_random):
"""TCPStatsClient.gauge works with absolute negative value and rate."""
cl = _tcp_client()
_test_gauge_absolute_negative_rate(cl, 'tcp', mock_random) | 5,328,729 |
def climate_radio_thermostat_ct101_multiple_temp_units_state_fixture():
"""Load the climate multiple temp units node state fixture data."""
return json.loads(
load_fixture(
"zwave_js/climate_radio_thermostat_ct101_multiple_temp_units_state.json"
)
) | 5,328,730 |
def get_TR_and_ntpts(dtseries_path, wb_command_path):
"""
:param dtseries_path: String, the full path to a .dtseries.nii file
:param wb_command_path: String, the full path to the wb_command executable
:return: Tuple of 2 numbers, the number of timepoints and repetition time
"""
if not os.path.ex... | 5,328,731 |
def GetPseudoAAC1(ProteinSequence, lamda=30, weight=0.05, AAP=[]):
"""
#######################################################################################
Computing the first 20 of type I pseudo-amino acid compostion descriptors based on the given
properties.
####################################... | 5,328,732 |
def reversedict(dct):
""" Reverse the {key:val} in dct to
{val:key}
"""
# print labelmap
newmap = {}
for (key, val) in dct.iteritems():
newmap[val] = key
return newmap | 5,328,733 |
def createNewEnsemble(templateVars, project, targetPath, mono):
"""
If "localEnv" is in templateVars, clone that ensemble;
otherwise create one from a template with templateVars
"""
# targetPath is relative to the project root
from unfurl import yamlmanifest
assert not os.path.isabs(targetP... | 5,328,734 |
def pi_tune():
"""Attempts to automatically tune the PI loop."""
print("TO BE IMPLEMENTED") # TODO
return | 5,328,735 |
def mincut_graph_tool(edges: Iterable[Sequence[np.uint64]],
affs: Sequence[np.uint64],
sources: Sequence[np.uint64],
sinks: Sequence[np.uint64],
logger: Optional[logging.Logger] = None) -> np.ndarray:
""" Computes the min cut on... | 5,328,736 |
def mock_graph_literal():
"""Creates a mock tree
Metasyntactic variables: https://www.ietf.org/rfc/rfc3092.txt
"""
graph_dict = [
{
"frame": {"name": "foo", "type": "function"},
"metrics": {"time (inc)": 130.0, "time": 0.0},
"children": [
{
... | 5,328,737 |
def parse_footer(fn):
"""
Parse the downloaded FOOTER file, which contains a header for each program
and (usually) a description line.
Yields either a nested 2-tuple of (header-program-name,
(description-program-name, description-text)) if a description can be
found, or a 1-tuple of (header-pro... | 5,328,738 |
def parse_ADD_ins(tokens):
"""Attempts to parse an ADD instruction."""
failure = None
assert len(tokens) > 0
if tokens[0].text.upper() != 'ADD':
return failure
statement = Obj()
statement.type = 'STATEMENT'
statement.statement_type = 'INSTRUCTION'
statement.instruction = 'ADD'
... | 5,328,739 |
def commonIntegerPredicate(field):
""""return any integers"""
return tuple(re.findall("\d+", field)) | 5,328,740 |
def spatialft(image, cosine_window=True, rmdc=True):
"""Take the fourier transform of an image (or flow field).
shift the quadrants around so that low spatial frequencies are in
the center of the 2D fourier transformed image"""
#raised cosyne window on image to avoid border artifacts
(dim1,dim2) = ... | 5,328,741 |
def _get_instrument_parameters(ufile, filemetadata):
""" Return a dictionary containing instrument parameters. """
# pulse width
pulse_width = filemetadata('pulse_width')
pulse_width['data'] = ufile.get_pulse_widths() / _LIGHT_SPEED # m->sec
# assume that the parameters in the first ray represent... | 5,328,742 |
def get_deployment_mode(path):
"""
Work out the 'deployment mode' from the global attributes in a NetCDF file
:param path: path to dataset
:return: Mode as a value from `DeploymentModes` enumeration
:raises ValueError: if mode cannot be determined or is invalid
"""
fname = os.path.basena... | 5,328,743 |
def split_reaction(reac):
""" split a CHEMKIN reaction into reactants and products
:param reac: reaction string
:type reac: str
:returns: reactants and products
:rtype: (tuple of strings, tuple of strings)
"""
em_pattern = one_of_these([PAREN_PLUS_EM + STRING_END,
... | 5,328,744 |
def bond_stereo_parities(sgr):
""" bond parities, as a dictionary
"""
return mdict.by_key_by_position(bonds(sgr), bond_keys(sgr),
BND_STE_PAR_POS) | 5,328,745 |
def archive_fs(locations):
"""Fixture to check the BagIt file generation."""
archive_path = locations['archive'].uri
fs = opener.opendir(archive_path, writeable=False, create_dir=True)
yield fs
for d in fs.listdir():
fs.removedir(d, force=True) | 5,328,746 |
def encode(text):
"""
Encode to base64
"""
return [int(x) for x in text.encode('utf8')] | 5,328,747 |
def _get_ip():
"""
:return: This computer's default AF_INET IP address as a string
"""
# find ip using answer with 75 votes
# https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
ip = ''
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
... | 5,328,748 |
def _get_value(cav, _type):
"""Get value of custom attribute item"""
if _type == 'Map:Person':
return cav["attribute_object"]["id"] \
if cav.get("attribute_object") else None
if _type == 'Checkbox':
return cav["attribute_value"] == '1'
return cav["attribute_value"] | 5,328,749 |
def test_post_order_with_empty_input():
"""To test post_order method with an empty tree."""
tree_new = BST()
with pytest.raises(TypeError) as err:
tree_new.post_order_traversal(tree_new.root)
assert str(err.value) == (f'There is no node to traverse.') | 5,328,750 |
def get_inference(model, vectorizer, topics, text, threshold):
"""
runs inference on text input
paramaters
----------
model: loaded model to use to transform the input
vectorizer: instance of the vectorizer e.g TfidfVectorizer(ngram_range=(2, 3))
topics: the list of topics in the model
... | 5,328,751 |
def get_message_id(update: dict, status_update: str) -> int:
"""функция для получения номера сообщения.
Описание - функция получает номер сообщения от пользователя
Parameters
----------
update : dict
новое сообщение от бота
status_update : str
состояние сообщения, изменено или ... | 5,328,752 |
def gmm_clustering_predict(model, X):
"""
X is a (N, 1) array
"""
X = np.clip(X, -2.5, 2.5)
return model.predict(X) | 5,328,753 |
def http_request(url, method='GET', timeout=2, **kwargs):
"""Generic task to make an http request."""
headers = kwargs.get('headers', {})
params = kwargs.get('params', {})
data = kwargs.get('data', {})
request_kwargs = {}
if headers:
request_kwargs['headers'] = headers
if params:
... | 5,328,754 |
def start_grpc_server(server: Server):
"""
Start the given gRPC `server`.
This does not block so, if you don't have a mainloop, this will simply
finish immediatly with the thread/process.
"""
server.start() | 5,328,755 |
def unify_nest(args: Type[MultiNode], kwargs: Type[MultiNode], node_str, mode, axis=0, max_depth=1):
"""
Unify the input nested arguments, which consist of sub-arrays spread across arbitrary nodes, to unified arrays
on the single target node.
:param args: The nested positional arguments to unify.
:... | 5,328,756 |
def ast_for_inv_exp(inv: 'Ast', ctx: 'ReferenceDict'):
"""
invExp ::= atomExpr (atomExpr | invTrailer)*;
"""
assert inv.name is UNameEnum.invExp
atom_expr, *inv_trailers = inv
res = ast_for_atom_expr(atom_expr, ctx)
if len(inv_trailers) is 1:
[each] = inv_trailers
if each.n... | 5,328,757 |
def json_writer(docs, json_file_path: str, source: str = None):
"""Converts a collection of Spacy Doc objects to a JSON format,
such that it can be used to train the Spacy NER model. (for Spacy v2)
Source must be an aggregated source (defined in user_data["agg_spans"]), which
will correspond to the tar... | 5,328,758 |
def euler42_():
"""Solution for problem 42."""
pass | 5,328,759 |
def create_input_pipeline(files,
batch_size,
n_epochs,
shape,
crop_shape=None,
crop_factor=1.0,
n_threads=2):
"""Creates a pipefile from a list of image files.
... | 5,328,760 |
def validate_supervise(key_name: str, sup_conf: Dict, params: Dict) -> None:
"""
Validate the supervise config subblock to be used for ETLBlock supervise operation.
Parameters
----------
key_name : The subkey that maps to this extract subblock.
sup_conf : The extract sub-config dict or config['... | 5,328,761 |
def confirm_email_page():
"""Returns page for users that have not confirmed their
email address"""
if not g.loggedIn:
return redirect(url_for('general.loginPage'))
next = request.args.get('next')
if general_db.is_activated(g.user):
if next is not '':
return make_auth_to... | 5,328,762 |
def get_movie_names(url_data):
"""Get all the movies from the webpage"""
soup = BeautifulSoup(url_data, 'html.parser')
data = soup.findAll('ul', attrs={'class' : 'ctlg-holder'}) #Get all the lines from HTML that are a part of ul with class = 'ctlg-holder'
movie_list = []
for div in data:
... | 5,328,763 |
def message_results():
"""Shows the user their message, with the letters in sorted order."""
message = request.form.get('message')
encrypted_message = sort_letters(message)
return render_template('message_results.html', message=encrypted_message) | 5,328,764 |
def fsum(iterable): # real signature unknown; restored from __doc__
"""
fsum(iterable)
Return an accurate floating point sum of values in the iterable.
Assumes IEEE-754 floating point arithmetic.
"""
pass | 5,328,765 |
def flatten_dict(dicts, keys):
"""
Input is list of dicts. This operation pulls out the key in each dict and combines the values into a new list mapped to the original key. A new dictionary is formed with these key -> list mappings.
"""
return {
key: flatten_n([d[key] for d in dicts])
fo... | 5,328,766 |
def main(
source_files: List[str], destination_file: Optional[str], fail_on_failures: bool
) -> None:
"""
Convert2JUnit
This tool allows you to convert various reports into the JUnit format.
"""
report = initialize_report(destination_file, source_files)
apply_source_files(report, source_fil... | 5,328,767 |
def delete_file(file_name):
"""
Delete a file, does nothing if file does not exist.
:param file_name: file to delete
.. versionadded:: 9.3.1
"""
if file_name:
try:
os.remove(file_name)
except (FileNotFoundError, PermissionError):
pass | 5,328,768 |
def render_url(fullpath, notebook=False): # , prefix="files"):
"""Converts a path relative to the notebook (i.e. kernel) to a URL that
can be served by the notebook server, by prepending the notebook
directory"""
if fullpath.startswith('http://'):
url = fullpath
else:
url = (radiopad... | 5,328,769 |
def register():
"""Register User route."""
email = request.form.get('email')
password = request.form.get('password')
new_user = User.register(email, password)
if new_user:
return jsonify({'message': 'Registration successful.'}), 201
return jsonify({'message': 'Invalid username or passwor... | 5,328,770 |
def route_sns_task(event, context):
"""
Gets SNS Message, deserialises the message,
imports the function, calls the function with args
"""
record = event['Records'][0]
message = json.loads(
record['Sns']['Message']
)
return run_message(message) | 5,328,771 |
def RAND_pseudo_bytes(*args, **kwargs): # real signature unknown
"""
Generate n pseudo-random bytes.
Return a pair (bytes, is_cryptographic). is_cryptographic is True
if the bytes generated are cryptographically strong.
"""
pass | 5,328,772 |
def release_dp_mean_absolute_deviation(x, bounds, epsilon):
"""Release the dp mean absolute deviation.
Assumes dataset size len(`x`) is public.
Theorem 27: https://arxiv.org/pdf/2001.02285.pdf
"""
lower, upper = bounds
sensitivity = (upper - lower) * 2. / len(x)
x = np.clip(x, *bounds)
... | 5,328,773 |
def train(hparams, datas=None, scope=None):
"""build the train process"""
# 1. create the model
model_creator = select_model_creator(hparams)
train_model = _mh.create_model(model_creator, hparams, 'train')
# eval_model = _mh.create_model(model_creator, hparams, 'eval')
# infer_model = _mh.create_model(model_cre... | 5,328,774 |
def create_test_account(test_case, username="TestUser"):
"""
Creates user TestUser
"""
test_case.client.post(reverse("users:register"), {"username": username,
"password": "password",
"confirm_pass... | 5,328,775 |
def get_configuration(spec_path):
"""Get mrunner experiment specification and gin-config overrides."""
try:
with open(spec_path, 'rb') as f:
specification = cloudpickle.load(f)
except pickle.UnpicklingError:
with open(spec_path) as f:
vars_ = {'script': os.path.basena... | 5,328,776 |
def inspect_single_run(raw_df, tag):
"""
:param :
:return: None
"""
df = raw_df[
(raw_df['tag'] == tag)
].copy()
print(len(df))
print(df[['seed_input_graph', 'seed_embedding', 'solution_frequency']])
print(df.columns)
print(len(df))
print(df.head())
for j ... | 5,328,777 |
def LoadScores(firstfile, prevfile):
"""Load the first and previous scores. For each peptide, compute a prize
that is -log10(min p-value across all time points). Assumes the scores
are p-values or equivalaent scores in (0, 1]. Do not allow null or missing
scores.
Return: data frame with scores a... | 5,328,778 |
def add_makeflags(job_core_count, cmd):
"""
Correct for multi-core if necessary (especially important in case coreCount=1 to limit parallel make).
:param job_core_count: core count from the job definition (int).
:param cmd: payload execution command (string).
:return: updated payload execution comm... | 5,328,779 |
def process_map(file_in, validate):
"""Iteratively process each XML element and write to csv(s)"""
with codecs.open(NODES_PATH, 'w') as nodes_file, \
codecs.open(NODE_TAGS_PATH, 'w') as nodes_tags_file, \
codecs.open(WAYS_PATH, 'w') as ways_file, \
codecs.open(WAY_NODES_PATH, 'w') as... | 5,328,780 |
def _gen_find(subseq, generator):
"""Returns the first position of `subseq` in the generator or -1 if there is no such position."""
if isinstance(subseq, bytes):
subseq = bytearray(subseq)
subseq = list(subseq)
pos = 0
saved = []
for c in generator:
saved.append(c)
if le... | 5,328,781 |
def fnCalculate_Bistatic_RangeAndDoppler(pos_target,vel_target,pos_rx,pos_tx,wavelength):
"""
Calculate measurement vector consisting of bistatic range and Doppler shift for 3D bistatic case.
pos_rx, pos_tx = position of Rx and Tx in [km].
pos_target = position of target in [km].
wavelength = wavele... | 5,328,782 |
def all_permits(target_dynamo_table):
"""
Simply return all data from DynamoDb Table
:param target_dynamo_table:
:return:
"""
response = target_dynamo_table.scan()
data = response['Items']
while response.get('LastEvaluatedKey', False):
response = target_dynamo_table.scan(Exclusi... | 5,328,783 |
def maximum_difference_sort_value(contributions):
"""
Auxiliary function to sort the contributions for the compare_plot.
Returns the value of the maximum difference between values in contributions[0].
Parameters
----------
contributions: list
list containing 2 elements:
a Numpy.... | 5,328,784 |
def load_test_val_train_files(version):
"""Load the test, validation and train labels and images from the data folder.
Also does the basic preprocessing (converting to the right datatype, clamping and rescaling etc.)
return images_train, images_validation, images_test, labels_train, labels_validati... | 5,328,785 |
def get_primer_target_sequence(id, svStartChr, svStartPos, svEndChr, svEndPos, svType, svComment, primerTargetSize, primerOffset, blastdbcmd, genomeFile):
"""Get the sequences in which primers will be placed"""
if svType in ["del", "inv3to3", "trans3to3", "trans3to5", "snv", "invRefA", "invAltA"]:
targe... | 5,328,786 |
def human_format(num):
"""
:param num: A number to print in a nice readable way.
:return: A string representing this number in a readable way (e.g. 1000 --> 1K).
"""
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
return '%.2f%s' % (num, ['', 'K', 'M', 'G... | 5,328,787 |
def torchserve(
model_path: str,
management_api: str,
image: str = TORCHX_IMAGE,
params: Optional[Dict[str, object]] = None,
) -> specs.AppDef:
"""Deploys the provided model to the given torchserve management API
endpoint.
>>> from torchx.components.serve import torchserve
>>> torchserv... | 5,328,788 |
def ExpandRange(r,s=1):
"""expand 1-5 to [1..5], step by 1-10/2"""
if REGEX_PATTERNS['step'].search(r):
[r1,s] = r.split('/')
s=int(s)
else:
r1 = r
(start,end) = r1.split('-')
return [i for i in range(int(start),int(end)+1,s)] | 5,328,789 |
def write_file_if_changed(name, data):
""" Write a file if the contents have changed. Returns True if the file was written. """
if path_exists(name):
old_contents = read_file(name)
else:
old_contents = ''
if (data != old_contents):
write_file(name, data)
return True
return False | 5,328,790 |
def _get_preprocessor_loader(plugin_name):
"""Get a class that loads a preprocessor class.
This returns a class with a single class method, ``transform``,
which, when called, finds a plugin and defers to its ``transform``
class method. This is necessary because ``convert()`` is called as
a decorato... | 5,328,791 |
def preprocess_sample(data, word_dict):
"""
Args:
data (dict)
Returns:
dict
"""
processed = {}
processed['Abstract'] = [sentence_to_indices(sent, word_dict) for sent in data['Abstract'].split('$$$')]
if 'Task 2' in data:
processed['Label'] = label_to_onehot(data['Task... | 5,328,792 |
def read_input_file(input_file_path):
"""
read inputs from input_file_path
:param input_file_path:
:return:
"""
cprint('[INFO]', bc.dgreen, "read input file: {}".format(input_file_path))
with open(input_file_path, 'r') as input_file_read:
dl_inputs = yaml.load(input_file_read, Loader... | 5,328,793 |
async def test_burn(
async_stubbed_sender, async_stubbed_sender_token_account_pk, test_token
): # pylint: disable=redefined-outer-name
"""Test burning tokens."""
burn_amount = 200
expected_amount = 300
burn_resp = await test_token.burn(
account=async_stubbed_sender_token_account_pk,
... | 5,328,794 |
def test_cMpc_to_z_array():
"""
Test passing a comoving distance array returns a redshift array
"""
comoving_distance_array = np.array([0.0, 3000])
# Must return an array
expected_redshift_array = np.array([0.0, 0.8479314667609102])
calculated_redshift_array = pyxcosmo.cMpc_to_z(comoving_di... | 5,328,795 |
def PWebFetch (url, args, outfile, err):
"""
Generic Fetch a web product
Sends a http post request to url and sames response to outfile
Throws exception on error
* url = where the request to be sent,
e.g."https://www.cv.nrao.edu/cgi-bin/postage.pl"
* args = dict or argum... | 5,328,796 |
def run_client(
cfg: DictConfig,
comm: MPI.Comm,
model: nn.Module,
loss_fn: nn.Module,
num_clients: int,
train_data: Dataset,
test_data: Dataset = Dataset(),
):
"""Run PPFL simulation clients, each of which updates its own local parameters of model
Args:
cfg (DictConfig): th... | 5,328,797 |
def task_deploy_docs() -> DoitTask:
"""Deploy docs to the Github `gh-pages` branch.
Returns:
DoitTask: doit task
"""
if _is_mkdocs_local(): # pragma: no cover
return debug_task([
(echo, ('ERROR: Not yet configured to deploy documentation without "use_directory_urls"',)),
... | 5,328,798 |
def plugin(version: str) -> 'Plugin':
"""Get the application plugin."""
return XPXPlugin | 5,328,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.