content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def smoP(dataMatIn, classLabels, C, toler, maxIter, kTup = ('lin',0)):
"""
完整的线性SMO算法
Parameters:
dataMatIn - 数据矩阵
classLabels - 数据标签
C - 松弛变量
toler - 容错率
maxIter - 最大迭代次数
kTup - 包含核函数信息的元组
Returns:
oS.b - SMO算法计算的b
oS.alphas - SMO算法计算的alphas
"""
oS = optStruct(np.mat(dataMatIn), np.... | 9,900 |
def _get_output_data(output_list, heat, stack_id):
"""
获取output数据
"""
response = {
'code': 200,
'msg': 'ok',
'status': utils.INSTANTIATED,
'data': []
}
for item in output_list['outputs']:
output = heat.stacks.output_show(stack_id, item['output_key'])
... | 9,901 |
def _ensure_str(s):
"""convert bytestrings and numpy strings to python strings"""
return s.decode() if isinstance(s, bytes) else str(s) | 9,902 |
def get_polarimeter_index(pol_name):
"""Return the progressive number of the polarimeter within the board (0…7)
Args:
pol_name (str): Name of the polarimeter, like ``R0`` or ``W3``.
Returns:
An integer from 0 to 7.
"""
if pol_name[0] == "W":
return 7
else:
retu... | 9,903 |
def merge_sort(collection):
"""
Pure implementation of the fastest ordered collection with heterogeneous
: parameter collection : some mutable ordered collection with heterogeneous
comparable items inside
: return : a sollectiojn order by ascending
Examples :
>>> me... | 9,904 |
def sma_centroids(dataframe, column, short_window, long_window, min_width=None, **kwargs):
"""Identify centermost point between two SMA interception points
Define regions as being bounded by two consecutive interceptions of SMAs
with different window widths, then choose the centermost data point within
... | 9,905 |
def delMsg(msgNum):
"""Deletes a specified message from the inbox"""
global usrPrompt
try:
inboxMessages = json.loads(api.getAllInboxMessages())
# gets the message ID via the message index number
msgId = inboxMessages['inboxMessages'][int(msgNum)]['msgid']
msgAck = api.tras... | 9,906 |
def convert_similarities( in_file_path, out_json_file_path):
"""
Iterate over every row in a TSV file and import each as a compound document.
We don't yet create edges for compounds.
"""
with open( in_file_path, newline='') as csv_fd:
reader = csv.reader(csv_fd, delimiter=' ', quotechar='"')... | 9,907 |
def stage_static_files(sample_type, working_dir, debug=False):
"""Stage static files in the current working directory"""
stage_static_latex(sample_type, working_dir)
stage_static_pdfs(sample_type, working_dir) | 9,908 |
def capitalize_first(str):
"""Capitalizes only the first letter of the given string.
:param str: string to capitalize
:return: str with only the first letter capitalized
"""
if str == "":
return ""
return str[0].upper() + str[1:] | 9,909 |
async def test_get_entity(opp, client):
"""Test get entry."""
mock_registry(
opp,
{
"test_domain.name": RegistryEntry(
entity_id="test_domain.name",
unique_id="1234",
platform="test_platform",
name="Hello World",
... | 9,910 |
def min_cost_edge(G, T):
"""Returns the edge with the lowest cost/weight.
Parameters
----------
G : NetworkX graph
T : Prim's Algorithm
Returns
-------
The edge with the lowest cost/weight.
"""
edge_list = possible_edges(G, T)
edge_list.sort(key = lambda e : cost(G... | 9,911 |
def get_image_html_tag(fig, format="svg"):
"""
Returns an HTML tag with embedded image data in the given format.
:param fig: a matplotlib figure instance
:param format: output image format (passed to fig.savefig)
"""
stream = io.BytesIO()
# bbox_inches: expand the canvas to include the lege... | 9,912 |
def reformat_language_tuple(langval):
"""Produce standardly-formatted language specification string using given language tuple.
:param langval: `tuple` in form ('<language>', '<language variant>'). Example: ('en', 'US')
:return: `string` formatted in form '<language>-<language-variant>'
"""
if lang... | 9,913 |
def _create_ghostnet(variant, width=1.0, pretrained=False, **kwargs):
"""
Constructs a GhostNet model
"""
cfgs = [
# k, t, c, SE, s
# stage1
[[3, 16, 16, 0, 1]],
# stage2
[[3, 48, 24, 0, 2]],
[[3, 72, 24, 0, 1]],
# stage3
[[5, 72, 40, 0.25,... | 9,914 |
def re_suffix(string):
""" Remove any “os.extsep” prefixing a string, and ensure that
it ends with a “$” – to indicate a regular expression suffix.
"""
if not string:
return None
return rf"{string.casefold().lstrip(QUALIFIER).rstrip(DOLLA)}{DOLLA}" | 9,915 |
def _alternate_dataclass_repr(object) -> None:
"""
Overrides the default dataclass repr by not printing fields that are
set to None. i.e. Only prints fields which have values.
This is for ease of reading.
"""
populated_fields = {
field.name: getattr(object, f"{field.name}")
for f... | 9,916 |
def which_coords_in_bounds(coords, map_shape):
"""
Checks the coordinates given to see if they are in bounds
:param coords Union[array(2)[int], array(N,2)[int]]: [int, int] or [[int, int], ...], Nx2 ndarray
:param map_shape Tuple[int]: shape of the map to check bounds
:return Union[bool array(N)[boo... | 9,917 |
def get_activation_function(activation_function_name: str):
"""
Given the name of an activation function, retrieve the corresponding function and its derivative
:param cost_function_name: the name of the cost function
:return: the corresponding activation function and its derivative
"""
try:
... | 9,918 |
def url_split(url, uses_hostname=True, split_filename=False):
"""Split the URL into its components.
uses_hostname defines whether the protocol uses a hostname or just a path (for
"file://relative/directory"-style URLs) or not. split_filename defines whether the
filename will be split off ... | 9,919 |
def memdiff_search(bytes1, bytes2):
"""
Use binary searching to find the offset of the first difference
between two strings.
:param bytes1: The original sequence of bytes
:param bytes2: A sequence of bytes to compare with bytes1
:type bytes1: str
:type bytes2: str
:rtype: int offset of... | 9,920 |
def decomposeJonesMatrix(Jmat):
""" Decompose 2x2 Jones matrix to retardance and diattenuation vectors """
Jmat = Jmat / cp.sqrt(cp.linalg.det(Jmat))
q = cp.array([Jmat[0, 0] - Jmat[1, 1], Jmat[1, 0] + Jmat[0, 1], -1j * Jmat[1, 0] + 1j * Jmat[0, 1]]) / 2
tr = cp.trace(Jmat) / 2
c = cp.arccosh(tr)
... | 9,921 |
def format_utc(time):
"""Format a time in UTC."""
return as_utc(time).strftime('%Y-%m-%d %H:%M:%S.%f') | 9,922 |
def install_and_build_package( app, tool_dependency, actions_dict ):
"""Install a Galaxy tool dependency package either via a url or a mercurial or git clone command."""
sa_session = app.model.context.current
install_dir = actions_dict[ 'install_dir' ]
package_name = actions_dict[ 'package_name' ]
a... | 9,923 |
def plugin_scope():
"""Returns the capability as the remote network driver.
This function returns the capability of the remote network driver, which is
``global`` or ``local`` and defaults to ``local``. With ``global``
capability, the network information is shared among multipe Docker daemons
if th... | 9,924 |
def _create_chimeric_msa( # pylint: disable=too-many-arguments
output_folder,
cluster,
subexon_df,
gene2speciesname,
connected_subexons,
aligner='ProGraphMSA',
padding='XXXXXXXXXX',
species_list=None):
"""Return a modified subexon_df, the dict of chim... | 9,925 |
def _expand_sources(sources):
"""
Expands a user-provided specification of source files into a list of paths.
"""
if sources is None:
return []
if isinstance(sources, str):
sources = [x.strip() for x in sources.split(",")]
elif isinstance(sources, (float, int)):
sources =... | 9,926 |
def get_stream(stream_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStreamResult:
"""
This data source provides details about a specific Stream resource in Oracle Cloud Infrastructure Streaming service.
Gets detailed information about a stream, includi... | 9,927 |
def get_job(JobName=None):
"""
Retrieves an existing job definition.
See also: AWS API Documentation
Exceptions
:example: response = client.get_job(
JobName='string'
)
:type JobName: string
:param JobName: [REQUIRED]\nThe name of the job definition to retrieve... | 9,928 |
def test_thematic_breaks_018():
"""
Test case 018: (part a) Four spaces is too many:
"""
# Arrange
source_markdown = """ ***"""
expected_tokens = [
"[icode-block(1,5): :]",
"[text(1,5):***:]",
"[end-icode-block:::True]",
]
expected_gfm = """<pre><code>***
... | 9,929 |
def components(path):
"""Split a POSIX path into components."""
head, tail = os.path.split(os.path.normpath(path))
if head == "":
return [tail]
elif head == "/":
return [head + tail]
else:
return components(head) + [tail] | 9,930 |
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
"""
Fusion method.
"""
n_channels_int = n_channels
in_act = input_a + input_b
t_act = ops.Tanh()(in_act[:, :n_channels_int, :])
s_act = ops.Sigmoid()(in_act[:, n_channels_int:, :])
acts = t_act * s_act
return acts | 9,931 |
def test_copy_report_to_s3() -> None:
"""
Tests the copying of the report
to an s3 bucket
"""
file_name = "test_file"
s3_bucket_name = "test_bucket"
account_name = "12345666757"
response = True
s3_client = Mock(upload_file=Mock(return_value=response))
actual_response = copy_repo... | 9,932 |
def _classes_dict(filename):
"""
Open JSON file and read the data for the Classes (and Origins).
filename - the file name as a string.
Runtime: O(n)
"""
class_dict = {} # {'robot': ['blitzcrank']}
class_bonus_dict = {}
dict = { 1: {}, 2: {}, 3: {}, 4 : {}, 6 : {}} # { 1 : { 'robot' : set... | 9,933 |
def main() -> None:
"""Entry point of this test project.
"""
_: ap.Stage = ap.Stage(background_color='#333')
interface: Points2DInterface = Points2DInterface()
interface.variable_name = 'test_point_2d_interface'
interface.points = ap.Array([ap.Point2D(10, 20), ap.Point2D(30, 40)])
... | 9,934 |
def test_get_bitinformation_dim():
"""Test xb.get_bitinformation is sensitive to dim."""
ds = xr.tutorial.load_dataset("rasm")
bitinfo0 = xb.get_bitinformation(ds, axis=0)
bitinfo2 = xb.get_bitinformation(ds, axis=2)
assert_different(bitinfo0, bitinfo2) | 9,935 |
def set_incident_seen(incident, user=None):
"""
Updates the incident to be seen
"""
is_org_member = incident.organization.has_access(user)
if is_org_member:
is_project_member = False
for incident_project in IncidentProject.objects.filter(incident=incident).select_related(
... | 9,936 |
def single_parity_check(
llr: np.array,
mask_steps: int = 0,
last_chunk_type: int = 0,
) -> np.array:
"""Compute beta value for Single parity node."""
all_sign = np.sign(np.prod(llr))
abs_alpha = np.fabs(llr)
first_min_idx, second_min_idx = np.argsort(abs_alpha)[:2]
result =... | 9,937 |
def show_section(res, section, caveat_outcome=None):
"""
Shows a given named section from a description of an ingestion submission.
The caveat is used when there has been an error and should be a phrase that describes the fact that output
shown is only up to the point of the caveat situation. Instead o... | 9,938 |
def send_uart(ctx, index, binary, data):
"""Send data to UART.
UART1 is the AT Command interface, so you probably want to use
UART3!
"""
if binary:
try:
data = bytes.fromhex(data)
except ValueError:
click.echo('Invalid binary data')
return
lor... | 9,939 |
def _deserialize_job_result(user_input: JSON) -> JobResult:
"""Deserialize a JobResult from JSON."""
job = _deserialize_job(user_input['job'])
plan = _deserialize_plan(user_input['plan'])
is_done = user_input['is_done']
outputs = dict() # type: Dict[str, Asset]
for name, asset in user_input['... | 9,940 |
def _brute_force_knn(X, centers, k, return_distance=True):
"""
:param X: array of shape=(n_samples, n_features)
:param centers: array of shape=(n_centers, n_features)
:param k: int, only looking for the nearest k points to each center.
:param return_distance: bool, if True the return the distance al... | 9,941 |
def proceed():
"""Proceed without waiting for any action to be triggered on the consumer."""
yield _proceed | 9,942 |
def remove_rule(rule_id):
"""Remove a single rule"""
ruleset = packetfilter.get_ruleset()
ruleset.remove(rule_id)
packetfilter.load_ruleset(ruleset)
save_pfconf(packetfilter)
return redirect(url_for('rules', message=PFWEB_ALERT_SUCCESS_DEL), code=302) | 9,943 |
def setup_argparse(parser: argparse.ArgumentParser) -> None:
"""Setup argument parser for ``cubi-tk sea-snap pull-isa``."""
parser.add_argument("--hidden-cmd", dest="sea_snap_cmd", default=run, help=argparse.SUPPRESS)
group_sodar = parser.add_argument_group("SODAR-related")
group_sodar.add_argument(
... | 9,944 |
def HexToMPDecimal(hex_chars):
""" Convert bytes to an MPDecimal string. Example \x00 -> "aa"
This gives us the AppID for a chrome extension.
"""
result = ''
base = ord('a')
for i in xrange(len(hex_chars)):
value = ord(hex_chars[i])
dig1 = value / 16
dig2 = value % 16
result += chr(dig1 ... | 9,945 |
def genome_level_parallelization(bam_file, ref_file, vcf_file, output_dir_path, max_threads, confident_bed_tree):
"""
This method calls chromosome_level_parallelization for each chromosome.
:param bam_file: path to BAM file
:param ref_file: path to reference FASTA file
:param vcf_file: path to VCF f... | 9,946 |
def assert_shape(tensor, ref_shape):
"""Assert that the shape of a tensor matches the given list of integers.
None indicates that the size of a dimension is allowed to vary.
Performs symbolic assertion when used in torch.jit.trace().
"""
if tensor.ndim != len(ref_shape):
raise AssertionErro... | 9,947 |
async def concurrent(streamqueue: asyncio.Queue,
trace_name='concurrent',
name='stream'):
"""Run code concurrently in different streams.
:param streamqueue: asyncio.Queue instance.
Queue tasks define the pool of streams used for concurrent execution.
"""
i... | 9,948 |
def fit_growth_curves(input_file, file_data_frame, file_data_units,
condition_unit, time_unit, cell_density_unit):
"""
:Authors:
Chuankai Cheng <chuankai@usc.edu> and J. Cameron Thrash <thrash@usc.edu>
:License:
MIT
:Version:
1.0
:Date:
2021-03-17
:Repository: https://github.com/t... | 9,949 |
def stringify(li,delimiter):
""" Converts list entries to strings and joins with delimiter."""
string_list = map(str,li)
return delimiter.join(string_list) | 9,950 |
def norm_w(x, w):
"""
Compute sum_i( w[i] * |x[i]| ).
See p. 7.
"""
return (w * abs(x)).sum() | 9,951 |
def WordSyllables(outf, words, segments, IFflag=False, Adaptflag=True):
"""writes out a grammar defining Word* in terms of Syllables. words should be a sequence of Word symbols"""
if IFflag=='Segments':
for word in words:
if Adaptflag:
ruleprefix = word
els... | 9,952 |
def _tensor_run_opt_ext(opt, momentum, learning_rate, gradient, weight, moment):
"""Apply momentum optimizer to the weight parameter using Tensor."""
success = True
success = F.depend(success, opt(weight, moment, learning_rate, gradient, momentum))
return success | 9,953 |
def get_config_settings(env: str = "dev") -> Dict:
"""
Retrieves configuration from YAML file
"""
config_fh = construct_config_path(env)
with open(config_fh, "r") as f:
data = yaml.safe_load(f)
return data | 9,954 |
def get_all(connection: ApiConnection, config: str, section: str = None) -> dict:
"""Get all sections of a config or all values of a section.
:param connection:
:param config:UCI config name
:param section:[optional] UCI section name
:return: JSON RPC response result
"""
return request(conne... | 9,955 |
def load_module(module, app):
"""Load an object from a Python module
In:
- ``module`` -- name of the module
- ``app`` -- name of the object to load
Return:
- (the object, None)
"""
r = __import__(module, fromlist=('',))
if app is not None:
r = getattr(r, app)
re... | 9,956 |
def get_routes(app: web.Application) -> list:
"""
Get the full list of defined routes
"""
return get_standard_routes(app) + get_custom_routes(app) | 9,957 |
def cb_round(series: pd.Series, base: Number = 5, sig_dec: int = 0):
""" Returns the pandas series (or column) with values rounded per the
custom base value
Args:
series (pd.Series): data to be rounded
base (float): base value to which data should be rounded (may be
deci... | 9,958 |
def makeGaussian(size, sigma=3, center=None):
""" Make a square gaussian kernel.
size is the length of a side of the square
fwhm is full-width-half-maximum, which
can be thought of as an effective radius.
"""
x = np.arange(0, size, 1, float)
y = x[:, np.newaxis]
if center is None:
x0 ... | 9,959 |
def cmd_list(txn, path, args):
"""List raw keys/values from database."""
recurse = (8 if args['-R'] else 0)
keys = txn.raw.list_keys(path, recurse=recurse)
if args['--quiet']:
if args['values']:
values = [txn.raw.get(key) for key in keys]
print(" ".join(values))
e... | 9,960 |
def average_relative_error(y_pred, y_true):
"""Calculate Average Relative Error
Args:
y_true (array-like): np.ndarray or torch.Tensor of dimension N x d with actual values
y_pred (array-like): np.ndarray or torch.Tensor of dimension N x d with predicted values
Returns:
float: Avera... | 9,961 |
def do_device_shutdown(cs, args):
"""Shutdown a specific device in the pool."""
device = _find_device(cs, args.mac)
cs.devices.shutdown(device) | 9,962 |
def validate_and_upload(region, conf):
"""Validate and upload CloudFormation templates to S3."""
templates = collect_templates(conf)
error = False
for t in templates:
if not t.validate():
error = True
if error:
exit(1)
for t in templates:
t.upload()
proces... | 9,963 |
def write_package_file(type, output_dir, pkg_name, pkg_ver, additional_args=None):
"""Reads the template file for the given type and writes out the package file (setup.py, package.json, etc)"""
if additional_args is None:
additional_args = []
if type == 'python':
template_file = os.path.joi... | 9,964 |
def main():
"""
Main function. Start translation of relation triplets based on command line arguments.
"""
optparser = init_optparser()
(options, args) = optparser.parse_args()
fetch_relation_triples_of_file(options.input, options.output, options.log, options.lang) | 9,965 |
def make_subprocess_hook_mock(exit_code: int, output: str) -> Mock:
"""Mock a SubprocessHook factory object for use in testing.
This mock allows us to validate that the RenvOperator is executing
subprocess commands as expected without running them for real.
"""
result_mock = Mock()
result_mock.... | 9,966 |
def binstr2int(bin_str: str) -> int:
"""转换二进制形式的字符串为10进制数字, 和int2binstr相反
Args:
bin_str: 二进制字符串, 比如: '0b0011'或'0011'
Returns:
转换后的10进制整数
"""
return int(bin_str, 2) | 9,967 |
def _nodeset_compare(compare, a, b, relational=False):
"""
Applies a comparison function to node-sets a and b
in order to evaluate equality (=, !=) and relational (<, <=, >=, >)
expressions in which both objects to be compared are node-sets.
Returns an XPath boolean indicating the result of the com... | 9,968 |
def test_cl_shift(options):
"""
Create tests for centerline shifts
8 out of 8 points are on one side of the mean
>= 10 out of 11 points are on one side of the mean
>= 12 out of 14 points are on one side of the mean
>= 14 out of 17 points are on one side of the mean
>= 16 out of 20 points ar... | 9,969 |
def _scale(tensor):
"""Scale a tensor based on min and max of each example and channel
Resulting tensor has range (-1, 1).
Parameters
----------
tensor : torch.Tensor or torch.autograd.Variable
Tensor to scale of shape BxCxHxW
Returns
-------
Tuple (scaled_tensor, min, max), where min and max ar... | 9,970 |
def get_moscow_oh(opening_hours):
"""
returns an OpeningHourBlock from a fake json
corresponding to a POI located in moscow city
for different opening_hours formats.
"""
return get_oh_block(opening_hours, lat=55.748, lon=37.588, country_code="RU") | 9,971 |
def get_firebase_credential_errors(credentials: str):
""" Wrapper to get error strings for test_firebase_credential_errors because otherwise the
code is gross. Returns None if no errors occurred. """
try:
test_firebase_credential_errors(credentials)
return None
except Exception as e... | 9,972 |
def url(endpoint, path):
"""append the provided path to the endpoint to build an url"""
return f"{endpoint.rstrip('/')}/{path}" | 9,973 |
def is_collision(line_seg1, line_seg2):
"""
Checks for a collision between line segments p1(x1, y1) -> q1(x2, y2)
and p2(x3, y3) -> q2(x4, y4)
"""
def on_segment(p1, p2, p3):
if (p2[0] <= max(p1[0], p3[0])) & (p2[0] >= min(p1[0], p3[0])) & (p2[1] <= max(p1[1], p3[1])) & (p2[1] >= min(p1[1],... | 9,974 |
def plot_bar_graph_one_time(
example_table_xarray, time_index, predictor_indices, info_string=None,
figure_object=None, axes_object=None):
"""Plots predictors at one time as bar graph.
:param example_table_xarray: xarray table in format returned by
`example_io.read_file`.
:param tim... | 9,975 |
def reshape_nda_to_2d(arr) :
"""Reshape np.array to 2-d
"""
sh = arr.shape
if len(sh)<3 : return arr
arr.shape = (arr.size/sh[-1], sh[-1])
return arr | 9,976 |
def spellchecker():
"""Spellcheck the Markdown and ReST files on the site"""
if platform.system() == "Darwin":
# Mac seems to use ispell as a default, but openbsd and linux
# use aspell. No need to maintain exceptions for multiple
# dictionaries.
raise click.ClickException(
... | 9,977 |
async def async_setup(hass, config):
"""Initialize the DuckDNS component."""
domain = config[DOMAIN][CONF_DOMAIN]
token = config[DOMAIN][CONF_ACCESS_TOKEN]
session = async_get_clientsession(hass)
result = await _update_duckdns(session, domain, token)
if not result:
return False
as... | 9,978 |
def mock_signal(*args):
"""Mock creation of a binary signal array.
:return: binary array
:rtype: np.ndarray
"""
signal = np.array([1, 0, 1])
return signal | 9,979 |
def matmul(a, b):
"""np.matmul defaults to bfloat16, but this helper function doesn't."""
return np.matmul(a, b, precision=jax.lax.Precision.HIGHEST) | 9,980 |
def find_preard(path, metadata_pattern='*.json'):
""" Match pre-ARD metadata with imagery in some location
Parameters
----------
path : str or Path
Path to a metadata file or directory of files (returning matches
inside the directory)
metadata_pattern : str, optional
If ``pa... | 9,981 |
def predictions(logit_1, logit_2, logit_3, logit_4, logit_5):
"""Converts predictions into understandable format.
For example correct prediction for 2 will be > [2,10,10,10,10]
"""
first_digits = np.argmax(logit_1, axis=1)
second_digits = np.argmax(logit_2, axis=1)
third_digits = np.argmax(logit... | 9,982 |
def main(args):
"""Main function"""
tracker = Tracker(args.host, port=args.port, port_end=args.port_end, silent=args.silent)
tracker.proc.join() | 9,983 |
def savecommandline(theargs, thename):
"""
Parameters
----------
theargs
thename
Returns
-------
"""
tide_io.writevec([" ".join(theargs)], thename + "_commandline.txt") | 9,984 |
def plot_temperature_hist(runs):
"""Plot temperature histograms for all the runs"""
num_runs = 0
for run in runs:
if len(run.thermal.data_frame):
num_runs += 1
if num_runs == 0:
return
axis = pre_plot_setup(ncols=num_runs)
if num_runs == 1:
axis = [axis]
... | 9,985 |
def execute_parent(parent_path, child_path, input_tensor_npy, return_full_ctx=False):
"""Execute parent model containing a single StreamingDataflowPartition by
replacing it with the model at child_path and return result."""
parent_model = load_test_checkpoint_or_skip(parent_path)
iname = parent_model.g... | 9,986 |
def find_program(prog, paths):
"""Finds the specified program in env PATH, or tries a set of paths """
loc = spawn.find_executable(prog)
if(loc != None):
return loc
for loc in paths:
p = os.path.join(loc, prog)
if os.path.exists(p):
return p
return None | 9,987 |
def fibonacci(position):
"""
Based on a position returns the number in the Fibonacci sequence
on that position
"""
if position == 0:
return 0
elif position == 1:
return 1
return fibonacci(position-1)+fibonacci(position-2) | 9,988 |
def visualize_gebco(source, band, min=None, max=None):
"""
Specialized function to visualize GEBCO data
:param source: String, Google Earth Engine image id
:param band: String, band of image to visualize
:return: Dictionary
"""
data_params = deepcopy(DATASETS_VIS[source]) # prevent mutation... | 9,989 |
def show():
""" Send values for turning pixels on """
if not available:
return 2
else:
lockBus()
try:
bus.write_byte(arduinoAddress, 0x06)
except:
errorMsg = sys.exc_info()[0]
errorHandler(5, errorMsg)
unlockBus() | 9,990 |
def mini_batch_generator(input_data, batch_size=64, shuffle=True):
"""Generator for training mini-batches
Args:
input_data (ndarray): Input training data.
batch_size (int): Size of the mini batch.
shuffle (bool): If the data is shuffled before mini batch generation.
"""
n_sample... | 9,991 |
def bound_concurrency(size):
"""Decorator to limit concurrency on coroutine calls"""
sem = asyncio.Semaphore(size)
def decorator(func):
"""Actual decorator"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
"""Wrapper"""
async with sem:
... | 9,992 |
def _download_file(url, required_length, STRICT_REQUIRED_LENGTH=True):
"""
<Purpose>
Given the url, hashes and length of the desired file, this function
opens a connection to 'url' and downloads the file while ensuring its
length and hashes match 'required_hashes' and 'required_length'.
tuf.util... | 9,993 |
def tune_speed_librosa(src=None, sr=_sr, rate=1., out_type=np.ndarray):
"""
变语速
:param src:
:param rate:
:return:
"""
wav = anything2wav(src, sr=sr)
spec = librosa.stft(wav)
spec = zoom(spec.T, rate=1 / rate, is_same=0).T
out = librosa.istft(spec)
# out = librosa.griffinlim(s... | 9,994 |
def fqn_from_file(java_filepath: pathlib.Path) -> str:
"""Extract the expected fully qualified class name for the given java file.
Args:
java_filepath: Path to a .java file.
"""
if not java_filepath.suffix == ".java":
raise ValueError("{} not a path to a .java file".format(java_filepath... | 9,995 |
def assert_raises(*args, **kwargs):
"""Assert an exception is raised as a context manager or by passing in a
callable and its arguments.
As a context manager:
>>> with assert_raises(Exception):
... raise Exception
Pass in a callable:
>>> def raise_exception(arg, kwarg=None):
... ... | 9,996 |
def test_tuple_init():
"""Check validation at Tuple init."""
with pytest.raises(ValueError):
Tuple(0)
with pytest.raises(ValueError):
Tuple(str)
with pytest.raises(ValueError):
Tuple({})
with pytest.raises(ValueError):
Tuple([str])
with pytest.raises(ValueErro... | 9,997 |
def print_log_info1(t0tot, t0_gN):
"""
Args:
t0tot:
t0_gN:
"""
logging.info("Central Reads per t0set, in millions:\n")
# We iterate over the set names
for k in t0tot.keys():
try:
logging.info(f"{k}: {t0_gN[k].sum()/e6:.2f}")
except Exception:
... | 9,998 |
def proxy(ctx, control, host, port, socket, proxy):
"""Settings to configure the connection to a Tor node acting as proxy."""
if control == 'port':
if host is None or port is None:
raise click.BadOptionUsage(
option_name='control',
message=f"--control mode '{... | 9,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.