content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def from_settings(settings):
"""Return a dict created from application settings.
Args:
settings (dict): An application's settings.
Returns:
dict: The database-specific settings, formatted to use with
:func:`connection_url`.
"""
return {
k.replace('DATABASE_', '... | 56e03e01a0222f9aa560a9ebf585e51473c2406f | 640,167 |
import time
def timeit(method):
"""
A Python decorator for printing out the execution time for a function.
Adapted from:
www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods
"""
def timed(*args, **kw):
time_start = time.time()
result = m... | 0a2ab147343fdb5bd54818b7c474bbb6d59d7f90 | 640,168 |
def offset_to_next_multiple(num, mult):
"""Calculates the amount needed to round num upward to the next multiple of mult.
If num is divisible by mult, then this returns 0, not mult.
"""
if mult == 0:
return 0
else:
offset = mult - (num % mult)
if offset == mult:
... | 189260be93961d52bd834c4b5b930875417f5d43 | 640,170 |
def secondary_spherical(rho, phi):
"""Zernike secondary spherical."""
return 20 * rho**6 + - 30 * rho**4 + 12 * rho**2 - 1 | 825178bd82ba3119409aa529c4950f2875ab92be | 640,171 |
def get_hesitancy_dict(geo_df):
""" Return dictionary of hesitancy proportions.
Input:
geo_df: (dataframe) location geomatic dataframe typically output
from get_county_mapping_data().
Output:
Dictionary with keys not_hesitant, hesitant_or_unsure, and
strongly_hesita... | c2f50e481b674a2d8ac878b748699626a812cbf3 | 640,182 |
def fixed_embeddings_name(channel_id):
"""Returns the name of the fixed embedding matrix for some channel ID."""
return 'fixed_embedding_matrix_%d' % channel_id | 6d344e8c3b4f8e0e0ff69c38900f308154b1cdcf | 640,189 |
import json
def convert_format_in_metrics_list(metrics):
"""Converts from human-friendly metadata format to BigQuery friendly format.
Before:
'metadata': {'file': 'example.py'}
After:
'metadata': [{'key': 'file', 'value': '"example.py"'}]
Args:
metrics: A list of metrics dicts.
Returns:
... | 738c55a14ea6021e6b4bb6386e37ff5374092256 | 640,190 |
def postorder_traversal(node):
"""
recursive implementation of postorder traversal in which root is processed after left and right child
:param node: Node of a binary tree
"""
if node is None:
return None
postorder_traversal(node.left)
postorder_traversal(node.right)
print(node.... | d7e31fe74caec41966b27f0c780054254e3ec5a6 | 640,191 |
def uniform_but_one_dataset_no_weight(n, p):
"""Generates an unweighted dataset according to the AMS lower bound.
Args:
n: The size of the dataset
p: The frequency moment (used as a parameter in the lower bound)
Returns:
A list of keys, where all keys appear once, except for one key which
accoun... | ffb8c4dfd4a2db713d4ebeeb6cca3a3836f5a010 | 640,194 |
from typing import Callable
from typing import List
from typing import Tuple
from typing import Any
import inspect
def get_func_arguments_types_defaults(func: Callable) -> List[Tuple[str, Tuple, Any]]:
"""
Parse function arguments, types and default values
Args:
func: a function to be xeamined
... | 85226fe2b86c73a605eec0338190bc8cfe53e010 | 640,199 |
def get_lines(self):
"""The list returned contains all the Line of the SurRing
Parameters
----------
self : SurfRing
A SurfRing object
Returns
-------
line_list : list
list of lines delimiting the surface
"""
line_list = self.out_surf.get_lines()
line_list.ext... | 9a9966fa86ed8f4a5aebc996fa4252ad67d12ffb | 640,200 |
import binascii
def hex(b) -> str:
"""
Returns the hexily version of the binary datas.
:param b: binary datas
:return: the string
"""
return binascii.hexlify(b).decode('utf8') | 77141aefdde7af177cc36eb3317679a3f5743df0 | 640,204 |
def get_last_change(path):
"""
Figure out when the given path has last changed, recursively if a directory
"""
last_changed = path.stat().st_mtime
if path.is_dir():
for entry in path.glob("**/*"):
entry_changed = entry.stat().st_mtime
if entry_changed > last_changed:... | 1b1c2d58fa982ae83c2d84115e22f1b30773e377 | 640,209 |
def slice2enlist(s):
"""Convert a slice object into a list of (new, old) tuples."""
if isinstance(s, (list, tuple)):
return enumerate(s)
if s.step == None:
step = 1
else:
step = s.step
if s.start == None:
start = 0
else:
start = s.start
return enumerat... | 9414afdb247e2f7eadc35a77edbcc78ec7353d1e | 640,211 |
from typing import OrderedDict
import six
def _extract_simplified_filter_fields(filter_fields):
"""
Takes the filter_fields and simplifies them to a form django-filter can understand
"""
# If we are just dealing with a list we are fine
if not isinstance(filter_fields, dict):
return filter_... | f36d8a9804d45071f19aa5e5e3d0a87d1883d5f5 | 640,212 |
import html
def convert_unicode_to_html(text):
"""Convert unicode text to HTML by escaping it."""
return html.escape(text).encode("ascii", "xmlcharrefreplace").decode() | fbc448a9d63d69bdaa5223b98e5d0c2cc1f455dd | 640,214 |
import time
def timeMilis(plusSecs=0, plusMins=0, plusHours=0):
"""
Return current time in milis if no arguments.
If arguments are present it will be current time plus argument time.
Arguments:
plusSecs {int}: Add this amount of seconds to current time
plusMins {int}: Add this amount ... | 8a1800be78acb9e6fad78469d253ed137bde02a9 | 640,215 |
def _app_complete_on_provider(application, provider):
"""
Determines if an Application is completely available on a Provider, i.e. all active ApplicationVersions have a
ProviderMachine + InstanceSource on given Provider.
Args:
application: Application object
provider: Provider object
... | 9fb3d4671a9cfd0b6207306b48314a0b303a6b52 | 640,216 |
def ins_all_positions(x, l):
"""Return a list of lists obtained from l by inserting x at every possible index."""
res = []
for i in range(0, len(l) + 1):
res.append(l[:i] + [x] + l[i:])
return res | 82621c1c027126bc839ba28ab1bc338abf077e5b | 640,217 |
def ok(ret_code: int) -> bool:
"""Convert a posix exit code to a boolean."""
return ret_code == 0 | 93c9e724804112e6d48f5e2392482e9afb997c25 | 640,224 |
import pathlib
def _glob(filenames, pattern: str, invert: bool = False):
"""Applies a glob pattern to a string list of file names.
Args:
filenames: The list of file names.
pattern: The glob pattern to apply.
invert: If True, returns file names which evaluate to False.
Returns:
... | 2cf5e00d1e757461e167c0c8325c621abf6e2997 | 640,226 |
def flatten_list(lofl):
"""
Flatten a list of lists.
"""
new_list = []
for item in lofl:
if type(item) == list:
rl = flatten_list(item)
new_list.extend(rl)
else:
new_list.append(item)
return new_list | b7307b23de20ff84b6ee250ffaf099049d063930 | 640,230 |
def calc_intensity(locations):
""" Calculate intensity per location"""
max_duration = float(max(locations.values()))
result = {}
for key, value in locations.items():
result[key] = value/max_duration
return result | ea6a8fe0f8c6a882ebaf6452b09635b7ec702a9e | 640,233 |
import math
def split_dataset(inputs, targets, train_perc=0.7, val_perc=0.1, test_perc=0.2):
"""
Splits dataset into training, validation and test set
Output:
train-, validation- and test inputs : (percentage * n)x2 dimension FloatTensor
train-, validation- and test targets : (percentage * n... | ae64a7660f39eff77ce18a39ef398a5e3397b0ea | 640,234 |
def assign_weights(context):
"""
Assign weights to securities that we want to order.
"""
long_weight = 0.5 / len(context.longs)
short_weight = -0.5 / len(context.shorts)
return long_weight, short_weight | 93a5d72985e4aed919d35346f67004b148c45517 | 640,237 |
def fake_role(**kwargs):
"""Fixture to return a dictionary representing a role with default values set."""
kwargs.setdefault("id", 9)
kwargs.setdefault("name", "fake role")
kwargs.setdefault("colour", 7)
kwargs.setdefault("permissions", 0)
kwargs.setdefault("position", 55)
return kwargs | 5c2e700ca0f0158ee0b827808a9a82ea7b6be494 | 640,238 |
def declare_variables(variables, macro):
"""
This is the hook for the functions
- variables: the dictionary that contains the variables
- macro: a decorator function, to declare a macro.
"""
variables['baz'] = "John Doe"
# Note - will need to switch the /master in the docs repo
# to match the... | e925094f760c557ac68ff2aad5d9ea526b96d28c | 640,239 |
def degFormatter(deg):
"""Formats degrees as X˚
Args:
deg: float
Returns:
string
"""
return "${:d}^\circ$".format(int(deg)) | 3efd98c59334f1b4ff59fb18fc19a6aaa3d2618d | 640,242 |
def get_grams(sentence, n):
"""
Returns phrases i.e. windowed sub
strings with range (1-N) window
Keyword arguments:
sentence -- utterance (str)
n -- max_ngram (int)
"""
all_grams = []
for l in range(1, n + 1):
grams = [" ".join(sentence[i:i + l]) for i in range(len(sentence... | e23d88476231cf7912adadbee2f4159be81f262b | 640,243 |
def save_epoch(epoch, filename):
"""Save an epoch to a given filename
:param epoch:
The epoch that should be saved.
:type epoch: Epoch
:param filename:
The filename where to save the epoch
:type filename: str
"""
return epoch.save(filename) | 5db36429d6a6999441f3719c38c89b474f53c0ff | 640,245 |
def dateToInt(date, strfmt='%Y%m%d'):
""" Converts a datetime date into int
Parameters:
-----------
date : datetime
date in datetime format
strfmt : string
format in which the int date will be generated
Example:
dateToInt(dt.date(2015,10,23),'%Y')
"""
... | 4cbdb6b94fa7b86ef59cb5636bbe17ced56f3cbe | 640,248 |
def shout(text):
"""Return text in uppercase."""
return text.upper() | aaf06325592a836d57edbfd7c3774594edf87813 | 640,250 |
def _window_has_intervening_extrema(window, contour, mode):
"""
Steps 8/9. If there exists a sequence of equal maxima or minima, check if the sequence
contains an intervening opposite extrema, i.e. if a sequence of two equal maxima contains
a minima between them.
>>> maxima_group = [
... (2, [2, {1}]),
... (4... | f2ce05aa779679415d1542c4a190fae6a49ff65b | 640,254 |
def get_refdes_parts(anno_record):
""" Given an annotation record with a reference designator, return the corresponding subsite, node and sensor.
"""
subsite = None
node = None
sensor = None
refdes = anno_record.get('referenceDesignator')
if '-' not in refdes:
subsite = refdes
el... | 54a3996fab9811c7110eeb9e817afa49c359b419 | 640,255 |
from typing import Optional
def _serialize_comment(prefix: str, comment: Optional[str]) -> str: # pylint: disable=unsubscriptable-object
"""Serialize a comment, with an optional prefix."""
return "%s%s" % (prefix, comment) if comment else "" | 99acb1b16f0f8628a516687cf88af8587c6d317c | 640,259 |
def safe_filename(name):
"""Utility function to make a source short-name safe as a
filename."""
name = name.replace("/", "-")
return name | fb2ccf5b3cd4511c36ac7fac9b8cdfb7bff1291d | 640,263 |
def rectangle_dot_count(vertices):
""" Count rectangle dot count include edge """
assert len(vertices) == 2
width = abs(vertices[0][0] - vertices[1][0])
height = abs(vertices[0][1] - vertices[1][1])
dot_count = (width + 1) * (height + 1)
return dot_count | 2e330a5137482e7bf1eb2396936c61a0497bbe62 | 640,267 |
def GiB(val):
"""Calculate Gibibit in bits, used to set workspace for TensorRT engine builder."""
return val * 1 << 30 | b21be2501b4e2011b38cb44d2159e97f7b0aa851 | 640,269 |
def gete2wlandw2el_fromdf(df, missingval='*'):
"""Get dict inputs for the EM algorithm from a pandas dataframe.
Parameters
----------
df: pandas.DataFrame
dataframe, indexed by the question, and where column names
represent the various workers. Entries are the labels assigned
by... | 3c51a1f8b58718867e8309555388b2832ad0dfeb | 640,271 |
from typing import Optional
import re
import logging
def Prompt(message: str, validator: str = '.*') -> Optional[str]:
"""Prompt the user for input.
Args:
message: the prompt message displayed to the user
validator: a regular expression to validate any responses
Returns:
a response string if succe... | ce9bdcde354fe1a99413771641364cd24a882d7e | 640,272 |
def get_shorturl(ctx, slug):
"""Get the target of a shorturl by its slug."""
query = 'SELECT `target` FROM `shorturls_public` WHERE `slug` = %s'
ctx.execute(query, (slug))
candidate = ctx.fetchone()
return candidate['target'] if candidate else None | 9e986febb1d5ef0c78dee1bf05eb5ddf5e1a25f3 | 640,274 |
def is_float(value):
"""Check if value is a float."""
return isinstance(value, float) | a0b52166c42b6bceaffa18e8057f0408196acaab | 640,275 |
def player_last_awarded_submission(profile):
"""Returns the last awarded submission date for the profile."""
entry = profile.scoreboardentry_set.order_by("-last_awarded_submission")
if entry:
return entry[0].last_awarded_submission
else:
return None | 15e3ec8b0b0fc218c89a3dbe0484b30191dd399f | 640,276 |
def denormalize_colors(rgb_norm, mean_rgb=(0.485, 0.456, 0.406), std_rgb=(0.229, 0.224, 0.225)):
"""
Denormalize colors
Args:
rgb_norm: Image in RGB format, normalized by normalize_colors()
Numpy array of shape (h, w, 3)
mean_rgb, std_rgb: Mean and standard deviation for RGB cha... | 01cc5e25496647919f9841b9432a5422813558a7 | 640,281 |
def isdict(mixed):
"""
Check if the given argument is a dict.
:param mixed:
:return: bool
"""
return isinstance(mixed, dict) | cfd7938614ccfb79ae87338c5b036fc4ae4d7fe3 | 640,283 |
def swagger_type_to_pydantic_type(t, models=[]):
"""Given a swagger type or format or ref definition, return its corresponding python type"""
# Take a swagger type and return the corresponding python type
if t in models:
return t
mapping = {
# swagger type: pydantic type (https://pydant... | 10be23eed09be6b8ee05bd47b9e83464fbe147f4 | 640,285 |
def getTol(**kwargs):
"""
Returns the tolerances based on kwargs.
There are two ways of specifying tolerance:
1. pass in "tol" which will set atol = rtol = tol
2. individually set atol and rtol.
If any values are unspecified, the default value will be used.
"""
DEFAULT_TOL = 1e-12
if... | 3692e44eaca2dc2d4818c2e96d8437b71250f737 | 640,286 |
def get_seat_id(row, column):
"""Get seat id from row and column."""
return row * 8 + column | d18f9a990007189c86d23ad29b5694565f8c5526 | 640,288 |
def get_function_name(func):
""" Return the name of a function """
return func.__name__ | 17b7a1b5756371abcd47a7627c19eebba32573da | 640,291 |
def Name(uri):
"""Get just the name of the object the uri refers to."""
# Since the path is assumed valid, we can just take the last piece.
return uri.split('/')[-1] | e0ef4264d82d97675222c015f2bd0dd9cc0accac | 640,293 |
def write(fn, data):
"""
Write string to a file.
"""
f = open(fn, "w")
f.write(data)
f.close()
return True | afe49cb91e180a16f12059fb9e2a7e0c1e271c97 | 640,295 |
def rm_www_prefix(text):
"""
Remove www prefix
"""
prefix = "www."
if text.startswith(prefix):
return text[len(prefix) :]
return text | e9b460268126f13531cbeb308d7960d0694ef8f8 | 640,296 |
def is_string(value, arg_name, logger=None):
"""
Verifies whether a parameter is correctly defined as string.
:param value: value of the parameter
:param arg_name: str, parameter name
:param logger: logger instance
:return: boolean, True if value is a string, False otherwis... | df86a421b43a4b432e8c0d6770af1e9aef3727ec | 640,300 |
def is_complex(object):
"""Check if the given object is a complex number"""
return isinstance(object, complex) | 2ca855f273fb52ba2f3203ac5d4363ccdb3c454d | 640,301 |
import copy
def strip_registered_meta_comments(messy_dict_or_list, in_place=False):
"""Removes Prereg Challenge comments from a given `registered_meta` dict.
Nothing publicly exposed needs these comments:
```
{
"registered_meta": {
"q20": {
"comments": [ ... ], <~~... | 85ef4ab3dd7e193c9048d32255963b5d21362e4a | 640,308 |
def int_to_hex(num):
"""Convert an int to a hexadecimal string"""
num = int(num)
vals = { 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
if num < 0:
sign = '-'
num = -num
else:
sign = ''
if num < 10:
return sign + str(num)
if num < 16:
return si... | 6d62ceb245defecc9f857928b010dbf6ff2120f3 | 640,315 |
import string
import random
def random_string(n=5, uppercase=True):
"""Generates a random string of a given length, containing only uppercase letters and digits."""
letters = string.ascii_uppercase if uppercase else string.ascii_lowercase
return ''.join(random.choice(letters + string.digits) for _ in range(n)) | 17217709bd8b6dd2985ec43c3323641af9e59fe5 | 640,320 |
def construct_return_statement(prediction, dog_detection, human_detection):
"""Construct a str return statement from predicted breed and results of dog/human detector."""
if dog_detection:
return 'This is a {}.'.format(prediction)
elif human_detection:
return 'This human looks like a {}.'.fo... | 3a675ab56706b34efc4b3e511566ead2fc26799f | 640,329 |
from typing import Any
import json
def jsonify(obj: Any) -> str:
"""Convert a Python object to JSON."""
return json.dumps(obj, sort_keys=True, indent=4) | 95a128b5b26d22ac52d82a06c3764786a1f7f903 | 640,330 |
def RunLengthDecode(data):
"""
RunLength decoder (Adobe version) implementation based on PDF Reference
version 1.4 section 3.3.4:
The RunLengthDecode filter decodes data that has been encoded in a
simple byte-oriented format based on run length. The encoded data
is a sequence of runs... | b771c38ca0acab438c7ea72b2b3b00517e1327c6 | 640,331 |
def poisson(t, y, den):
"""Poisson's equation for radially symmetric density den(r) = |u(r)|^2."""
y1, y2 = y
y1d = y2
y2d = -den(t) / t
return [y1d, y2d] | 88edf97499185d51e86cb5777e44ae342e15ce98 | 640,333 |
def code_block(lines, language=''):
"""
Mark the code segment for syntax highlighting.
"""
return ['```' + language] + lines + ['```'] | 746fb444353fa141ab6b0e0324db4809c129e64f | 640,334 |
def normalize(s):
"""
Normalize strings to space joined chars.
Args:
s: a list of strings.
Returns:
A list of normalized strings.
"""
if not s:
return s
normalized = []
for ss in s:
tokens = [c for c in list(ss) if len(c.strip()) != 0]
normalized... | 98ca9bb41ef72087a2e154b37bde056acef9420c | 640,335 |
def find_flat_segment(polygon):
"""
Find beginning and end indexes of a horizontal section in the polygon.
This section can be made of several consecutive segments.
If the polygon contains several flat sections, this function only identify the first one.
The polygon is a list of 2D coordinates (x, y... | 7030beb603cfa24ab601d6d83a444692a6508f4d | 640,341 |
def test_classifier(classifier, inputs, labels):
"""Compute mean subset accuracy for a classifier.
Args:
classifier: A scikit-learn classifier.
inputs: a Kx464 array of linearised input images.
labels: a K-vector of integer labels.
Returns:
A scalar mean accuracy score.
"""
return classifier... | 8f0968c4df172a91a914c81ca9e763c831fa7bf6 | 640,342 |
import re
def name_check(name):
"""
NAME: name_check
----------
DESCRIPTION: Replaces and corrects users' park name query with a unique identifier in order
to save them searching for the exact name of the national park. Works for the top 20 national
parks in terms of number of visits.
----... | 4f1cb36da3cd24784903e0dca7ea191bc200ee3a | 640,344 |
def _get_outside_corners(corners, board):
"""
Return the four corners of the board as a whole, as (up_left, up_right, down_right, down_left).
"""
xdim = board.n_cols
ydim = board.n_rows
if corners.shape[1] * corners.shape[0] != xdim * ydim:
raise Exception("Invalid number of corners! %d... | 9ddd8b60771e74451a4ea7abd4bd5bb55846d89e | 640,347 |
def c_to_f(temperature):
"""
Converts a temperature in Celsius to Fahrenheit.
"""
return temperature * 9 / 5 + 32 | 865f92d2c170c3eaf03f097c4cc1f79bf16a12ef | 640,350 |
def get_intersection(u, v, node_presence):
"""
Get the intersection between the presence of u and v.
:param u: First Node
:param v: Second Node
:param node_presence: Node presence
:return: Interection
"""
intersec = []
for ut0, ut1 in zip(node_presence[u][::2], node_presence[u][1::2... | 95d368872af2c3b3abb88a773ff448149f526fb6 | 640,354 |
def scale(df, samples, scale_value=100):
"""Return copy of dataframe with a set of columns normalized
Parameters
----------
df : pandas dataframe
The data frame to be normalized
samples : list of str
Column identifiers to use for indexing the data frame
scale_value : Optional[fl... | 441c766ec03adf59c51ac8d79a4b8ec3e53d42b9 | 640,358 |
def _check_array_range(istart, iend, npts):
"""
Takes two indices, checks that they are in the correct order, ie. start
is smaller than end, checks that start>=0 and end<=npts, and checks
that start!=end.
"""
istart = int(istart if istart<iend else iend)
iend = int(istart if istart>iend ... | b042448a0169d686e1a185133e8c324d5c74d242 | 640,359 |
def GetObjcopyCmd(target):
"""Return a suitable objcopy command."""
if target == 'mips32':
return 'mipsel-nacl-objcopy'
return 'arm-nacl-objcopy' | 75651777e07b275a0fc503ab17f29e0152788af2 | 640,360 |
def c_to_f(c_temp):
"""
Converts from Celsius to Farenheint
"""
try:
return (float(c_temp) * 9.0 / 5.0) + 32.0
except ValueError:
return None | f32139c4c21eccae59ef35cd932b4941de601c96 | 640,362 |
import re
def get_no_export_output(vm_host):
"""
Get no export routes on the VM
Args:
vm_host: VM host object
"""
out = vm_host.eos_command(commands=['show ip bgp community no-export'])["stdout"]
return re.findall(r'\d+\.\d+.\d+.\d+\/\d+\s+\d+\.\d+.\d+.\d+.*', out[0]) | b3f9a12245c0d4331e88da07ffb7918fabce4c5f | 640,363 |
def iterable(item):
"""
Predicate function to determine whether a object is an iterable or not.
>>> iterable([1, 2, 3])
True
>>> iterable(1)
False
"""
try:
iter(item)
return True
except TypeError:
return False | 14edd2795694245cca22d748307bf4722851b216 | 640,366 |
def get_geofence_collection_arn(region, account_id, collection_name):
""" Helper to convert Geofence Collection name to ARN, since this information is not available directly from the
Geofencing API. """
return f"arn:aws:geo:{region}:{account_id}:geofence-collection/{collection_name}" | 390f35418111b4a0d806a690172c99903362e4c0 | 640,368 |
def tofloat(v):
"""Check and convert a string to a real number"""
try:
return float(v) if v != '.' else v
except ValueError:
raise ValueError('Could not convert %s to float' % v) | 9345a55bcd4f4e8e57aef9d456eb6ba7e0b26646 | 640,376 |
def _pow(a, b):
"""C-like power, a**b
"""
return a**b | 02101594d22a3366912b468de96bfe0bdab44102 | 640,379 |
import urllib.request
def get_htmls(urls, timeout):
"""get htmls from urls array.
args:
urls([str]): urls string array.
timeout(int): seconds
return:
[url, html]
url: str
html: str
"""
ret = []
for url in urls:
try:
with urllib.reques... | 3a687ce8b46d8952dd5d2d78338f74393c8d57d6 | 640,382 |
def has_proper_name(user=None):
"""Whether user has enough data with which to form a proper name.
:param user: Django user object
:returns: True, False, or None (if unknown)
:rtype: bool | None
.. note::
User must be authenticated or function will return None.
"""
ret = None
... | e632c7ef6637f910188a5969b3be5ba2e85b415e | 640,385 |
def tap(x, label=None):
"""Prints x and then returns it."""
if label:
print('%s: %s' % (label, x))
else:
print(x)
return x | edf5b258b2bd28b6b8100192fee4dd5ff6fb9387 | 640,388 |
import re
def ParseHostPort(address):
"""Parses the provided address string as host:port and
returns a tuple of (str host, int port).
"""
host_port_re = re.match(r"([a-zA-Z0-9-\.]+):([0-9]{1,5})$", address)
if not host_port_re:
raise TypeError("bad host:port: %s" % address)
host = host_port_re.group(1... | f34ab3ff27b3fb16a4d2f00d070b94ce0e35399f | 640,389 |
def compute_murphree_stage_efficiency(mu, alpha, L, V):
"""
Return the sectional murphree efficiency, E_mv.
Parameters
----------
mu: float
Viscosity [mPa*s]
alpha: float
Relative volatility.
L: float
Liquid flow rate by mol.
V: float
Vapor flow r... | 01a6b269454fda2fabaf84a8eb1d53b7beed8d16 | 640,392 |
def fuselage(Sts,qm,Ltb):
""" Compute weifht estimate of human-powered aircraft fuselage
Assumptions:
All of this is from AIAA 89-2048, units are in kg. These weight estimates
are from the MIT Daedalus and are valid for very lightweight
carbon fiber composite structures. This may n... | 0acf6ad50dba85cd9f8ccc7602200b67f5ef4b60 | 640,394 |
from decimal import Decimal
def euler_totient(num, factors):
"""
Given a number n and all its distinct prime factors, compute φ(n).
The insight is that for every distinct prime factor p of a number n, the portion of numbers coprime to A "decays" by exactly (1/p).
"""
totient = Decimal(num)
fo... | 3a13f622ed11b69ae0c3c54b06f00b1752f3d135 | 640,396 |
from typing import List
def get_bit_index(number: int) -> List[int]:
"""Get bit indices from number.
Args:
number: A number (greater than 0).
Returns:
List of bit indices.
Examples:
number: 4 (`100` in 2 ary number), Returns: [3]
number: 6 (`110` in 2 ary number), Re... | aa33c6a3cdd0657f5d571e41bb19ff8d4761694f | 640,399 |
import requests
def process_image(ID, filename, method):
"""
POST request the user to process the image
Args:
ID (str): user name
filename (str): filename that should exist in database
method (str): processing method
Returns:
r6.json() (str): Confirmation that image w... | 1e36f2fce60a962f4909dd9bd35962be64dd0b81 | 640,404 |
def quantized_rotation(img, factor):
"""
Rotate an image counterclockwise by an integer factor times 90 degrees.
"""
if factor % 4 == 0:
pass
elif factor % 4 == 1:
img = img.transpose(-2, -1).flip(-1)
elif factor % 4 == 2:
img = img.flip(-2).flip(-1)
elif factor % 4 =... | 686f27106f0561725434ed7cd9915862d785d09f | 640,405 |
def byte2str(e):
"""Return str representation of byte object"""
return e.decode("utf-8") | 1d7ef5858be2144dcb8edbb85511bc5bf056a56d | 640,406 |
import torch
def generate_all_anchors(anchors, H, W):
"""
Generate dense anchors given grid defined by (H,W)
Arguments:
anchors -- tensor of shape (num_anchors, 2), pre-defined anchors (pw, ph) on each cell
H -- int, grid height
W -- int, grid width
Returns:
all_anchors -- tensor of ... | a7a7a09eca5bbd0a4de8874d3d056651455c47ac | 640,409 |
def store_listings(db, listings):
"""
Store listings in database.
Listings already contained in the database are ignored.
Returns the number of listings that were stored.
"""
cursor = db.cursor()
tuples = [(x, y['street'], y['number'], y['suburb'], y['rent'],
y['area']) for x... | 9f589d50f00a37953fef1c4492ee5d56072ea0b4 | 640,416 |
def valid_command(val, valid=[]):
"""Validate given command among accepted set."""
#pylint: disable=dangerous-default-value
assert val in valid, 'invalid command: %s' % val
return val | 5f9781e427faf7ea61773300457539b5bb963c0e | 640,419 |
import inspect
def _get_callable(obj, of_class = None):
""" Get callable for an object and its full name.
Supports:
* functions
* classes (jumps to __init__())
* methods
* @classmethod
* @property
:param obj: function|class
:type obj: Callable
:param of_class: Class that thi... | 9b62e0de62a5a8a2592820f7d6e183395921f838 | 640,420 |
def substr(word, pos, length):
"""Return the substr of word of given length starting/ending at pos; or None."""
W = len(word)
if pos >= 0 and pos+length <= W:
return word[pos:pos+length]
elif pos < 0 and abs(pos)+length-1 <= W:
return word[W+pos+1-length:W+pos+1]
else:
return... | 4aa758d9e26ddd0ea10585c9be82ef35f34ffe4a | 640,421 |
def spacing(space, IPA):
"""
Assign space based on its location
Parameters
----------
IPA : bool
A flag used to determine the type of alphabet
space : str
The type of space chosen by user
Returns
-------
list
a list of spaces for prefixes, suffixes, and word... | 00c9c08b207ef27064a0ee1ec97bc72305a1af08 | 640,424 |
def insert_roi(conn, cur, exp_id, series, offset, size):
"""Inserts an ROI into the database.
Args:
conn (:obj:`sqlite3.Connection): Connection object.
cur (:obj:`sqlite3.Cursor): Cursor object.
exp_id (int): ID of the experiment.
series (int): Series within the experiment. ... | 94fbc438a381d273c89c724bf07f080373063f64 | 640,428 |
import re
def normalize_name(name, separator="_"):
"""Normalizes a name by replacing all non-alphanumeric characters with underscores."""
return re.sub("[^A-Za-z0-9_]+", separator, name) | fa186c1601657d960ba6630ab508883228b40452 | 640,429 |
def compose1(h, g):
"""Return a function f, such that f(x) = h(g(x))."""
def f(x):
return h(g(x))
return f | 2b09e83a0a8c6813572e2f99596a2a41c4390e73 | 640,435 |
from pathlib import Path
def fixture_checksum_file(fixtures_dir: Path) -> Path:
"""Return the path to file to test checksum"""
return fixtures_dir / "26a90105b99c05381328317f913e9509e373b64f.txt" | cec0b7751e94dd8214140458e18f5445a2cb87f5 | 640,440 |
def create_query_string(graph_name: str, keyword: str):
"""
This methods generates the query string for the keyword-search in put.
:param graph_name: graph to be queried, default is "default graph",
like "<http://localhost:3030/60d5c79a7d2c38ee678e87a8/60d5c79d7d2c38ee678e87a9>"
:param keyword:... | 4c22524195222bcfb515a160db770b68b893b17d | 640,446 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.