content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def mask_to_surface_type(ds, surface_type, surface_type_var="land_sea_mask"):
"""
Args:
ds: xarray dataset, must have variable slmsk
surface_type: one of ['sea', 'land', 'seaice', 'global']
Returns:
input dataset masked to the surface_type specified
"""
if surface_type == "gl... | 0ee07b852c142d0041841288c54bbc68afdd65f8 | 16,108 |
def clip(value, lower, upper):
""" clip a value between lower and upper """
if upper < lower:
lower, upper = upper, lower # Swap variables
return min(max(value, lower), upper) | c7324ecd1e6e734a613071c26c2c00c33d2c487e | 16,112 |
import asyncio
async def do_after_sleep(delay: float, coro, *args, **kwargs):
"""
Performs an action after a set amount of time.
This function only calls the coroutine after the delay,
preventing asyncio complaints about destroyed coros.
:param delay: Time in seconds
:param coro: Coroutine t... | 913998318c8438b2afaf9fcb6e687c4e4a8149e6 | 16,115 |
from typing import Dict
def extract_tags(repo_info: Dict) -> Dict:
"""Extracts the tags from a repository's metadata.
Args:
repo_info: The repository's metadata.
Returns:
The repository's tags.
"""
tags = {}
repo_tags = repo_info.get("tags")
if repo_tags:
for repo... | 108e343a84e7a076a6d42e4a3c2cdf0c12389e6b | 16,117 |
def xgcd(a: int, b: int) -> tuple:
"""Extended Euclidean (GCD) algorithm
gcd(a, b) = u*a + v*b
Returns gdc, u, v
"""
x, x1, y, y1 = 1, 0, 0, 1
while b:
q, a, b = a // b, b, a % b
x, x1 = x1, x - q * x1
y, y1 = y1, y - q * y1
return a, x, y | 3dba9fee305f2c423f84607177ca1b9025d33978 | 16,118 |
def flatten(data):
"""Recursively flatten lists"""
result = []
for item in data:
if isinstance(item, list):
result.append(flatten(item))
else:
result.append(item)
return result | bb4a7a91f921f67bed3d70e74246e1cc8eec825c | 16,120 |
def get_train_test_modifiers(modifier=None):
"""Append the modifier to 'train' and 'test'"""
modifier_train = 'train'
modifier_test = 'test'
if modifier is not None:
modifier_train = modifier_train + '_' + modifier
modifier_test = modifier_test + '_' + modifier
return modifier_train,... | 6adb8e2a6bb427de059ef7cd127476342ba39a3f | 16,123 |
def logp_gradient(variable, calculation_set=None):
"""
Calculates the gradient of the joint log posterior with respect to variable.
Calculation of the log posterior is restricted to the variables in calculation_set.
"""
return variable.logp_partial_gradient(variable, calculation_set) + sum(
... | 8c1dd9207e1c08826d51053cb887a86d06306367 | 16,124 |
def mock_db_url(tmpdir):
"""Fixture to provide mock db url
This url is intended to be the location of where to place the local sqlite
databases for each unit test"""
dbname="dcae_cli.test.db"
config_dir = tmpdir.mkdir("config")
return "/".join(["sqlite://", str(config_dir), dbname]) | a6f06b15edfb685ebb0ff38ae421091f06039563 | 16,125 |
def reproject_extent(extent, current_extent):
"""
Changes an extent from its current spatial reference to the spatial reference on another extent object
:param extent:
:param current_extent:
:return:
"""
return extent.projectAs(current_extent.spatialReference) | b64e98c15cda62e1a4855050a63b7ff7fcd38610 | 16,129 |
def _get_feature_help(module: object) -> str:
"""
Get the docstring of the imported module
:param module: the imported module object
:return: The docstring as string
"""
return module.__doc__ or "[ERROR] Missing the module docstring" | 804f3586137adf7a22231225bd326fff2fcbd704 | 16,130 |
def get_model_parameters(model):
"""FUNCTION::GET_MODEL_PARAMETERS: Gets all the parameters of a model.
---
Arguments:
---
>- model {keras.Model} -- The model to analyze.
Returns:
---
>- {list[string]} -- layer Names
>- {list[np.array]} -- layer Weights
>- {list[tensor]} -- layer Outputs
>- {list[t... | 96341de438b0359425381ebed400ab38da35304a | 16,132 |
def two_letter_language_code(feed):
"""
feed.language conforms to
http://www.rssboard.org/rss-language-codes
sometimes it is of the form de-de, de-au providing a hint of dialect
thus, we only pick the first two letters of this code
:param feed:
:return:
"""
return fe... | f4da54d15e73a1c317a90cce08de4a44d55ae273 | 16,135 |
from typing import Type
import importlib
def _string_to_class(string: str) -> Type:
"""
Parse a string into a Python class.
Args:
string: a fully qualified string of a class, e.g. 'mypackage.foo.MyClass'.
Returns:
The class.
"""
components = string.split(".")
class_name =... | e756b35a5d34aaeffa8ddc4e96130da3a3bc5d04 | 16,137 |
def roundup(val, width):
"""roundup a value to N x width-bits"""
x = (width >> 3) - 1
return (val + x) & ~x | 45a303ca8f2ba5312fe89e73542606dbe68ed627 | 16,142 |
def sum_keep_digits(m: int, n: int, digit_count: int) -> int:
"""Finds the last base-10 digits of the sum of two non-negative integers.
Args:
m: The first non-negative integer addend.
n: The second non-negative integer addend.
digit_count: The number of least significant digits of the r... | c09bf6a9bf681deae133bb787e2f1b50711dd24a | 16,150 |
def split_layouts_by_arrow(s: str) -> tuple:
"""
Splits a layout string by first arrow (->).
:param s: string to split
:return: tuple containing source and target layouts
"""
arrow = s.find('->')
if arrow != -1:
source_layout = s[:arrow]
target_layout = s[arrow + 2:]
... | 30781f9a5d7b8b342c2a7d9fefb2085b2e990994 | 16,157 |
import pathlib
def parse_bind_volume(bind_arg):
"""unpack volume bind bind_arg (e.g., /foo:/bar) to dict where the key is a
resolve pathlib.Path and the value is an unresolved (in-container)
pathlib.PosixPath."""
# can be up to three, but we only want the first two
bind_arg = bind_arg.split(":")
... | ea2b4ac8ba03e3829ab4db69684ebf49767e0c94 | 16,158 |
def strip_lines(s, side='r'):
"""
Splits the given string into lines (at newlines), strips each line
and rejoins. Is careful about last newline and default to stripping
on the right only (side='r'). Use 'l' for left strip or anything
else to strip both sides.
"""
strip = (str.rstrip if side ... | 4995710e9df31e7e210621b3f9be0af38642324e | 16,160 |
def _draw_bbox_pil(canvas, bbox, color, stroke):
"""Draws BBox onto PIL.ImageDraw
:param bbox: BBoxDiim
:param color: Color
:param stroke: int
:returns PIL.ImageDraw
"""
xyxy = bbox.xyxy_int
if stroke == -1:
canvas.rectangle(xyxy, fill=color.rgb_int)
else:
canvas.rectangle(xyxy, outline=color.... | a5dd958cd18a9f9129567af55d5057b105d4fe59 | 16,162 |
def _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit):
""" Constructs dict with URL params
:param tile_id: original tile identification string provided by ESA (e.g.
'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01')
:type tile_id: str
:param bbo... | 029d6b2ecd0871fde521a98d3edb09f2a6bf947b | 16,164 |
def padding_string(pad, pool_size):
"""Get string defining the border mode.
Parameters
----------
pad: tuple[int]
Zero-padding in x- and y-direction.
pool_size: list[int]
Size of kernel.
Returns
-------
padding: str
Border mode identifier.
"""
if pad ... | 985828faf9c072b623776be23e8ef0b7c680aba8 | 16,166 |
def apply_eqn(x, eqn):
"""
Given a value "x" and an equation tuple in the format:
(m, b)
where m is the slope and b is the y-intercept,
return the "y" generated by:
y = mx + b
"""
m, b = eqn
return (m * x) + b | 1d5078905a20e6b83c2186f6aefbedaa70863fea | 16,167 |
def ext_euclid_alg (m, n):
""" Extended Euclidean algorithm for gcd.
Finds the greatest common divisor of
two integers a and bm and solves for integer
x, y such that ax + by = 1. From Knuth, TAOCP
vol. I, p. 14.
Variables --
q, r -- quotient and remainder
a, b -- am + bn = gcd
... | f6ee18c045dd6c26023ff70ab43dde550071023c | 16,168 |
import torch
def get_prior_precision(args, device):
""" Obtain the prior precision parameter from the cmd arguments """
if type(args.prior_precision) is str: # file path
prior_precision = torch.load(args.prior_precision, map_location=device)
elif type(args.prior_precision) is float:
prior... | b3a34d3831c42b490f1750c47de06743e5ff0b8a | 16,170 |
def to_redfish_version(ver32):
"""
Converts a PLDM ver32 number to a Redfish version in the format vMajor_Minor_Errata
"""
if ver32 == 0xFFFFFFFF: # un-versioned
return ''
else:
return 'v'+str((ver32 >> 24) & 0x0F)+'_'+str((ver32 >> 16) & 0x0F)+'_'+str((ver32 >> 8) & 0x0F) | 56ccd29c01b7307fa8ee47ae5e7fa4fb89163523 | 16,185 |
def restrictToHostsOnCurrentStage(statsboardData, hostsOnCurrentStage):
"""
Removes data for hosts not on current stage from statsboardData, and
returns the new version.
:param statsboardData:
:param hostsOnCurrentStage:
:return:
"""
# NOTE: can be optimized if necessary.
newData =... | 740f2c55a14472c36b3f6109fe2e89ef5880e04b | 16,187 |
def POUF_unblind(params, ai, zi):
""" Unblind the messages to recover the raw outputs of the POUF """
G, g, o = params
xi = [a.mod_inverse(o) * z for a,z in zip(ai, zi)]
return xi | 2fb5d1e2d758422dd7df9ff16baa1c834e320f7b | 16,188 |
from typing import List
def align_lines(lines: list, column_separator: str = "|") -> List[str]:
"""
Pads lines so that all rows in single column match. Columns separated by '|' in every line.
:param lines: list of lines
:param column_separator: column separator. default is '|'
:return: list of lin... | 2ec537752bfce3d261d7202e9b9266a9ae0dd87f | 16,189 |
from typing import SupportsIndex
def ireplace(text: str, old_: str, new_: str, count_: SupportsIndex = -1) -> str:
"""Case-insensitive :py:meth:`str.replace` alternative.
:param text: String to search through.
:param old_: Case-insensitive substring to look for.
:param new_: Case-sensitive substring ... | 8509314192458c867b6471a381dc6470a2546902 | 16,192 |
def alpha(requestContext, seriesList, alpha):
"""
Assigns the given alpha transparency setting to the series. Takes a float value between 0 and 1.
"""
for series in seriesList:
series.options['alpha'] = alpha
return seriesList | 25ef9bad1b39549585bdb175e487236591d0816f | 16,194 |
def ask_yes_no_question(question):
"""Prints a question on the CLI that the user must respond
with a yes or no.
:param question: Text of the question. Include question mark on it.
:type question: str
:return: Whether the user said 'y' (True) or 'n' (False).
:rtype: bool
"""
answer = ''
... | 6a70b135879e0fcd27ba6bc7fbc330a0660bd729 | 16,196 |
def akmcsInfocheck(akmcsInfo):
""" Helper function to check the AKMCS dictionary.
Checks akmcsInfo dict and sets default values, if required
parameters are not supplied.
Args:
akmcsInfo (dict): Dictionary that contains AKMCS information.
Returns:
akmcsInfo: Checked/Modified AKMCS ... | 5e70785cb2c6050f9e10b8936e64ed19b71cf4d5 | 16,204 |
def is_null(value, replace: str = ""):
"""
Checks if something is empty and will replace it with the given value
Parameters
----------
value
A thing to check if empty
replace : string
The thing to replace it with
"""
return value if value else replace | ae81cf7842de03653b7496984f577d67c3edecf2 | 16,205 |
def mean(values):
"""
Mean function.
"""
m = 0.0
for value in values:
m = m + value/len(values)
return m | 4415b4f9aa373b54418683301ffe751249270d4c | 16,207 |
def set_pianoroll_shape(pianoroll, data_shape):
"""Set the pianoroll shape and return the pianoroll."""
pianoroll.set_shape(data_shape)
return pianoroll | ca326624a83252411aa996b31bd6cfd8dd6c5baa | 16,209 |
def evs_to_policy(search_policy_evs, *, temperature=1.0, use_softmax=True):
"""Compute policy targets from EVs.
Args:
search_policy_evs: Float tensor [T, B, 7, max_actions]. Invalid values are marked with -1.
temperature: temperature for softmax. Ignored if softmax is not used.
use_soft... | 46ac6e9fee0a8c010aef23519cbc594f0c0eb09d | 16,210 |
def extract_list (data_str, to_float=False):
""" Extract a list of floating point values from a string
"""
split_str = data_str.split(',')
if to_float == True:
split_str = [float(x) for x in split_str]
return split_str | 09825f9d7533bfbe9812bd6956b096cc33cb0be1 | 16,211 |
def prompt(message, values=None):
"""Prompt a message and return the user input.
Set values to None for binary input ('y' or 'n'), to 0 for integer input, or to a list of possible inputs.
"""
if values is None:
message += ' (y/n)'
message += ' > '
while 1:
ans = input(message)
... | 4d6b87b84ed1dfd95722e0055a8df3b1b34f1e84 | 16,212 |
def words_vec(w2v, words, use_norm=False):
"""
Return a dict that maps the given words to their embeddings.
"""
if callable(getattr(w2v, 'words_vec', None)):
return w2v.words_vec(words, use_norm)
return {word: w2v.wv.word_vec(word, use_norm) for word in words if word in w2v.wv} | 46447f389800e36d7149da245fb0d38be24bbbe3 | 16,213 |
import asyncio
def in_async_call(loop, default=False):
"""Whether this call is currently within an async call"""
try:
return loop.asyncio_loop is asyncio.get_running_loop()
except RuntimeError:
# No *running* loop in thread. If the event loop isn't running, it
# _could_ be started ... | 9ed888e0d8ee27d18c843a184071d9596880c039 | 16,216 |
def dictlist_lookup(dictlist, key, value):
"""
From a list of dicts, retrieve those elements for which <key> is <value>.
"""
return [el for el in dictlist if el.get(key)==value] | 94e90b29c8f4034357be2b8683115f725c24b374 | 16,218 |
def df_to_geojson(df, geometry, coordinates, properties):
"""
Convert a pandas DataFrame to a GeoJson dictionary.
Parameters
----------
df : pandas DataFrame
DataFrame containing the geojson's informations.
geometry : String
The type of the geometry (Point, Polygon, etc.).
c... | 75fa808dca18b89e2e259425b9b9e67bb8ac2415 | 16,221 |
def get_bytes(block_nums):
"""
Takes an array of block integers and turns them back into a bytes object.
Decodes using base 256.
:param block_nums: Blocks (list of ints)
:return: Original data (bytes)
"""
message = []
for block in block_nums:
block_text = []
while bloc... | 429325cd37a3f821b751237659626907eb19d4a9 | 16,222 |
def check_positive_int(string):
"""Convert a string to integer and check if it's positive.
Raise an error if not. Return the int.
"""
if int(string) > 0:
return int(string)
else:
raise RuntimeError("Integer must be positive.") | 1e32994a2d9d58b1361a9228b78210398c19c94e | 16,225 |
def clamp_value(my_value, min_value, max_value):
"""Limit value by min_value and max_value."""
return max(min(my_value, max_value), min_value) | f3478b08f3e2e38ba3459d487adc9c462468c32e | 16,226 |
def _buses_with_gens(gens):
"""
Return a list of buses with generators
"""
buses_with_gens = list()
for gen_name, gen in gens.items():
if not gen['bus'] in buses_with_gens:
buses_with_gens.append(gen['bus'])
return buses_with_gens | 5cf9e918a55e140053bceb538cd1f15b331c253d | 16,229 |
import hashlib
def get_key(model_params, mw_range, bins):
"""
Generate a hash key based on the model parameters used and the fited
mw_range and number of bins.
"""
hasher = hashlib.md5()
hasher.update(bytes(str(model_params), 'ASCII'))
hasher.update(bytes(str(mw_range), 'ASCII'))
hashe... | 50fe5d13bf9f897c76ee144c576212ec483e1948 | 16,230 |
from typing import Any
import hashlib
def md5(item: Any) -> str:
"""Compute the MD5 hash of an object.
Args:
item:
The object to compute the MD5 hash on.
Returns:
The MD5 hash of the object.
"""
return hashlib.md5(str(item).encode()).hexdigest() | 5589eb0a38b9f099a7f4b418d719b9c089110d5a | 16,237 |
def SortLists(sortbylist,otherlists,reverse=False):
"""This function sorts lists similar to each list being a column
of data in a spreadsheet program and choosing one column to sort
by.
The sortbylist is the column or list that you wish to sort by and
otherlists is a list of the other lists or colu... | 132678fa35f008e4f987ffca57e729840438ca72 | 16,244 |
from typing import Any
def is_json_string(value: Any) -> bool:
"""Check if the provided string looks like json."""
# NOTE: we do not use json.loads here as it is not strict enough
return isinstance(value, str) and value.startswith("{") and value.endswith("}") | 16418c37fc1d348e4d1e5805c485f181e514d537 | 16,249 |
def get_filediff_encodings(filediff, encoding_list=None):
"""Return a list of encodings to try for a FileDiff's source text.
If the FileDiff already has a known encoding stored, then it will take
priority. The provided encoding list, or the repository's list of
configured encodingfs, will be provided a... | 5c951bbc6266daa058de58bdeb1382ea6dc93ada | 16,254 |
def get_group_command_url(environment: str,
enterprise_id: str,
group_id: str) -> str:
"""
Build and return pipeline url for scapi endpoint
:param environment:
:param enterprise_id:
:param group_id:
:return: Url
"""
url = f'https://{env... | 34402dbe263ddd5cd4b04b247beb09701f2b2cc6 | 16,256 |
def mutate_query_params(request, mutations):
"""
Return a mutated version of the query string of the request.
The values of the `mutations` dict are interpreted thus:
* `None`, `False`: Remove the key.
* Any other value: Replace with this value.
:param request: A HTTP request.
:type reque... | 215a79ce82859eb415454876c1c80cdfdb34d7f6 | 16,257 |
import math
import random
def Move(Location, xT):
"""
This function will return the new location (as a tuple) of a particle after it has
isotropically scattered
Location: Location of particle before scattering
xT: Total cross section of medium
"""
# Sample distance to collision
Distan... | 5902de845db37e5848fbf64954f971fcdce60c89 | 16,258 |
def get_color(col, color):
"""Function needed for backwards compatibility with the old "col" argument in
plt functions. It returns the default color 'C0' if both arguments are None.
If 'color' is not None, it always uses that. If 'color' is None and
'col' is an integer, it returns the corresponding 'CN... | b4e7cbeacca0e730cb2fa5f320318da83cabfc1a | 16,261 |
def stations_by_river(stations):
"""Creates a dictionary of stations that are located on the same river. The river is the key for this dictionary"""
river_dictionary = {}
for i in stations:
station_list = []
for j in stations:
if i.river == j.river:
station_list.a... | cf6d324c10ecb756dfa4c506adbbd16316a0d500 | 16,267 |
def get_margin(length):
"""Add enough tabs to align in two columns"""
if length > 23:
margin_left = "\t"
chars = 1
elif length > 15:
margin_left = "\t\t"
chars = 2
elif length > 7:
margin_left = "\t\t\t"
chars = 3
else:
margin_left = "\t\t\t\t"... | c50b1253a737d787f696216a22250fb2268216ab | 16,275 |
def unique_list(it):
"""
Create a list from an iterable with only unique element and where
the order is preserved.
Parameters
----------
it : iterable
Items should be hashable and comparable
Returns : list
All items in the list is unique and the order of the ite... | 5122b3fdb7a489df856ad6ff4a17da58a99a8160 | 16,277 |
def f4(x):
"""Evaluate the estimate x**4+x**3+x**2+x."""
return x*(x*(x*x+x)+x)+x | 6a5e258d77992e8c15a6dddb04627a7d5c8467d9 | 16,278 |
import re
def _is_private_name(name):
""" Return true if the given variable name is considered private.
Parameters
----------
name : str
Variable name to check
"""
# e.g. __name__ is considered public.
is_reserved_public_name = re.match(r"__[a-zA-Z0-9_]+__$", name) is not None
... | 1232f6a52ffc9d07d7ed286771c3c75bc80db8b7 | 16,280 |
import shlex
def shell_join(argv, delim=" "):
"""Join strings together in a way that is an inverse of `shlex` shell parsing into `argv`.
Basically, if the resulting string is passed as a command line argument then `sys.argv` will equal `argv`.
Parameters
----------
argv : list(str)
List ... | d58fb2d899bc1f72adf0dd22bdc55ddc9ffeecfb | 16,282 |
def inverted_index_add(inverted, doc_id, doc_index):
"""
Add Invertd-Index doc_index of the document doc_id to the
Multi-Document Inverted-Index (inverted),
using doc_id as document identifier.
{word:{doc_id:[locations]}}
"""
for word, locations in doc_index.items():
indices = in... | 4ef0cad9892a09dfaeb730487f413836ba72b7d3 | 16,283 |
def append(xs, ys):
"""
Adds all the elements of xs and ys and returns a combined list.
"""
return xs + ys | e629ece09214a88465d780bb82f2b6f1a82af18a | 16,289 |
import re
def get_all_text(elem):
"""Returns all texts in the subtree of the lxml.etree._Element, which is
returned by Document.cssselect() etc.
"""
text = ''.join(elem.itertext())
return re.sub(r'\s+', ' ', text).strip() | 1c8e2e8743147fd3b09488445d8578a89f5346d7 | 16,294 |
def _collect_mexp_symbols(value):
"""Get symbols in a math expression.
:param value: The math expression.
:rtype : list of str
:return: A list of symbols.
"""
# Get symbols.
fsm = value.free_symbols
# Initialize symbol list.
ret = []
# Pop symbols.
while len(fsm) != 0:... | c031212e3af5bd485dc572c4cf9bb31cfc2be3db | 16,297 |
def _inBoundaries(value, bounds):
"""
Tell if an integer value is within a range.
Parameters
----------
value : int
A value to be tested.
bounds : int | tuple(int, int)
Low boundary of the range, or a tuple of the form (low, high+1).
Returns
-------
boolean
... | dcc9fcf993ee7b25bb0f6b8cb8acea7b0474fad5 | 16,298 |
def has_neighbor(prop1: str, prop2: str) -> str:
"""
Builds the statements required for: The person who `prop1` has a neighbor who `prop2`.
For example, "The Norwegian lives next to the Blue house."
We can solve this by doing a disjunction of all satisfying possibilities. Because we've
previously s... | d63dd6e09ce822cdcd87970dd205ee34857ad8f4 | 16,300 |
def bl_little_mock(url, request):
"""
Mock for bundle lookup, small output.
"""
littlebody = b'<?xml version="1.0" encoding="UTF-8"?><availableBundlesResponse version="1.0.0" sessionId="7762de1a-909c-4afb-88fe-57acb69e9049"><data authEchoTS="1366644680359"><status code="0"><friendlyMessage>Success</frie... | 0b35d1e30c32b89351341103ba9013ca95c0ba2e | 16,307 |
from typing import Optional
def _transform_op(op: Optional[str]) -> str:
"""Transforms an operator for MongoDB compatibility.
This method takes an operator (as specified in a keyword argument) and transforms it
to a ``$`` prefixed camel case operator for MongoDB.
"""
if op is None:
return... | 6168e84387ade258b2907445e5d3536228053521 | 16,309 |
def stop_server(proc):
"""
Stop server process.
proc: ShellProc
Process of server to stop.
"""
return proc.terminate(timeout=10) | c126ca840b56407f1eea8af943f4602532df13df | 16,318 |
def get_oct(value):
"""
Convert an integer number to an octal string.
"""
try:
return oct(value)
except:
return value | 0e07b02f7a727c5942c1f6f1d7d1ca12506328f4 | 16,327 |
import torch
def compute_distance_histograms(a, dx, b, dy):
"""
Computes the squared distance between histograms of distance of two
mm-spaces. The histograms are obtained by normalising measures to be
probabilities.
Parameters
----------
a: torch.Tensor of size [Batch, size_X]
Input m... | 7758c15cea89d9eabba2fbf95decd6252bec532d | 16,329 |
def gather_3rd(params, indices):
"""Special case of tf.gather_nd where indices.shape[-1] == 3
Check https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/gather_nd
for details.
Args:
params: Tensor, shaped [B, d_1, ..., d_i], di >= 2
indices: LongTensor, shaped [B, i_1, ... | 948acdbb83b283cc0bef743d679e7d30fbaa0ad6 | 16,330 |
def apply_date_format(in_data):
""" This routine adds the default UTC zone format to the input date time string
If a timezone (strting with + or -) is found, all the following chars
are replaced by +00, otherwise +00 is added.
Note: if the input zone is +02:00 no date conversion is done,
at th... | 2a9cd63f1b0a341c3c859d80b538af5ecf56d21d | 16,332 |
def near(array, value):
"""Find the nearest point within the array and return its index"""
idx = (abs(array - value)).argmin()
return idx | 0e683e8a94a54cd4e53f6d147ca8d4d907ec84c2 | 16,338 |
import time
def bench_from_sample( distribution, sample, n=1000 ):
"""Bench the training of a probability distribution."""
tic = time.time()
for i in range(n):
distribution.summarize( sample )
return time.time() - tic | c9d97badda06a9b5340dc360e1ba7d043a6e2c29 | 16,339 |
def packal_username(author):
"""Format usernames for Packal."""
user = author.lower()
user = user.replace(" ", "-")
return user | c8f9c5ab67deb95775a787a5cb8cceab67ea73f1 | 16,341 |
def _get_all_nearest_neighbors(method, structure):
"""Get the nearest neighbor list of a structure
Args:
method (NearNeighbor) - Method used to compute nearest neighbors
structure (IStructure) - Structure to study
Returns:
Output of `method.get_all_nn_info(structure)`
"""
re... | 5e1e33c7b06951933d8603a75006c6895b742293 | 16,345 |
def rolling_average(n, data):
"""
Function to calculate an n day rolling average given a list of covid data pts
@param n: an int representing the number of points to average into the past
@param data: a list of dictionaries representing covid data pts
@return: the n day death, death increase, infec... | ba02b006176d8b37ed53e5f2cd46c64a92b7dcc2 | 16,353 |
def checkPW(md5str: str, USER_PASSWD: str):
"""检查本地数据库中密码和计算后的密码是否一致
:param md5str: 计算后的密码(字符串)
:param USER_PASSWD: 本地的存的密码(字符串)
:return: bool
"""
return md5str == USER_PASSWD | 2bbe3864493700ff907b00ff9f82c45723e1a2d7 | 16,355 |
def count_letters(word,find):
"""
Example function with types documented in the docstring.
Ce code doit retourner le nombre d'occurences d'un caractère passé en paramètre dans un mot donné également
Parameters
----------
param1 : str
Le 1er paramètre est une chaine de caractères
param2 : char
Le 2ème para... | 327e6b4fd99d03b27473b9620d6147909d0cf6e4 | 16,357 |
def one_space(value):
""""Removes empty spaces, tabs and new lines from a string and adds a space between words when necessary.
Example:
>>> from phanterpwa.tools import one_space
>>> one_space(" My long \r\n text. \tTabulation, spaces, spaces. ")
'My long text. Ta... | ff3ce941437186c734bd2815fff9d23ba581bec7 | 16,360 |
def small_push_dir(tmpdir):
"""Create a small pg data directory-alike"""
contents = 'abcdefghijlmnopqrstuvwxyz\n' * 10000
push_dir = tmpdir.join('push-from').ensure(dir=True)
push_dir.join('arbitrary-file').write(contents)
# Construct a symlink a non-existent path. This provoked a crash
# at o... | 6f3fa0f6b291f4d18a8f33624ad55045c45b7261 | 16,361 |
def create_cmnd(
analysis, sim_start_date, sim_end_date, use_sim_manager, attributes, no_close
):
"""Create a command string for automatic processing."""
args = []
if use_sim_manager:
args.append("UseSimManager")
if sim_start_date:
args.append(f"SimStartDate {sim_start_date[0]} {si... | b95fc466a9c61a125bf09d6fc5dd77bf4575756d | 16,365 |
def SplitCoordinates(xyz_str):
"""
Function to split coord. str in float list
xyz_str: (str) a list input of "x,y,z" coordinates
"""
xyz = []
for i in range (len(xyz_str)):
x_,y_,z_ = xyz_str[i].split(",")
xyz.append([float(x_),float(y_),float(z_)])
return(xyz) | 808a3c73783d8f36a2ecd70d128fca49fc7f7e1e | 16,368 |
def vectorOFRightDirection(OFvect, FOE):
"""Returns True if OF vector is pointing away from the FOE, False otherwise."""
# Get points of optical flow vector
a1, b1, c1, d1 = OFvect
# If left side of FOE
if a1 <= FOE[0]:
if c1 <= a1:
return False
# If right side of FOE
el... | febe984f172ffbcf6557bbad0829d52e83c94dd7 | 16,372 |
def get_best_model(comparison_result, metric="fmeasure", reverse=False):
"""
Returns the model row in dataframe which has the best performance on a given metric
:param comparison_result: a dataframe containing evaluation info about various models
:param metric: metric on which a comparison is be made,... | fd4deb629386c537b59552528e99ee27391d7aa3 | 16,374 |
import re
def is_timeline_speed_request(text):
"""
Returns true if the specified text requests the home timeline speed.
"""
tlspeed_re = '流速'
return not re.search(tlspeed_re, text) is None | 9c14ed5f095043dd02aa8fc254a45e702925eeef | 16,376 |
def wprota(self, thxy="", thyz="", thzx="", **kwargs):
"""Rotates the working plane.
APDL Command: WPROTA
Parameters
----------
thxy
First rotation about the working plane Z axis (positive X toward
Y).
thyz
Second rotation about working plane X axis (positive Y toward ... | ef0dd188ad663d190f85490d9229d28bdb5b3fce | 16,379 |
from typing import List
import itertools
def generate_combinations(urls: List[str], params: List[dict]) -> List[tuple]:
"""
Private method to combine urls and parameter
dictionaries in tuples to pass to the download
method.
Args:
- urls (List[str]): list of urls
- params (List[dic... | 4e24e85a49a685c810b3d4089886abac7c785bfb | 16,383 |
from typing import Union
from typing import Tuple
from typing import List
from typing import Any
def deep_tuple_to_list(inp: Union[Tuple, List]) -> List[Any]:
"""Transform a nested tuple to a nested list.
Parameters
----------
inp: Union[Tuple, List]
The input object.
Returns
-------... | 770b4f653b734ecd2caf1d6b56ac090e4ffe3208 | 16,387 |
from pathlib import Path
from typing import Dict
import json
def make_temporary_features_json(
make_temporary_folders_and_files: Path,
test_input_json: Dict,
test_input_json_filename: str,
) -> Path:
"""Make a temporary features JSON file."""
# Define the list of folders and filenames for possibl... | 5e7274e33d5ca6cda29798c6e80f782129788a9b | 16,388 |
def word16be(data):
"""return data[0] and data[1] as a 16-bit Big Ended Word"""
return (data[1] << 8) | data[0] | 4f9c05993980ed95ffdd6fe26389a9025c41f7c9 | 16,389 |
def is_latitude_norther_than(lat_a, lat_b):
"""
Check if lat_a is norther than lat_b
"""
is_latitude_a_negative = lat_a < 0
is_latitude_b_negative = lat_b < 0
same_sign = is_latitude_a_negative == is_latitude_b_negative
if not is_latitude_a_negative and is_latitude_b_negative:
r... | 290c0a4f298290bb375170c6748515b7a7218d95 | 16,392 |
from typing import Tuple
from typing import List
def get_metadata(description: str) -> Tuple[str, List[str], str]:
"""Returns a tuple of (description, tags, category) from a docstring.
metadata should be of the form key: value, e.g. category: Category Name"""
tags: List[str] = []
category: str = ""
... | 21e28d7a3c802d2513f2bf8eaeccc215070a2e24 | 16,394 |
def get_repo_dicts(r):
"""Return a set of dicts representing the most popular repositories."""
response_dict = r.json()
repo_dicts = response_dict['items']
return repo_dicts | 822a0dc0674b2eda5210fdd88257d894c3dc902c | 16,398 |
def _partition(array, low, high):
"""Choose the first element of `array`, put to the left of it
all elements which are smaller, and to the right all elements which
are bigger than it.
Return the final position of this element.
"""
if low >= high:
return
i = low + 1
j = high
... | 89f23c2e0c14c9a516e8b895e888936773fbfe94 | 16,400 |
def db_to_power(decibel):
"""
Returns power value from a decibel value.
"""
return 10**(decibel/10) | 5188d8d646f2421546cf894ad45d2bdd30d97e53 | 16,402 |
def _get_rid_for_name(entries, name):
"""Get the rid of the entry with the given name."""
for entry in entries.values():
if entry['name'] == name:
return entry['rid']
raise ValueError(u'No entry with name {} found in entries {}'.format(name, entries)) | 0791f3185404ca59417fd9196467c8aef69c429c | 16,404 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.