content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calc_easter(year):
"""
Returns Easter as a date object. Because Easter is a floating mess
year - the year to calc easter for
"""
a = year % 19
b = year // 100
c = year % 100
d = (19 * a + b - b // 4 - ((b - (b + 8) // 25 + 1) // 3) + 15) % 30
e = (32 + 2 * (b % 4) + 2 * (c /... | 5,319,200 |
def MACDFIX(ds, count, signalperiod=-2**31):
"""Moving Average Convergence/Divergence Fix 12/26"""
ret = call_talib_with_ds(ds, count, talib.MACDFIX, signalperiod)
if ret == None:
ret = (None, None, None)
return ret | 5,319,201 |
def create_dataset(form_data, params=None, use_doi=False):
"""
Create dataset in Metax.
Arguments:
form_data {object} -- Object with the dataset data that has been validated and converted to comply with the Metax schema.
params {dict} -- Dictionary of key-value pairs of query parameters.
... | 5,319,202 |
def charge_from_grid(rate_to_charge):
""" import power from grid
Keyword arguments: rate to charge
"""
if (config.PROD):
client.write_register(2703, int(rate_to_charge*0.01 if rate_to_charge > 0 else 1000))
logging.info(f"Importing from Grid @ {rate_to_charge} KwH" )
return | 5,319,203 |
def blrPredict(W, data):
"""
blrObjFunction predicts the label of data given the data and parameter W
of Logistic Regression
Input:
W: the matrix of weight of size (D + 1) x 10. Each column is the weight
vector of a Logistic Regression classifier.
X: the data matri... | 5,319,204 |
def _compare_objects(obj1, obj2):
"""
FIXME:
CALL: print(f'compare_objects (ops2,operations): {_compare_objects (ops2,operations)}')
DEBUG Helper to compare 2 numpy arrays
"""
result = (obj1 == obj2).all()
return result | 5,319,205 |
async def log(log_text):
""" Untuk perintah .log, meneruskan pesan atau argumen perintah ke grup log botp """
if BOTLOG:
if log_text.reply_to_msg_id:
reply_msg = await log_text.get_reply_message()
await reply_msg.forward_to(BOTLOG_CHATID)
elif log_text.pattern_match.group... | 5,319,206 |
def mds_torch(pre_dist_mat, weights=None, iters=10, tol=1e-5, verbose=2):
""" Gets distance matrix. Outputs 3d. See below for wrapper.
Assumes (for now) distrogram is (N x N) and symmetric
Outs:
* best_3d_coords: (3 x N)
* historic_stress
"""
if weights is None:
we... | 5,319,207 |
def get_pair(expr, index):
"""Get the field of an expression using python syntax
Arguments:
- `expr`: an expression
- `index`: an integer equal to 0 or 1
"""
if index == 0:
return Fst(expr)
elif index == 1:
return Snd(expr)
else:
raise Exception("Index applie... | 5,319,208 |
def plot_logs(path, outpath, key="loss"):
# TODO: add log-scale, annotations, smoothing
"""Plot logs from a .sqlite database."""
events, logs, val_logs = get_logs(path)
sns.set()
plt.clf()
if key in logs.keys():
sns.lineplot(x="step", y=key, data=logs)
if key in val_logs.keys():
... | 5,319,209 |
def get_standardized_layers(hparams, dp=None, ps_devices=None):
"""Get the common attention and feed-forward layers.
The returned layer functions will have the following signature:
y, extra_loss = fct(x)
extra_loss is set to 0.0 if the layer doesn't have extra loss.
If dp is provided, the layers will be ... | 5,319,210 |
def row_contains_data(fieldnames, row):
"""Returns True if the value of atleast on of the fields is truthy"""
for field in fieldnames:
if row.get(field):
return True
return False | 5,319,211 |
def create_model(name, batch_size, learning_rate = 0.0001, wd = 0.00001, concat = False, l2_loss = False, penalty = False, coef = 0.4, verbosity = 0):
"""
Create a model from model.py with the given configuration
Args:
name : name of the model (used to create a specific folder to save/load para... | 5,319,212 |
def fs(path:str, mode:Mode='rb'):
"""Opens file locally or via s3 depending on path string."""
s3 = s3fs.S3FileSystem()
return partial(
{True: s3.open, False: open}[is_s3_path(path)],
mode=mode
)(path) | 5,319,213 |
def create_logger(log_file):
""" Zack's Generic Logger function to create onscreen and file logger
Parameters
----------
log_file: string
`log_file` is the string of the absolute filepathname for writing the
log file too which is a mirror of the onscreen display.
Returns
... | 5,319,214 |
def reformat(inName, outName):
"""Transform spreadsheet format into database format"""
print "Processing %s to %s" % (inName, outName)
inFile = open(inName)
outFile = open(outName, "w")
while 1:
line = inFile.readline()
if line == '':
break
(rowCol, row, col, name, seq, seqSize, prodS... | 5,319,215 |
def test_pathcheck_single_with_formatting():
"""Single path ok with string formatting."""
context = Context({
'ok1': 'arb',
'pathCheck': './tests/testfiles/glob/{ok1}.3'})
pathchecker.run_step(context)
assert context, "context shouldn't be None"
assert len(context) == 3, "context s... | 5,319,216 |
def test_to_gbk(encode_str, py_version):
"""Test str_to_unicode, we can get a expected type."""
result = utils.to_gbk(encode_str, py_version)
assert isinstance(result, str) | 5,319,217 |
def _check_stop_list(stop):
"""
Check stop words list
ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95
"""
if stop == "thai":
return THAI_STOP_WORDS
elif isinstance(stop, six.string_types):
raise ValueError("not a built-in s... | 5,319,218 |
def bound_spectral_radius(arr, bound=1.2):
"""Set the spectral radius of the square matrix ``arr`` to ``bound``.
This is performed by making an Eigendecomposition of ``arr``, rescale all
Eigenvalues such that the absolute value of the greatest matches ``bound``
and recompose it again.
Parameters
... | 5,319,219 |
def boxplot_dict(values_dict, title=None, xlabel=None, ylabel=None, vert=True):
"""Create boxplot form dictionary.
This function does not call `matplotlib.pyplot.plot()`.
Parameters
----------
values_dict : dict with str to array_like
Dictionary with one entry per box plot. The key (st... | 5,319,220 |
def removed_arg(name, arg):
"""Checks if the deprecated argument is populated.
Raises warning, if not None.
Args:
name: name of deprecated argument
arg: the argument to check
"""
if arg is not None:
removed_warning(name) | 5,319,221 |
def protect_with_lock() -> Callable:
""" This is a decorator for protecting a call of an object with a lock
The objects must adhere to the interface of having:
- A mapping of ids to query_lock objects
Objects adhering to this interface(LockableQueryObject) are:
- all the exchanges
-... | 5,319,222 |
def tile(infile, outdir, size=DEFAULT_TILE_SIZE):
"""Tiles the given input to a grid."""
with rasterio.open(infile) as dataset:
tiles = create_tiles(*dataset.bounds, size)
for tile in tiles:
tile.subset(infile, outdir) | 5,319,223 |
def _handle_dates():
"""Collect and return data information."""
currentdate = datetime.date.today()
year = currentdate.year
month = currentdate.month
print(f"[INFO] Current year / month: {year:04d} / {month:02d}")
return currentdate | 5,319,224 |
def add_to_five(number):
"""Add to the 5 by any number.
:param number:
"""
gifs = FrozenGif()
acceptable = (int, float)
type_number = type(number)
if type_number in acceptable:
# get answer
answer = 5 + number
response = int(input("Ente... | 5,319,225 |
def mergeticklists(list1, list2, mergeequal=1):
"""helper function to merge tick lists
- return a merged list of ticks out of list1 and list2
- CAUTION: original lists have to be ordered
(the returned list is also ordered)"""
# TODO: improve along the lines of http://aspn.activestate.com/ASPN/Cook... | 5,319,226 |
def test_url(url, size=17):
"""Test whether the given URL is accessible."""
try:
with gopen(url) as stream:
data = stream.read(size)
if len(data) == size:
return True
return False
except Exception as e:
print(e)
return False | 5,319,227 |
def credentials_to_token(credentials):
"""
Transforms an Oauth2 credentials object into an OAuth2Token object
to be used with the legacy gdata API
"""
import gdata.gauth
credentials.refresh(httplib2.Http())
token = gdata.gauth.OAuth2Token(
client_id=credentials.client_id,
cl... | 5,319,228 |
def solve2x2(lhs, rhs):
"""Solve a square 2 x 2 system via LU factorization.
This is meant to be a stand-in for LAPACK's ``dgesv``, which just wraps
two calls to ``dgetrf`` and ``dgetrs``. We wrap for two reasons:
* We seek to avoid exceptions as part of the control flow (which is
what :func:`nu... | 5,319,229 |
def fetch_global_notifications(count=0) -> dict:
"""
Always returns notifications in user view.
"""
cfg = get_config()
if count == 0:
count = cfg.default_max_notes
global_feed = get_global_feed()
global_notes = global_feed.get_notifications(count=count, user_view=True)
return glo... | 5,319,230 |
def getClusterPositionsRedshift(hd_clu, cluster_params, redshift_limit):
"""
Function to get the positions and redshifts of the clusters that pass the required criterion
@hd_clu :: list of cluster headers (each header ahs info on 1000 clusters alone)
@cluster_params :: contains halo_mass_500c and centra... | 5,319,231 |
def PydevdLog(level, *args):
""" levels are:
0 most serious warnings/errors
1 warnings/significant events
2 informational trace
"""
if level <= DebugInfoHolder.DEBUG_TRACE_LEVEL:
#yes, we can have errors printing if the console of the program has been finished (and we're stil... | 5,319,232 |
def validate_photo_file_size(value):
"""
Validates that video upload is below environment max size
"""
filesize = value.size
if filesize > 1048576 * float(settings.MAX_PHOTO_UPLOAD_SIZE_MB):
LOGGER.warning('Video size exceeds max upload size',
extra={'size': filesize})... | 5,319,233 |
def lark_to_field_definition_node(tree: "Tree") -> "FieldDefinitionNode":
"""
Creates and returns a FieldDefinitionNode instance extracted from the
parsing of the tree instance.
:param tree: the Tree to parse in order to extract the proper node
:type tree: Tree
:return: a FieldDefinitionNode ins... | 5,319,234 |
def variant_wraps(vfunc, wrapped_attributes=VARIANT_WRAPPED_ATTRIBUTES):
"""Update the variant function wrapper a la ``functools.wraps``."""
f = vfunc.__main_form__
class SentinelObject:
"""A unique sentinel that is not None."""
sentinel = SentinelObject()
for attr in wrapped_attributes:
... | 5,319,235 |
def write_generic_includes(s):
"""
Writes the includes that all messages need
@param s: The stream to write to
@type s: stream
"""
s.write('#include <string>\n')
s.write('#include <vector>\n')
s.write('#include <map>\n')
s.write('#include <ostream>\n')
s.write('#include "ros... | 5,319,236 |
def gradient_activity(activity, periods=1, append=True, columns=None):
"""Compute the gradient for all given columns.
Read more in the :ref:`User Guide <gradient>`.
Parameters
----------
activity : DataFrame
The activity to use to compute the gradient.
periods : int or array-like, def... | 5,319,237 |
def password_validators_help_texts(password_validators=None):
"""
Return a list of all help texts of all configured validators.
"""
help_texts = []
if password_validators is None:
password_validators = get_default_password_validators()
for validator in password_validators:
help_t... | 5,319,238 |
def spherical_schwarzchild_metric(x,M=1):
""" Computes the schwarzchild metric in cartesian like coordinates"""
bs,d = x.shape
t,r,theta,phi = x.T
rs = 2*M
a = (1-rs/r)
gdiag = torch.stack([-a,1/a,r**2,r**2*theta.sin()**2],dim=-1)
g = torch.diag_embed(gdiag)
print(g.shape)
return g | 5,319,239 |
def _get_pathless_grib_file_names(
init_time_unix_sec, model_name, grid_id=None, lead_time_hours=None):
"""Returns possible pathless file names for the given model/grid.
:param init_time_unix_sec: Model-initialization time.
:param model_name: See doc for `nwp_model_utils.check_grid_name`.
:para... | 5,319,240 |
def test_calling_behaviour_builder_before_defining_name_sets_name_as_call(behaviour_builder):
""" :type behaviour_builder: BehaviourBuilder """
behaviour_builder()
assert behaviour_builder.behaviour.name == '__call__' | 5,319,241 |
def get_picard_mrkdup(config):
"""
input: sample config file output from BALSAMIC
output: mrkdup or rmdup strings
"""
picard_str = "mrkdup"
if "picard_rmdup" in config["QC"]:
if config["QC"]["picard_rmdup"] == True:
picard_str = "rmdup"
return picard_str | 5,319,242 |
def ChoiceColor():
""" 模板中随机选择bootstrap内置颜色 """
color = ["default", "primary", "success", "info", "warning", "danger"]
return random.choice(color) | 5,319,243 |
def filter_command_line(line):
"""Returns and updates the command line starting with the flag"""
line_flag = line.strip().split(":")[0].strip()
new_line = line.strip()[len(line_flag) + 1:].strip().lstrip(":").strip()
if line_flag == EXEC_FLAG:
return new_line
elif line_flag == ERRCHECK_FLAG:... | 5,319,244 |
async def ytm(text):
"""Feed search result to Marshmallow."""
global g_listEcho
await bot.say("!youtube " + text)
g_listEcho.append(marshmallowPrefix) | 5,319,245 |
def handle_not_allowed(environ, start_response):
"""Return a 405 response when method is not allowed.
If _methods are in routing_args, send an allow header listing
the methods that are possible on the provided URL.
"""
_methods = util.wsgi_path_item(environ, '_methods')
headers = {}
if _met... | 5,319,246 |
def load_image(path: str):
"""
Return a loaded image from a given path.
:param path: (str) relative path of the iamge.
:return: PIL image.
"""
image = Image.open(path)
return image | 5,319,247 |
def search_in_between(begin,
end,
string,
max_matches=0,
remove_empty_matches=False,
use_regex=False):
"""
Searches for a string enclosed between a specified begin- and end-sequence.
Also enclosed \... | 5,319,248 |
def log_gen() -> Iterator[int]:
"""Logarithmic generator.
"""
y = 1
while True:
adder = max(1, math.pow(10, int(math.log10(y))))
yield int(y)
y = y + int(adder) | 5,319,249 |
def mergeSeries(sdata, resetIdx=False):
"""
Merge Series
Inputs:
> sdata: Either a list of dictionary of Series data
> resetIdx (False by default): should we reset the indices?
Output:
> The merged Series
"""
if isinstance(sdata, list):
retval = concat(sdata... | 5,319,250 |
def ranking_overview(request):
"""
Show history of rankings for top N teams in current ranking
"""
# Check which rounds are complete
rnd_complete = get_completed_rounds()
# Calculate ranking after each of these rounds
increment_rnds = []
ranking_matrix = []
round_names = []
... | 5,319,251 |
def set_console_log_level(log_level=_DEFAULT_CONSOLE_LOG_LEVEL):
"""
<Purpose>
Allow the default log level for console messages to be overridden. If
'log_level' is not provided, log level defaults to 'logging.INFO'.
<Arguments>
log_level:
The log level to set for the console handler.
'lo... | 5,319,252 |
def release_lock(lock_name, identifier):
"""
:param lock_name: 锁名称
:param identifier: uid
:return: True or False
"""
lock = "string:lock:" + lock_name
pip = redis_client.pipeline(True)
while True:
try:
pip.watch(lock)
lock_value = redis_client.get(lock)
... | 5,319,253 |
def add_user():
""" Add a user"""
payload = request.json
for required_key in users_schema:
if required_key not in payload.keys():
return jsonify({"message": f"Missing {required_key} parameter"}), 400
user = db.users.find_one({"email": payload["email"]})
if user is not None:
... | 5,319,254 |
def __get_str_md5(string):
"""
一个字符串的MD5值
返回一个字符串的MD5值
"""
m0 = hashlib.md5()
m0.update(string.encode('utf-8'))
result = m0.hexdigest()
return result | 5,319,255 |
def create_optimizers() -> List[OptimizationProcedure]:
"""Creates a list of all optimization procedures"""
optimizers: List[OptimizationProcedure] = []
ordering_rules = TaskOrderingRule.__subclasses__()
for rule in ordering_rules:
optimizers.append(StationOrientedStrategy(rule()))
... | 5,319,256 |
def command_get_file_list(ip_addr, directory):
"""command.cgi?op=100: Get list of files in a directory. Not recursive.
:raise FlashAirBadResponse: When API returns unexpected/malformed data.
:raise FlashAirDirNotFoundError: When the queried directory does not exist on the card.
:raise FlashAirHTTPError... | 5,319,257 |
def axml_content(d):
"""
OwcContent dict to Atom XML
:param d:
:return:
"""
# <owc:content type="image/tiff" href=".."
if is_empty(d):
return None
else:
try:
content_elem = etree.Element(ns_elem("owc", "content"), nsmap=ns)
mimetype = extract_p(... | 5,319,258 |
def average_water_consumed(wn):
"""
Compute average water consumed at each node, qbar, computed as follows:
.. math:: qbar=\dfrac{\sum_{k=1}^{K}\sum_{t=1}^{lcm_n}qbase_n m_n(k,t mod (L(k)))}{lcm_n}
where
:math:`K` is the number of demand patterns at node :math:`n`,
:math:`L(k)` is the number o... | 5,319,259 |
def PrintRevision():
"""Print the current Clang revision."""
# gyp runs update.py --print-revision even when clang isn't used.
# It won't use the value, but we must not error.
if not os.path.exists(LLVM_DIR):
print "0"
return
# TODO(hans): This needs an update when we move to prebuilt Clang binaries.... | 5,319,260 |
def _shuffle(arr1, arr2):
"""
Shuffles arr1 and arr2 in the same order
"""
random_idxs = np.arange(len(arr1))
np.random.shuffle(random_idxs)
return arr1[random_idxs], arr2[random_idxs] | 5,319,261 |
def assign_output(request):
"""assigns the given files as version outputs for the given entity
"""
logger.debug('assign_output')
logged_in_user = get_logged_in_user(request)
full_paths = request.POST.getall('full_paths[]')
original_filenames = request.POST.getall('original_filenames[]')
e... | 5,319,262 |
def make_pipeline(tfidf_vectorizer, model):
""" Creates sklearn NLP pipeline
:param vectorizer: Vectorizer object
:param model: Model object
:return: Pipeline object
"""
tfidf_vectorizer = tfidf_vectorizer
model = model
pipeline = Pipeline([("tfidf", tfidf_vectorizer),
... | 5,319,263 |
def pnf_peeling_mechanism(item_counts, k, epsilon):
"""Computes epsilon-DP top-k counts by the permute-and-flip peeling mechanism.
The peeling mechanism (https://arxiv.org/pdf/1905.04273.pdf) adaptively uses
the counts as a utility function for the exponential mechanism. Once an item
is selected, the item is ... | 5,319,264 |
def format_date(timestamp):
"""Reusable timestamp -> date."""
return datetime.date.fromtimestamp(timestamp).isoformat() | 5,319,265 |
def apps(ctx):
"""Manages applications""" | 5,319,266 |
def getpwuid(uid):
"""
getpwuid(uid) -> (pw_name,pw_passwd,pw_uid,
pw_gid,pw_gecos,pw_dir,pw_shell)
Return the password database entry for the given numeric user ID.
See pwd.__doc__ for more on password database entries.
"""
if uid > sys.maxint or uid < 0:
raise Key... | 5,319,267 |
def main():
""" Main function, grab arugments, grab dm arguments, on a loop send dm """
auth_file = sys.argv[1]
arg_file = sys.argv[2]
quote_file = sys.argv[3]
auth = auth_setup(auth_file)
api = tweepy.API(auth)
while True:
time.sleep(3000)
user = get_random_user(arg_file)... | 5,319,268 |
def train(model, optimizer, loader, epoch):
"""
Train the models on the dataset.
"""
# running statistics
batch_time = AverageMeter("time", ":.2f")
data_time = AverageMeter("data time", ":.2f")
# training statistics
top1 = AverageMeter("top1", ":.3f")
top5 = AverageMeter("top5", ":.... | 5,319,269 |
def ResidualBlock(name, input_dim, output_dim, filter_size, inputs, resample=None, he_init=True):
"""
resample: None, 'down', or 'up'
"""
if resample == 'down':
conv_shortcut = functools.partial(lib.ops.conv2d.Conv2D, stride=2)
conv_1 = functools.partial(
lib.ops.conv2d.Conv2... | 5,319,270 |
def run_uGLAD_direct(
Xb,
trueTheta=None,
eval_offset=0.1,
EPOCHS=250,
lr=0.002,
INIT_DIAG=0,
L=15,
VERBOSE=True
):
"""Running the uGLAD algorithm in direct mode
Args:
Xb (np.array 1xMxD): The input sample matrix
trueTheta (np.array 1xDxD): The corresp... | 5,319,271 |
def twitter_api():
"""Returns an authenticated tweepy.API instance.
Returns None on failure.
"""
try:
auth = tweepy.OAuthHandler(TWITTER_API_KEY, TWITTER_API_KEY_SECRET)
auth.set_access_token(TWITTER_ACCESS_TOKEN,
TWITTER_ACCESS_TOKEN_SECRET)
ap... | 5,319,272 |
def worker(sleep, ncores, workername, project_id_filter, checks, checks_only,
capability, config):
"""Start a worker process."""
project_ids = list(project_id_filter) if project_id_filter else []
capabilities = list(capability) if capability else []
if config:
worker_config = pytail... | 5,319,273 |
def run(config_json_path):
"""
parse config file
"""
config_json = json.load(open(os.path.abspath(config_json_path), "r"))
monitor_out_dir = os.path.abspath(config_json["monitor_out"])
output_dir = os.path.abspath(config_json["output_dir"])
emulator_id = config_json["emulator_id"]
real_... | 5,319,274 |
def cargar_perfil(usuario, contrasenia):
""" Retorna el perfil correspondiente a un usuario y una contraseña """
global perfil, error
try:
L = instaloader.Instaloader()
L.login(usuario, contrasenia)
perfil = instaloader.Profile.from_username(L.context,... | 5,319,275 |
def export_queries_to_sql_file(queries: list, sql_file_path: str):
"""
Exports queries from list of queries to sql file
:param queries: List of queries for export to SQL file
:type queries: list
:param sql_file_path: Path for output SQL file with queries
:type sql_file_path: str
"""
with... | 5,319,276 |
def as_general_categories(cats, name="cats"):
"""Return a tuple of Unicode categories in a normalised order.
This function expands one-letter designations of a major class to include
all subclasses:
>>> as_general_categories(['N'])
('Nd', 'Nl', 'No')
See section 4.5 of the Unicode standard fo... | 5,319,277 |
def upload_directory(
directory: str = './',
upsert=False,
ignore_duplicate_error=False,
recursive=False,
pattern='*'):
"""
Upload files in a directory to the database.
:param directory: [Optional] The root directory to upload. Defaults to the current working directo... | 5,319,278 |
def main():
"""Main procedure."""
# execute logic
logger.info('{}...'.format(_('Processing')))
args = get_args()
# connect to db
conn = db_connect(args.host, args.port, args.database, args.user, args.password)
with conn.cursor() as c:
# get list of tables in the original schema
... | 5,319,279 |
def log_to_true_stdout(name="open_cp"):
"""Start logging to the "real" `stdout`. In a Jupyter notebook, this will
print logging to the console the server is running in (and not to the
notebook) itself.
"""
_log_to(_sys.__stdout__, name) | 5,319,280 |
def tExtract(rft, T_INDEX):
"""T_INDEX is either of T_WL, T_SPEC, T_COM """
tdat = [dat[T_INDEX] for dat in rft[RFT_T] if (dat[T_WL] >= rft[RFT_R][R_WL] and dat[T_WL] <= rft[RFT_R][R_WH])]
return tdat | 5,319,281 |
def open_txt(path: Union[str, Path], cf_table: Optional[dict] = cmor) -> xr.Dataset:
"""Extract daily HQ meteorological data and convert to xr.DataArray with CF-Convention attributes."""
meta, data = extract_daily(path)
return to_cf(meta, data, cf_table) | 5,319,282 |
def prepare_data(filename, tmp_prefix, dbargs, osm2pgsql, projection):
""" Stage OSM data into a temporary set of tables using osm2pgsql.
"""
args = osm2pgsql.split() + ['--create', '--merc', '--prefix', tmp_prefix]
for (flag, key) in [('-d', 'database'), ('-U', 'user'), ('-W', 'password'), ('-H', ... | 5,319,283 |
def dc_coordinates():
"""Return coordinates for a DC-wide map"""
dc_longitude = -77.016243706276569
dc_latitude = 38.894858329321485
dc_zoom_level = 10.3
return dc_longitude, dc_latitude, dc_zoom_level | 5,319,284 |
def test_temperature_from_potential_temperature():
"""Test temperature_from_potential_temperature calculation."""
theta = np.array([286.12859679, 288.22362587, 290.31865495, 292.41368403]) * units.kelvin
pressure = np.array([850] * 4) * units.mbar
real_t = np.array([273.15, 275.15, 277.15, 279.15]) * un... | 5,319,285 |
def get_arguments():
"""
Obtains command-line arguments.
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--clusters',
type=argparse.FileType('rU'),
required=True,
metavar='CLUSTERS',
help='read cluster assignments... | 5,319,286 |
def request_id_to_key(request_id):
"""Converts a request id into a TaskRequest key.
Note that this function does NOT accept a task id. This functions is primarily
meant for limiting queries to a task creation range.
"""
return ndb.Key(TaskRequest, request_id ^ task_pack.TASK_REQUEST_KEY_ID_MASK) | 5,319,287 |
def get_web_app_premier_add_on_slot(name: Optional[str] = None,
premier_add_on_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
slot: Optional[str] = None,
... | 5,319,288 |
def lmap(f: Callable, x: Iterable) -> List:
"""list(map(f, x))"""
return list(map(f, x)) | 5,319,289 |
def calculate_acc(result_path, label_path):
"""
Calculate accuracy of VGG16 inference.
Args:
result_path (str): the directory or inference result.
label_path (str): the path of data label in .npy format.
"""
top1_acc = Top1CategoricalAccuracy()
labels = np.load(label_path, allow... | 5,319,290 |
def callback(message):
"""
Function to retrieved the published message and run the
whole pipeline to create a model in AutoML
params: message - string containing train budget and session ID
"""
print(message.data)
message.ack()
input_dict = json.loads(message.data)
db = TinyDB('versi... | 5,319,291 |
def C4925577_Materials_MaterialAssignedToTerrain():
"""
Summary:
Three spheres are suspended above the terrain. Beneath two of the balls,
there is a different material painted on the terrain.
They should all bounce at different heights per their respective terrains
Terrain entity: PhysX Terrain... | 5,319,292 |
def fallible_to_exec_result_or_raise(
fallible_result: FallibleExecuteProcessResult, description: ProductDescription
) -> ExecuteProcessResult:
"""Converts a FallibleExecuteProcessResult to a ExecuteProcessResult or raises an error."""
if fallible_result.exit_code == 0:
return ExecuteProcessResult(
fal... | 5,319,293 |
def cumprod_np(a: np.ndarray, mod: int) -> np.ndarray:
"""Compute cumprod over modular not in place.
the parameter a must be one dimentional ndarray.
"""
n = a.size
assert a.ndim == 1
m = int(n**0.5) + 1
a = np.resize(a, (m, m))
for i in range(m - 1):
a[:, i + 1] = a[:, i + 1] *... | 5,319,294 |
def install_requirements():
"""
Install the requirements from the base.txt file to the remote virtualenv.
"""
with cd(get_project_root()):
run_pip("install -r requirements/base.txt") | 5,319,295 |
def table_of_contents(df_documentation=''):
"""
Function::: table_of_contents
Description: brief description here (1 line)
Details: Full description with details here
Inputs
doc_csv_file: FILE csv file with documentation of functions
Outputs
tab_contents: STR Table ... | 5,319,296 |
def mock_get_location_business_from_sam(client, duns_list):
""" Mock function for location_business data as we can't connect to the SAM service """
columns = ['awardee_or_recipient_uniqu'] + list(update_historical_duns.props_columns.keys())
results = pd.DataFrame(columns=columns)
duns_mappings = {
... | 5,319,297 |
def repeat(N, fn):
"""repeat module N times
:param int N: repeat time
:param function fn: function to generate module
:return: repeated loss
:rtype: MultiSequential
"""
return MultiSequential(*[fn() for _ in range(N)]) | 5,319,298 |
def dense_to_one_hot(labels_dense, num_classes):
"""Convert class labels from scalars to one-hot vectors."""
num_labels = labels_dense.shape[0]
index_offset = numpy.arange(num_labels) * num_classes
labels_one_hot = numpy.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.ravel()-... | 5,319,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.