content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def read_file(fname):
""" Read a file and return the raw data. Create a new file if necessary. """
if not os.path.isfile(fname):
with open(fname, mode='w', encoding='utf-8') as f:
#TODO: Um. Something more professional perhaps
print('NEWFILE!!!!')
f.write('')
... | 5,295,900 |
def get_total_innocent_reds(executions: List[RevisionResults]) -> int:
"""
Get number of innocent red commits from a given list of execution results.
:param executions: list of execution results
:return: number of innocent red commits
"""
count = 0
previous_fails = set()
for res in exec... | 5,295,901 |
def read_ffindex(file):
"""Read a ffindex and return a list of all the lines in the file .
Args:
file (string): path to the ffindex
Returns:
list of string: The file read line by line
"""
fh = open(file, "r")
index = []
for line in fh:
index.append(line.rstrip(... | 5,295,902 |
def load_ppi(fname='bio-decagon-ppi.csv'):
"""
Returns networkx graph of the PPI network and a dictionary that maps each gene ID to a number
:param fname:
:return:
"""
fin = open(fname)
print('Reading: %s' % fname)
fin.readline()
edges = []
for line in fin:
gene_id1, gene... | 5,295,903 |
def get_field_from_args_or_session(config, args, field_name):
"""
We try to get field_name from diffent sources:
The order of priorioty is following:
read_default_contract_address - command line argument (--<field_name>)
- current session configuration (default_<filed_name>)
"""
rez = getattr... | 5,295,904 |
def scrape_all_songs():
""" Gets all lyrics from all available songs on the wiki. """
print('Scraping all songs from {}'.format(URL))
soup = scrapekit.handle_url(URL)
song_elements = []
tables = soup.findAll('table')
for t in tables:
field_index = scrapekit.get_col_index(t, field_name=... | 5,295,905 |
def load(filepath):
"""
:param filepath:
A str or :class:`pathlib.Path` object gives a path of network graph
data ({'nodes': ..., 'links': ...}) in JSON or YAML formats
:param ac_args: keyword arguments given to anyconfig.load
:return: An instance of networkx.Graph
"""
cnf = ut... | 5,295,906 |
def _create_mapping_files(array, from_id, description, savepath, query_chunk_size=1000):
"""Create mapping files between uniprot ACs and other identifiers.
Queries the UniProt mapping service to retrieve mappings for all
non-UniProt identifiers found in the dataset.
See:
http://www.uniprot.org... | 5,295,907 |
def calculate_patch_digest(target, hash=hashlib.md5):
"""Calculate the digest of the entire project based on the files listed
in the esky_filelist. This will ensure that patches don't break if any
superfluous files have been added to the application folder"""
filelist = load_filelist(target)
if file... | 5,295,908 |
def pdf_from_template(html_template, data):
"""
!Requirement: make sure that wkhtmltopdf is installed in your system
For more configuration info: https://pypi.org/project/pdfkit/
Generate a pdf file from html template
:param html_template str: html template with jinja template strings
:param d... | 5,295,909 |
def insert(event, context):
"""Track the count of what we could and could not insert, and call the func to insert
"""
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))
cloudtrail_log = get_from_s3(bucket, key)
... | 5,295,910 |
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
logging.info("g %s, %s", g, hasattr(g, 'sqlite_db'))
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db | 5,295,911 |
def log_header(header=None):
# pylint: disable=R0912
"""Flask decorator to log headers or a specific header
:param header:
This can be a string as to which header to log
"""
def decorator(func):
"""Function decorator to log header(s)"""
def wrapped_function(*args, **kwargs):... | 5,295,912 |
def show_abs_oovs(abstract, vocab, article_oovs):
"""Returns the abstract string, highlighting the OOVs.
"""
unk_id = vocab._word2id(UNKNOWN_TOKEN)
words = abstract.split()
vwords = []
for w in words:
if vocab._word2id(w) == unk_id:
if article_oovs is None:
vw... | 5,295,913 |
def test_rsvp_first_visit(test_client):
"""
GIVEN a flask app
WHEN a user first visits '/rsvp'
THEN check that the 'Current Status:' data displays
"""
log_in(test_client)
response = test_client.get("/rsvp")
assert b"Current Status: []" in response.data | 5,295,914 |
def train(model, train_set, test_set):
"""
开始训练
"""
loss_function = nn.CrossEntropyLoss()
# loss_function = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(), lr=config.learning_rate)
writer = SummaryWriter(log_dir="log")
epoch = 0
step = 0
# making dataset
train_data... | 5,295,915 |
def compute_rq_name(rq_type, oslevel):
"""
Compute rq_name.
if oslevel is a complete SP (12 digits) then return RqName = oslevel
if oslevel is an incomplete SP (8 digits) or equal Latest then execute
a metadata suma request to find the complete SP level (12 digits)
Compute the suma r... | 5,295,916 |
def test1() -> None:
"""function test1
Args:
Returns:
"""
pass | 5,295,917 |
def score_paper(arxiv_id):
"""
Sum up the 'influentialCitationCount' (Semantic Scholar) from each author
"""
if arxiv_id in paper_scores:
return paper_scores[arxiv_id]
# request data
base_url = 'https://api.semanticscholar.org/v1/paper/arXiv:'
try:
response = urllib.request.... | 5,295,918 |
def resolve(module_name, obj_name):
"""
Resolve a named object in a module.
"""
return getattr(importlib.import_module(module_name), obj_name) | 5,295,919 |
def mock_read_narrative(style):
"""
Mocks the NarrativeIO.read_narrative() function.
Style should be one of "good", "bad", or "private".
A "good" narrative will just return the valid read_narrative()
results by loading and returning the given file. (will raise a
ValueError if file is None).
... | 5,295,920 |
def normalize_query_parameters(query_string):
"""
normalize_query_parameters(query_string) -> dict
Converts a query string into a dictionary mapping parameter names to a
list of the sorted values. This ensurses that the query string follows
% encoding rules according to RFC 3986 and checks for dup... | 5,295,921 |
def test_atomic_unsigned_long_enumeration_2_nistxml_sv_iv_atomic_unsigned_long_enumeration_3_1(mode, save_output, output_format):
"""
Type atomic/unsignedLong is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/unsignedLong/Schema+Instance/NISTSchema-SV-IV-atomic-uns... | 5,295,922 |
def _match(token: bytes, request: HttpRequest) -> bool:
"""
Calculate signature and return True if it matches header.
Args:
token: string, the webhook_token.
request: an HttpRequest object from which the body content and
X-Signature header will be extracted and matched.
Ret... | 5,295,923 |
def read_in(fn):
"""Read in data to header and data"""
with open(fn,'r') as f:
data=[]
start_right=0
for line in f:
words = line.strip().split()
words = [word.strip() for word in words]
if words[0] == "#" or words[0]=='ID':
start_right ... | 5,295,924 |
def arg_filtered_tests(pav_cfg, args: argparse.Namespace,
verbose: TextIO = None) -> List[Path]:
"""Search for test runs that match based on the argument values in args,
and return a list of matching test id's.
Note: I know this violates the idea that we shouldn't be passing a
ge... | 5,295,925 |
def get_users(token, include_locale=False, presence=False):
"""
Get user list
"""
params = {
"token": token,
"include_locale": include_locale,
"presence": presence
}
r = get("https://slack.com/api/users.list", params=params)
if r.ok:
rparsed = r.json()
... | 5,295,926 |
def convertScene(convertContext, data):
"""
Converts a Scene. The data is expected to contain the following elements:
- sharedItems: an optional array of shared item lists. Each element of the array is itself an
array with the following members:
- type: the name of the item list type.
- name: the name of th... | 5,295,927 |
def test_update_case_existing_collaborator(mock_app, case_obj):
"""Tests the CLI that updates a case"""
## GIVEN a CLI object
runner = mock_app.test_cli_runner()
## WHEN providing a case id and a valid collaborator
result = runner.invoke(cli, ["update", "case", case_obj["_id"], "-c", "cust000"])
... | 5,295,928 |
def test_day9_test2():
"""Can output a 16-digit number?"""
prog = [1102, 34915192, 34915192, 7, 4, 7, 99, 0]
q2 = Queue()
c = Computer(prog, None, q2)
c.run_until_stop()
output = queue_to_list(q2)[0]
output_n_digit = len(str(output))
assert output_n_digit== 16 | 5,295,929 |
def registerPlayer(name):
"""Adds a player to the tournament database.
The database assigns a unique serial id number for the player. (This
should be handled by your SQL database schema, not in your Python code.)
Args:
name: the player's full name (need not be unique).
"""
DB=connect()
... | 5,295,930 |
def valid_rfc5737(network: str) -> bool:
"""
Verify an IP Address is in RFC5737
"""
answer = False
if IPNetwork(network) in IPNetwork('192.0.2.0/24'):
answer = True
elif IPNetwork(network) in IPNetwork('198.51.100.0/24'):
answer = True
elif IPNetwork(network) in IPNetwork('2... | 5,295,931 |
def writer(fastq1_out, side_car_out, fastq2_out=None, data_queue=None, max_qname_len=__max_qname_len__):
"""Write templates to file
:param fastq1_out: Name of FASTQ1
:param side_car_out: Name of side car file for long qnames
:param fastq2_out: If paired end, name of FASTQ2
:param data_queue: multiprocessing ... | 5,295,932 |
def create_noisy_signal(signal_fp, snr, noise_fp=None, offset=None):
"""
Create a noisy signal of a specified SNR.
Parameters
----------
signal_fp : string
File path to clean input.
snr : float
SNR in dB.
noise_fp : string
File path to noise. Default is to use randoml... | 5,295,933 |
def number_size (N):
"""size(N:long) : int
Returns the size of the number N in bits.
"""
bits, power = 0,1L
while N >= power:
bits += 1
power = power << 1
return bits | 5,295,934 |
def default_login():
"""View with login form."""
if len(request.access_route) > 1:
ip = request.access_route[-1]
else:
ip = request.access_route[0]
login_attempt = LoginAttempt()
previous_attempts = login_attempt.get_failed_attempts_count(
ip,
(time.time() - 60*60*24... | 5,295,935 |
def test_retrieve_http_params_get_tags():
"""Retrieve REST parameters from an Argparse Namespace - GET /tags"""
args = Namespace(
endpoint_name='get-tags',
offset=42,
limit='all',
visibility='public'
)
assert ShaarliV1Client._retrieve_http_params(args) == \
('GET'... | 5,295,936 |
def mnist_1_5():
"""
train: (12163, 784), test: (2027, 784)
"""
eps_dataset = 0.3
classes = [1, 5] # 2 is 1, 6 is -1 in the binary classification scheme
(X_train, y_train), (X_test, y_test) = mnist_keras.load_data()
X_train, X_test = (
X_train.astype(np.float64) / 255.0,
X_... | 5,295,937 |
def standardize_team_name(team: str) -> str:
"""Standardizes team name across sites
Args:
team (str): the code or team name
Returns:
str: team name, Atlanta Falcons, Baltimore Ravens, etc.
"""
matches = _standardize(team, TEAM_NAMES)
if not matches:
logging.warn(f'no m... | 5,295,938 |
def get_num_shorts(string_list):
""" Returns the number of occurences of 'Short' in an input string list.
Args:
string_list(list of string objects)
Returns:
numShorts(int): Number of occurences of 'Short'
"""
numShorts = 0
for marker in string_list:
if (marker == '... | 5,295,939 |
def get_saved_artists(auths=None, offset=0, limit=20):
"""
Extracts and returns a list containing the IDs for all artists followed by any of the accounts defined in 'sources'.
:param auths: dict() being the 'sources'-tree of the auth object as returned by authorize()
:param offset: int() defining at whi... | 5,295,940 |
def _try_to_date(x):
"""Wrapper around :func:`pandas.to_datetime` that returns
the input unaltered if it's not a date.
Don't attempt converting numeric or boolean arrays.
"""
if x.dtype.kind != 'U': # unicode string
return x
try:
# In case of ambiguity, prefer European format DD... | 5,295,941 |
def ping_live_counter():
"""Pings the live Yo counter."""
headers = {'Auth-Token': current_app.config['LIVE_COUNTER_AUTH_TOKEN'],
'Connection': 'close'}
try:
requests.get(current_app.config['LIVE_COUNTER_URL'], stream=True,
headers=headers, timeout=20)
except... | 5,295,942 |
def at_2_Pa(value):
"""
converts pressure in at (technical atmosphere) to Pa
:param value: pressure value in at (technical atmosphere)
:return: pressure value in Pa
"""
return value * const_at | 5,295,943 |
def main():
"""Go Main Go"""
config = util.get_config()
spr_client = util.get_spreadsheet_client(config)
drive = util.get_driveclient(config)
# Fake last conditional to make it easy to reprocess one site...
res = (
drive.files()
.list(q=("title contains 'Soil Texture Data'"), ma... | 5,295,944 |
def evaluate(results, annotations, checkpoint, iou_threshold=0.5, save_path=None):
""" Evaluate a given dataset using a given retinanet.
# Arguments
results : detection results
annotations : original data
iou_threshold : The threshold used to consider when a detection ... | 5,295,945 |
async def get(request: Request, organization_id: UUID) -> services.organization.Organization:
"""Organization get """
return await services.organization.get(
organization_id=typeof.OrganizationID(organization_id),
member=request.app.state.member,
) | 5,295,946 |
def _terminate_task(type: str, index: int):
"""
Terminate a task.
Parameters:
type: the bucket of the task
index: which task inside the bucket
"""
if not _TASK_FILE.is_file():
print("You don't have a task yet.")
else:
data = {}
with open(_TASK_FILE) as js... | 5,295,947 |
def w_quest_class(sentence):
"""
process what question about classification
Input=sentence Output=class Sentence
"""
analysis = y_n_ques(W_QUESTION, 'classification' + '+' + sentence[4], sentence[5:])
if analysis.sn:
#The d... | 5,295,948 |
def oprint(*a, **kw):
"""Command output"""
cprint(*a, color=OUTPUT_COLOR, **kw) | 5,295,949 |
def exp_so3(v):
"""
Grassia, F. S. (1998).
Practical parameterization of rotations using the exponential map
"""
angle = np.linalg.norm(v)
if angle < np.power(np.finfo(float).eps, 0.25):
na = 0.5 + angle * angle * 1.0 / 48.0
else:
na = np.sin(angle * 0.5) / angle
ct = n... | 5,295,950 |
def choose(chooser: Callable[[TSource], Option[TResult]]) -> Projection[TSource, TResult]:
"""Choose items from the sequence.
Applies the given function to each element of the list. Returns
the list comprised of the results x for each element where the
function returns `Some(x)`.
Args:
cho... | 5,295,951 |
def create_j2env(template_dir) -> jinja2.Environment:
"""
Create a Jinja2 enviornment instance used when template building the containerlab
topology file.
Parameters
----------
template_dir: str
The file path where the Jinja2 template file is located.
Returns
-------
A Jinj... | 5,295,952 |
def _unpack_lists(input_list):
"""Unpacks a list of strings containing sublists of strings
such as provided by the data table in the 2d U-net training pipeline card
Args:
input_list (list): list of strings which contain sublists
Returns:
list: list of hidden items from the tabl... | 5,295,953 |
def cross_match_PS1_DR2(wcs_data, SE_catalog, image_bounds,
band='g', radius=None, clean_catalog=True,
pixel_scale=2.5, mag_thre=15, sep=2.5*u.arcsec,
verbose=True):
"""
Use PANSTARRS DR2 API to do cross-match with the SE source catalog.
... | 5,295,954 |
def get_raw_column(table_name, column_name):
"""
Get a wrapped, registered column.
This function cannot return columns that are part of wrapped
DataFrames, it's only for columns registered directly through Orca.
Parameters
----------
table_name : str
column_name : str
Returns
... | 5,295,955 |
def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads, batch_group_count=1):
"""Compute the shape tuple of a conv given input shapes in canonical order."""
if isinstance(pads, str):
pads = lax.padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)
if len(pads) != len(lhs_shape) - 2:
msg = "Wrong ... | 5,295,956 |
def shapes_chunks_maxmem(draw, ndim=3, itemsize=4, max_len=10_000):
"""Generate the data we need to test rechunking_plan."""
shape = []
source_chunks = []
target_chunks = []
for n in range(ndim):
sh = draw(st.integers(min_value=1, max_value=max_len))
sc = draw(st.integers(min_value=1... | 5,295,957 |
def reset(ctx):
"""Reset machine"""
init(ctx, 'reset')
c = ctx.current
tclient = telnet.TelnetClient(c.host, c.user, c.pwd)
tclient.open()
tclient.hard_reset()
tclient.close() | 5,295,958 |
def db_insert_filename_mutagen(conn, cursor, filename, size, metadata, filehash):
# print ("Scanning file {}".format(filename))
""" insert data into database
:param conn: connection
:param filename: filename to insert
:param size of file
:param metadata object
:param cursor name of cursor co... | 5,295,959 |
def statistics_print(sim: Simulator):
"""Print of simulation statistics regarding ATIS and non ATIS users"""
print()
atis_yes, atis_no = [], []
for a in sim.actors:
if a.atis is not None:
atis_yes.append(a.total_travel_time)
else:
atis_no.append(a.total_travel_tim... | 5,295,960 |
def vhat(train_position):
"""
Define the maximum speed of the train in (m/s) as a function of the
position.
"""
# Take desired profile speed and add some buffer only if lower than 100
speed_profile = np.minimum(vbar(train_position) + 30 / 3.6,
np.ones(train_... | 5,295,961 |
def get(a_map, name):
"""Return a _DescriptorInspector around the attribute, or None."""
try:
value = a_map[name]
except KeyError:
return None
else:
return DescriptorInspector(value) | 5,295,962 |
def download_lsun(lsun_dir, category, dset, tag, overwrite=False):
"""
Download LSUN data and unpack
Arguments:
lsun_dir (str): LSUN data directory
category (str): LSUN category
dset (str): dataset, "train", "val", or "test"
tag (str): version tag, use "latest" for most rece... | 5,295,963 |
def jaccard(gt_bbox, bbox_list):
"""Compute the jaccard overlap of two sets of boxes. The jaccard overlap
is simply the intersection over union of two boxes. Here we operate on
ground truth boxes and default boxes.
E.g.:
A ∩ B / A U B = A ∩ B / (area(A) + area(B) - A ∩ B)
Args:
box... | 5,295,964 |
def cc_sample(shape, sigma, alpha, mu=None, repeats=1, **backend):
"""Sample random fields with a constant correlation.
This function computes the square root of the covariance matrix by SVD.
Parameters
----------
shape : sequence[int]
Shape of the image / volume.å
sigma : float
... | 5,295,965 |
def get_KKP_mech_from_eqn_file_as_df(folder=None, Mechanism='Tropchem',
filename=None, verbose=True,
debug=False):
"""
Get KPP mechanism as a pandas DataFrame
"""
# Set the filename if not provided
if isinstance(filename, type... | 5,295,966 |
def _ActivationParams(op, inexpr, etab):
"""Get activation parameters"""
whichActivation = op.WhichOneof('NonlinearityType')
par = getattr(op, whichActivation)
if whichActivation == 'linear':
alpha = _expr.const(par.alpha, dtype='float32')
beta = _expr.const(par.beta, dtype='float32')
... | 5,295,967 |
def parse_arguments(argv):
"""Parse command line arguments
Args:
argv (list): list of command line arguments including program name
Returns:
The parsed arguments as returned by argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(description='Preprocessing')
parser.add_argument('--bucke... | 5,295,968 |
def test_invalid_pipeline_override_stdout(sh):
"""A Pipeline will override existing stdout redirections."""
echo = sh("echo").stdout("/tmp/tmp_file")
pipe = echo | sh("grep")
assert pipe == Pipeline.create(sh("echo").stdout("/tmp/tmp_file"), sh("grep")) | 5,295,969 |
def test_min_temp():
"""Test that minimum temperature range enforcement works."""
h5 = os.path.join(TESTDATADIR, 'wtk/ri_100_wtk_2012_invalid.h5')
# sites set with bad temperature.
for site in [5, 12, 45, 54, 97, 103, 142, 166]:
with WindResource(h5) as wind:
og_min = np.min(wind[... | 5,295,970 |
def ln2float(module):
"""Batchnorm to Float."""
if isinstance(module, torch.nn.LayerNorm):
print('Warning: Casting LayerNorm to fp32 ...')
module.float()
for child in module.children():
ln2float(child)
return module | 5,295,971 |
def error_view(template_dir=None):
"""
Create the Error view
Must be instantiated
import error_view
ErrorView = error_view()
:param template_dir: The directory containing the view pages
:return:
"""
if not template_dir:
template_dir = "Pylot/Error"
template_page = "%s/... | 5,295,972 |
def supply_backend(optional: Union[callable, bool]=False, index_exists: bool=True):
"""
Decorator to pass the initialized backend to the decorated callable. \
Used by command line entries. If the backend cannot be created, return 1.
:param optional: Either a decorated function or a value which indicate... | 5,295,973 |
def task_detail(request, structure_slug, ticket_id, task_id,
structure, can_manage, ticket, office_employee=None):
"""
View task details
:type structure_slug: String
:type ticket_id: String
:type task_id: String
:type structure: OrganizationalStructure (from @has_admin_privilege... | 5,295,974 |
def test_qmark_bulk_insert(db_parameters):
"""
Bulk insert using qmark paramstyle
"""
import snowflake.connector
snowflake.connector.paramstyle = u'qmark'
engine = _get_engine_with_qmark(db_parameters)
con = engine.connect()
import pandas as pd
try:
con.execute(
... | 5,295,975 |
def isOutputFileClosed(path):
"""Returns true if target output file is closed, else false.
Shows popup if file already in use.
Clears contents, so only usable for mode 'w'"""
try:
f = open(path, "w")
f.close()
return True
except PermissionError:
ctypes.windll.... | 5,295,976 |
def convert_time(timestring, date='1990-01-01'):
"""Convert time string to have leading zeros.
:param timestring: Byte array in '%H:%M:%S' without leading zeros.
:param date: Date of the timestamp (defaults to 1990-01-01)
:return: time object
"""
return datetime.strptime(' '.join((date, timest... | 5,295,977 |
def load(tabular, bindings=None, delimiter=None):
"""Load the tabular data into curses.
The tabular data can be a filename to a csv file or a Pandas dataframe.
Launches a curses view.
"""
if delimiter is None:
delimiter = "," # default Pandas behavior
name = ""
if isinstance(tabu... | 5,295,978 |
def compute_t_shift(metadata, i, t_p_interp, p_interp, p_file, date_ref,
time_ref, dpdt_thresh=10, plot_pressure=True):
"""
***OBSOLETE***: I determined that a multiplicative factor more accurately
adjusts the Belsorp time than a time shift. See compute_t_multiplier.
Computes number... | 5,295,979 |
async def test_request_air_drop_prefetched_blockhash(async_stubbed_sender_prefetched_blockhash, test_http_client_async):
"""Test air drop to async_stubbed_sender."""
resp = await test_http_client_async.request_airdrop(
async_stubbed_sender_prefetched_blockhash.public_key(), AIRDROP_AMOUNT
)
asse... | 5,295,980 |
def quickHBar(ax, xticks, values, colors="b", lw=None):
"""
This function draws an horizontal bar graph
:Arguments:
:type ax: matplotlib Axis2D
:param ax: Axis on which bar graph will be drawn
:type xticks: list
:param xticks: Listo of labels for the bars
:type val... | 5,295,981 |
def free_resource(resource): # type: ignore # Signature is one line above.
"""Callback called when resource is consumed and can be freed."""
del _RESOURCES[resource] | 5,295,982 |
def signals_extraction_worker(
filepath: str,
metadata: list,
hdf5_path: str,
hdf5_dataset=None,
):
"""Extract the signals of the edf files and save them in a HDF5 dataset.
Args:
filepath: the path the .edf file without its extension.
metadata: dictionaries containing the metada... | 5,295,983 |
def test_different_entities_not_equal():
"""
Test that two different entities are not equal
"""
ent = entity.NeuralEntity()
copies = [ent.copy() for _ in range(5)]
copies[0].weights[1] += 1
copies[1].biases[0] = np.array([0])
copies[2].weights.append(None)
copies[3].biases[1] = None... | 5,295,984 |
def exportFromNotebook(notebookPath, outFNames, outFPath=None, encoding='utf-8') :
"""
Routine to auto-generate a python script from Jupyter notebook cells.
Exports code cells that start with
# export name1 name2 ...
where one of the names is in the supplied list of outFNames.
Use outFNames=... | 5,295,985 |
def enable_train_mode(mod: T) -> T:
"""Return a module in training mode."""
return mod.train() | 5,295,986 |
def ld_probe_last_day_difficulty():
"""
This function creates a csv file for the LD Probe test. Each row will be the last day of each difficulty within each
block. Afterward, the function will ask the user to save the newly created csv file in a directory.
"""
df = data_setup('LD Probe')
... | 5,295,987 |
def main():
"""cm.
Usage:
cm --help
cm [--echo] [--debug] [--nosplash] [-i] [COMMAND ...]
Arguments:
COMMAND A command to be executed
Options:
--file=SCRIPT -f SCRIPT Executes the script
-i After start keep the shell interactive,
... | 5,295,988 |
def train_step(real_image, label, noise):
"""
:param real_image:
:param fake_image:
:return:
"""
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
generated_image = generator(noise, label, training=True)
real_output = discriminator(real_image, label, training=... | 5,295,989 |
def test_process_message_bad_message_keys(
mock_validate_message, mock_download, mock_transcode,
mock_upload, mock_callback, sqs_queue_bad_message_keys):
"""
This test proves that when input and output keys are bad
we don't try to process them, instead we handle the exception and
calls call... | 5,295,990 |
def compute_accuracy(logits, labels, mask):
"""Compute the accuracy"""
logits = logits[mask]
labels = labels[mask]
_, indices = torch.max(logits, dim=1)
correct = torch.sum(indices == labels)
return correct.item() * 1.0 / len(labels) | 5,295,991 |
def run(ceph_cluster, **kw):
"""
pre-requisites:
1. Create a volume with a name
2. Create a subvolume with a name
3. Create a subvolume group with a name
Test operation:
1. Try to create a volume with the same name
2. Try to create a subvolume with the same name
3. Try to create a s... | 5,295,992 |
def fixture_env():
"""Environment fixture"""
yield Environment() | 5,295,993 |
def create_snapshot(
directory: directories.Directory,
context: targets.TargetContext,
*,
timestamp: datetime.datetime,
dry_run: bool,
) -> None:
"""
Create a snapshot of the current backup for this Directory.
"""
target_directory = directory.target_path
snapshot_name = directory... | 5,295,994 |
def consistent(a, b):
""" It is possible for an argument list to satisfy both A and B """
return (len(a) == len(b) and
all(issubclass(aa, bb) or issubclass(bb, aa)
for aa, bb in zip(a, b))) | 5,295,995 |
def adjust_image(f, max_size=(800, 800), new_format=None, jpeg_quality=90, fill=False, stretch=False,
return_new_image=False, force_jpeg_save=True):
"""
Підганяє зображення під параметри.
max_size - максимальний розмір картинки. один з розмірів може бути None (авто)
new_format - формат ... | 5,295,996 |
def is_cloneable(owner, name):
"""Verify if a repository is clone-able.
Parameters
----------
owner : string
User name of the owner of the repository.
name : string
Name of the repository to clone.
Returns
-------
cloneablility : 2-tuple
A 2-tuple indicating the... | 5,295,997 |
def audio_upload():
"""
To POST files to this endpoint:
$ curl -F "audio=@some_file.mp3" localhost:8080/api/v0.1/audio
TODOs:
- Store user data (who uploaded this? IP address?)
- File metadata
"""
app.logger.info("Upload request from {}".format(request.remote_addr))
audio_data... | 5,295,998 |
def limit_to_appropriate_columns(
*, res: pandas.DataFrame, transform: VariableTreatment
) -> pandas.DataFrame:
"""
Limit down to appropriate columns.
:param res:
:param transform:
:return:
"""
assert transform.plan_ is not None # type hint
assert transform.score_frame_ is not None... | 5,295,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.