content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Sequence
from typing import List
def bubble_sort_iter(seq: Sequence) -> List:
"""
Sort a sequence with the iterative bubble sort algorithm.
Parameters
----------
seq : Sequence
Returns
-------
List
"""
lst: List = list(seq)
length: int = len(lst)
f... | 89dcdbfc14c04ad1294d481eda61e338ee6e1bbc | 611,580 |
import hashlib
import base64
def calculate_data_md5(data):
"""计算数据的MD5
:param data: 数据
:return MD5值
"""
md5 = hashlib.md5()
md5.update(data)
return base64.b64encode(md5.digest()) | 10528573f2b057ffa9ccce1257322419f5660529 | 611,581 |
def anchor_scales_from_str(anchor_scales_str):
"""
Parses a command line argument string for the anchor scales.
:param anchor_scales_str: comma-separated integers, e.g. "128,256,512".
:return: list of integers.
"""
return [int(dim) for dim in anchor_scales_str.split(',')] | 7155dd0336cec996a3e8a624cf10aedcb315f079 | 611,583 |
def z_region_pass(region, upper_limit=None, lower_limit=None):
"""return True if extended region [xmin, xmax, ymin, ymax, zmin, zmax] is
within upper and lower z limits
Args:
region (list): a long-region [xmin, xmax, ymin, ymax, zmin, zmax]
upper_limit (float): the z-max
lower_limit ... | 5c140d17c7356bd69db8672ca0620ab3499f07f6 | 611,586 |
def gini_node(n_classes, w_samples, y_sum):
"""Computes the gini impurity criterion in a node.
Parameters
----------
n_classes : int
Number of label classes
w_samples : float
Weighted number of samples in the node
y_sum : ndarray
Array of shape (n_classes,) and float d... | 3a15007dcc7e3315896a6c8830264b5a1513ddca | 611,587 |
def comment_string_with_block(string, block_comment):
"""Return string commented using block comments"""
if not string:
return string
beg, end = block_comment
return beg + ' ' + string.replace(beg, '').replace(end, '') + ' ' + end | b1c08bab1ba9bf5bf865d0f0a11afaca50eb6865 | 611,588 |
def clear_builtins(attrs):
"""
Clears the builtins from an ``attrs`` dict
Returns a new dict without the builtins
"""
new_attrs = {}
for key in attrs.keys():
if not(key.startswith('__') and key.endswith('__')):
new_attrs[key] = attrs[key]
return new_attrs | 1f1ec69fd3bd7df3110a8f0971911ae82d91547c | 611,589 |
import torch
def get_ndc_rays(H, W, focal, near, rays_o, rays_d):
"""
Transform rays from world coordinate to NDC.
NDC: Space such that the canvas is a cube with sides [-1, 1] in each axis.
For detailed derivation, please see:
http://www.songho.ca/opengl/gl_projectionmatrix.html
https://github... | 6bba680569bbe2401b0c3462f28faaa2867240ad | 611,591 |
def indent_docstr(s, indent, n=1, trim=True):
"""Add common indentation to all lines except first
Args:
s (str): docstring starting at indentation level 0
indent (str): text used for indentation, in practice
this will be the level of the declaration + 1
n (int): don't indent... | fb99e0c0608153acc289a317f782c2ec85d5eefa | 611,592 |
def decimal_string(value, precision=6, padding=False):
""" Convert float to string with limited precision
Parameters
----------
value : float
A floating point value.
precision :
Maximum number of decimal places to print
Returns
-------
value : string
The specif... | aa4b2c4e76a43d257a650e9409f8df6b90d6fd64 | 611,598 |
import socket
def get_localIP_to_remoteIP(connection_type, external_ip, external_port=80):
"""
<Purpose>
Resolve the local ip used when connecting outbound to an external ip.
<Arguments>
connection_type:
The type of connection to attempt. See socket.socket().
external_ip:
The ext... | 5b8c3299dbf3534664e84661de1deb82bfcbf8ce | 611,599 |
def negation(f):
"""Negate a filter.
Args:
f: filter function to invert
Returns:
A filter function that returns the negation of f.
"""
def keep(paths):
l = set(paths)
r = set(f(paths))
return sorted(list(l-r))
return keep | b732a7ebab22b8647f8e0d957b77258fff95e52b | 611,601 |
def findExtname(fimg, extname, extver=None):
"""
Returns the list number of the extension corresponding to EXTNAME given.
"""
i = 0
extnum = None
for chip in fimg:
hdr = chip.header
if 'EXTNAME' in hdr:
if hdr['EXTNAME'].strip() == extname.upper():
if... | 85ea37acb00033904c5b84fa4ec16127f71c582a | 611,603 |
def register_blueprints(app, blueprints):
"""
Register blueprints in views.
"""
for blueprint in blueprints:
app.register_blueprint(blueprint)
return None | 3b1be1d20187452efc3761462620c847f856f1ab | 611,606 |
import click
def main() -> int:
"""Console script for mspelling."""
click.echo("This is the cli for the mspelling project")
click_url = "https://click.palletsprojects.com/"
click.echo(f"See the click docs at {click_url} for more details")
return 0 | 17cf0f0084ec5e491963865f959be3cb1ca3647d | 611,608 |
from typing import List
def ue(i:int) -> List[int]:
"""Exponential-Golomb code for positive i - https://en.wikipedia.org/wiki/Exponential-Golomb_coding"""
i = i + 1
r = []
while i > 0:
r.insert(0, i % 2)
i = i >> 1
if len(r) == 0:
r = [0]
r0 = [0] * (len(r) - 1)
r0.... | e6f6006fb958a9dfc9d3fbf0ca694831dd6053f5 | 611,611 |
import re
def proto_refactor(proto_filename, namespace, namespace_path):
"""This method refactors a Protobuf file to import from a namespace
that will map to the desired python package structure. It also ensures
that the syntax is set to "proto2", since protoc complains without it.
Args:
prot... | f06b7a35067afe26324690ba6b787439485f56fc | 611,612 |
def mean(xs):
"""Returns the mean of the given list of numbers"""
return sum(xs) / len(xs) | 05404301294bf2ff7c632857d31d33c78741bcfd | 611,614 |
def __nexo(soup):
"""
Gets the most read news from the Jornal Nexo page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Jornal Nexo Page
"""
news = []
headers = soup.find('ul', class_='Recent__list___G501w').find_all('h4')
for header in headers:
... | 330edd2b4c361e092a13eceb3ffac21689e889ea | 611,616 |
def add_to_divide(number, divisor):
""" this function returns the int needed to be added to number to make it divisable by divisor"""
tmp = number%divisor
if tmp == 0:
return 0
return divisor - tmp | 9fed6637defcd02cca6ec57dd244f92675031271 | 611,617 |
def prune(word):
""" Removes all non-letter symbols from the start and the end of a `word` and lowercase it."""
punctiation_signs = '!?.,#''"`%()_*@\n'
pruned = ''
for char in word:
if not char in punctiation_signs:
pruned = pruned + char
return pruned.lower() | 5de925ecbdb338aff61843e694a84998d7feec46 | 611,620 |
def get_strides_and_extra(numpoints, col):
"""
stride data to get less numpoints.
Calculate the strides and get the points left at the end as extra
:param col: column to calculate with
:param numpoints: number of wanted points
"""
lx = col.size
if lx <= numpoints:
return None, N... | 03f4c7f03a9285e59aa46ca999a3860ec3b1be0d | 611,621 |
def validate_verb(verb_str):
"""
Determines whether or not the supplied verb is a valid HTTP verb.
"""
valid_verbs = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE']
if verb_str in valid_verbs:
return True
return False | e86280aafb6c6298c4a9ae8509eb1186f23bcb67 | 611,628 |
def _outFile_from_url(url, save_dir):
"""
Define the filename for a grib2 file from its URL.
Parameters
----------
url : str
A URL string for a grib2 file we want to download.
save_dir : dir
The directory path to save the file.
"""
if 'pando' in url:
outFile = '_... | b18f990c774f0cf038892c67bfd24904543e51bc | 611,629 |
def length_hint(obj, default=0):
"""
Return an estimate of the number of items in obj.
This is useful for presizing containers when building from an iterable.
If the object supports len(), the result will be exact. Otherwise, it may
over- or under-estimate by an arbitrary amount. The result will be... | a16fc0c1993d5675c663702e0f68b8973af64ce3 | 611,630 |
def _log_probability_picklable(theta, instance, name):
"""
Method for multiprocessing to work with class instance methods (making it
pickleable).
"""
return getattr(instance, name)(theta) | a651e2a76eaca032e837624a604ed4f536de4702 | 611,632 |
def get_course_display_string(descriptor):
"""
Returns a string to display for a course or course overview.
Arguments:
descriptor (CourseBlock|CourseOverview): a course or course overview.
"""
return ' '.join([
descriptor.display_org_with_default,
descriptor.display_number_w... | 5f8a6e24f510a37113083c4729e7c1fd279ab76f | 611,637 |
def create_firewall(context):
"""Creates a VPC firewall config.
The VPC firewall config depends on the VPC network having been completely
instantiated, so it includes a dependsOn reference to the list of resources
generated by the network sub-template.
Args:
context: the DM context object.
Returns:... | b4d55379437c9de0dfbf3c3dd0c65c1b3aabedfb | 611,638 |
import re
def __extract_personal_access_token_from_repo_url(repo_url: str) -> str:
"""
:param repo_url: a string of the format: ``https://<personal_access_token>@github.com/<owner>/<repo name>.git``
:return: the value of ``<personal_access_token>``
"""
return re.findall(r'https:\/\/(.*)@', repo_ur... | 26b2c8df2dec3824a439100bc2e91000a7c7f91e | 611,639 |
import re
def fill_CMake_lists(cmake_contents, example_name, extra_names, vtk_modules, web_repo_url):
"""
Fill in the template parameters in a CMakeLists template file.
The output is a CMakeLists.txt file with Name substituted for {{{1}}}
:param cmake_contents: The template file.
:param example_na... | c4ddd0d84687bed6bf898155dd2f5e6f1b2faf27 | 611,640 |
def single_choice(title, labels, callbacks=None, exitable=False):
"""
Display a choice to the user. The corresponding callback will be called in case of
affermative or negative answers.
:param title: text to display (e.g.: 'What is your favorite color?' )
:param labels: list of possibile choices to ... | 9b77ba8dd8df528a3c68a2c6fbe963d8c11e8366 | 611,641 |
def average_batch_errors(errors, n_samples, batch_size):
"""
Computes average error per sample.
Parameters
----------
errors : list
List of errors where each element is a average error
per batch.
n_samples : int
Number of samples in the dataset.
batch_size : int
... | dfd6c05afcc99f2b945401989d4f3a4517e53ad0 | 611,642 |
import struct
def read_4(stream):
""" read 4 byte (long) from stream """
return struct.unpack('<L', stream.read(4))[0] | a663f14a3e71c4aed2aa94be5404d836d12035d4 | 611,643 |
import builtins
def _assign_global(packname, varname, value):
"""Assigns a value to a package global variable and returns the value"""
namespace = getattr(builtins, packname)
setattr(namespace, varname, value)
return value | 22bfc2ffd939416c3bb3ce43f668170c736bf891 | 611,646 |
def get_tile_index(rank: int, total_ranks: int) -> int:
"""
Returns the zero-indexed tile number, given a rank and total number of ranks.
"""
if total_ranks % 6 != 0:
raise ValueError(f"total_ranks {total_ranks} is not evenly divisible by 6")
ranks_per_tile = total_ranks // 6
return rank... | 9df137454eb6873c052bd0da5acb52b5b240721b | 611,649 |
import multiprocessing
def valid_n_jobs(n_jobs):
"""
Validates and assigns correct number of cpu cores.
Parameters
----------
n_jobs : int
Number of desired cpu cores.
Returns
-------
Valid number of cpu cores.
"""
max_cpus = multiprocessing.cpu_count()
if n_j... | a4998934add0b215961c84fa361eefe91565da61 | 611,650 |
import math
def _is_integer(float_value):
"""True if 'float_value' is an integer (such as 5.0)."""
return math.ceil(float_value) == float_value | c3e918f3004de9809c009b9ec90056b50fdb62cb | 611,656 |
def assemble_elided_status(complete_words, elided_words):
"""
Remixes the complete and elided words of a status text to match
word original order.
Args:
complete_words (list): List of complete words in reverse order from original status text.
elided_words (list): List of elided words in... | 1ed0c3ffd5a39de87bd1c03b6c11ee2fb18f9b82 | 611,657 |
def convert_homopoints_to_points(points_4d):
"""Project 4d homogenous points (4xN) to 3d points (3xN)"""
assert len(points_4d.shape) == 2
assert points_4d.shape[0] == 4
points_3d = points_4d[:3, :] / points_4d[3:4, :]
assert points_3d.shape[1] == points_3d.shape[1]
assert points_3d.shape[0] == 3
return po... | cb2aade097c4c5bcc75af90e25484a020773e5ae | 611,659 |
def _SitecustomizeRemovalEntry(is_prebuilt_image):
"""Returns a Dockerfile entry that removes `sitecustomize` if it's Vertex AI Training pre-built container images."""
return "RUN rm -rf /var/sitecustomize" if is_prebuilt_image else "" | 31203fc54634d3d5f4412903f146e9d79e60f839 | 611,661 |
def scale_columns(prefix,first,last):
"""
Create a list of scale parameter column names with name prefixX with X
from first to last (inclusive)
"""
return [prefix+str(i) for i in range(first,last+1)] | b99411ff2c66147b0608c0870671ea6af68a25e8 | 611,668 |
import copy
def merge_dicts(a, b):
"""Recursively merge two dictionaries.
The input dictionaries are not modified. A deepcopy of ``a`` is
created and then ``b`` is merged into it.
Example:
Here is an example usage of this function:
>>> from cloudmarker import util
>>> a = {'... | 54bae2acf85befe85c5c2f0d7153a28543574e18 | 611,671 |
def swap_32b(val):
""" Swap 32b val
:param val: 32b value
:return: swapped 32b """
tmp = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF)
tmp = (tmp << 16) | (tmp >> 16)
return tmp & 0xFFFFFFFF | c5bbabf981a49675017f41f0bdc9055285b34da8 | 611,672 |
def find_if(predicate, seq):
"""If there is an element of seq that satisfies predicate; return it.
>>> find_if(callable, [3, min, max])
<built-in function min>
>>> find_if(callable, [1, 2, 3])
"""
for x in seq:
if predicate(x): return x
return None | d3b5b38eb5af9318d797542ebc631265673a985b | 611,676 |
def count_padding_bases(seq1, seq2):
"""Count the number of bases padded to
report indels in .vcf
Args:
seq1, seq2 (str): alleles in .vcf
Returns:
n (int):
Examples:
REF ALT
GCG GCGCG
By 'left-alignment', REF and ATL are alignmed:
... | 5b184ab3552edea6d301ba5a95168971220344a4 | 611,680 |
import glob
def has_glob(pth):
"""
Return True if pth contains glob metacharacters (*, ?, [])
"""
return pth != glob.escape(pth) | dd739739d0b1bde4fd00105e77c259cd085927b7 | 611,681 |
def constraint_0(maze):
"""Checks if maze is empty."""
return(False if len(maze) == 0 else True) | 7915f38322e818dfb96b960e1937042f1a38d5bf | 611,687 |
from pathlib import Path
def get_root_path() -> Path:
"""
Return project root path.
:return: PurePath subclass
"""
return Path(__file__).parent.parent | 9864269e3d6d2d3f813cdbe786dbe049bbd1b96f | 611,691 |
def get_lengths_from_mix(ttspec):
"""
Get set of shift lengths and order them ascending by length
:param ttspec: YAML representation of tour type mix parameters
:return: A sorted list of shift lengths.
Example: [8, 16, 20, 24]
"""
len_set = set([])
for m in ttspec['tourtypes']:
... | cdd950d0d43b06b776f8febd2238ca962a271de9 | 611,697 |
def wrappable_range_overlaps(start, end, test,
wrap_after=59, wrap_to=0,
overlap=False
):
"""Figure out whether a range of numbers (specified by 'start' and
'end') has any overlap with the set of numbers in the set 'test'.
... | 0a2e826780fa60ced9eb5e2ce44cb559d46dad9f | 611,698 |
def get_names(raw_objs):
"""
[{'name': 'Action', 'id': 28}, {'name': 'Adventure', 'id': 12}]
"""
return [obj['name'] for obj in raw_objs] | 82883e1a1f81115d20023f91f33f829b198cd638 | 611,701 |
def get_output_type(operation):
"""
Find the name of the output type of the specified operation. This method first explores
the responseMessages defined for the operation. If a successful responseMessage (i.e.
response code in 200's range), has been declared with a responseModel, that will be
considered outpu... | 755f7717d36867b4e16cce75bb0d5e2db5343c7b | 611,707 |
from typing import List
def split_list_into_chunks(xs: List, chunks_size: int) -> List:
"""
Creates a new list with sub lists (chunks) from the original xs list.
"""
list_with_chunks = [xs[i : i + chunks_size] for i in range(0, len(xs), chunks_size)]
return list_with_chunks | 94fbbabcefeb596502b75dc3aed8f205710e069d | 611,711 |
def hex2dec(string):
"""Convert a hexadecimal string to decimal number"""
return int(string,16) | ca919f0bb714420fc125abc034e7a98d58b325e4 | 611,713 |
def _null_slice(s: slice):
"""Return true if a slice does nothing e.g. list[:]"""
return s.start is s.step is s.stop is None | 7e21151d2a35145bf90ae31b13da53713b4669df | 611,714 |
def get_programme_ids(il_inputs_df, level):
"""
Returns a Serise of Agg ids by level for the FM programme file generation
:param il_inputs_df: IL input items dataframe
:type il_inputs_df: pandas.DataFrame
:param level: fm_programme level number
:type level: int
"""
return il_inputs_df... | 0dee3ea6b184194fb2abe291b43d37b8a853e22a | 611,719 |
def convert_tags(tags):
"""
Convert tags from AWS format [{'Key': '...', 'Value': '...'}, ...] to {'Key': 'Value', ...} format
:param tags: tags in native AWS format
:return: dict with tags ready to store in DynamoDB
"""
# dynamodb does not like empty strings
# but Value can be empty, so c... | 2b9f99302bc832baf87ef228ac3d09b3d148cd22 | 611,720 |
def _make_validation_key(game_id: str) -> str:
"""Make the redis key for game validation."""
return 'ttt:{}:valid'.format(game_id) | 4d1c8e37877ba516a99bd4d20513c4d56a01c219 | 611,723 |
def integral_image(x):
"""Integral image / summed area table.
The integral image contains the sum of all elements above and to the
left of it, i.e.:
.. math::
S[m, n] = \sum_{i \leq m} \sum_{j \leq n} X[i, j]
Parameters
----------
x : ndarray
Input image.
Returns
... | fd69d16e2a86a3d7523d75d8fdb5e3c1692245d9 | 611,724 |
def _IsOneSubstringOfAnother(s1, s2):
"""Checks if one of the string arguements is substring of the other.
Args:
s1: The first string.
s2: The second string.
Returns:
True if one of the string arguements is substring of the other.
False otherwise.
"""
return s1 in s2 or s2 in s1 | 7de93f281b49dfe9fb98ee8f63357a29a32e780e | 611,729 |
def padblanc8(sval):
"""Make string 8 characters long by padding with blanks
Args:
sval (str): String
Returns:
String of 8 characters, padded with blanks
"""
lens = len(sval)
blank = ' '
if lens >= 8:
return sval[0:8]
else:
lb = 8 - lens
ret... | 15290c492c7b74c897baa9fce78e3a9f565c84b5 | 611,730 |
def read_magic(fobj):
"""Read magic bytes.
Parameters
----------
fobj : file-like object
The file to read from.
Returns
-------
bytes
magic byte sequence read
"""
return fobj.read(4) | ae471af250bb29ac38f66e76aca5321b0ec493ba | 611,732 |
def guessFont(fname):
"""Given a font name like "Tahoma-BoldOblique", "Bitstream Charter Italic"
or "Perpetua Bold Italic" guess what it means.
Returns (family, x) where x is
0: regular
1: bold
2: italic
3: bolditalic
"""
italic = 0
bold = 0
if "-" not in fn... | 7f58f2cc4b04da2d2c3a564a42440a3ab3a75f1e | 611,735 |
def dn_to_micro_jy(dn, zp, err=None):
"""Convert pixel values (DN) to µJy.
Parameters
----------
dn : array
Pixel values.
zp : array or scalar
Zeropoint (or zeropoints) corresponding to the DN measurements
to bring them into the AB system, where
.. math::
... | 1ed20a7628baa85e6338907326d980c2e2f72aca | 611,747 |
def prompt(message):
"""Creates a simple y/n prompt with custom message. Returns boolean value."""
choice = input(message).split(" ")[0]
if choice != "y":
return False
return True | 6852bb37649919567a51fe45217efb333bb60b5e | 611,749 |
def stations_by_river(stations):
"""Builds and reuturns a dictionary which maps river names (key) to a list of station objects on a given river.
Stations is a list of MonitoringStation objects. """
stations_by_river_dictionary = {}
for station in stations:
if station.river != None:
sta... | 32489f74003c073f90fa3dad9e032ac3e9f524e0 | 611,750 |
import random
def get_random_crop_params(orig_size, target_size):
"""Gets bounding box parameters for a random crop
Parameters
----------
orig_size : int or tuple
Size of image in the form of (width, height)
target_size : int or tuple
Size of random crop in the form of (width, height)
Returns
... | ae3efac3bad76fa84e01c9603ed466f753ee59f5 | 611,751 |
def count_episodes_by_director(episodes):
"""Constructs and returns a dictionary of key-value pairs that associate each director with a
count of the episodes that they directed. The director's name comprises the key and the
associated value a count of the number of episodes they directed. Duplicate keys are... | a9f0c8976d207d499debbe3bb25458efe4dbacf4 | 611,753 |
def bottom_k(seq, k, kmer_len, stride_len=1):
"""
Return bottom-k minhash sketch fingerprint of sequence.
Parameters
----------
seq : string sequence to perform bottom-k sketch on
k : number of hash value representatives in bottom-k sketch
kmer_len : int the length of the k-mers of the sequence
... | 6811c2ca61eb27ca2fc680aa798e339e63fd38e8 | 611,757 |
import unicodedata
def _unicode_ci_compare(s1, s2):
"""
Perform case-insensitive comparison of two identifiers, using the
recommended algorithm from Unicode Technical Report 36, section
2.11.2(B)(2).
"""
return unicodedata.normalize('NFKC', s1).casefold() == unicodedata.normalize('NFKC', s2).c... | 087b5799d0c1b6d827a15794a665fd8e92650e86 | 611,759 |
import pkg_resources
def _get_entry_points(keyword, strip=[], package_prefix="bob.bio."):
"""Returns the list of entry points for registered resources with the given keyword."""
return [
entry_point
for entry_point in pkg_resources.iter_entry_points(package_prefix + keyword)
if not ent... | f8267689a874ce89e5afcc4faed2742d5c0210af | 611,760 |
def calc_frame_length(dur_frame_millisec, sr):
"""Calculates the number of samples necessary for each frame
Parameters
----------
dur_frame_millisec : int or float
time in milliseconds each frame should be
sr : int
sampling rate of the samples to be framed
Returns
---... | 5b75cdc4312b44eac5158e41c06cc0da1b0952d9 | 611,764 |
def to_uint256(value: int) -> bytes:
"""Encodes an unsigned integer as a big endian uint256."""
return value.to_bytes(32, "big") | 236f5f16d13258ed1ad9bf194b2cebbc14666305 | 611,765 |
import logging
def terminal_logger(name="MilanBot", level=logging.INFO):
"""
RetA wrapper for retrieving basic logging function
:param name:
:param level:
:return:
"""
logging.basicConfig(level=level)
return logging.getLogger(name=name) | 33802fc6afdeed4ccb3c78802f072227f5ee0966 | 611,766 |
def toTimeStr(seconds):
"""
Convert the given number of seconds into a nice string
"""
secs = int(seconds % 60)
mins = int(seconds / 60)
retVal = ''
if mins == 1:
retVal = '1 minute, '
elif mins > 1:
retVal = '%d minutes, ' % mins
# If mins == 0, don't bother adding ... | 8c9f85bca1f02bfa9764a4c0adc56cb52ee06ac8 | 611,767 |
import math
def safepow(a, b):
"""Raise a to b-th power, but return NaN on float domain error"""
try:
return math.pow(a, b)
except (ValueError, OverflowError):
return float('nan') | 1715b832117e72d3cb63c8674d36ccef011297bd | 611,768 |
def translate_parameters(args):
"""
Translate the names of the parameters between command line and source code.
"""
args.gpu = not args.use_cpu
args.num_workers = args.nproc
args.optimizer = "Adam"
args.loss = "default"
if hasattr(args, "predict_atlas_intensities"):
args.atlas =... | 7e9f0a2f0d6bbc8cae32b1c0319016bb6a5c7745 | 611,771 |
def solve_by_dichotomy(f, objective, a, b, tolerance):
"""
Apply the dichotomy method to solve the equation f(x)=objective, x being the unknown variable.
a and b are initial x values satisfying the following inequation: (f(a) - objective) * (f(b) - objective) < 0.
The iterative method stops once f(x) is... | 07fdeeb2ab111bfe37450b150931b27ea38706eb | 611,774 |
def mk_quote_string_for_target(value):
"""
mk_quote_string_for_target(target_name) -> str
Return a quoted form of the given target_name suitable for including in a
Makefile as a target name.
"""
# The only quoting we currently perform is for ':', to support msys users.
return value.replace... | 17e86c66edc52efa5c6943c638471e043cbf1a2f | 611,777 |
def is_blank(s: str) -> bool:
"""Checks if a string is blank or not"""
return not bool(s and not s.isspace()) | 865ec1f7cb8d03e72759fdc701ef061cfe830862 | 611,789 |
from typing import Dict
import string
def assign_coordinates(starting_position: tuple, spacing: int) -> Dict:
""" Assigns coordinates to the points
Args:
starting_position (tuple): Coordinates of point A1
spacing (int): Spacing per step on x columns and y rows
Returns:
... | 9d541003d1cd3597f28949faa758b867d445cf72 | 611,790 |
from typing import Tuple
from typing import Dict
import io
import tarfile
def get_items_from_tar(binary: bytes) -> Tuple[str, Dict[str, bytes]]:
"""
Return dictionary of tar file contents.
Parameters
----------
binary : bytes
byte array of zip file
Returns
-------
Tuple[str, ... | 76ae36e6411c480ef7e01c8978a3badb5064c870 | 611,792 |
def load_labels(label_file):
""" load list of labels from file (one per line) """
labels = []
with open(label_file, 'r') as handle:
labels = [line.strip() for line in handle]
return labels | 8eb0110f6172bfc6179b2650f596833f8fc162bf | 611,795 |
import torch
def get_rand_coord(start, end, steps):
"""Returns random coordinates.
Parameters
----------
start : torch.Tensor
lower boundaries
end : torch.Tensor
upper boundaries
steps : torch.Tensor
number of steps for coordinate cumputation
Returns
-------
... | b3c40872d4cfd41d160f2dd31c94bd0b982aed0a | 611,797 |
def is_SQLiteDB(db_file:str)->bool:
"""
Function to check if a file is a valid SQLite database
Inputs:
- file (str) : full path of the file/DB in question
Ouputs:
- is_SQLiteDB (bool) : file is a SQLite DB or not
"""
with open(db_file, "rb") as file:
header = file.read(10... | 985c5c1d6ef8f2a27747596c1b809ac6cf7e3549 | 611,798 |
def ql_2dplot(ax,xvals,yvals,plottitle,xtitle,ytitle,xlim=None,ylim=None):
"""
Make 2d plot of specific metrics provided in configuration file
Args:
ax: matplotlib subplot
xvals: QA metric to be plotted along the xaxis
yvals: QA metric to be plotted along the yaxis
plottitle... | 8cc704cffd76e5512bd88a3d4e44961f5496544a | 611,799 |
from typing import Tuple
def int_(buffer: bytes, offset: int = 0) -> Tuple[int, int]:
"""
Unpack signed int from Starbound save file.
:param buffer: Starbound save file
:param offset: position in Starbound save file
:return: int, new offset
"""
value = 0
while True:
tmp = buff... | 59fb90201c66ccdaed9709a0a1e70fea845e31a6 | 611,800 |
def stop_follower_callback(request, response):
"""
Stop the robot
"""
global should_move
global finalization_countdown
should_move = False
finalization_countdown = None
return response | 4d911325bf2d19cd0bf0b1eff34e8156054c68ce | 611,802 |
def check_rgb_match(sample_rgb, target_rgb, precision):
"""Check if a triplet of some sample RGB values can be considered to be the same as a triplet of some target RGB values."""
return abs(sum(sample_rgb) - sum(target_rgb)) <= precision | acd979b6f977d236900f4dd0f5e7b335dd54034a | 611,804 |
import socket
import errno
def mock_server_receive(sock, length):
"""Receive `length` bytes from a socket object."""
msg = b''
while length:
chunk = sock.recv(length)
if chunk == b'':
raise socket.error(errno.ECONNRESET, 'closed')
length -= len(chunk)
msg += ch... | 1f9071e453ac617754b8b09cc36293a6d9e51dcb | 611,807 |
from pkg_resources import parse_version
def package_version_ok(pkg, min_version=None):
###############################################################################
"""
Checks that the loaded package's version is >= that the minimum required one.
If no minimum version is passed, then return True
"""... | 027a935859cf2486529d5e8e5427fb29eb5b69e4 | 611,812 |
def compare(user_score, computer_score):
"""Compares user score and computer score and check who won the Blackjack"""
# If you and the computer are both over, you lose.
if user_score > 21 and computer_score > 21:
return "You went over. You lose 😤"
if user_score == computer_score:
return "Draw 🙃"
... | 00311083f0435efe39623831bd577662008e5fba | 611,819 |
def pair_arrays(t_arrs):
"""Returns a generator that pairs consecutive arrays in the tuple
't_arrs.'"""
t_new = (t_arrs[0], *t_arrs)
rg = range(len(t_new)-1)
gen = ((t_new[i], t_new[i+1]) for i in rg)
return gen | 8c9eb5cb262e5d39a4cf8ca8eb2217444c52c1f9 | 611,821 |
def critical_mach(fineness_ratio_nose: float) -> float:
"""
Returns the transonic critical Mach number for a streamlined fuselage.
Fitted to data from Raymer "Aircraft Design: A Conceptual Approach" 2nd Ed., Fig. 12.28.
See figure + study + fit in: /studies/FuselageCriticalMach/
Args:
fin... | 72d1136ab9452f093bb09a34179e694c1655e873 | 611,827 |
def displayRange(layer):
"""Returns a string representation of a layer's frame range."""
if layer.data.chunk_size != 1:
return '%s chunked %s' % (layer.data.range, layer.data.chunk_size)
return layer.data.range | 8428c7bd95f5e5b6eda24954e45b08495a6b2229 | 611,832 |
def get_participant_name(line):
"""
Purpose: Retrieves a participant's name from the line.
Example: "Eric Simon 3 5 10" returns "Eric Simon"
"""
all_words_and_nums = line.split()
participant_name = ""
for i in range(len(all_words_and_nums)):
if all_words_and_nums[i].isdigit():
... | 2ed78817fd5dde756d637bc45b9cb1c195aac63d | 611,834 |
import math
def get_num_shards(num_samples: int, samples_per_shard: int, min_num_shards: int) -> int:
"""
Returns the number of shards.
:param num_samples: Number of training data samples.
:param samples_per_shard: Samples per shard.
:param min_num_shards: Minimum number of shards.
:return: N... | 5408b1ce98c6a0e21e14ea35d0d35cb146b7a2cf | 611,836 |
def handler(value, context, provider): # pylint: disable=unused-argument
"""Mock handler."""
return "mock" | 2e46dbc468e65b683f8911cc26c6c478db3ffc2a | 611,842 |
def is_date(cells, valid_formats):
"""
Does the Excel number format contain a date convertion?
:param cells: A single cell with a value which could be a date
:param valid_formats: Sequence of valid Excel date format strings
e.g. = ('dd/mm/yyyy',)
:return: bool
"""
try:
... | d8bbb4d68ff2e47337aa3041232f7a38372ba97f | 611,843 |
def GCreadlines(fobject, comment='#'):
"""Strip files from comments.
fobject: file object to be read
comment: string indicating comment.
"""
lines = []
for l in fobject.readlines():
# ignore comments and empty lines
l = l.strip()
pos = l.find(comment)
if pos>-1:... | 0947a79273bc4731e86c5711a1c792d91c7531ea | 611,844 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.