content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def slic(image, n_segments=100, compactness=10., max_iter=10, sigma=0,
spacing=None, multichannel=True, convert2lab=None,
enforce_connectivity=False, min_size_factor=0.5, max_size_factor=3,
slic_zero=False):
"""Segments image using k-means clustering in Color-(x,y,z) space.
Parameter... | 71,500 |
def build_from_path(in_dir, out_dir, num_workers=1, index=1):
"""Preprocesses the Biaobei dataset from a given input path into a given output directory.
Args:
in_dir: The directory where you have downloaded the Biaobei dataset
out_dir: The directory to write the output into
num_workers: ... | 71,501 |
def str_ljust(x, width, fillchar=' '):
"""Fills the right side of string samples with a specified character such that the strings are right-hand justified.
:param int width: The minimal width of the strings.
:param str fillchar: The character used for filling.
:returns: an expression containing the fil... | 71,502 |
def partition_folder_path(file_path):
"""
This function provides the output path to which the data frame will be created
:param file_path: file path from config_utils for the value 'output_file_path'
:return: output file path with date partition
"""
file_path = file_path + str(datetime.datetime.... | 71,503 |
def index(request):
"""Loads main page containing a MapBox map and the weight sliders."""
return render(request, "map/index.html") | 71,504 |
def parse_move(s: str) -> int:
"""
:param s:
:return:
"""
try:
v = int(s)
except ValueError:
v = -1
return v | 71,505 |
def exception_to_string(exc: Exception) -> str:
"""Convert exception to string stackrace"""
# Either use passed original exception or whatever we have
return TRACEBACK_HEADER + "".join(format_tb(exc.__traceback__)) + str(exc) | 71,506 |
def delete_site_config(config_dir):
"""
Delete site configs to local directory specified in config_dir
:param config_dir: path to directory containing site configuration
:return: None
"""
shutil.rmtree(config_dir, ignore_errors=True) | 71,507 |
def nc_copy_variables_attributes(nc_source, nc_destination, includes=[],
excludes=[], renames=None, attr_includes=None,
attr_excludes=None, attr_renames=None,
attr_defaults=None, attr_appends=None):
"""Copy NetCDF var... | 71,508 |
def indice_x_norm(x_selected:float, x_norm:pd.Series):
"""
This function finds the indices for different values of the independent
variable (x). The script considers the selected x_fixed point
(for example: 0.15, 0.30, 0.45, 0.60, 0.75, 0.90). The output of the
function are the observed limi... | 71,509 |
def get_all_drives(session, start=None, limit=None, return_type=None,
**kwargs):
"""
Retrieves details for all drives for the VPSAOS.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type start: int
:param start: Th... | 71,510 |
def preload_filter_options():
"""
Aggregate all Articles' existing values for given FILTER_OPTION_KEYS and save them to the FilterOption collection in Mongo, replacing those that already exist.
"""
filter_options = {key: set() for key in FILTER_OPTION_KEYS}
# keep track of set of casefolded values to preserve... | 71,511 |
def cache(self, key, fn):
"""
:param self: the object that will hold the cached value
:param key: the key/attribute for the cached value
:param fn: the function returning the value to be cached
:return: the value returned by fn on first call
"""
if not hasattr(self, key):
value = fn... | 71,512 |
def cursorColorForColormap(colormapName):
"""Get a color suitable for overlay over a colormap.
:param str colormapName: The name of the colormap.
:return: Name of the color.
:rtype: str
"""
return _COLORMAP_CURSOR_COLORS.get(colormapName, 'black') | 71,513 |
def alarm_to_time(alarm: str):
""" This function converts the time when the alarm is setted into seconds """
time_alarm = time.strptime(alarm + ":00", "%Y-%m-%dT%H:%M:%S")
return time.mktime(time_alarm) | 71,514 |
def timer():
"""
:this time is collect period.get from the db.
"""
print("Successfully completed a cycle, sleeping for 5 seconds ...")
time.sleep(5)
return | 71,515 |
def _compute_ious(dt, gt):
""" compute pairwise ious """
ious = np.zeros((len(dt), len(gt)))
for g_idx, g in enumerate(gt):
for d_idx, d in enumerate(dt):
ious[d_idx, g_idx] = _jaccard(d, g)
return ious | 71,516 |
def get_top_articles():
"""Most popular three articles of all time"""
sql = """SELECT articles.title, COUNT(*) AS views
FROM articles, log
WHERE log.path = '/article/' || articles.slug
GROUP BY articles.title
ORDER BY views DESC
LIM... | 71,517 |
def plot_binary_grid(masks, image_paths=""):
"""Plots a grid of results.
Takes masks and option image_paths argument. If:
Only masks, plots B&W binaries.
Both masks and image_paths, uses get_overlay_image.
Contributor: @tsipkens, Oct/2020
:param masks: list of binary masks
:param i... | 71,518 |
def wiki_request(store, **params):
"""Build a network request for a given store"""
# Default parameter
params["format"] = "json"
# Build request
url = os.path.join(store, WIKI_API_FILE)
data = urllib.parse.urlencode(params).encode()
res = opener.open(url, data)
# Return JSON results
return json.loa... | 71,519 |
def overlap2(data):
"""
"""
# Make a copy of the data.
data2 = copy.copy(data)
# Extract the first and last year and month.
firstYear = int(data2[0][0][0 : 4])
firstMonth = int(data2[0][0][5 : 7])
lastYear = int(data2[-1][0][0 : 4])
lastMonth = int(data2[-1][0][5 : 7])
naTemp ... | 71,520 |
def meridional_curve(n_0, pitch, length, r_i, theta_i, npoints=40):
"""
Points on path of a ray passing through a grin lens.
Args:
n_0: index of refraction at center of grin lens [unitless]
pitch: pitch or period of the lens [unitless]
length: axial length of the lens [mm]
r... | 71,521 |
def restore_model(session, saver, path):
""" Initializes a model that has been previously trained and
returns global step
Args:
session: Tensorflow session
saver: Tensorflow saver
path: Path where model to be loaded is
Returns:
Global step variable
"""
logger.info... | 71,522 |
def strip(fileName):
"""strip debugging informations from shared libraries and executables - mingw only!!! """
if CraftCore.compiler.isMSVC() or not CraftCore.compiler.isGCCLike():
CraftCore.log.warning(f"Skipping stripping of {fileName} -- either disabled or unsupported with this compiler")
ret... | 71,523 |
def get_fake_users():
"""Restituisce una lista di utenti fake"""
with open('db/fake-data/users.json') as f:
data = json.load(f)
users = []
for row in data['results']:
user = {
'username': row['login']['username'],
'email': row['email'],
... | 71,524 |
def spherical_to_cartesian(theta, phi, rho):
""" Converts spherical coordinates into cartesian. """
x = rho * np.sin(phi) * np.cos(theta)
y = rho * np.sin(phi) * np.sin(theta)
z = rho * np.cos(phi)
return x, y, z | 71,525 |
def insert(df: pd.DataFrame, col_name, col_value, allow_duplicates=False):
"""Adds a column to the end of the DataFrame
:param df: DataFrame
:param col_name: name of column to insert
:param col_value: value of column to insert
"""
return df.insert(len(df.columns), col_name, col_value, allow_dup... | 71,526 |
def doChangePageSize(request, pageSize):
""" Changes page size in user preferences"""
try:
u = User.objects.get(user=request.user.id)
u.pagesize = pageSize
u.save()
return HttpResponse(_('saved pagesize %s') % pageSize)
except Exception, inst:
return HttpResp... | 71,527 |
def initialize_weights(model: nn.Module, activation: str = 'relu'):
"""Initialize trainable weights."""
for _, m in model.named_modules():
if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity=activation)
if m.bias is ... | 71,528 |
def _solve_lagrange123_com_slow(i, q, xtol=1e-6):
"""
Solve for L1, L2, or L3 x position in the CoM frame in units of semi-major
axis *a*.
Parameters
----------
i : {1,2,3}
L point to solve for
q : float
Mass ratio m2/m1
xtol : float
Tolarance value for solver.
... | 71,529 |
def is_abs_bpath(d):
"""Returns true if it's an absolute blaze path"""
return is_valid_bpath(d) and d.startswith('/') | 71,530 |
def get_network_fn(name, num_classes, weight_decay=0.0, is_training=False):
"""Returns a network_fn such as `logits, end_points = network_fn(images)`.
Args:
name: The name of the network.
num_classes: The number of classes to use for classification.
weight_decay: The l2 coefficient for the model weight... | 71,531 |
def job_product(job_name, pre_request=None):
"""Decorator to register a function as a job product handler.
Example::
@job_product('build-playlist-report')
def playlist_report_product(results):
csv_file = "\n".join(results['file_lines'])
response = HttpResponse(conte... | 71,532 |
def blockplural(parser, token):
"""
Same as plural filter
Example:
{% blockplural amount %}{% trans "Book" %}{% endblockplural %}
"""
nodelist = parser.parse(('endblockplural',))
parser.delete_first_token()
tag_name, amount = token.split_contents()
return PluralNode(nodelist, am... | 71,533 |
def preprocess_text(input: TextPreprocessingInput) -> TextProcessingOutput:
"""Clean up text data based on selected preprocessing steps."""
text = input.text
if PreprocessingStep.REMOVE_SPECIAL_CHARACTERS in input.preprocessing_steps:
text = re.sub(r"\W", " ", text)
if PreprocessingStep.REMOV... | 71,534 |
def annotate(args):
"""Apply Autoperf HPC annotations to C/C++ code.
Args:
args: Provided by argparse.
"""
from .annotation.annotation import annotate as anno
anno(args) | 71,535 |
async def send_comradely_reminder() -> None:
"""Send a comradely reminder."""
if not (env.COMRADELY_CONTACT and env.COMRADELY_MESSAGE):
return
log.info("Sending comradely message")
signal.send_message(env.COMRADELY_MESSAGE, env.COMRADELY_CONTACT) | 71,536 |
def dso_nexus_add_proxy_repo(url, login_username, login_password, verbose,
repository_name, remote_repo_url):
"""Add a Maven proxy repositories to the Nexus instance specified by URL"""
exit_code = 0
errors = {}
with nexus.Nexus(
url, login_username, login_password, ... | 71,537 |
def sdss_fits_url(plate, mjd, fiber):
"""Return the URL of the spectrum FITS file"""
return SDSS_URL % dict(plate=plate, mjd=mjd, fiber=fiber) | 71,538 |
def verbose(message):
"""Color format a message for verbose messages"""
if __use_colors():
return "%s%s%s" % (COLOR_VERB, message, attr(0))
else:
return message | 71,539 |
def dropout_constr(options, use_noise, trng, sampling):
"""This constructor takes care of the fact that we want different
behaviour in training and sampling, and keeps backward compatibility:
on older versions, activations need to be rescaled at test time;
on newer veresions, they are rescaled at traini... | 71,540 |
def to_inter_sets(lines):
"""Groups linked entities and interpretation set."""
group_by_qid = defaultdict(set)
for cols in lines:
group_by_qid[cols[0]].add(cols[2])
return group_by_qid | 71,541 |
def gini_index(targets) -> float:
"""
Computes the gini index for a given target labels.
Arguments:
targets: A numpy array of shape (n_samples, )
Returns:
The gini index for the given target labels.
"""
label_count = np.bincount(targets)
return 1 - np.sum((label_count / len(t... | 71,542 |
def _call_slugs(filename, symbolic, strategy_file,
affinity=None, logfile=None,
other_options=None):
"""Call `slugs` and log memory usage and time.
@param filename: path to SlugsIn file
@param symbolic: if `True`, then make symbolic strategy
@param strategy_file: dump st... | 71,543 |
def test_three() -> None:
""" Test with three """
run_test([THREE], 'tests/expected/three.txt.out') | 71,544 |
def hyperopt_fit (model, X, Y, T, p0, **estimation_settings):
"""Calls Hyperopt.
Exists to make passing arguments to the objective function easier.
Arguments:
model, X, Y, T, p0, estimation_settings: Just like other
optimizers, see DE_fit.
estimation_settings (dict): Optional. A... | 71,545 |
def get_type(data_field, derives=None):
"""
Parse type defined in <DataField> object and returns it.
Parameters
----------
data_field : eTree.Element
<DataField> or <DerivedField> XML element that describes a column.
derives : eTree.Element
<DataField> XML element that the derived field derive... | 71,546 |
async def test_default_availability_payload(opp, mqtt_mock):
"""Test availability by default payload with defined topic."""
await help_test_default_availability_payload(
opp, mqtt_mock, number.DOMAIN, DEFAULT_CONFIG
) | 71,547 |
def zero_grads(tensors):
"""
Sets gradients of list of Tensors to zero in place
"""
for p in tensors:
if p.grad is not None:
p.grad = torch.zeros_like(p.grad) | 71,548 |
def initialize_personality():
"""
Initializes personality. Downloads the tarball and extracts the system image
"""
download_personality_tarball()
get_system_image_from_tarball()
override_options_for_personality() | 71,549 |
def matrix_product(m1, m2):
"""
Args:
m1 (mpmath.matrix or numpy.ndarray): first matrix
m2 (mpmath.matrix or numpy.ndarray): second matrix
Returns:
matrix product m1 * m2 with same data type as m1 and m2
"""
if isinstance(m1, mpmath.matrix) and isinstance(m2, mpmath.ma... | 71,550 |
def exec_command_rc(*cmdargs, **kwargs):
"""
Wrap creating subprocesses.
Return exit code of the invoked command.
"""
# 'encoding' keyword is not supported for 'subprocess.call'.
# Remove it thus from kwargs.
if 'encoding' in kwargs:
kwargs.pop('encoding')
return subprocess.call... | 71,551 |
def random_points_and_masses(max_points=10, min_mass=0.5, max_mass=2.0,
max_coord=rbf_high, min_separation=0.5):
"""
returns:
-shape [N, 3] numpy array of points, where N is between 2 and max_points
-shape [N] numpy array of masses
"""
num_points = random.randint(2, ... | 71,552 |
def imresize(image, factor, interp="nearest", mode=None):
"""
resize an image with a specified resizing factor, this factor can also be
the target shape of the resized image specified as tuple.
"""
interp_methods = {
"nearest": PIL.Image.NEAREST,
"bicubic": PIL.Image.BICUBIC,
... | 71,553 |
def enum_class_getitem(context, builder, sig, args):
"""
Return an enum member by index name.
"""
enum_cls_typ, idx = sig.args
member = enum_cls_typ.instance_class[idx.literal_value]
return context.get_constant_generic(builder, enum_cls_typ.dtype,
member.v... | 71,554 |
def load_src_sample(args, suffix='', sources=None, mf=None):
"""
Load data from src_sample files
:param args: command line params (used if sources are given by name or not given at all)
:param suffix: may be used to select a ranage of files (e.g. suffix='*') or specific realizations
:param sources: ... | 71,555 |
def get_key_from_insecure_cbc(encryption_oracle):
"""Recovers the key from the lazy encryption oracle using the key also as iv.
The approach used is the simple one outlined in the challenge description.
"""
block_length = find_block_length(encryption_oracle.encrypt)
prefix_length = find_prefix_lengt... | 71,556 |
def mises_pari_rembourse_si_perdant(cotes, mise_max, rang=-1, remb_freebet=False,
taux_remboursement=1, output=False):
"""
Calcule les mises lorsque l'un des paris est rembourse. Par
defaut, la mise remboursee est placee sur la cote la plus haute et le
remboursement e... | 71,557 |
def sort_2GX(*msg):
""" Route T-Stick messages for T-Stick #015. """
if msg[0] == 0:
return False
elif msg[0] == 1:
named_return = collections.namedtuple('tstick_sensor', 'rawcapsense')
rawcapsense = msg[1:]
return named_return(list(rawcapsense))
# capsense_bits = coo... | 71,558 |
def export_tweets():
"""
Export all results as CSV file from the latest tweet.
:param limit: limit the number of result to be returned
"""
@copy_current_request_context
def generate():
import io, csv
output = io.StringIO()
writer = csv.DictWriter(output, dialect='unix'... | 71,559 |
def dump_query_and_targets_to_log(query, targets):
"""Dump the Sequence objects in query and targets to the log as a DEBUG message."""
# Log our sequences:
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug("Query Sequence:")
dump_sequence_to_log(query)
LOGGER.debug("Target Sequenc... | 71,560 |
def read_double(fid, count=1):
""" Read 64bit float from bti file """
return _unpack_simple(fid, '>' + ('d' * count), count) | 71,561 |
def test_solver(a,b,c):
""" Test that the program works, for a triangle of sides a,b,c."""
# first find the angles, testing SSS
a1,b1,c1,A,B,C = solve(a=a,b=b,c=c)
assert tuple_isclose((a,b,c), (a1,b1,c1))
test_triangle(a,b,c,A,B,C)
tri = (a,b,c,A,B,C)
# SAS tests
assert tuple_isclose(t... | 71,562 |
def main(argv):
"""Terminates any kubernetes cluster associated with the account that is running
with the name <username>.facebook360.dep.k8s.local.
Args:
argv (list[str]): List of arguments (used interally by abseil).
"""
aws_util = AWSUtil(FLAGS.csv_path)
ec2_file = os.path.expanduser... | 71,563 |
def test__break_pattern_should_fail_with_one_char_separator():
"""
Tests the _break_pattern function fails if the separator pattern has less than 2 character.
The reason for enforcing this is because single-char separator patterns cannot be escaped correctly.
"""
with pytest.raises(ValueError):
... | 71,564 |
def is_rover_in_perpetual_loop(Rover):
"""
Check to see if rover is is in perpetual loop
Inputs:
Rover (Rover object)
Returns:
bool statement of the sign uniformity of the latest Rover steers
"""
if Rover.angling_towards_sample_start_time and not Rover.approaching_sample_end_time... | 71,565 |
def is_cuttingboard(fn, size_th):
"""Decides if fn belongs to the cutting board of if it contains information.
The criterion to decide if a file is part of a recording is the following.
If a video is part of a recording it has to have a size of aprox 4GB
(maximum size of a file in the FAT system). But,... | 71,566 |
def gdf_geom_clip(gdf_in, clip_geom):
"""Filter a dataframe to contain only features within a clipping geometry
Parameters
---------
gdf_in
geopandas dataframe to be clipped in
province_geom
shapely geometry of province for what we do the calculation
Returns
-------
fil... | 71,567 |
def getAnm(P, mstr, Bmat, findmin, findmax, Ndec):
"""
Return the (N+1)^2-element list containing SHDs of STFTs
:param P: STFTs of the M channels of recordings
:param mstr: Dict containing the microphone array properties
:param Bmat: List of response equalisation matrices
:param findmin: Index ... | 71,568 |
def _(message, *_):
"""
NOOP implementation of sphinx.locale.get_translation shortcut.
"""
return message | 71,569 |
def create(count, descriptorType=None, withoutTAP=False, withoutNTOR=False):
"""Create **count** descriptors of type **descriptor_type**.
:param int count: The number of descriptors to generate.
:type descriptorType: str or ``None``
:param descriptorType: One of ``"relay"``, ``"bridge"``,
``"hi... | 71,570 |
def random_color_hsv():
"""random a hex color, only random h value to get a brighter color"""
h, s, v = random.random(), 1, 1
float_rgb = colorsys.hsv_to_rgb(h, s, v)
return convert_rgb([int(x * 255) for x in float_rgb]) | 71,571 |
def optional(f: Callable[[S], T], x: Optional[S]) -> Optional[T]:
"""Apply ``f`` to ``x`` if ``x`` is not ``None``."""
if x is None:
return None
return f(x) | 71,572 |
def op_elem_vec_names(vecs, elem_op_labels, op_label_abbrevs):
""" TODO: docstring """
if op_label_abbrevs is None: op_label_abbrevs = {}
return [op_elem_vec_name(vecs[:, j], elem_op_labels, op_label_abbrevs) for j in range(vecs.shape[1])] | 71,573 |
def pdist(x, y, z, index, dmax=8.0):
"""
Pairwise distance computation for points in cartesian space.
Does return distance vectors.
"""
dmax2 = dmax**2
m = len(x)
n = m*(m - 1)//2
dx = np.empty((n, ), dtype=np.float64)
dy = dx.copy()
dz = dx.copy()
dr = dx.copy()
atom0 =... | 71,574 |
def ss(inlist):
"""
Squares each value in the passed list, adds up these squares and
returns the result.
Usage: lss(inlist)
"""
ss = 0
for item in inlist:
ss = ss + item * item
return ss | 71,575 |
def make_pre_build_hook(extra_compiler_config_params):
"""Return a pre-build hook function for C++ builders.
When called, during graph build, it computes and stores the compiler-config
object on the target, as well as adding it to the internal_dict prop for
hashing purposes.
"""
def pre_build_... | 71,576 |
def stats_scraper(stat_type, columns, season_id, f):
"""
stat_type = "pitching"|"batting"
columns: the number columns to scrape from the table
season_id: the ps season id
f: an open file where to write the lines
"""
table = get_stats_table(stat_type, season_id)
for row in table[0]("tr")... | 71,577 |
def melfrequencies_mel_filterbank(
num_bands, freq_min, freq_max, num_fft_bands
):
"""Returns centerfrequencies and band edges for a mel filter bank
Parameters
----------
num_bands : int
Number of mel bands.
freq_min : scalar
Minimum frequency for the first band.
freq_max : s... | 71,578 |
def set_switch_parent(controls, parent_switch):
"""
Args:
parent_switch (str): The name of a control group that has a switch (the control group has a switch when its 1 of 2 rigs are on 1 joint chain)
"""
controls = util.convert_to_sequence(controls)
for control in controls:
... | 71,579 |
def get_commit_link(repo_name: str, commit_sha: str) -> str:
"""
Build a commit URL for manual browser access using full repository name and commit SHA1
:param repo_name: full repository name (i.e. `{username}/{repoanme}`)
:param commit_sha: 40 byte SHA1 for a commit
:return: A commit URL
"""
... | 71,580 |
def create_short_link(db: Session, link: schemas.ShortLink):
"""Create and add a new short link
"""
chars = string.ascii_letters + string.digits
random_string = ''.join(random.choice(chars) for i in range(8))
new_short_link = models.ShortLink(
short_link_path = random_string
)
# Ch... | 71,581 |
def test_make_optimization_constraints_not_in_analysis(test_analysis_with_data):
"""Test that a FeroError is raised if the constraints are not in the analysis"""
with pytest.raises(FeroError):
test_analysis_with_data.make_optimization(
"test",
{
"goal": "maximize... | 71,582 |
def find_local_raw_5minute_file(station_id=None, month_unix_sec=None,
top_directory_name=None,
raise_error_if_missing=True):
"""Finds raw 5-minute file on local machine.
This file should contain 5-minute METARs for one station-month.
:param s... | 71,583 |
def print_missing_primary_keys(inspector: Any, schema: str) -> None:
"""Find and print tables in database that don't have primary keys."""
no_pks = []
for table in inspector.get_table_names(schema):
pks = inspector.get_pk_constraint(table, schema)
if len(pks) == 0:
no_pks.append(... | 71,584 |
def username(user_id):
"""
Find the user name associated to a user ID.
"""
return UserIndex.instance().username(user_id) | 71,585 |
def get_sqr_levels():
"""Get the sawtooth levels and take out the even harmonics to get square levels."""
saw_levels = get_saw_levels()
levels = []
for i in range(len(saw_levels)):
n = i + 1
level = saw_levels[n] if n % 2 != 0 else 0
levels.append(level)
return levels | 71,586 |
def test_fileformat_pass_with_encoding_from_config(fs):
"""Get encoding from config."""
payload = """this {k1} is line 1
this is line 2 {k2}
this is line 3
this {k3} is {k4} line 4
this !£$% * is {k5} line 5
"""
in_path = './tests/testfiles/testsubst.txt'
fs.create_file(in_path, contents=payload, enco... | 71,587 |
def load_temporal_statistics(keys):
"""Load statistical features of the lifted data, computed over the
temporal domain at each spatial point.
Parameters
----------
keys : list(str)
Which data set(s) to load. Options:
* {var}_min : minimum of variable var
* {var}_max : maximu... | 71,588 |
def check_type(val, type_spec):
"""Checks whether `val` is of TFF type `type_spec`.
Args:
val: The object to check.
type_spec: An instance of `tff.Type` or something convertible to it that the
`val` is checked against.
Raises:
TypeError: If the inefferred type of `val` is not `type_spec`.
""... | 71,589 |
def parse_gpu_info_lines(gpu_lines):
"""Parses the gpu info from 2 lines cut out from the nvidia-smi result.
Args:
gpu_lines (list of strings): Two nvidi-smi lines representing current gpu info.
Returns:
Tuple: Gpu id ('gpuX') and a dict with gpu info.
"""
gpu_id = 'gpu{}'.format(... | 71,590 |
def get_file_list(csv_dir, entity):
"""Get list of CSV files for a given entity"""
csv_file_list = os.listdir(csv_dir)
file_list = []
for file in csv_file_list:
if entity in file:
file_list.append(file)
return file_list | 71,591 |
def submit_batch_detection_api(images_to_detect: Iterable[str],
task_lists_dir: str,
detector_version: str,
account: str,
container: str,
sas_token: str,
... | 71,592 |
def module_cassette(request: FixtureRequest, github_client):
"""
Provides a Betamax cassette scoped to the test module
which record and plays back interactions with the GitHub API.
""" # noqa: D400
cassette_name = request.module.__name__.split('.')[-1]
with Betamax(github_client.session) as vcr:
# print(f"Us... | 71,593 |
def fill_between_angle(arr, s, e, center=None, is_radian=True):
"""Fill Between ``s`` and ``e``.
Args:
arr (np.ndarray) : Input array.
s (Number) : Start angle of fill.
e (Number) : End angle of fill.
center (tuple) : Center coor... | 71,594 |
def export(request, project_id):
"""get the status of train job sent to custom vision
@FIXME (Hugh): change the naming of this endpoint
@FIXME (Hugh): refactor how we store Train.performance
"""
project_obj = Project.objects.get(pk=project_id)
train_obj = Train.objects.get(project_id=proj... | 71,595 |
def convert(data, in_format, out_format):
"""Call TogoWS for file format conversion.
Arguments:
- data - string or handle containing input record(s)
- in_format - string describing the input file format (e.g. "genbank")
- out_format - string describing the requested output format (e.g. "fasta")
... | 71,596 |
def test_get_external_market_center_price(monkeypatch, ro_worker):
""" Simply test if get_external_market_center_price does correct proxying to PriceFeed class
"""
def mocked_cp(*args):
return 1
from dexbot.strategies.external_feeds.price_feed import PriceFeed
monkeypatch.setattr(PriceFee... | 71,597 |
def sort_by_labels(github_repo, pr_nums):
"""Sorts PR into groups based on labels.
This implementation sorts based on importance into a singular group. If a
PR uses multiple labels, it is sorted under one label.
The importance order (for the end-user):
- breaking changes
- highlight
- feat... | 71,598 |
def _get_submodel(model, name):
""" Return the first occurence of a sub-model. Search is performed by
model name.
"""
if not isinstance(model, CompoundModel):
return model if model.name == name else None
for m in model.traverse_postorder():
if m.name == name:
return ... | 71,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.