content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def milestone_portfolio(milestone_name: str):
"""Create milstone portfolio"""
portfolio = create_milestone_portfolio(milestone_name)
print(f"Created milestone portfolio {portfolio}") | 77,700 |
def update_config(configfile=None, modulename=None):
"""Updates the system configuration either from a ConfigObj
(INI-style) config file, a module name specified in dotted notation
or both (the module name is assumed to have a ".cfg" extension).
If both are specified, the module is called first,
fol... | 77,701 |
def which(executable):
"""find the location of an executable"""
if 'PATH' in os.environ:
envpath = os.environ['PATH']
else:
envpath = os.defpath
PATH = envpath.split(os.pathsep)
locations = PATH + [
'/usr/local/bin',
'/bin',
'/usr/bin',
'/usr/local/sb... | 77,702 |
def conv_output_shape(
h_w: Tuple[int, int],
kernel_size: Union[int, Tuple[int, int]] = 1,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
) -> Tuple[int, int]:
"""
Calculates the output shape (height and width) of the output of a convolution layer.
kernel_size, stride, padding and... | 77,703 |
def reflection_matrix(v):
"""Generate reflection matrix that represents reflection of points \
in a mirror plane defined by normal `Vector` `v`.
Parameters
----------
v : :class:`~sknano.core.math.Vector`
Returns
-------
:class:`~numpy:numpy.ndarray`
"""
from ._vector impo... | 77,704 |
async def normalize_postcode_middleware(request, handler):
"""
If there is a postcode in the url it validates and normalizes it.
"""
postcode: Optional[str] = request.match_info.get('postcode', None)
if postcode is None or postcode == "random":
return await handler(request)
elif not is_... | 77,705 |
def normalize_v(x):
"""
normalize a vector
:param x: input
:return: normalized vector
"""
mn = np.min(x)
mx = np.max(x)
for i in range(len(x)):
x[i] = (x[i] - mn) / mx - mn
return x | 77,706 |
def checkout(request, template_name="order/checkout.html"):
"""
Displays the customer info form for checkout
"""
loginform = LoginForm()
addressform = AddressForm()
if request.method == 'POST':
addressform = AddressForm(request.user, request.POST)
if addressform.is_valid():
... | 77,707 |
def main():
"""Regenerates the 'requirements.txt' file using the 'requirements.in'
file to produce a deterministic list of all the dependencies that should be
in the 'third_party/python_libs' folder.
"""
# This code is copied from the pip-compile script. We cannot use the
# pip-compile script be... | 77,708 |
def extract(s):
"""Return a list of each individual emoji in the string."""
return EMOJI.findall(s) | 77,709 |
def fixture_grid_result():
"""
Load the expected grdproject grid result.
"""
return xr.DataArray(
data=[
[427.85062, 431.05698, 452.34268],
[563.92957, 540.5212, 501.46896],
[740.80133, 679.1116, 554.78534],
[794.233, 829.4449, 764.12225],
... | 77,710 |
def reset_units(seed=None):
"""
Set all units to new, self-consistent, floating-point values. See package
documentation for detailed explanation and examples:
http://pypi.python.org/pypi/numericalunits
reset_units() --> units are randomized. This is the suggested use, and is
done automatically ... | 77,711 |
def test_check_071():
""" Font follows the family naming recommendations ? """
from fontbakery.specifications.name import com_google_fonts_check_071 as check
# Our reference Mada Medium is known to be good
ttFont = TTFont("data/test/mada/Mada-Medium.ttf")
# So it must PASS the check:
print ("Test PASS with... | 77,712 |
def save_metrics(metrics, exp_dir, filename='metrics.json'):
"""
Load metrics from the given exp directory..
Parameters
----------
metrics : ``dict``
Metrics to save
exp_dir : ``str``
Folder to load metrics from
filename : ``str``, optional (default: 'metrics.json')
... | 77,713 |
def setup(bot: StarBot) -> None:
"""Load the extension."""
bot.add_cog(ExtensionManagement(bot)) | 77,714 |
def test_rotate_exception():
"""
Test Rotate with invalid parameters
"""
logger.info("test_rotate_exception")
try:
_ = c_vision.Rotate("60")
except TypeError as e:
logger.info("Got an exception in Rotate: {}".format(str(e)))
assert "not of type [<class 'float'>, <class 'i... | 77,715 |
def all_scalars(fields: List[Field]) -> bool:
"""Checks if all fields are scalars."""
boolean = True
for f in fields:
boolean = boolean and f.is_boson
return boolean | 77,716 |
def sum_all(grid_values):
"""
Calculates the sum of all grid values.
Results in scores from
:param grid_values: values of grid
:return: metrics score
"""
score = sum(grid_values)
return score | 77,717 |
def _ec_helper_native():
"""Loads the ec_helper_native library.
Returns:
The ctypes ec_helper_native library.
"""
cdll.LoadLibrary(find_library('crypto'))
cdll.LoadLibrary(find_library('ssl'))
return cdll.LoadLibrary('./ec_helper_native.so') | 77,718 |
def formulate_condition(analyses_pattern: str, analyses_list: str) -> str:
""" formulate WHERE SQL condition from analyses_pattern """
condition = ''
if analyses_pattern:
a_range = re.match(r'(\d+)\.\.(\d+)', analyses_pattern)
if a_range:
condition = " WHERE analysis_id BETWEEN %... | 77,719 |
def lossNet(input_shape=(256, 256, 3),
styleLayers=["block1_conv2", "block2_conv2", "block3_conv3", "block4_conv3"],
contentLayers=["block3_conv3"]):
"""Creates the network to compute the style loss.
This network outputs a dictionary with outputs values for style and content, based on a ... | 77,720 |
def test_skipped_errors(run_line):
"""
Confirms --skipped-errors option for task show parses the output of
GET /task/<task_id>/skipped_errors
"""
meta = load_response_set("cli.skipped_error_list").metadata
result = run_line(f"globus task show --skipped-errors {meta['task_id']}")
assert "/~/... | 77,721 |
def _path(from_object, to_object):
"""
Calculates the 'path' of objects starting from 'from_object'
to 'to_object', along with the index of the first common
ancestor in the tree.
Returns (index, list) tuple.
"""
if from_object._root != to_object._root:
raise ValueError('No connecti... | 77,722 |
def initialize_worker():
""" Function called to initialize python on workers
"""
from rfpipe import search, state, metadata, candidates, reproduce, source, util
t0 = time.Time.now().mjd
search.set_wisdom(512)
st = state.State(inmeta=metadata.mock_metadata(t0, t0+0.001, 27, 16, 16*32, 4, 5e4, da... | 77,723 |
def add_elements(arr, k):
"""
Given a non-empty array of integers arr and an integer k, return
the sum of the first k element that has at most two digits.
Example:
Input: arr = [111,21,3,4000,5,6,7,8,9], k = 4
Output: 24 # sum of 21 + 3
Constraints:
1. 1 <= len(arr) <= 100... | 77,724 |
def parse_filter(components, kind):
"""
Parese any filter
"""
filters = []
pieces = kind.split('_')
parenthsis =0
is_in_quotes = False
start_tracking = False
# loop the the data
for ii, s in enumerate(components):
#print('where - ' + s)
# find the end of the columns
(p, is_in_quotes) = track_parenth... | 77,725 |
def getATT(file):
"""use Ohlbergs code to read in attitude data from file
and creates a dictionary for easy insertation
into a postgresdatabase.
"""
ap = attitude.AttitudeParser([file])
# sorting attitudes
tbl = ap.table
keys = tbl.keys()
if not keys:
return
keys.sort()
... | 77,726 |
def write_model_inputs(
scenario_directory, scenario_id, subscenarios, subproblem, stage, conn
):
"""
Get inputs from database and write out the model input
projects.tab (to be precise, amend it) and project_carbon_tax_allowance.tab files.
:param scenario_directory: string, the scenario directory
... | 77,727 |
def graph_kml(
env,
fname="graph.kml",
icon="http://maps.google.com/mapfiles/kml/shapes/donut.png",
size=0.5,
scale=0.5,
width=5,
):
"""Create a kml visualisation of graph. Env variable needs to contain
graph."""
# create a kml file containing the visualisation
kml = Kml()
f... | 77,728 |
def keysInter(x):
"""Keys interpolation function
"""
y = np.zeros(x.shape)
abs_x = np.abs(x)
idx1 = np.bitwise_and(abs_x >= 0, abs_x < 1)
idx2 = np.bitwise_and(abs_x >= 1, abs_x <= 2)
y[idx1] = 1.5 * abs_x[idx1] ** 3 - 2.5 * abs_x[idx1] ** 2 + 1
y[idx2] = -0.5 * abs_x[idx2] ** 3 + 2.5 * ... | 77,729 |
def rotate_landmarks(landmarks, eye_center, angle, row):
""" rotate landmarks to fit the aligned face
:param landmarks: dict of landmarks for facial parts as keys and tuple of coordinates as values
:param eye_center: tuple of coordinates for eye center
:param angle: degrees of rotation
:param r... | 77,730 |
def chk_slv_err(master, slaves, **kwargs):
"""Function: chk_slv_err
Description: Check the Slave's IO and SQL threads for errors.
Arguments:
(input) master -> Master instance.
(input) slaves -> Slave instances.
"""
print_template = "\nSlave:\t{0}"
slaves = list(slaves)
... | 77,731 |
def _lookup(name, func, multi, converters):
"""Look up a Webware field/cookie/value/session value. Return
'(realName, value)' where 'realName' is like 'name' but with any
conversion suffix strips off. Applies numeric conversion and
single vs multi values according to the comments in the source.
""... | 77,732 |
def fepack(widget, side, fill=tkinter.BOTH, expand=True, **kwargs):
"""
Pack `widget` on `side`, with default of fiiling in both dimensions and
turned on expansion.
"""
widget.pack(side=side, fill=fill, expand=expand, **kwargs) | 77,733 |
def generate_random_unit_vector():
"""
Generates a random unit vector.
:return: 3-elem np array with magnitude 1
"""
vec = np.random.normal(size=3)
mag = np.linalg.norm(vec)
if mag <= 1e-5:
return generate_random_unit_vector()
else:
return vec / mag | 77,734 |
def Grab_Tutorials():
""" internal command ~"""
import re
full_array = []
dirs,files = xbmcvfs.listdir(py_path)
# Check all the modules for functions with tutorial info
for file in files:
file_path = os.path.join(py_path,file)
if file.endswith('.py') and file != 'tutorials.py':
... | 77,735 |
def read_chunk(addr):
"""Read a chunk's metadata."""
# In GLIBC versions <= 2.24 the `mchunk_[prev_]size` field was named `[prev_]size`.
# To support both versions, change the new names to the old ones here so that
# the rest of the code can deal with uniform names.
renames = {
"mchunk_size"... | 77,736 |
def version():
"""
Determine ffmpeg version and build information
"""
verdata = subprocess.check_output([bpath.ffpath, '-version'])
vdx = {
'version': vmatch(r'^ffmpeg version ([^ ]+).*', verdata),
'date': vmatch(r'.*^built on (.+) with.*$', verdata),
'config': vm... | 77,737 |
def dense_brightness_weight(image, sigma_X = 4, sigma_I = 10, r = 5):
"""
Calculate bright_weight(connection) for image
Args:
image: ndarray [B,H,W,C].
sigma_X: sigma for metric of distance.
sigma_I: sigma for metric of intensity.
r: radius of circle that only the neighb... | 77,738 |
def to_dict_of_lists(G,nodelist=None):
"""Return adjacency representation of graph as a dictionary of lists.
Parameters
----------
G : graph
A NetworkX graph
nodelist : list
Use only nodes specified in nodelist
Notes
-----
Completely ignores edge data for MultiGr... | 77,739 |
async def test_flow_no_devices_found(hass):
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] is None
with patch(
"homeassistant.compon... | 77,740 |
def calc_VFA_T1(S1, S2, fa1, fa2, TR):
"""Equation to calculate T1 from two T1w UTE GRE 'magnitude' images with different flip angles"""
T1 = -1.0 * TR / np.log((S1/np.sin(fa1) - S2/np.sin(fa2)) / (S1/np.tan(fa1) - S2/np.tan(fa2)))
return T1 | 77,741 |
def is_type_name(type_name):
"""Does not handle keywords.
"""
return type_name[0].isupper() | 77,742 |
def make_splits(
df: pd.DataFrame, train_ratio: float = 0.8, val_ratio: float = 0.1
):
"""
TODO
"""
#unused_fnames = set(df["id"].unique())
used_fnames = set()
train_df = pd.DataFrame(columns=df.columns)
val_df = pd.DataFrame(columns=df.columns)
test_df = pd.DataFrame(columns=df.col... | 77,743 |
def gauss_int(x, mu, sigma, A=1):
"""
integral of a gaussian from 0 to x, w/ args: mu, sigma, area, const.
"""
return A/2 * (1 + erf((x - mu)/sigma/np.sqrt(2))) | 77,744 |
def update_zone():
"""
Updates the zone in constants.INSTALLER_ROUTE53
"""
# update the zone in route
if config.ENV_DATA.get("region"):
def_zone = 'provider "aws" { region = "%s" } \n' % config.ENV_DATA.get("region")
replace_content_in_file(constants.INSTALLER_ROUTE53, "xyz", def_zon... | 77,745 |
def pad_data(matrix):
"""
pad data to fit mini-batch training
:param matrix:
:return:
"""
padded_index = matrix.shape[1]
data, data_len = [], []
for i in range(matrix.shape[0]):
seq = matrix.getrow(i).indices
data.append(seq)
data_len.append(len(seq))
longest... | 77,746 |
def predict(m, fn):
"""
Args:
m: the trained model
fn: the full path to a file in the same format as the test set
Returns:
list: a list of 0s and 1s, corresponding to the lines in the specified file.
"""
vectorize = TFIDF(VECTOR_SIZE)
ds = preprocess(fn, train=False)
... | 77,747 |
def generate_query_string_missing_row(tablename_left, tablename_right,
l_column_name, r_column_name,
primary_keys, columns_list,
type_cast_dict):
"""
This method will produce a query to detect row... | 77,748 |
def test_project_gnb_data_tfidf(db, test_profile, tmpdir, settings):
"""This fixture only creates the test project without any data."""
proj = create_project("test_project", test_profile, classifier="gnb")
test_data = read_test_data_backend(file="./core/data/test_files/test_no_labels.csv")
add_data(proj... | 77,749 |
def enc_state2(request):
"""The encoded state from compute_enc_state with another set of
parameters."""
return compute_enc_state(request) | 77,750 |
def pi_modulus(recon_pattern,
diffracted_pattern,
offset_v=1e-12):
"""
Transfer sample from real space to q space.
Use constraint based on diffraction pattern from experiments.
Parameters
----------
recon_pattern : array
reconstructed pattern in real space
... | 77,751 |
def grazing_effect_on_aboveground_production(tgprod, fracrc, flgrem, grzeff):
"""Adjust aboveground production with the impact of grazing.
Removal of biomass by herbivores directly impacts potential
aboveground production according to the amount of biomass removed
and the parameter grzeff, which a... | 77,752 |
def slow_conv(A, w, delays):
""" A simple implementation of convolution to compare against fast_conv """
#A is a NxM matrix, N is number of samples, M is dimensionality
Mw,D = w.shape
N,M = A.shape
assert Mw == M
y = np.zeros([N])
for k in range(N):
x = np.zeros([M, D])
fo... | 77,753 |
def window(seq, size=2, fill=0, fill_left=False, fill_right=False):
""" Returns a sliding window (of width n) over data from the iterable:
s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
"""
ssize = size - 1
it = chain(
repeat(fill, ssize * fill_left),
iter(seq),
repeat(fill, ssize *... | 77,754 |
def process(data, action):
"""Выполняет верхнюю операцию в стаке и возвращаем результат в стэк"""
if not action.function:
return True
# Если для операции не хватает аргументов или значение не подходит - выдаём ошибку
try:
# Берём нужное кол-во аргументов для операции
if ... | 77,755 |
def removeUser(username, db_conn = None):
"""
Removes a user from the database and postgres system. Admin rights required.
:param username str:
"""
if db_conn is None:
conn = usernameUtilities.log2nordb()
else:
conn = db_conn
if not checkPermissions('admin', conn):
r... | 77,756 |
def get_last_day_of_month(t: datetime) -> int:
"""
Returns day number of the last day of the month
:param t: datetime
:return: int
"""
tn = t + timedelta(days=32)
tn = datetime(year=tn.year, month=tn.month, day=1)
tt = tn - timedelta(hours=1)
return tt.day | 77,757 |
def get_Z_mats(V_mats):
"""
transform into conic matrix Z
Z = (V.T).dot(V)
Returns:
Z_mats (ndarray): Z is a conic representation of an ellipse
"""
Vt_mats = np.array(list(map(np.transpose, V_mats)))
Z_mats = Vt_mats @ V_mats
return Z_mats | 77,758 |
def git_create_pr_command(component, exclude_components, base): # noqa: D301
"""Create a GitHub pull request for each selected component.
\b
:param components: The option ``component`` can be repeated. The value may
consist of:
* (1) standard component name ... | 77,759 |
def main():
"""main entry"""
LOGGER.info('===== Start ingestion program.')
# Parse directories from input arguments
LOGGER.info('===== Initialize args.')
args = _parse_args()
_init_python_path(args)
accuarcies = []
overall_time_spents = []
valid_accuarcies1 = []
valid_accuar... | 77,760 |
def extract(geojson):
"""
[1] GeoJSON Specification
https://tools.ietf.org/html/rfc7946
"""
coordinates = list()
lines = list()
rings = list()
def extract_point(coords):
coordinates.append(tuple(coords))
return len(coordinates)-1
def extract_line(line_coords):... | 77,761 |
def wrap_message(messageText, width=79):
"""Word-wrap the message
:param str messageText: The text to alter.
:param int width: The column-number which to wrap at.
:returns: The wrapped text.
:rtype: str
.. Note: Originally a stand-alone script in
``Presentation/Tofu/MailingListManager/lscripts``."""
... | 77,762 |
def client_id_from_id_token(id_token):
"""
Extracts the client id from a JSON Web Token (JWT).
Returns a string or None.
"""
payload = JWT().unpack(id_token).payload()
aud = payload.get('aud', None)
if aud is None:
return None
if isinstance(aud, list):
return aud[0]
r... | 77,763 |
def route_agent(identifier):
"""Provide data from the DataPoint table for a specific Agent.
Args:
identifier: GraphQL identifier for the agent
Returns:
None
"""
# Initialize key variables
rows = []
screen = uri.graphql_filter(request)
# Get data from API server
po... | 77,764 |
def _convert_decoration_content_item(raw_data):
"""
Convert some raw data (usually a `dict`) to one of the registered
table content classes. Given that string is a valid table content
`str` values are returned unchanged.
"""
if _is_preprocessed_data(type(raw_data)):
return raw_data
e... | 77,765 |
def get_custom_kwargs(clazz, **kwargs):
"""
Filters kwargs based on the signature of the 'clazz'
:param clazz: Clean class or clean function to check the signature of
:param kwargs: optional arguments provided by the user
:return: filtered dictionary of kwargs
:raises ValueError: if a required ... | 77,766 |
def test_Footer(footer):
""":class:`.Footer` can be written."""
sdmx.to_xml(footer) | 77,767 |
def deprecate(message):
"""Display message about deprecation"""
global DEPRECATION_WARNINGS_ENABLED, _WARNINGS_ALREADY_ENABLED
# force enable DeprecationWarnings since most interactive shells have
# them disabled
if DEPRECATION_WARNINGS_ENABLED and not _WARNINGS_ALREADY_ENABLED:
_WARNINGS_AL... | 77,768 |
def run_dosxyz(wrk_dir, egs_inp, pegs_inp):
"""
run dosxyz with a given egs and pegs input files
"""
logging.info("Running DOSXYZ")
logging.debug(wrk_dir)
logging.debug(egs_inp)
logging.debug(pegs_inp)
start = time.time()
process_name = DXYZ
src = os.path.... | 77,769 |
def normalize_readsizes(input_paths, output_paths):
"""Normalize length of multiple long read fastq files."""
split_fastq_files(input_paths, output_paths) | 77,770 |
def test_color_manager_apply_extract_10():
"""
Test Extract Colour with incorrect value for topHat (Invalid Type)
"""
manager = ColorManager("topHat", "blue", 'a')
with pytest.raises(TypeError):
manager.apply(test_image_colour) | 77,771 |
def get_key_in_nested_dict(nested_dict, target_key):
"""
Traverses the passed dict to find and return the value of target_key in the dict.
:param nested_dict: dictionary to search in
:param target_key: key you are looking for
:return: values of key
"""
for key in nested_dict:
if key ... | 77,772 |
def get_type(entry: DirEntry) -> EntryType:
"""
Gets the type of directory entry held by this file.
May not function properly with non-POSIX file permission attributes.
Args:
entry (os.DirEntry): The directory entry object returned by os.scandir()
Returns:
EntryType: The type of d... | 77,773 |
def test_provider_aws_hooks_azs_regions(change_dir):
"""Verify the hook call works successfully."""
context = tackle('.', context_file='azs_regions.yaml', no_input=True)
assert len(context) > 1
assert len(context['azs']['us-east-1']) > 1 | 77,774 |
def move_to_output_dir(work_dir, output_dir, uuid=None, files=list()):
"""
Moves files from work_dir to output_dir
Input1: Working directory
Input2: Output directory
Input3: UUID to be preprended onto file name
Input4: list of file names to be moved from working dir to output dir
"""
fo... | 77,775 |
def read_configfile(configfile):
"""
Function to read the configfile.
Returns a hash.
"""
with open(configfile, 'r') as stream:
try:
confighash = yaml.safe_load(stream)
except yaml.YAMLError as exc:
error( exc )
return confighash | 77,776 |
def test_():
""" Testing the common_items function using a given input size """
# With additional sleep
sleep(0.01)
common = common_items(a1, a2) | 77,777 |
def delete_deflate_folder(instance):
""" Checks if the deflate folder exists, and deletes it. """
deflate_directory = get_deflation_directory(instance)
if os.path.exists(deflate_directory):
def on_error(instance, function, path, excinfo):
logger.warning(
"[project artif... | 77,778 |
def users():
"""user list"""
click.echo("users") | 77,779 |
def fpm(st1, st2, dt=0.01, fmin=1., fmax=10., nf=100, w0=6, norm='global',
st2_isref=True):
"""
Frequency-dependent Phase Misfit
.. seealso:: [Kristekova2009]_, Table 1. and 2.
:param st1: signal 1 of two signals to compare, type numpy.ndarray with
shape (number of components, number o... | 77,780 |
def clean_before_exit():
"""
These are some things that need to be done before exiting so that the user
does have any problems after they have run qr-filetransfer
"""
# Enable the cursor
cursor(True)
# Returning the cursor to home...
print("\r", end="")
# ...and printing "nothing"... | 77,781 |
def graph_edges_to_gdf(graph: nx.Graph) -> gpd.GeoDataFrame:
"""Create and fill a GeoDataFrame (geopandas) from edges of a networkX graph. The ``'geometry'`` attribute is used
for shapes.
Parameters
----------
graph : nx.Graph
Graph to parse
Returns
-------
gpd.GeoDataFrame
... | 77,782 |
def get_least_viewed_episode(episodes):
"""Identifies and returns episode with the lowest recorded viewership. Ignores episodes with
no viewship value. Ignores ties. Delegates to the function < has_viewer_data > the task of
determing if the episode includes viewership "episode_us_viewers_mm" data.
Para... | 77,783 |
async def pdf_to_embedded_images(
pdf_file: bytes = File(..., description="Upload a pdf file:")
):
"""This endpoint takes a pdf file and returns the embedded images."""
with tempfile.TemporaryDirectory() as target_temp:
doc = fitz.open(stream=io.BytesIO(pdf_file), filetype="pdf")
for i in ra... | 77,784 |
def twitter_api(input_encoding="utf-8"):
"""Returns an API that we can use to talk to Twitter. """
consumer_key = get_consumer_key()
consumer_secret = get_consumer_secret()
access_key, access_secret = \
get_access_tokens(consumer_key, consumer_secret)
api = ... | 77,785 |
def find_max_subarray_sum_brute(nums: List[Nums], k: int) -> Nums:
"""Given a list of numbers, find the maximum subarray sum of size k
Args:
nums: List[Nums]
k: int
Returns:
Nums
Raises:
ValueError if k < 0 or k > length of nums or nums is empty
"""
length = 0
... | 77,786 |
def create_simple_posting_with_cost_or_price(entry, account,
number, currency,
price_number=None, price_currency=None,
cost_number=None, cost_currency=None, costspec=None,
... | 77,787 |
def rmr_rcv_msg(vctx, ptr_mbuf):
"""
Refer to the rmr C documentation for rmr_rcv_msg
extern rmr_mbuf_t* rmr_rcv_msg(void* vctx, rmr_mbuf_t* old_msg)
"""
return _rmr_rcv_msg(vctx, ptr_mbuf) | 77,788 |
def lse( v_ij ):
"""[lse(v_ij)]_i = log sum_j exp(v_ij), with numerical accuracy."""
V_i = torch.max(v_ij, 1)[0].view(-1,1)
return V_i + (v_ij - V_i).exp().sum(1).log().view(-1,1) | 77,789 |
def get_instruments_filekinds(observatory, filepaths):
"""Given a list of filepaths return the mapping of instruments and
filekinds covered by the files.
"""
itmapping = defaultdict(set)
for filepath in filepaths:
instrument, filekind = get_file_properties(observatory, filepath)
itma... | 77,790 |
def all_reduce_max(
inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = None,
) -> Tensor:
"""
Create all_reduce_max operator for collective communication.
:param inp: input tensor.
:param group: communication group.
:param device: execution device.
:returns: reduced tensor... | 77,791 |
def set_vtk_celldata(grid, key, data):
"""Append cell data to the grid."""
vtk_type = vtk.VTK_INT if data.dtype == np.int64 else vtk.VTK_DOUBLE
vtkArray = numpy_to_vtk(data, array_type=vtk_type)
vtkArray.SetName(key)
grid.GetCellData().AddArray(vtkArray) | 77,792 |
def test_is_datasource_for(hmi_synoptic):
"""Test the is_datasource_for method of HMISynopticMap.
Note that header data to be provided as an argument
can be a MetaDict object, which in this case is
hmi.meta."""
assert hmi_synoptic.is_datasource_for(hmi_synoptic.data, hmi_synoptic.meta) | 77,793 |
def app(request):
"""
Displays default view for the app
:param request: HTTP Request
"""
request.session.flush()
results, search_query, message = [], None, None
if request.method == 'POST':
search_form = SearchForm(request.POST)
if search_form.is_valid():
query =... | 77,794 |
def has_roles(user):
"""Whether or not the user has any roles set in the system"""
return RoleAssignment.objects.filter(user=user).count() > 0 | 77,795 |
def get_output(interpreter, score_threshold):
""" Returns list of detected objects.
Args:
interpreter: Interpreter object.
score_threshold: score threshold.
Returns: bounding_box, class_id, score
"""
# Get all output details.
boxes = get_output_tensor(interpreter, 0)
class_id... | 77,796 |
def conversation_initiator_tally(user_name, msg_logs, scorecard_map):
"""
Give a bonus to the conversation initiator because that shows descent interest.
However, it's hard to differentiate a conversation initiator from a delayed response. So for now we use a simple
proxy:
1. if two messages from t... | 77,797 |
def miar_collect_journals():
"""collect miar info from all SourceRawData, save to files"""
MiarHarvesterManager.collect_journals() | 77,798 |
def _parse_args() -> argparse.Namespace:
"""
Creates an arg parser for AsciiQrCode and parses the supplied args.
:return: The parsed args.
"""
parser = argparse.ArgumentParser(description='Processes ASCII QR Codes.')
parser.add_argument('-v', '--verbose', action='store_true', default=False,
... | 77,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.