content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _yield_overlaps(x1, x2):
"""yield common hash values while iterating over two sorted lists of hashes
To properly compute the estimate, I need this to only process min(len(x1), len(x2)) elements
Returns an iterable object
"""
i = 0
j = 0
processed = 0
try:
while processed <= m... | 5,316,600 |
def bin_position(max_val):
"""returns position features using some symbols. Concatenate them at the end of
sentences to represent sentence lengths in terms of one of the three buckets.
"""
symbol_map = {0: " `", 1: " _", 2: " @"}
if max_val <= 3:
return [symbol_map[i] for i in range(max_val)... | 5,316,601 |
def norm(g,scale=True):
"""normalises a network on the last axis, scale decides if there is a learnable multiplicative factor"""
g.X=BatchNormalization(axis=-1,scale=scale)(g.X)
return g | 5,316,602 |
def plotFit(min_x, max_x, mu, sigma, theta, p):
"""plots the learned polynomial fit with power p
and feature normalization (mu, sigma).
"""
# We plot a range slightly bigger than the min and max values to get
# an idea of how the fit will vary outside the range of the data points
x = np.arange(min_x - ... | 5,316,603 |
def makeEvent(rawEvent, time = 0):
"""Create a midi event from a raw event received from the sequencer.
"""
eventData = rawEvent.data
if rawEvent.type == SSE.NOTEON:
result = NoteOn(time, eventData.note.channel, eventData.note.note,
eventData.note.velocity
... | 5,316,604 |
def rule2(n):
"""2sqrt"""
k = map(lambda x:x*2,rule1(n))
return k | 5,316,605 |
def charge_sublayers(ich):
""" Parse the InChI string for the formula sublayer.
:param ich: InChI string
:type ich: str
:rtype: dict[str: str]
"""
return automol.convert.inchi.charge_sublayers(ich) | 5,316,606 |
def f_split_path(fpath, normpath=True):
"""
Splits path into a list of its component folders
Args:
normpath: call os.path.normpath to remove redundant '/' and
up-level references like ".."
"""
if normpath:
fpath = os.path.normpath(fpath)
allparts = []
while 1:
... | 5,316,607 |
def get_path(*args):
""" utility method"""
return os.path.join(THIS_DIR, 'primitives_data', *args) | 5,316,608 |
def log_init(log_level: str):
"""日志初始化
:param log_level: 日志级别
:return:
"""
logging.basicConfig(level=log_level.upper(), format="%(asctime)s %(levelname)s:%(message)s") | 5,316,609 |
def mixcloud_profile():
""" Display the authorized user's profile """
# Note: We would normally do this but Mixcloud requires specific parameters
#client_id = current_app.config['CONFIG']['accounts']['mixcloud']['client_id']
#mixcloud_session = OAuth2Session(client_id, token=session['oauth_token'])
... | 5,316,610 |
def search_metas(metas, criteria, keywords):
""" Note: storage may contain message from others """
msgs = []
for meta in metas:
if not satisfy_criteria(criteria, meta):
continue
if keywords == None or len(keywords) == 0:
msgs.append(meta)
continue
... | 5,316,611 |
def count_large_cargos(b):
"""Gather number of large cargos in each planet."""
def find_planets():
return sln.finds(sln.find(b, By.ID, 'planetList'),
By.CLASS_NAME, 'planetlink')
num_planets = len(find_planets())
logging.info('Found {} planets'.format(num_planets))
fleet = {}
for... | 5,316,612 |
def dpt_groups_pseudotime(
adata: AnnData,
color_map: Union[str, Colormap, None] = None,
palette: Union[Sequence[str], Cycler, None] = None,
show: Optional[bool] = None,
save: Union[bool, str, None] = None,
): # pragma: no cover
"""Plot groups and pseudotime.
Args:
adata: :class:`~... | 5,316,613 |
def get_project(service, project_id):
"""Build service object and return the result of calling the API 'get' function for the projects resource."""
operation = service.projects().get(projectId=project_id).execute()
return operation | 5,316,614 |
def test_check_s3_output_folder_for_account_doesnt_exist(mocker) -> None:
"""
Check that there is an output storage location
for the account id.
"""
test_account = "test_account"
test_bucket = "test_bucket"
expected_response = {
'IsTruncated': True,
'ResponseMetadata': {
... | 5,316,615 |
def parse(src: str):
"""
Compila string de entrada e retorna a S-expression equivalente.
"""
return parser.parse(src) | 5,316,616 |
def citire_linie_de_comanda():
"""
1. calea catre folderul cu fisiere de input
2. calea pentru folderul de output
3. NSOL
4. Timpul de timeout
Obtin o lista cu numele fișierelor de input.
Creez fisiere de output pentru fiecare fisier de input.
"""
global gr
... | 5,316,617 |
def get_parser_init_and_actions(source: ast.Module) -> \
Tuple[List[ast.AST], str, Set[str]]:
"""
Function used to extract necessary imports, parser and argument creation
function calls
Parameters
----------
source : ast.Module
source file parsed into ATT
Returns
-------
... | 5,316,618 |
def write_json_to_file(filepath: Path, jsonstr: Dict[str, str], indent: int = 4, eof_line=True):
"""Dosyaya JSON yazar.
Dosya bulunamazsa ekrana raporlar hata fırlatmaz
Arguments:
filepath {Path} -- Okunacak dosyanın yolu
jsonstr {Dict[str, str]} -- JSON objesi
indent {int} -- JSON ... | 5,316,619 |
def get_version():
""" str: The package version. """
global_vars = {}
# Compile and execute the individual file to prevent
# the package from being automatically loaded.
source = read(os.path.join("test_python_package", "__version__.py"))
code = compile(source, "version.py", "exec")
exec(c... | 5,316,620 |
def stop_logging():
"""
disable logging
"""
global __loggingEnabled__
__loggingEnabled__ = False
print('logging stopped') | 5,316,621 |
def aTimesFiltered(data, filterFunction, microBin=False):
"""
Filter a list of arrivalTimes
===========================================================================
Input Meaning
---------------------------------------------------------------------------
data Object with ... | 5,316,622 |
def amrex_timing(output_filenames, data_filename):
"""Extract timing data and save it to an output file."""
import numpy as np
data = open(data_filename, 'w')
data.write(" PROC AVG MIN MAX\n")
for output_filename in output_filenames:
output = open(output_filename, 'r')
... | 5,316,623 |
def get_publication_group(project, group_id):
"""
Get all data for a single publication group
"""
connection = db_engine.connect()
groups = get_table("publication_group")
statement = select([groups]).where(groups.c.id == int_or_none(group_id))
rows = connection.execute(statement).fetchall()
... | 5,316,624 |
def format_traceback(exc_info, encoding='utf-8'):
"""
Returns the exception's traceback in a nice format.
"""
ec, ev, tb = exc_info
# Skip test runner traceback levels
while tb and _is_relevant_tb_level(tb):
tb = tb.tb_next
# Our exception object may have been turned into a string,... | 5,316,625 |
def creatadata(datadir=None,exprmatrix=None,expermatrix_filename="matrix.mtx",is_mtx=True,cell_info=None,cell_info_filename="barcodes.tsv",gene_info=None,gene_info_filename="genes.tsv",project_name=None):
"""
Construct a anndata object
Construct a anndata from data in memory or files on disk. If datadi... | 5,316,626 |
def test_declarative_region_modifier_zoom_in():
"""Test that '+' suffix on area string properly decreases extent of map."""
data = xr.open_dataset(get_test_data('narr_example.nc', as_file_obj=False))
contour = ContourPlot()
contour.data = data
contour.field = 'Temperature'
contour.level = 700 *... | 5,316,627 |
def get_report(path):
"""
Downloads the MVP report.
:param path:
:return:
"""
return flask.send_from_directory(Parameters.TMP_DIR, path) | 5,316,628 |
def qbinomial(n, k, q = 2):
"""
Calculate q-binomial coefficient
"""
c = 1
for j in range(k):
c *= q**n - q**j
for j in range(k):
c //= q**k - q**j
return c | 5,316,629 |
def _igraph_from_nxgraph(graph):
"""
Helper function that converts a networkx graph object into an igraph graph object.
"""
nodes = graph.nodes(data=True)
new_igraph = igraph.Graph()
for node in nodes:
new_igraph.add_vertex(name=str(node[0]), species=node[1]["specie"], coords=node[1]["co... | 5,316,630 |
def _tiramisu_parameters(preset_model='tiramisu-67'):
"""Returns Tiramisu parameters based on the chosen model."""
if preset_model == 'tiramisu-56':
parameters = {
'filters_first_conv': 48,
'pool': 5,
'growth_rate': 12,
'layers_per_block': 4
}
... | 5,316,631 |
def send_msg(request):
"""
发送消息
:param request:
:return:
"""
to_user = request.GET.get('toUser')
msg = request.GET.get('msg')
url = 'https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg?lang=zh_CN&pass_ticket=%s' %(TICKET_DICT['pass_ticket'],)
ctime = str(int(time.time()*1000))
pos... | 5,316,632 |
def get_type(path, follow=True, name_pri=100):
"""Returns type of file indicated by path.
path :
pathname to check (need not exist)
follow :
when reading file, follow symbolic links
name_pri :
Priority to do name matches. 100=override magic
This tries to use the contents... | 5,316,633 |
def ELA(impath, Quality=90, Multiplier=15, Flatten=True):
"""
Main driver for ELA algorithm.
Args:
impath: Path to image to be transformed.
Quality (optional, default=90): the quality in which to recompress the image. (0-100 integer).
Multiplier (optional, default=15): value with wh... | 5,316,634 |
def create_deployment_for_compin(compin: ManagedCompin, assessment: bool = False) -> str:
"""
Creates a Kubernetes deployment YAML descriptor for a provided compin. The compin's deployment template is enhanced
in the following ways:
(1) A node selector is added in order to ensure that Kubernetes sc... | 5,316,635 |
def titles_request() -> 'Response':
"""Request titles.
https://wiki.anidb.net/w/API#Anime_Titles
"""
return requests.get(_TITLES) | 5,316,636 |
def get_jds(text):
"""Given a text (string), returns a list of the Journal Descriptors contained"""
scores = jdi.GetJdiScoresByTextMesh(text, InputFilterOption(LegalWordsOption.DEFAULT_JDI))
output_filter_option = OutputFilterOption()
output_filter_option.SetOutputNum(3)
result = OutputFilter.Proc... | 5,316,637 |
def rpsbproc(results):
"""Convert raw rpsblast results into CD-Search results using rpsbproc.
Note that since rpsbproc is reliant upon data files that generally are installed in
the same directory as the executable (and synthaser makes no provisions for them
being stored elsewhere), we must make sure w... | 5,316,638 |
def test_file_missing():
"""Info.plist missing"""
wf = Workflow()
assert not os.path.exists(INFO_PLIST_PATH)
with pytest.raises(IOError):
wf.workflowdir | 5,316,639 |
def replacespecial(string, char_replacement=replacements):
"""Return unicode string with special characters replaced"""
return "".join(c if c not in char_replacement else char_replacement[c] for c in string) | 5,316,640 |
def parse_orcid_response(response):
"""
This safely digs into the ORCID user summary response and returns consistent dict
representation independent of the user's visibility settings.
"""
return {
"orcid": get_nested_key(response, "orcid-identifier", "path"),
"email": get_nested_key... | 5,316,641 |
def search(query, pageCount=1, extended=True):
"""
Do a Search API query for one or more pages of tweets matching the query.
After every 100 or slightly fewer tweets, a new request will be done to
get the next page.
:param query: Query text to search on the Twitter API.
:param pageCount: Count... | 5,316,642 |
def test_l1logistic_intercept():
"""Test that binary L1 Logistic fits an intercept when run."""
for fi in [True, False]:
X, y, w, b = make_classification(n_samples=100,
random_state=11,
n_features=4,
... | 5,316,643 |
def discrete_metropolis_hastings(P, n_samples = 10000, n_iterations = 10000, stepsize = None):
"""
Perform a random walk in the discrete distribution P (array)
"""
#ensure normality
n = np.sum(P)
Px = interp1d(np.linspace(0,1,len(P)), P/n)
x = np.random.uniform(0,1,n_samples)
... | 5,316,644 |
def test_load_error(language, spec_str, expected_exception, expected_reason):
"""
GIVEN language and spec string
WHEN load is called with the language and spec string
THEN the expected exception is raised with the expected reason.
"""
with pytest.raises(expected_exception) as exc:
spec.l... | 5,316,645 |
def vat(x, logits, model, v, eps, xi=1e-6):
"""
Generate an adeversarial perturbation.
Args:
x: tensor, batch of labeled input images of shape [batch, height, width, channels]
logits: tensor, holding model outputs of input
model: tf.keras model
v: ... | 5,316,646 |
def test_go_to_next_action():
"""
Test that the time stepping function works and that total value/price is updated correctly.
"""
# Variable setup
name = 'Testing'
starting_usd = 100.0
time_between_action = 1
price_file_name = 'test.csv'
price_period_name = price_file_name[:-4]
p... | 5,316,647 |
def bond_yield(price, face_value, years_to_maturity, coupon=0):
"""
"""
return (face_value / price) ** (1 / years_to_maturity) - 1 | 5,316,648 |
def bezierDetail(n=shape.bezierDetail):
"""Establishes the Bézier level of detail, i.e., the number of points
per Bézier curve segment."""
shape.bezierDetail = n
# precompute blending factors
shape.bezierBlend = []
for i in range(n + 1):
t = float(i) / n
u = 1 - t
shape.b... | 5,316,649 |
def getTime(type_of_clock):
"""
Arg:
type_of_clock...int
case '1': CLOCK_REALTIME;
case '2': CLOCK_MONOTONIC;
case '3': CLOCK_MONOTONIC_COARSE;
case '4': CLOCK_MONOTONIC_RAW;
case '5': CLOCK_BOOTTIME;
default: CLOCK_REALTIME;
Return:
String e.g. '... | 5,316,650 |
def ar_gain(alpha):
"""
Calculate ratio between the standard deviation of the noise term in an AR(1) process and the resultant
standard deviation of the AR(1) process.
:param alpha: Parameter of AR(1)
:return: Ratio between std of noise term and std of AR(1)
"""
return np.sqrt((1 + al... | 5,316,651 |
def fetch_data_2014():
"""For import data year 2014 from excel"""
static = open("airtraffict.csv", newline="")
data = csv.reader(static)
static = [run for run in data]
static_2014 = []
for run in static:
if run[3] == "2014":
static_2014.append(run)
return static_2014 | 5,316,652 |
def classifyChord(chordPosition):
"""
:param chordPosition:所有音符的位置,所有音符都是在不同弦上,并且各位置的距离是限制在人类手掌范围内的。
例如:([6, 5], [5, 7], [4, 7], [3, 5], [2, 5]),表示6弦5品,5弦7品,4弦7品,3弦5品,2弦5品
:return:和弦类型,是一个列表,用来表示所有非空弦音,从低品到高品对应的个数。
例如:输入([6, 5], [5, 7], [4, 7], [3, 5], [2, 5]),返回[[5,3],[7,2]]
和弦分类决定了和弦的处理方式
... | 5,316,653 |
def clean_columns(data):
"""
Removes : EventId, KaggleSet, KaggleWeight
Cast labels to float.
"""
data = data.drop(["DER_mass_MMC", "EventId", "KaggleSet", "KaggleWeight",], axis=1)
label_to_float(data) # Works inplace
return data | 5,316,654 |
def update_active_boxes(cur_boxes, active_boxes=None):
"""
Args:
cur_boxes:
active_boxes:
Returns:
"""
if active_boxes is None:
active_boxes = cur_boxes
else:
active_boxes[0] = min(active_boxes[0], cur_boxes[0])
active_boxes[1] = min(active_boxes[1], cu... | 5,316,655 |
def get_user_request():
"""Return the user's json."""
assert namespace_manager.get_namespace() == ''
person = get_person()
values = person.to_dict()
return flask.jsonify(objects=[values]) | 5,316,656 |
def paginate_data(counted, limit, offset):
"""
Custom pagination function.
:param counted:
:param limit:
:param offset:
:return: {}
"""
total_pages = ceil(counted / int(limit))
current_page = find_page(total_pages, limit, offset)
if not current_page:
return None
bas... | 5,316,657 |
def ones(shape, dtype=None):
"""Wrapper of `torch.ones`.
Parameters
----------
shape : tuple of ints
Shape of output tensor.
dtype : data-type, optional
Data type of output tensor, by default None
"""
return torch.ones(shape, dtype=dtype) | 5,316,658 |
def parse_catalog(catalog):
"""parses an atom feed thinking that it is OPDS compliant"""
author = None
title = None
links = []
entries = []
updated = None
for child in catalog:
if child.tag == LINK_ELEM:
links.append(parse_link(child))
elif child.tag == ENTRY_EL... | 5,316,659 |
def limit_of_performance():
"""We can see that testing a large prime is
quite slow. Testing large non-primes is quite fast.
"""
import time
t = time.perf_counter()
for i in range(30, 89):
m = 2**i-1
print(i, m, end="")
if isprimeg(m):
print("prime", end="")
... | 5,316,660 |
def get_queue(shares):
"""Transform category sizes to block queue optimally
catsizes = [cs1, cs2, cs3, cs4] - blocks numbers of each color category
"""
# Defining catsizes matching the MSE-limit
# amount = 1 # starting amount
# lim = 0.03 # MSE-limit
# while True:
# error = 0
... | 5,316,661 |
async def test_switch_set_state(hass, hk_driver, entity_id, attrs, events):
"""Test if accessory and HA are updated accordingly."""
domain = split_entity_id(entity_id)[0]
hass.states.async_set(entity_id, None, attrs)
await hass.async_block_till_done()
acc = Switch(hass, hk_driver, "Switch", entity_... | 5,316,662 |
def view_post(request, slug):
"""View post view"""
post = get_object_or_404(Post, slug=slug)
if not post.published:
raise Http404
ret_dict = {
'post': post,
}
ret_dict = __append_common_vars(request, ret_dict)
return render(request, 'blog/view_post.html', ret_dict) | 5,316,663 |
def UDP_transmission(data, UDP_IP, UDP_PORT):
"""Transmits data to IP:PORT via UDP"""
transmission = pickle.dumps(data)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
success = s.sendto(transmission, (UDP_IP, UDP_PORT))
print success
s.close() | 5,316,664 |
def relhum(temperature, mixing_ratio, pressure):
"""This function calculates the relative humidity given temperature, mixing
ratio, and pressure.
"Improved Magnus' Form Approx. of Saturation Vapor pressure"
Oleg A. Alduchov and Robert E. Eskridge
http://www.osti.gov/scitech/servlets/purl/548871/
... | 5,316,665 |
def submit(year, day, part, session=None, input_file=None):
"""
Puzzle decorator used to submit a solution to advent_of_code server and provide
result. If input_file is not present then it tries to download file and cache it
for submiting solution else it require to be provided with input_file path whic... | 5,316,666 |
def mse(y, y_pred):
"""
Computes mean squared error.
Parameters
----------
y: np.ndarray (1d array)
Target variable of regression problems.
Number of elements is the number of data samples.
y_pred: np.ndarray (1d array)
Predicted values for the given target va... | 5,316,667 |
def update_items(item_seq, batch_len=500, dry_run=True, start_batch=0, end_batch=None, ignore_errors=False, verbosity=1):
"""Given a sequence (queryset, generator, tuple, list) of dicts run the _update method on them and do bulk_update"""
stats = collections.Counter()
try:
try:
src_qs =... | 5,316,668 |
def hue_weight(image, neighbor_filter, sigma_I = 0.05):
"""
Calculate likelihood of pixels in image by their metric in hue.
Args:
image: tensor [B, H, W, C]
neighbor_filter: is tensor list: [rows, cols, vals].
where rows, and cols are pixel in image,
... | 5,316,669 |
def build_blueprint_with_loan_actions(app):
"""."""
blueprint = Blueprint(
'invenio_circulation',
__name__,
url_prefix='',
)
create_error_handlers(blueprint)
endpoints = app.config.get('CIRCULATION_REST_ENDPOINTS', [])
pid_type = 'loan_pid'
options = endpoints.get(pi... | 5,316,670 |
def featurize_and_to_numpy(featurizer, X_train, y_train, X_test, y_test):
"""
Featurize the given datasets, and convert to numpy arrays.
"""
featurizer.fit(X_train)
X_train_feats = featurizer.transform(X_train)
X_test_feats = featurizer.transform(X_test)
X_train_np = X_train_feats.astype(np... | 5,316,671 |
def noise_per_box_v2_(boxes, valid_mask, loc_noises, rot_noises,
global_rot_noises):
"""add noise for each box and check collision to make sure noisy bboxes do not collide with other boxes
loc_noises and rot_noises are some noisy candidates, first successful noisy bbox candidate is cho... | 5,316,672 |
def calculate_cornea_center_wcs(u1_wcs, u2_wcs, o_wcs, l1_wcs, l2_wcs, R, initial_solution):
"""
Estimates cornea center using equation 3.11:
min ||c1(kq1) - c2(kq2)||
The cornea center should have the same coordinates, however, in the presents of the noise it is not always the case.
Thus, the task... | 5,316,673 |
def batch_loss_variables(loss_vars, batch_size):
""" splits up los variables into batches """
obs, mask, act, adv, ret = loss_vars
num_examples = obs.shape[0]
num_batches = div_round_up(num_examples, batch_size)
for b in range(num_batches):
i = b * batch_size
yield obs[i:i + batch_... | 5,316,674 |
def luminosity(S_obs, z, D_L=0, alpha=0):
"""Get radio luminosity with error. Default is LDR2. See
https://www.fxsolver.com/browse/formulas/Radio+luminosity.
"""
if D_L == 0:
D_L, _ = get_dl_and_kpc_per_asec(z=z)
return (S_obs * 4 * np.pi * (D_L ** 2)) / (1 + z) ** (1 + alpha) | 5,316,675 |
def play(request, play_engine_class, variables):
"""
How to use yml_executor::
def test_experimental(play):
data = play.get_file_contents(
'/my/path/etc', 'login.yml')
play.execute_raw(data)
"""
context = None
skin = None
try:
... | 5,316,676 |
def add_categories_to(gifid, category_id):
"""
REST-like endpoint to add a category to a bookmarked gif
:returns: Customized output from GIPHY
:rtype: json
"""
user = (
models.database.session.query(models.users.User)
.filter(
models.users.User.token == flask.request... | 5,316,677 |
def compute_accuracy(model_path, data):
""""compute top k hits accuracy"""
sess = tf.Session()
saver = tf.train.import_meta_graph(model_path + '.meta')
saver.restore(sess, model_path)
graph = tf.get_default_graph()
# input
question_ids = graph.get_tensor_by_name('question_ids:0')
sequ... | 5,316,678 |
def vtk_image_to_array(vtk_image) :
""" Create an ``numpy.ndarray`` matching the contents and type of given image.
If the number of scalars components in the image is greater than 1, then
the ndarray will be 4D, otherwise it will be 3D.
"""
exporter = vtkImageExport()
exporter.Set... | 5,316,679 |
def delete_network_acl(acl_id):
"""Delete a network ACL."""
client = get_client("ec2")
params = {}
params["NetworkAclId"] = acl_id
return client.delete_network_acl(**params) | 5,316,680 |
def validate_property_directives(directives):
"""Validate the directives that appear at a property field."""
for directive_name in six.iterkeys(directives):
if directive_name in VERTEX_ONLY_DIRECTIVES:
raise GraphQLCompilationError(
u'Found vertex-only directive {} set on pro... | 5,316,681 |
def _delImage(id):
"""
deletes image from tmp dir, no longer wanted
"""
try:
imgPath = _getImagePath(id)
if os.path.isfile(imgPath):
os.unlink(imgPath)
except:
traceback.print_exc()
pass | 5,316,682 |
def catalog_sections(context, slug=None, level=3, **kwargs):
"""
Отображает иерерхический список категорий каталога.
Для каждой категории отображается количество содержащегося в ней товара.
Пример использования::
{% catalog_sections 'section_slug' 2 class='catalog-class' %}
:param context... | 5,316,683 |
def get_scrapable_links(
args, base_url, links_found, context, context_printed, rdf=False
):
"""Filters out anchor tags without href attribute, internal links and
mailto scheme links
Args:
base_url (string): URL on which the license page will be displayed
links_found (list): List of all... | 5,316,684 |
def AccuracyTestNMax():
"""[summary]
Test the accuracy using n-max random points
"""
plgs = getTestPolygons()
pnt = Point(0, 0)
# Calculate D using polygon partitioning method
print("---------D---------------")
for i in range(len(plgs)):
print(DistCalc.DistCalcPART(pnt, plgs[i]))... | 5,316,685 |
def save_checkpoint(state, is_best, checkpoint):
"""Save model and training parameters at checkpoint + 'last.pth.tar'. If is_best==True, also saves checkpoint + 'best.pth.tar'
Args:
state: (dict) contains model's state_dict, may contain other keys such as epoch, optimizer state_dict
is_best... | 5,316,686 |
def read_source_MCI(csv_path: str | None = "volume_sum_icv_site.csv"):
"""
:param csv_path: str
:return: Train and test dataset of independent variables X and dependent variable y
"""
MRI_source_df = pandas.read_csv(csv_path)
X_df = MRI_source_df.iloc[:, 2:-2]
del X_df['age']
... | 5,316,687 |
def get_exp_logger(sess, log_folder):
"""Gets a TensorBoard logger."""
with tf.name_scope('Summary'):
writer = tf.summary.FileWriter(os.path.join(log_folder), sess.graph)
class ExperimentLogger():
def log(self, niter, name, value):
summary = tf.Summary()
summary.valu... | 5,316,688 |
def rollDie():
"""returns a random int between 1 and 6"""
return random.choice([1, 2, 3, 4, 5, 6]) | 5,316,689 |
def add_commands(cli_group: click.group):
"""
add commands to cli group
args:
cli (click.group)
"""
cli_group.add_command(init)
cli_group.add_command(update)
cli_group.add_command(summary) | 5,316,690 |
def _extract_attachments(phase, testrun, used_parameter_names):
"""Extract attachments, just copy them over."""
for name, (attachment_data, mimetype) in sorted(phase.attachments.items()):
name = _ensure_unique_parameter_name(name, used_parameter_names)
testrun_param = testrun.info_parameters.add()
testr... | 5,316,691 |
def calc_ari(A, B):
""" Adjusted Rand Index"""
A = {v: k for k, s in A.items() for v in s}
B = {v: k for k, s in B.items() for v in s}
df = pd.DataFrame({'A': A, 'B': B}).dropna()
A = df['A'].to_list()
B = df['B'].to_list()
return adjusted_rand_score(A, B) | 5,316,692 |
def encode_adj(adj, max_prev_node=10, is_full=False):
"""
:param adj: n*n, rows means time step, while columns are input dimension
:param max_degree: we want to keep row number, but truncate column numbers
:return:
"""
if is_full:
max_prev_node = adj.shape[0] - 1
# pick up lower tr... | 5,316,693 |
def test_random_walk_labels_pd():
"""Random input test for the Labelled Random Walk kernel [n_jobs=-1/decorator]."""
train, test = generate_dataset(n_graphs=100,
r_vertices=(10, 20),
r_connectivity=(0.4, 0.8),
... | 5,316,694 |
def get_datasource_content_choices(model_name):
"""Get a list (suitable for use with forms.ChoiceField, etc.) of valid datasource content choices."""
return sorted(
[(entry.content_identifier, entry.name) for entry in registry["datasource_contents"].get(model_name, [])]
) | 5,316,695 |
def setFDKToolsPath(toolName):
""" On Mac, add std FDK path to sys.environ PATH.
On all, check if tool is available.
"""
toolPath = 0
if sys.platform == "darwin":
paths = os.environ["PATH"]
if "FDK/Tools/osx" not in paths:
home = os.environ["HOME"]
fdkPath = ":%s/bin/FDK/Tools/osx" % (home)
os.environ... | 5,316,696 |
def closeFiles():
"""Reopen all logfiles managed by ZConfig configuration."""
while _reopenable_handlers:
wr = _reopenable_handlers.pop()
h = wr()
if h is not None:
h.close() | 5,316,697 |
def datasplit(datastream,split_param=None,split_value=0.2):
"""
Very flexible function for splitting the dataset into train-test or train-test-validation dataset. If datastream
contains field `filename` - all splitting is performed based on the filename (directories are ommited to simplify
moving data a... | 5,316,698 |
def upd_p_fdtd_srl_2D_slope(p, p1, p2, fsrc, fsrc2, Nb, c, rho, Ts, dx, Cn,
A, B, C, x_in_idx, y_in_idx, x_edges_idx,
y_edges_idx, x_corners_idx,
y_corners_idx, slope_start):
"""
This FDTD update is designed for case 5: slope.
... | 5,316,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.