content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_input(data: str) -> (Set[str], Mapping[str, Mapping[str, int]]):
"""Extract the names and associated happines changes from data."""
names = set()
happiness_changes = {}
for line in data.splitlines():
match = INPUT.fullmatch(line)
if not match:
raise ValueError('Ille... | 5,319,300 |
def main(argv):
"""The program.
Returns an error code or None.
"""
try:
# Build an environment from the list of arguments.
env, writer = make_env_and_writer(argv)
try:
cmd = COMMANDS[env.options.command](env, writer)
cmd.execute()
finally:
... | 5,319,301 |
def merger(primary_path:str, secondary_path:str, desired_columns:list, shared_column="time"):
"""
--> Primary path is the global analysis file produced by analyzing NMR spectra
--> Secondary path is the raw-data file recorded by the DAQ.
--> Desired columns is a list of columns that you want to MIGRATE from the
... | 5,319,302 |
def set_volume(volume):
"""set_volume(value): return None
set the music volume"""
check_mixer()
sdl.Mix_VolumeMusic(int(volume * 128)) | 5,319,303 |
def slugify_ref(value: Text, allow_unicode: bool = False) -> Text:
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase.
Also strip leading and trailing whitespace.
:param value: text... | 5,319,304 |
def user_search():
"""UserSearch"""
value = request.args.get('search')
cur = MY_SQL.connection.cursor()
cur.execute(
'''SELECT id, username FROM accounts.users WHERE
username LIKE '%%%s%%';''',
(value)
)
users = json.dumps(cur.fetchall())
return users | 5,319,305 |
def graphcut(img1, img2, mask):
"""
Inputs:
Mask:
The 80px area out of the boundary. 2 dims.
Pixels on the edge of Img1 are marked with 1 and same for Img2. Internal pixels are marked with 3.
Img1 & Img2:
Here Img1 means source img, aka. the input img. Img2 is... | 5,319,306 |
def lutForTBMap():
""" produce a look up table for a red-black-blue colormap"""
cmap=mpl.colors.LinearSegmentedColormap.from_list('my_colormap',
['blue','black','red'],
256)
#I'm not entirely sure what this lower is for. Its use... | 5,319,307 |
def val_one_epoch(model: Module, dataloader: DataLoader, criterion,
device: str) -> typing.Tuple[typing.Union[np.ndarray, None],
dict]:
"""
Validate the given model for one epoch.
:param model: model to evaluate
:type model: Module
:pa... | 5,319,308 |
def multiply_something(num1, num2):
"""this function will multiply num1 and num2
>>> multiply_something(2, 6)
12
>>> multiply_something(-2, 6)
-12
"""
return(num1 * num2) | 5,319,309 |
def post_shift_dp(train_set, vali_set, test_set, logreg_model):
"""Post-shifts log. regression model for demographic parity using vali_set.
Returns the train, validation and test sets with the group attribute appended
as an additional feature, and the post-shifted linear model for the expanded
datasets.
Arg... | 5,319,310 |
def determine_acknowledgement(record, report, ignore_string):
"""Mark report for output unless ignored"""
if record[COMMENT_TEXT]:
comment = record[COMMENT_TEXT].lower()
else:
comment = ""
if ignore_string in comment:
report["should"] = False
return True
report["shou... | 5,319,311 |
def test_ping(client):
"""Test the ping view."""
resp = client.get(url_for('cd2h_repo_project.ping'))
assert resp.status_code == 200
assert resp.get_data(as_text=True) == 'OK' | 5,319,312 |
def estimate_infectious_rate_constant_vec(event_times,
follower,
t_start,
t_end,
kernel_integral,
count_events... | 5,319,313 |
def cotacaoBRL():
"""
Retorna a última cotação do Bitcoin em BRL - Mercado Bitcoin via API BitValor
"""
with urllib.request.urlopen("https://api.bitvalor.com/v1/ticker.json") as url:
data = json.loads(url.read().decode())
last = data['ticker_24h']['exchanges']['MBT']['last']
r... | 5,319,314 |
def adder(journal: Journal) -> List[JournalEntry]:
"""A task that requires previous phases to have recorded journal entres with tags 'x' and 'y', which it will sum.
Returns a new journal entry, titled 'x+y', containing the sum of the existing journal entries 'x' and 'y'
"""
x = journal.get_entry... | 5,319,315 |
def ensure_empty_dir(dir, clear_hidden=True):
"""
Make sure the given directory exists and is empty.
This function will create an empty directory if the directory doesn't exits,
or it will clean all content under the directory. Hidden files and sub
direcotries will be deleted if clear_hidden is True... | 5,319,316 |
def find(word,letter):
"""
find letter in word , return first occurence
"""
index=0
while index < len(word):
if word[index]==letter:
#print word,' ',word[index],' ',letter,' ',index,' waht'
return index
index = index + 1
return -1 | 5,319,317 |
def test_overwrite(TestModel, TestModel_entries, dynamo_local):
"""Putting an existing hash+range should replace the old entry"""
TestModel.put(
{"foo": "first", "bar": "one", "baz": "omg", "count": 999, "child": {"sub": "zero"}},
)
assert TestModel.query(foo="first").count() == 3
first_on... | 5,319,318 |
def subsample_ind(n, k, seed=32):
"""
Return a list of indices to choose k out of n without replacement
"""
rand_state = np.random.get_state()
np.random.seed(seed)
ind = np.random.choice(n, k, replace=False)
np.random.set_state(rand_state)
return ind | 5,319,319 |
def ex0_grand(source, destination, recall):
""" main function for parsing experiment 0 results into summary plots
Parameters
----------
source, destination : str
`source` of experiment pickles and `destination` of the resulting plots
recall : bool
`recall` previously aggregated... | 5,319,320 |
def HA2(credentails, request):
"""Create HA2 md5 hash
If the qop directive's value is "auth" or is unspecified, then HA2:
HA2 = md5(A2) = MD5(method:digestURI)
If the qop directive's value is "auth-int" , then HA2 is
HA2 = md5(A2) = MD5(method:digestURI:MD5(entityBody))
"""
if crede... | 5,319,321 |
def test_match_nonempty_notexpire() -> None:
"""Tests whether empty matches expire."""
match = Match()
match.create_deck(card_set)
part = Participant("ID", "NICK")
match.add_participant(part)
match.put_in_pool()
assert Match.get_by_id(match.id) is not None
Match.perform_housekeeping()
... | 5,319,322 |
def name_to_scope(
template: str,
name: str,
*,
maxlen: int = None,
params: Dict[str, Any] = None,
) -> str:
"""Return scope by given template possibly shortened on name part.
"""
scope = template.format(name=name, **params)
if maxlen and len(scope) > maxlen:
surplus = len(sc... | 5,319,323 |
def test_receipt_order(client, mocker):
"""Must return 200"""
mocker.patch(
"order.service.business_rules.Receipt.delivery",
return_value=response_status
)
response = client.delete("/api/receipt/42", headers=HEADERS)
assert response.status_code == status.HTTP_200_OK | 5,319,324 |
def bootstrap_idxs(n, rng: np.random.Generator = None):
"""
Generate a set of boostrap indexes of length n, returning the pair (in_bag, out_bag) containing the in-bag and
out-of-bag indexes as numpy arrays
"""
if rng is None or type(rng) is not np.random.Generator:
rng = np.random.default_rn... | 5,319,325 |
def recv_disconnect(data):
"""
Handles a user disconnecting
Args:
data (list): the data being sent over by the server
"""
global user_button_list
if len(data) == 2:
user_id_of_user_to_remove = int(data[1])
for i in range(len(user_button_list)):
if user_button... | 5,319,326 |
def test_relations(relations, expected_relations):
"""Test that relations are properly marshaled.
1. Create an embedded representation marshaler for an object with specific relations.
2. Marshal relations.
3. Check the marshaled relations.
"""
RelationsRepresentation = namedtuple("RelationsRepr... | 5,319,327 |
def run(argv=None):
"""Main entry point; defines and runs the wordcount pipeline."""
parser = argparse.ArgumentParser()
parser.add_argument('--input',
dest='input',
default='$GTFS_BUCKET/at/20190429120000/at.zip',
help='Input file to p... | 5,319,328 |
def check_skyscrapers(input_path: str):
"""
Main function to check the status of skyscraper game board.
Return True if the board status is compliant with the rules,
False otherwise.
>>> check_skyscrapers("check.txt")
True
"""
lst = read_input(input_path)
if check_columns(lst) and\
... | 5,319,329 |
def load_preprocessor(preproc_params: Dict[str, Any], device: str) -> Module:
"""Load preprocessor from module preprocessors.name"""
preproc = None
if preproc_params is not None:
preproc_module = importlib.import_module(
f"preprocessors.{preproc_params['name']}")
get_preprocessor... | 5,319,330 |
def get_image_ground_truth(image_id, dataset):
"""Load and return ground truth data for an image (image, mask, bounding boxes).
Args:
image_id:
Image id.
Returns:
image:
[height, width, 3]
class_ids:
[instance_count] Integer class IDs
bbo... | 5,319,331 |
def update_stream_metadata(stream_names):
"""
Updates the sidebar with metadata from a board live stream
"""
if not stream_names[0]:
return html.P("Metadata will appear here when you pick a stream"),
print(f"Getting metadata for {stream_names[0]}")
metadata = cfg.redis_instance.... | 5,319,332 |
def run(zone_file: pathlib.Path, zone_domain: str, cname: str, port: int, restart: bool, tag: str) -> None:
"""
:param zone_file: Path to the Bind-style zone file
:param zone_domain: The domain name of the zone
:param cname: Container name
:param port: The host port which is mapped to the port 53 of... | 5,319,333 |
def nested_field_map(name: str) -> Mapper:
"""
Arguments
---------
name : str
Name of the property.
Returns
-------
Mapper
Field map.
See Also
--------
field_map
"""
return field_map(
name,
python_to_api=lambda x: [[x]],
api_to_... | 5,319,334 |
def socket_state(realsock, waitfor="rw", timeout=0.0):
"""
<Purpose>
Checks if the given socket would block on a send() or recv().
In the case of a listening socket, read_will_block equates to
accept_will_block.
<Arguments>
realsock:
A real socket.socket() object to check for.
... | 5,319,335 |
def wrap_with_threadpool(obj, worker_threads=1):
"""
Wraps a class in an async executor so that it can be safely used in an event loop like asyncio.
"""
async_executor = ThreadPoolExecutor(worker_threads)
return AsyncWrapper(obj, executor=async_executor), async_executor | 5,319,336 |
def file_read(lines):
""" Function for the file reading process
Strips file to get ONLY the text; No timestamps or sentence indexes added so returned string is only the
caption text.
"""
# new_text = ""
text_list = []
for line in lines:
if re.search('^[0-9]', line) is None and re.se... | 5,319,337 |
def test_compound_template_validate_true(params, tstr):
"""Given a set of parameters for initializing a CompoundTemplate
and a test string, the test string should return True when passed
to the CompoundTemplate object's ``validate`` method.
"""
separator_type = params[1]
gr_params = [gp_tuple_to... | 5,319,338 |
def ipn(request):
"""PayPal IPN (Instant Payment Notification)
Cornfirms that payment has been completed and marks invoice as paid.
Adapted from IPN cgi script provided at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/456361"""
payment_module = config_get_group('PAYMENT_PAYPAL')
if payment... | 5,319,339 |
def has_file_ext(view, ext):
"""Returns ``True`` if view has file extension ``ext``.
``ext`` may be specified with or without leading ``.``.
"""
if not view.file_name() or not ext.strip().replace('.', ''):
return False
if not ext.startswith('.'):
ext = '.' + ext
retur... | 5,319,340 |
def compare_data(data1, data2):
""" Compare the data, raise error if it fails. """
# Maybe we can do this fast ...
try:
if data1 == data2:
return
except Exception:
pass
# Otherwise, dive in
deep_compare(data1, data2) | 5,319,341 |
def export_util(file, format, get, link, params):
"""
Download client data in some format and write to a file.
This is used by the export method on clients. It intended for internal use.
Parameters
----------
file: str or buffer
Filepath or writeable buffer.
format : str, optional
... | 5,319,342 |
def bucket_get(ctx, namespace, name, if_match, if_none_match):
"""
Gets the current representation of the given bucket in the given namespace.
Example:
bmcs os bucket get -ns mynamespace --name mybucket
"""
client = build_client('os', ctx)
render_response(client.get_bucket(
name... | 5,319,343 |
def convert(input_file, output_file):
"""
design name
violation message
list of violations
Total Count:
"""
# Converting Magic DRC
split_line = '----------------------------------------'
with open(input_file) as fp, open(output_file, 'w') as fpw:
drc_content ... | 5,319,344 |
def pvec1d(vec1d, precision=1, format="e", loglevel=INFO):
"""Printout of a 1-D vector.
@param[in] vec1d a 1-D vector
"""
v2a = np.array(vec1d)
for i in range(v2a.shape[0]):
logger.log(loglevel, "%% .%i%s " % (precision, format) % v2a[i])
logger.log(loglevel, '\n') | 5,319,345 |
def com_google_fonts_check_description_eof_linebreak(description):
"""DESCRIPTION.en_us.html should end in a linebreak."""
if description[-1] != '\n':
yield WARN,\
Message("missing-eof-linebreak",
"The last characther on DESCRIPTION.en_us.html"
"... | 5,319,346 |
def balanced_accuracy_score(y_true: np.array, y_score: np.array) -> float:
"""
Calculate the balanced accuracy for a ground-truth prediction vector pair.
Args:
y_true (array-like): An N x 1 array of ground truth values.
y_score (array-like): An N x 1 array of predicted values.
Returns:... | 5,319,347 |
def VOLTS(text):
""" Parse all voltages in tegrastats output
[VDD_name] X/Y
X = Current power consumption in milliwatts.
Y = Average power consumption in milliwatts.
"""
return {name: {'cur': int(cur), 'avg': int(avg)} for name, cur, avg in re.findall(VOLT_RE, text)} | 5,319,348 |
def check_dates(start, data_start, input_start, end, data_end, input_end,
R0_WINDOW):
"""Checks if user start and end dates (for R0 calculation) are valid given
the data start and end dates and R0_WINDOW value"""
# note that start is <= input_start
if input_start and (input_start > data... | 5,319,349 |
async def get_team_id(user_id: int) -> Union[int, None]:
"""Return the team id of a user based on their user id."""
data = await users.find_one(
{"user_id": user_id},
{"team_id": 1, "_id": 0},
)
if data:
team_id = data.get("team_id")
else:
team_id = None
return ... | 5,319,350 |
def _clone_static_fields(ex: TensorDict,) -> TensorDict:
"""Clone static fields to each ray.
Args:
ex: A single-camera or multi-camera example. Must have the following fields
-- frame_name, scene_name.
Returns:
Modified version of `ex` with `*_name` features cloned once per pixel.
"""
# Identi... | 5,319,351 |
def get_atom_types_selected(smi_file, database):
""" Determines the atom types present in an input SMILES file.
Args:
smi_file (str) : Full path/filename to SMILES file.
"""
# list of atom types to be selected
if database == "GDB-13":
atom_types = ['H', 'C', 'N', 'O', 'Cl']
p... | 5,319,352 |
def test_reset(db):
"""Test reset sequence."""
y = Template.create('FL', '{year}: File {counter}')
y15 = Sequence(y, year=2015)
y16 = Sequence(y, year=2016)
assert y15.next() == '2015: File 0'
assert y15.next() == '2015: File 1'
assert y16.next() == '2016: File 0'
assert y16.next() == ... | 5,319,353 |
def split(source: _LHE_STORAGE, stride: int):
"""Generator, splitting LHE file content into separate bytestrings
representing LHE files, with maximum number of events per bytestring
equal to stride.
Parameters
----------
source : Pathlike, string, or bytes
The variable or filepath conta... | 5,319,354 |
def run_profile(times, schedule, msid, model_spec, init, pseudo=None):
""" Run a Xija model for a given time and state profile.
:param times: Array of time values, in seconds from '1997:365:23:58:56.816' (cxotime.CxoTime epoch)
:type times: np.ndarray
:param schedule: Dictionary of pitch, roll, etc. va... | 5,319,355 |
def extract_optimized_structure(out_file, n_atoms, atom_labels):
"""
After waiting for the constrained optimization to finish, the
resulting structure from the constrained optimization is
extracted and saved as .xyz file ready for TS optimization.
"""
optimized_xyz_file = out_file[:-4]+".xyz"
... | 5,319,356 |
def get_genes(exp_file, samples, threshold, max_only):
"""
Reads in and parses the .bed expression file.
File format expected to be:
Whose format is tab seperated columns with header line:
CHR START STOP GENE <sample 1> <sample 2> ... <sample n>
Args:
exp_file (str): Name... | 5,319,357 |
def conv_name_to_c(name):
"""Convert a device-tree name to a C identifier
This uses multiple replace() calls instead of re.sub() since it is faster
(400ms for 1m calls versus 1000ms for the 're' version).
Args:
name: Name to convert
Return:
String containing the C version of this... | 5,319,358 |
async def default_async_on_open(conn: AsyncNetworkDriver) -> None:
"""
Async huawei_smartax default on_open callable
Args:
conn: AsyncNetworkDriver object
Returns:
N/A
Raises:
N/A
"""
await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level)
a... | 5,319,359 |
def generate(
symbol_table: intermediate.SymbolTable, namespace: csharp_common.NamespaceIdentifier
) -> Tuple[Optional[str], Optional[List[Error]]]:
"""
Generate the C# code of the visitors based on the intermediate representation
The ``namespace`` defines the AAS C# namespace.
"""
blocks = [cs... | 5,319,360 |
def get_account_id(role_arn):
"""
Returns the account ID for a given role ARN.
"""
# The format of an IAM role ARN is
#
# arn:partition:service:region:account:resource
#
# Where:
#
# - 'arn' is a literal string
# - 'service' is always 'iam' for IAM resources
# - 'regi... | 5,319,361 |
def clic(root, jeu, canvas, couleurs, coups_restants, info_clic):
"""
Action executée au clic de la grille graphique.
Propage la couleur cliquée à partir du point 0, 0 selon les conditions énumérées dans la fonction colorier. Met à
jour la partie graphique de la grille.
Paramètres
----------
... | 5,319,362 |
def retrieve_context_topology_node_total_potential_capacity_total_potential_capacity(uuid, node_uuid): # noqa: E501
"""Retrieve total-potential-capacity
Retrieve operation of resource: total-potential-capacity # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:param node_uuid: ID of node_uuid
... | 5,319,363 |
def create_mae_netcdf(simulation_path, stop_times=None, exact_path=None):
"""Create a new netCDF file with mean absolute error."""
if '/results.nc' not in simulation_path:
# no simulation results
return
# read data
with tf.gfile.GFile(simulation_path, 'rb') as f:
ds = xarray.open_dataset(f.read())... | 5,319,364 |
def google_search(phrase: str = None) -> None:
"""Opens up a Google search for the phrase received. If nothing was received, gets phrase from user.
Args:
phrase: Takes the phrase spoken as an argument.
"""
phrase = phrase.split('for')[-1] if 'for' in phrase else None
if not phrase:
... | 5,319,365 |
def GHP_Op_max(Q_max_GHP_W, tsup_K, tground_K):
"""
For the operation of a Geothermal heat pump (GSHP) at maximum capacity supplying DHN.
:type tsup_K : float
:param tsup_K: supply temperature to the DHN (hot)
:type tground_K : float
:param tground_K: ground temperature
:type nProbes: float... | 5,319,366 |
def attention_lm_decoder(decoder_input,
decoder_self_attention_bias,
hparams,
name="decoder"):
"""A stack of attention_lm layers.
Args:
decoder_input: a Tensor
decoder_self_attention_bias: bias Tensor for self-attention
(see c... | 5,319,367 |
def list_to_dict(data: list, value: Any = {}) -> dict:
"""Convert list to a dictionary.
Parameters
----------
data: list
Data type to convert
value: typing.Any
Default value for the dict keys
Returns
-------
dictionary : dict
Dictionary of the input data
"""... | 5,319,368 |
def Routing_Meta():
"""Routing_Meta() -> MetaObject"""
return _DataModel.Routing_Meta() | 5,319,369 |
def get_tag_name(tag):
"""
Extract the name portion of a tag URI.
Parameters
----------
tag : str
Returns
-------
str
"""
return tag[tag.rfind("/") + 1:tag.rfind("-")] | 5,319,370 |
def create_user(token, user_name, maps_to_id):
"""
Creates the user account in Keycloak
"""
users_url = '{keycloak}/auth/admin/realms/{realm}/users'.format(
keycloak=KEYCLOAK['SERVICE_ACCOUNT_KEYCLOAK_API_BASE'],
realm=KEYCLOAK['SERVICE_ACCOUNT_REALM'])
headers = {'Authorization': '... | 5,319,371 |
def construct_url(test):
"""Construct URL for the REST API call."""
server_env_var = test["Server"]
server_url = os.environ.get(server_env_var)
if server_url is None:
log.error("The following environment variable is not set {var}".format(var=server_env_var))
return None
url = "{base... | 5,319,372 |
def view_profile(request, username=None):
"""view a user's profile
"""
message = "You must select a user or be logged in to view a profile."
if not username:
if not request.user:
messages.info(request, message)
return redirect("collections")
user = request.user
... | 5,319,373 |
def test_atomic_non_positive_integer_min_inclusive_3_nistxml_sv_iv_atomic_non_positive_integer_min_inclusive_4_3(mode, save_output, output_format):
"""
Type atomic/nonPositiveInteger is restricted by facet minInclusive
with value -911248228325171715.
"""
assert_bindings(
schema="nistData/ato... | 5,319,374 |
def test_randomized_init_seed():
"""Initializing as randomized should set seed value as None."""
b = FloatingPointGenerator(random=True)
with pytest.raises(AttributeError):
_ = b.seed_value | 5,319,375 |
def main():
"""Where all the magic happens"""
args = parse_args()
LOG.info('Scraping for new job offers...')
job_offers = extract_job_offers()
new_job_offers = store_offers(job_offers)
LOG.info('%d new job offers found', len(new_job_offers))
try:
send_mail(
new_job_offers... | 5,319,376 |
def bf_shannon_entropy(w: 'Tensor[N, N]') -> 'Tensor[1]':
"""
Compute the Shannon entropy of w.
Warning: this method is very inefficient.
It should only be used on small examples, e.g., for testing purposes.
"""
Z = torch.zeros(1).double().to(device)
H = torch.zeros(1).double().to(device)
... | 5,319,377 |
def list_events(directory, page_filter, key_filter, with_disabled):
"""List the events of a deck, page, or key"""
container = FC.get_entity_container(directory, page_filter, key_filter, "event")
FC.list_content(container, container.event_class, with_disabled=with_disabled) | 5,319,378 |
def extract_y(x, coefficients, degree):
"""
:param x: a matrix containing in each row the first 'degree' powers of a random number in the interval [-3, 2]
:param coefficients: vector of coefficients w_star' (in ascending order: from x**0 to x**n)
:return y : value of y that satisfy the polynomial given ... | 5,319,379 |
def model_scattered_light(data, errs, mask,
verbose=True,
deg=[5,5], sigma=3.0, maxiter=10):
"""
Fit a 2D legendre polynomial to data (only using data in the mask).
Iteratively sigma-clip outlier points.
"""
scatlight = data.copy()
scatlighterr... | 5,319,380 |
def Convert_Data_To_GrayScale(data):
"""
This function converts an image data set in grayscale
input:
data: input data set
return: a numpy array of grayscale images
"""
return np.sum(data/3, axis=3, keepdims=True) | 5,319,381 |
def remove_dataset(src_name):
"""
Removes the specified dataset from active datasets
Parameters:
src_name: Name of dataset to remove
Output:
"""
try:
LOGGER.info("Removing {}".format(src_name))
DATA_CUPBOARD.remove_data("dataset", src_name)
except NameError:
L... | 5,319,382 |
def jittered_center_crop(frames,
box_extract,
box_gt,
search_area_factor,
output_sz,
scale_type='original',
border_type='replicate'):
""" For each frame in frames, ex... | 5,319,383 |
def np_sample_kumaraswamy(a, b, size):
"""
Numpy function to sample k ~ Kumaraswamy(a, b)
Args:
a: shape parameter 1
b: shape parameter 2
size: Return shape of np array
"""
assert a>0 and b>0, "Parameters can not be zero"
U = np.random.uniform(size=size)
K = (1 - (1 - U)**(1... | 5,319,384 |
def find_meta(meta, file, error=True):
"""
Extract __meta__ value from METAFILE.
file may contain:
__meta__ = 'value'
__meta__ = '''value lines '''
"""
try:
text = read(file)
except Exception as err:
raise RuntimeError("Failed to read file") from err
tbase = ... | 5,319,385 |
def get_training_input(filenames, params):
""" Get input for training stage
:param filenames: A list contains [source_filename, target_filename]
:param params: Hyper-parameters
:returns: A dictionary of pair <Key, Tensor>
"""
with tf.device("/cpu:0"):
src_dataset = tf.data.TextLineDat... | 5,319,386 |
def test_main():
"""Tests the function main() independently from main() click command
This pattern aids in writing tests, as the function with the click decorators can be
separately tested from the script functionality itself. In addition, the main()
function can now be imported and used in other pytho... | 5,319,387 |
def write_config():
"""
# Set these inside travis. Note, it is on a per repo basis.
# https://docs.travis-ci.com/user/environment-variables/#Encrypting-Variables-Using-a-Public-Key
# travis encrypt PYPI_USERNAME=super_secret --add
# travis encrypt PYPI_PASSWD=super_secret --add
"""
if not os... | 5,319,388 |
def cbar(ni, nj, resources, commcost):
""" Average communication cost """
n = len(resources)
if n == 1:
return 0
npairs = n * (n - 1)
return 1. * sum(commcost(ni, nj, a1, a2) for a1 in resources.values() for a2 in resources.values()
if a1 != a2) / npairs | 5,319,389 |
def get_electrostatic_potentials(outcar, atoms):
""" Retrieve the electrostatic averaged potentials from the OUTCAR file
:param outcar: content of the OUTCAR file (list of strings)
:param atoms: number of atoms of each atomic species (list of integers)
:return: dictionary with the electrostatic potentia... | 5,319,390 |
def visualize_pc(points, label_title=None, fig_title='figure', export=False, filename='fv_pc', display=False):
""" visualizes the point cloud representation as an image
INPUT:
OUTPUT:
"""
f = plt.figure()
ax = plt.axes()
f.canvas.set_window_title(fig_title)
# plt.get_current_fig_manage... | 5,319,391 |
def get_metrics_delta(metric_name, label_suffix, labels, before_metrics, after_metrics):
"""Calculate the difference between 2 samples"""
s1 = find_sample_by_labels(metric_name, label_suffix, labels, before_metrics)
s2 = find_sample_by_labels(metric_name, label_suffix, labels, after_metrics)
if not s1 ... | 5,319,392 |
def convert_region_type(region_type):
"""
Convert the integer region_type to the corresponding RegionType enum object.
"""
return int_to_region_type[region_type] | 5,319,393 |
def test__validate_config(cardinality_dataset):
"""
What does this test do and why?
Tests the validate config function on the profiler
"""
with pytest.raises(AssertionError) as e:
UserConfigurableProfiler(cardinality_dataset, ignored_columns="col_name")
assert e.typename == "AssertionEr... | 5,319,394 |
def configure_platform(prefixes=None, which_command=None):
"""
Configures the current context's platform support.
:param prefixes: overrides for the default platform prefixes; unspecified keys will remain
unchanged from their defaults
:type prefixes: {str: str|FunctionType}
:param which_co... | 5,319,395 |
def CreateMessageWithAttachment(sender, to, subject, message_text, file_dir,
filename):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text o... | 5,319,396 |
def fit_to_data(x: np.ndarray, y: np.ndarray) -> np.ndarray:
"""
Fit @a func to data in @a x and @a y
Create an initial estimate for parameters, because timestamps are very big
"""
p0 = np.array([1.0, x[0] - 100, 0.0])
popt, _ = scipy.optimize.curve_fit(f=weight, xdata=x, ydata=y, p0=p0)
re... | 5,319,397 |
def new_url(fiscal_year, dept_str=DEPARTMENTS_DICT['1700']):
"""
modify the URL
https://www.fpds.gov/ddps/FY07-V1.4/1700-DEPARTMENTOFTHENAVY/1700-DEPARTMENTOFTHENAVY-DEPTOctober2006-Archive.zip
to be correct for the `fiscal_year` given.
"""
assert type(fiscal_year) is str, "fiscal year must be s... | 5,319,398 |
def main():
""" Entry point of the program """
width = 1000 # Terrain width
height = 500 # Terrain height
# Compute different layers of the landscape
layer_1 = midpoint_displacement([250, 0], [width, 200], 1.4, 20, 12)
layer_2 = midpoint_displacement([0, 180], [width, 80], 1.2, 30, 12)
lay... | 5,319,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.