content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import subprocess
def DpkgHostArchitecture():
"""Return the host architecture."""
return subprocess.check_output(
['dpkg-architecture', '-qDEB_HOST_GNU_TYPE']).strip() | 32cf86531ba0ae2f426576aa896d918eeee525cb | 660,395 |
def get_next_super_layer(layer_dependency_graph, super_nodes, current_layer):
"""
Return the immediate next super layer of current layer.
:param layer_dependency_graph: dependency graph of the model
:param super_nodes: list of all super nodes
:param current_layer: the layer whose next super layer n... | d7a0e606c10974510d0d250d15d26537f8440494 | 660,396 |
def load_file(filename):
"""Load a file into the editor"""
if not filename:
return '', 0, 0
with open(filename, 'r') as f:
contents = f.read()
return contents, len(contents), hash(contents) | 5302edac4c47891856b749f7011c92ffa9a8077d | 660,397 |
import torch
def batchify_image(input):
"""Promotes the input tensor (an image or a batch of images) to a 4D tensor
with three channels, if it is not already. Strips alpha channels if
present.
"""
if input.ndim == 2:
input = input[None]
if input.ndim == 3:
input = input[None]
... | f59a0e31ecf3bc490992f6d164b59975dfe8067b | 660,399 |
def simple_unordered_list():
"""Create a simple unordered list."""
return [15, 7, 77, 128, -5, 0] | 6c8802f68aec842f72b8bb38150e767b720a57b9 | 660,400 |
def add_peak_args(parser):
"""
call peaks using clipper, pyicoclip
"""
parser.add_argument('--peak-caller', required=True,
dest='peak_caller',
choices=['clipper', 'pyicoclip'],
help='Peak-caller, clipper|pyicoclip')
parser.add_argument('-i', '--bam_files', nargs='+', requir... | 9d004c0f3d189d28bba4db216ace308e97281129 | 660,402 |
def is_position_valid(position, password):
"""Check if position is valid for password."""
return 0 <= position < len(password) and password[position] is None | 217960f4b4e25dd4e35856787055712462d6eb10 | 660,403 |
import traceback
def get_func_name():
"""
Get the name of the calling function
:return: calling-function`s name
"""
return traceback.extract_stack()[-2][2] | f330bf6b219c6b06cd35de77d54c6088b2043cc7 | 660,404 |
import unicodedata
def remove_diacritics(raw_text: str) -> str:
"""
>>> raw_text = "Montréal, über, 12.89, Mère, Françoise, noël, 889, اِس, اُس"
>>> remove_diacritics(raw_text)
'Montreal, uber, 12.89, Mere, Francoise, noel, 889, اس, اس'
"""
nfkd_form = unicodedata.normalize("NFKD", raw_text)
... | fe80736ef58d829f4511576d94e096814cd79857 | 660,405 |
def historical_limit():
"""max days"""
return 90 | 9905ddcc6bbd6a3f7e6864423cc6dee90fdb102a | 660,406 |
def list_deduplication(li: list) -> list:
"""
列表去重
"""
if not li:
return list()
res = list(set(li))
res.sort(key=li.index)
return res | 218dedb63ab0617a568ba6315e11cc24dac55af1 | 660,407 |
import urllib3
import requests
def getRawEventsDetails(epmserver, epmToken, authType, setid, category, eventid, version=None):
"""
Get raw event details
This method enables the user to retrieve raw events file data from EPM according
to a predefined filter
"""
# build the URL
... | b24bd28d7bf4d07230aec62985a8aba8cf1875fa | 660,408 |
from typing import Counter
import copy
def apply_edit_script(word_form: str, edit_rules: list, verbose: bool = True):
"""Applies an edit script to a word_form to produce a lemma. Does not case.
Args:
word_form (str)
lemma (str)
edit_rules (list): list of strings, where each string is ... | fbc09de5330a5c0e06ddebab3506b3263e392a50 | 660,409 |
def xl_col_to_name(col, col_abs=False):
"""Convert a zero indexed column cell reference to a string.
Args:
col: The cell column. Int.
col_abs: Optional flag to make the column absolute. Bool.
Returns:
Column style string.
"""
col_num = col
if col_num < 0:
rais... | 11ebb0e82847e5a1cddeace375a5a0cc3f30bf1b | 660,410 |
import posixpath
import os
import fnmatch
def should_skip(filename, config, path='/'):
"""Returns True if the file should be skipped based on the passed in settings."""
for skip_path in config['skip']:
if posixpath.abspath(posixpath.join(path, filename)) == posixpath.abspath(skip_path.replace('\\', '/... | bd11941a272a7cbca48b4bb71994724ea52d0f5c | 660,411 |
import six
import re
def check_if_error_message_equal(formatted_msg, unformatted_msg):
"""
Helper assertion for testing that a formatted error message matches the
expected unformatted version of that error.
"""
# Replace all `{}` style substitutions with `.*` so that we can run a regex
# on th... | 6f6550fe899121921372ca8a0a76f1289623f052 | 660,412 |
import re
def check_url_protocol(url):
"""Ensures a given url has the http:// protocl."""
if re.compile('http://').match(url) == None:
url = 'http://' + url
return url
else:
return url | 10b7346a82a7126cef2cb7af6eab5004b3a74ed5 | 660,413 |
import logging
def __set_loggerformat(startmethode):
"""Stellt die passende Formattierung ein"""
if startmethode == "auto":
frm = logging.Formatter("%(levelname)s: %(message)s", "%d.%m.%Y %H:%M:%S")
else:
frm = logging.Formatter("%(asctime)s %(levelname)s: %(message)s", "%d.%m.%Y %H:%M:%S"... | ddf632d0f6676f37910d014e9df294d1d3956d5c | 660,415 |
import re
def is_doi(str):
"""
check if a string is a valid DOI
@param str: str to check
@type str: str
@return: True if DOI
@rtype: bool
"""
doi_regex = re.compile('\\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)\\b')
return True if doi_regex.match(str) else False | 03d48d6d9fc6a6f3bd7ec48ecacb6279e76bef22 | 660,416 |
def correct_tu_dataframe(df):
"""
RpoH sigma factor should not be used to transcribed stable RNA.
"""
#incorrect_sigma_32 = ["TU0_3463_from_RPOH_MONOMER",
# "TU0_1181_from_RPOH_MONOMER",
# "TU0_1182_with_TERM0_1116_from_RPOH_MONOMER",
# ... | a26a9c068495ddfb3e14bbe1fd427b63b4969f65 | 660,417 |
def compute_jaccard_similarity_score(x, y):
"""
Jaccard Similarity J (A,B) = | Intersection (A,B) | / | Union (A,B) |
"""
intersection_cardinality = len(set(x).intersection(set(y)))
union_cardinality = len(set(x).union(set(y)))
return intersection_cardinality / float(union_cardinality) | b58e2d8ede4fbbf46493cb976e15c54fd4858693 | 660,418 |
def _strip_result(context_features):
"""Keep only the latest instance of each keyword.
Arguments
context_features (iterable): context features to check.
"""
stripped = []
processed = []
for feature in context_features:
keyword = feature['data'][0][1]
if keyword not in pr... | 563acd1b633cc1a2b8d79520b86982bfc1acd3d1 | 660,419 |
def get_curVersion():
"""
get program version
"""
return "V1.0.2" | 4e411ab0076bfbab783db5980a8138a305c31dcb | 660,420 |
import os
def get_oss_connection_info(module):
""" Check module args for credentials, then check environment vars access_key """
access_key = module.params.get('alicloud_access_key')
secret_key = module.params.get('alicloud_secret_key')
region = module.params.get('alicloud_region')
if not access... | 383e0ea56863199c87cf8af0b9835713285e7428 | 660,421 |
def format_polygon_line(indiviual_points):
"""
Given a list of coordinates [lat1, long1, lat2, long2, lat3, long3, ...], create a string with
longitude latitude couples separated by commas, and enclosed in parentheses, ex:
'(long1 lat1, long2 lat2, long3 lat3, ...)'
:param indiviual_points: a list o... | d793c183c3222583d157689b900563c56751868d | 660,422 |
import os
def check_outlook_d(path):
"""Checks the existence of the Outlook common filepath in the given path
Returns the path if it exists, None otherwise"""
application_data = path + "\\Local Settings\\Application Data\\Microsoft\\Outlook"
if os.path.exists(application_data):
return appl... | 66d32753275bd746e99a5e58248dde854b41b3d8 | 660,423 |
def get_image_uri(region_name):
"""Return object detection algorithm image URI for the given AWS region"""
account_id = {
"us-east-1": "811284229777",
"us-east-2": "825641698319",
"us-west-2": "433757028032",
"eu-west-1": "685385470294",
"eu-central-1": "813361260812",
... | 4e50dacf12aac8d157f094a510b7f6ec45261fb0 | 660,424 |
def removeSpacesAndTabs(data):
"""
Remove all tabs and spaces.
>>> removeSpacesAndTabs("a Sting With Spaces")
'aStingWithSpaces'
>>> removeSpacesAndTabs("a\tSting\tWith\tTabs")
'aStingWithTabs'
"""
return data.replace(" ", "").replace("\t", "") | 6a9263990cfac06fade6c5b69b1c44f93a8f3cbf | 660,425 |
def sort_string(text: str) -> str:
"""Sort string punctuation, lowercase and then uppercase."""
return ''.join(sorted([x for x in text], key=str.swapcase)) | 2d1094d3f620b5486ec2ac09ddb0705c1e50128f | 660,426 |
def cliffsDeltaSlow(lst1,lst2,
dull = [0.147, # small
0.33, # medium
0.474 # large
][0] ):
"""Returns true if there are more than 'dull' difference.
Warning: O(N)^2."""
n= gt = lt = 0.0
for x in lst1:
for y in lst2:... | a8f43dae7eb3050938aac0a9fa4bc3e96e1d5590 | 660,428 |
import argparse
def get_args_from_command_line():
"""Parse the command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--keys_folder_name", type=str, help="Name of the folder where keys are stored")
parser.add_argument("--search_method", type=str,
hel... | bd41a6446920483306cdf26d5fc6fbc1976da4cc | 660,429 |
def strip_matching(from_str, char):
"""Strip a char from either side of the string if it occurs on both."""
if not char:
return from_str
clen = len(char)
if from_str.startswith(char) and from_str.endswith(char):
return from_str[clen:-clen]
return from_str | 9e5f5340e2ffde51d4fe8ed524561c99e0a22dcd | 660,430 |
import numpy
def pca(x_array):
"""
Run principal component analysis.
Parameters
----------
x_array : array_like
The dataset to be used for computing PCA. It has dimensions (m x n)
where m is the number of examples (observations) and n is
the number of features.
Return... | 8e0a322fb7245b755f87b8bcdb6a8d09f63a05d1 | 660,434 |
import torch
def _select_all_triplets(distance_matrix, triplet_mask, margin=0.2):
"""
See:
* https://omoindrot.github.io/triplet-loss
"""
anchor_positive_dist = distance_matrix.unsqueeze(2)
anchor_negative_dist = distance_matrix.unsqueeze(1)
# Compute a 3D tensor of size (batch_size,... | 8df8d328c7279d509dc530bf34687deb7edfe084 | 660,435 |
def find_all_starts(seq):
"""Find the starting index of all start codons in a lowercase seq"""
# Initialize array of indices of start codons
starts = []
# Find index of first start codon (remember, find() returns -1 if not found)
i = seq.find('atg')
# Keep looking for subsequence incrementing ... | cc60a6b0622a326e6ff1b90775d138cd901cdb92 | 660,436 |
import sys
def python_2_unicode_compatible(klass):
"""Backported from django 1.5."""
if sys.version_info[0] != 3:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass | 438dcc3051aa6e42cb98fca3158a3b6b765e3ff2 | 660,438 |
def GetNodeList(cluster):
"""returns an ordered list of all nodes below cluster
the ordering is done using the lengths of the child nodes
**Arguments**
- cluster: the cluster in question
**Returns**
- a list of the leaves below this cluster
"""
if len(cluster) == 1:
return [cluster]
... | fa74be0cd75d08652884bbf62706c4b96541d445 | 660,439 |
def ns_to_ms(nanos, rounding=True, decimals=3):
"""
Converts nanoseconds to milliseconds, with optional rounding.
:param nanos: A numeric value of nano seconds
:param rounding: Whether to apply rounding (default is 3 decimal places)
:param decimals: The amount of decimal places to round to
:ret... | fe341d092682de76124871229cd793d11a39d9c8 | 660,440 |
import decimal
import re
def convert_currency(value):
"""
convert number likes HKD 4.40
:param value:
:return:
"""
if value:
try:
result = decimal.Decimal(re.sub(r'[^\d.]', '', value))
except decimal.InvalidOperation as e:
raise e
else:
... | 260638836d97607e51d6b0dbf936208daac63bc0 | 660,441 |
def decompose_valuefmt(valuefmt):
"""Returns a tuple of string parts extracted from valuefmt,
and a tuple of format characters."""
formats = []
parts = valuefmt.split('%')
i = 1
while i < len(parts):
if parts[i].startswith('s') or parts[i].startswith('d'):
formats.append(part... | 2cdb518ad95f694f56d339f4597e1afb338aa9e5 | 660,442 |
import platform
def is_linux() -> bool:
"""
:return: True if running on Linux. False otherwise.
"""
return platform.system().lower() == 'linux' | 2126de6751fdaf27eab606eef54230690270e4bf | 660,443 |
def refractive_index_broadband_vapour(sigma):
"""
Parameters
----------
sigma : {float, numpy.array}, unit=µm-1
vacuum wavenumber, that is the reciprocal of the vacuum wavelength
Returns
-------
n_ws : {float, numpy.array}
refractive index for standard moist air at sea leve... | c721b8e30d3afb2d7c629baed717cd8c32c6ac45 | 660,444 |
def clean_brackets(
string,
brackets=(("(", ")"),),
):
"""Removes matching brackets from the outside of a string
Only supports single-character brackets
"""
while len(string) > 1 and (string[0], string[-1]) in brackets:
string = string[1:-1]
return string | d6cb7575ec0a8f4cad4c3fa859d998bc6d483d99 | 660,445 |
def splinter_clean_cookies_urls():
"""List of urls to clean cookies on their domains."""
return [] | 8407b3324e88b817ab4f248e3bd5834fbeb1baf2 | 660,446 |
from typing import Tuple
def calculate_literal_value(bits: str) -> Tuple[int, str]:
"""Computes the value of a literal type packet."""
value_bits = ""
stop = False
current_bit = 0
while not stop:
value_bits += bits[current_bit + 1 : current_bit + 5]
if bits[current_bit] == "0":
... | dc1471caaf7eb59a1507206bd284099acaf5d660 | 660,447 |
def _skip_invalid_model(method):
"""
Decorator. Skips an SBML model and prints an error if libsbml
model extraction fails rather than raising an exception.
:param method: Method expecting a non-null return value from
libsbml.SBMLDocument.getModel().
"""
def wrapped(mpath, **kwar... | 5069d5a4a0a811d32bdb6480a34cd5b46a6605ec | 660,448 |
def remove_sound_descriptions(subs):
"""
Removes phrases that are enclosed with square brackets in the subtitles, for example [KNOCKING ON DOOR]
:param subs:
:return:
"""
for sub in subs:
if '[' in sub.text and ']' in sub.text:
t = sub.text
sub.text = t[:t.index('... | c02d9550d7320fd9478f381302515b0af4b50e32 | 660,449 |
def _clip_array(input_array, vmin, vmax):
"""
This function clips an array values
between user defined minimum and maximum
values.
Parameters
----------
input_array
vmin
vmax
Returns
-------
Notes
-----
Micro benchmark results showed that for a block size of 100,... | f7f5843e5ecbfecd53a6f92138b525987fd8dff1 | 660,450 |
def one(data: list, digits: tuple = (2, 4, 3, 7)) -> int:
"""
In the output values, how many times do digits 1 (2), 4 (4), 7 (3), or 8 (7) appear?
"""
return sum([len([value for value in output if len(value) in digits]) for _, output in data]) | ec5bd1f846c393ce7b75df72f4e05c2ba14ad10c | 660,451 |
def remove_0_values(data, labels):
"""Remove all the values to 0 from a data list and the corresponding index in a labels list.
:param list data: the data list to remove the 0 from.
:param list labels: the list labeling the data.
:returns: the list of the data with the 0 values removed and the corresp... | 3ac17a45eefeb0c6599dd0dc348ac155e7dfef35 | 660,452 |
def stringOfList(list, sep=" "):
""" Convert a list of items to a string of items, separated by sep """
result = ""
for it in list:
result += sep + str(it)
return result | bdfcc06c1f2633383c9571941c774de22ee62ae3 | 660,453 |
def pipette_selection(left_pipette, right_pipette, volume):
"""
Function to select pipette based on expected volumes. Will also adjust volume is pipette needs to pick up >1x
@param left_pipette:
@param right_pipette:
@param volume:
@return:
"""
loop = 1
pipette = ""
if volume > ... | 22a05a01ce6617fbc8b8f296447cb03596f462f6 | 660,454 |
def get_keys_from_osm_json(osm_json):
"""
Obtain all keys from queried OSM results, and do not include repeated elements.
Parameters
----------
osm_json : JSON
Returns
-------
List
"""
osm_keys = []
for element in osm_json['elements']:
keys = list(element["tags"].k... | c07f20798c732ba3cd7615eb5e849ff4e59bf069 | 660,455 |
from typing import List
def _reGlue(words: List[str]) -> str:
"""Helper function to turn a list of words into a string"""
ret = ""
for i in range(len(words)):
ret += words[i] + " "
ret = ret.strip()
return ret | 05e62307550e48fe1e7f387b4b5b618edd83e986 | 660,456 |
import os
import torch
def load_gp_outer_loop_checkpoint(folder):
"""Loads the outer loop checkpoint of the Gaussian process from the provided folder
Args:
folder(str): Path to the folder that contains the checkpoint
Returns:
torch.tensor: Tensor containing the learning rate priors o... | 5061104d62d568523f4a93eb258d311c8df8022a | 660,457 |
from typing import MutableMapping
from contextlib import suppress
def delete_recursive_dictionary_keys(dct_to_change: MutableMapping, list_of_keys_to_remove: list) -> MutableMapping:
"""
Removes the specified keys from the specified dict.
Args:
dct_to_change: Dictionary to modify
list_of_k... | e73f19521edcbcdbb21b2ced1911aea55d5af5ca | 660,458 |
import argparse
def get_parser() -> dict:
""" """
description = "test for the custom scoring metrics, adjusted from the official socring metrics."
parser = argparse.ArgumentParser(
description=description,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argumen... | 4f3c366ae140c2d6fab611b52a803b74e7c0f959 | 660,459 |
def generate_community_tags_scores(database, community):
"""
This function generates the most important terms that describe
a community of similar documents, alongside their pagerank and in-degree scores.
"""
# Get all intersecting nodes of the speficied community,
# ranked by their in-degree (... | c7623fdbad3389ec5c3dbf55c6758036c7cfce03 | 660,460 |
def cut_line(str, line_len):
"""
Wrap output
"""
result = []
temp = []
for idx, item in enumerate(str.split()):
temp.append(item)
if (idx + 1) % line_len == 0:
result.append(' '.join(temp))
temp = []
if len(temp) != 0:
result.append(' '.join(te... | cb1b101cfe92bf06ed57aa4e79c22e6381c046b6 | 660,461 |
import re
def _remove_assignment_id(s):
"""Remove the trailing (xxxxx) from a Canvas assignment name."""
return re.sub(r" +\(\d+\)$", "", s) | 766f37c0530f3bbc03a0545a30902edf888d1422 | 660,462 |
from typing import List
def find_common_name_for_boxes(boxes: List[str]) -> str:
"""
A brute-force solution for finding two boxes where the difference in box
names is limited to a single character. Returns the common characters in
the box names.
The algorithm just loops through the boxes and comp... | abc9600ac07074f8da5612d12155512586892ba1 | 660,463 |
import torch
def f1_loss(y_true: torch.Tensor, y_pred: torch.Tensor, is_training=False) -> torch.Tensor:
"""
Calculate F1 score. Can work with gpu tensors
FROM https://gist.github.com/SuperShinyEyes/dcc68a08ff8b615442e3bc6a9b55a354
The original implementation is written by Michal Haltuf on Kaggle.
... | 8a1270992bd63e4f84eb8f8e7f0f9633ec12e744 | 660,464 |
def bounding_box(patches):
""" Return the bounding box of the given patches """
mins = [float('inf'), float('inf')]
maxs = [-float('inf'), -float('inf')]
for patch in patches:
shape = patches[patch]['shape']
min_pos = [min(shape.bbox[i], shape.bbox[i + 2]) for i in range(2)]
... | e93c01a11a69a1649e66211975e93ead079bec44 | 660,465 |
def distance_between_notes(first_note, second_note):
""" returns distance between two notes, as a number of half-tones"""
notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
first_index = notes.index(first_note)
second_index = notes.index(second_note)
distance = second_index - ... | 7461e2b78a8c3eaed31ea872a64c212a0a5df9f3 | 660,466 |
def manual_classify_building(building_type):
"""
Adopt manual classification from the paper and add further tags
'Estimation of Building Types on OpenStreetMap Based on Urban Morphology Analysis'
"""
residential = ['apartments','aparments (s)',
'domitory','house','residentia... | e633aae78ba61d2fbcbfe0122ab543f4e99b7653 | 660,468 |
def is_window_in_area(window, area):
"""
Checks if a window is within an area.
To determine whether a window is within an area it checks if the x and y of
the window are within that area. This means a window can "hang out" of an
area but still be considered to be in the area.
Args:
win... | 9bc3c841176042169221cd8cde0127a808ad0498 | 660,469 |
import re
def get_year_from_cmip(filename):
"""
Given a file name, assuming its a cmip file, return the start and end year
"""
p = r'\d{6}-\d{6}\.nc'
s = re.search(pattern=p, string=filename)
if not s:
raise ValueError("unable to match file years for {}".format(filename))
start, e... | 863c404708463f04fdfea8e269c39cbded413aaa | 660,471 |
def update_gc_function(segment):
"""[summary]
Args:
segment ([type]): [description]
Returns:
[type]: [description]
"""
# GC = α ∗ WaitT + β ∗ TrvlT + μ ∗ Trate + γ ∗ stddev
if segment['flow'] > segment['max_flow']:
segment['wait_time'] += 1
elif segment['wa... | 95372ed4b7d1f2e268defa665235fecc416ec857 | 660,472 |
def _standardize_and_copy_config(config):
"""Returns a shallow copy of config with lists turned to tuples.
Keras serialization uses nest to listify everything.
This causes problems with the NumericColumn shape, which becomes
unhashable. We could try to solve this on the Keras side, but that
would require lot... | a71635195b87d63209f0ca289f51800b023a6d55 | 660,473 |
import math
def _doy_fraction(doy):
"""Fraction of the DOY in the year (Eq. 50)
Parameters
----------
doy : scalar or array_like of shape(M, )
Day of year.
Returns
-------
array_like
DOY fraction [radians].
"""
return doy * (2.0 * math.pi / 365) | 96019f7c2f132f52ad4e98b101dd2220cac93aaf | 660,475 |
import os
def in2out(in_file, word, transform=True, out_dir=None):
"""
creates an out_file name from an in_file name by adding word to the
in_file name and writing it to the output_directory if specified.
if transform is True, the word replaces the extension of in_file.
if False it adds it to the ... | de6d905d12d07d51cbb99dcee16da3751a1bba8e | 660,476 |
def split_grads_by_size(threshold_size, device_grads):
"""Break gradients into two sets according to tensor size.
Args:
threshold_size: int size cutoff for small vs large tensor.
device_grads: List of lists of (gradient, variable) tuples. The outer
list is over devices, the inner list is over indi... | 2e182650be07b1ce2bfe6cc3ee4b34c9915160f7 | 660,477 |
import sys
def readLabels(labelsfile):
"""
Reads the simpoint generate labels file and return the labels in a list
@type labelsfile: string
@param labelsfile: name of the labels file (simpoint generated)
@rtype labels: list
@return labels: labels generated by simpoint
"""
print('R... | 037b01ef1fa210bb9128452a281d9dcf0713a93f | 660,478 |
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
return [... | 00f0b6c16553461eb0a92e823f15b8175f431a54 | 660,479 |
def reward(traffic: int,
toll: float,
hp: float,
cost: float):
""" 单步奖赏计算函数
Parameters
----------
traffic:
车流量
cost:
开销
hp:
健康度
Returns
-------
"""
# 平均hp大约每日-0.1
income = traffic * toll
# print([income * 0.05*10... | c6fe4beb9d1463b0fad162e6c7097a00d5ee562f | 660,480 |
def module_cache_path(ctx):
"""Returns the Clang module cache path to use for this rule."""
return ctx.genfiles_dir.path + "/_objc_module_cache" | 62468fb1ea68626a86611c8b3190fa8da3390dd7 | 660,481 |
def reshape_data(train, test):
"""Normalizing both train and test sets Simultaneously .
Parameters
----------
train : numpy array
test : numpy array
Returns
-------
numpy array
reshaped train and test set .
"""
x_train = train.reshape(train.shape[0], train.shape[1], tr... | fddb3541434efa16c8c68dfcf728673d4fb3d41a | 660,482 |
def parse_volume_bindings(volumes):
"""
Parse volumes into a dict.
:param volumes: list of strings
:return: dict
"""
def parse_volume(v):
if ':' in v:
parts = v.split(':')
if len(parts) > 2:
hp, cp, ro = parts[0], parts[1], parts[2]
... | 34a72defb428e109ac400b6ff31681dd6e16a9c5 | 660,483 |
def _get_totals_row(slocgroup):
"""Returns the row for TOTALS."""
totallines = slocgroup.totallines
def average(key):
total = totallines(key)
return total / len(slocgroup.filenamesToSlocInfos)
return ['TOTALS',
totallines('code'), average('codeperc'),
totallines... | 380dfda71574ed08f5f5c1379e352987346ca8f0 | 660,484 |
def read_relative_operator_basenames(task):
""" Read list of relative operators basenames.
Returns:
(list) : list of relative operators basenames
"""
relative_operator_filename = "relative_operators.dat"
# read list of unit tensors
relative_operator_stream = open(relative_operator_fil... | 3a558d7dfd81ef1abcb83b62ceae5c34ef17a6a1 | 660,485 |
from typing import Sequence
from typing import List
def averaged_knots_constrained(
n: int, p: int, t: Sequence[float]) -> List[float]:
""" Returns an averaged knot vector from parametrization vector `t` for a
constrained B-spline.
Args:
n: count of control points - 1
p: degree
... | 7dfd08fd8b0d332e992ca4a837b8b43516ac264b | 660,486 |
def _utf8(s):
"""ensure utf8 bytes"""
if not isinstance(s, bytes):
s = s.encode('utf8')
return s | 0bf271d867777625baf5ee3dc5d554e811ad158e | 660,487 |
from typing import Callable
from typing import Tuple
from typing import Any
from typing import Dict
from warnings import warn
def format_errwarn(func: Callable[[], Tuple[Any, Dict, Dict]]):
""" Wraps a function returning some result with dictionaries for errors and
warnings, then formats those errors and ... | d8dd854ca3ce3a45c07432a51a69ff78758a3da9 | 660,488 |
from pathlib import Path
def get_home_dir():
"""
Return user home directory
"""
return str(Path.home()) | 311d56187b6200b2b7f88f526a0fa0478feb27ab | 660,489 |
def create_fold_names(model_name:str, n_splits=5) -> list:
"""
List comprehension that creates the folder names.
Parameters
----------
`model_name` : `str`\n
Model name.
`n_splits` : `int`, `optional`\n
Number of splits used for kfold cross validation, by default 5
Returns
... | b7aff7da2c759daa5ed5600246be3ee3073da722 | 660,490 |
import json
def output_fn(prediction, content_type):
"""Return prediction"""
return json.dumps(prediction.tolist()) | 87245d451b87ffa77c12f0be72d5eeb1b24c0059 | 660,491 |
import logging
def parse_time_window(timewindow):
"""
Args:
timewindow (str, optional): time window for plot. Must be in format: 'YYYY-MM-DD:YYYY-MM-DD'
Returns:
list:str containing starting and ending times
"""
return_list = []
try:
parts = timewindow.split(":")
... | b1d115a7f26f34b28106043a35ceff700a638c88 | 660,492 |
def ValidJsIdentifier(x):
"""Returns True if x is valid javascript identifier."""
# This is just an approximation
if not x: return False
nodash = x.replace('_', 'a')
return nodash.isalnum() and nodash[0].isalpha() | 101c3f48d0d9a134e2a01f6aeb198e2122cf5519 | 660,493 |
def Additive(layer1, layer2):
"""
Learns the difference of two layers.
layer1: prior drift
layer2: posterior drift layer
"""
init_fn1, apply_fn1 = layer1
init_fn2, apply_fn2 = layer2
def init_fun(rng, input_shape):
output1, params1 = init_fn1(rng, input_shape)
output2, p... | dbafda71ef9709b3856520b61f7c867e8ea37bd1 | 660,494 |
def _SnakeToCamelString(field_name):
"""Change a snake_case string into a camelCase string.
Args:
field_name: str, the string to be transformed.
Returns:
str, the transformed string.
"""
parts = field_name.split('_')
if not parts:
return field_name
# Handle field_name with leading '_'s by c... | 4499203fb763b74c6fcc93d9d8611c6b08641fc6 | 660,495 |
def compile_flags(args):
"""
Build a dictionnary with an entry for cppflags, ldflags, and cxxflags.
These options are filled according to the command line defined options
"""
compiler_options = {
'define_macros': args.defines,
'undef_macros': args.undefs,
'include_dirs': a... | 2216fdbb0e5ec6929fd741a6b5ced0166c30c5b1 | 660,497 |
def _latest_report_info_dir(bucket):
"""Returns a GCS URL to the latest report info for the given bucket."""
return 'gs://{0}/latest_report_info/'.format(bucket) | 172fe8d1b8ad038c95b9ec9f629f59d17b5bacb7 | 660,499 |
def get_styles(features, collections, links=True):
"""
Based on which features and collection are provided,
the styles for all features are determined here
"""
models = []
models.extend([f.kml_style for f in features])
models.extend([c.kml_style for c in collections])
if not links:
... | 1413b7ffc2c68ae86e93d0c6e65e2f0f7338d3aa | 660,500 |
def parse_dir(save_dir):
"""Parses the save directory to get only the directory (without the file name) to save the pictures to
:param save_dir: save directory string
:return: save directory string without the file name
"""
dir_list = save_dir.split('/')
dir = ''
if len(dir_list) == 1:
... | d40ff6ff03859654210bce5ed67d33f25e07a467 | 660,502 |
def collect_images_by_parent( html_elements, url_base ):
"""Iterates over a list of html elements containing image hyperlinks and collects their urls.
Parameters:
html_elements - A list of BeautifulSoup tags.
url_base - A string that gives the base part of the image urls.
"""
image_src ... | 816d1e30092c710330d38953f8d5bc296775c15f | 660,503 |
def coordinate_of_sequence(sequence):
"""
___0__1__2__3__4__
4| 1 2 3 4 5
3| 6 7 8 9 10
2| 11 12 13 14 15
1| 16 17 18 19 20
0| 21 22 23 24 25
"""
y = 4 - ((sequence - 1) // 5)
x = (sequence - 1) % 5
return x, y | 3f6a81a9eb0a2e1fe9e4d68fd212b7914ea700be | 660,505 |
def _mod_name_key(typ):
"""Return a (__module__, __name__) tuple for a type.
Used as key in Formatter.deferred_printers.
"""
module = getattr(typ, '__module__', None)
name = getattr(typ, '__name__', None)
return (module, name) | 6c8b63bee7e0342f1c48295123d4be2caa55f537 | 660,506 |
def _mg_getitem_ ( mgraph , item ) :
"""Get graph with certain index
>>> mg = ....
>>> g0 = mg[0]
"""
for i , g in enumerate ( mgraph ) :
if i == item : return g
raise IndexError("Invalid index for multigraph %s" % item ) | 10464dd5882eb287abd83b57361f2a0f48b87bb1 | 660,507 |
import math
def parse_cat_actions(raw: dict) -> dict:
"""Parse the permission labels into a layered dict."""
def set_len(item, target):
measure = int(math.ceil(len(item) / 10.0)) * 10
if measure > lengths[target]:
lengths[target] = measure
cats = {}
cat_actions = {}
l... | 38259546101532a7499f9fcba3b7493b98f85bf9 | 660,508 |
def compute_recall_at_k(real_gains, predicted_gains, k=5):
"""This function computes recall-at-k, i.e. the proportion of relevant items found in the top-k
recommendations.
"""
relevant_documents = [elem[0] for elem in real_gains]
retrieved_documents = [elem[0] for elem in sorted(predicted_gains, key = lambda... | f28905c5b5d70e7f58a0c4be06ce94d76be1ca62 | 660,509 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.