INTELLECT-1 Dataset
Collection
INTELLECT-1 Training dataset
•
5 items
•
Updated
•
9
text
stringlengths 3
1.05M
|
---|
/*!
* JavaScript Cookie v2.1.2
* https://github.com/js-cookie/js-cookie
*
* Copyright 2006, 2015 Klaus Hartl & Fagner Brack
* Released under the MIT license
*/
;(function (factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
var OldCookies = window.Cookies;
var api = window.Cookies = factory();
api.noConflict = function () {
window.Cookies = OldCookies;
return api;
};
}
}(function () {
function extend () {
var i = 0;
var result = {};
for (; i < arguments.length; i++) {
var attributes = arguments[ i ];
for (var key in attributes) {
result[key] = attributes[key];
}
}
return result;
}
function init (converter) {
function api (key, value, attributes) {
var result;
if (typeof document === 'undefined') {
return;
}
// Write
if (arguments.length > 1) {
attributes = extend({
path: '/'
}, api.defaults, attributes);
if (typeof attributes.expires === 'number') {
var expires = new Date();
expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);
attributes.expires = expires;
}
try {
result = JSON.stringify(value);
if (/^[\{\[]/.test(result)) {
value = result;
}
} catch (e) {}
if (!converter.write) {
value = encodeURIComponent(String(value))
.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
} else {
value = converter.write(value, key);
}
key = encodeURIComponent(String(key));
key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent);
key = key.replace(/[\(\)]/g, escape);
return (document.cookie = [
key, '=', value,
attributes.expires ? '; expires=' + attributes.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
attributes.path ? '; path=' + attributes.path : '',
attributes.domain ? '; domain=' + attributes.domain : '',
attributes.secure ? '; secure' : ''
].join(''));
}
// Read
if (!key) {
result = {};
}
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all. Also prevents odd result when
// calling "get()"
var cookies = document.cookie ? document.cookie.split('; ') : [];
var rdecode = /(%[0-9A-Z]{2})+/g;
var i = 0;
for (; i < cookies.length; i++) {
var parts = cookies[i].split('=');
var cookie = parts.slice(1).join('=');
if (cookie.charAt(0) === '"') {
cookie = cookie.slice(1, -1);
}
try {
var name = parts[0].replace(rdecode, decodeURIComponent);
cookie = converter.read ?
converter.read(cookie, name) : converter(cookie, name) ||
cookie.replace(rdecode, decodeURIComponent);
if (this.json) {
try {
cookie = JSON.parse(cookie);
} catch (e) {}
}
if (key === name) {
result = cookie;
break;
}
if (!key) {
result[name] = cookie;
}
} catch (e) {}
}
return result;
}
api.set = api;
api.get = function (key) {
return api(key);
};
api.getJSON = function () {
return api.apply({
json: true
}, [].slice.call(arguments));
};
api.defaults = {};
api.remove = function (key, attributes) {
api(key, '', extend(attributes, {
expires: -1
}));
};
api.withConverter = init;
return api;
}
return init(function () {});
}));
|
#!/usr/local/bin/python3
class Cat():
species = 'mamal'
def __init__(self, name, age):
self.name = name
self.age = age
# Instantiate the Cat object with 3 cats
cat1 = Cat('Tigger', 1)
cat2 = Cat('Smokey', 4)
cat3 = Cat('Patch', 10)
def oldest_cat(*args):
'''
INFO: Create a function that finds the oldest cat
'''
return max(args)
if __name__ == '__main__':
# 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function
print(f'The oldest cat is {oldest_cat(cat1.age,cat2.age,cat3.age)}')
|
//>>built
define(
"dijit/form/nls/tr/ComboBox", //begin v1.x content
({
previousMessage: "Önceki seçenekler",
nextMessage: "Diğer seçenekler"
})
//end v1.x content
);
|
import numpy as np
import matplotlib.pyplot as plt
from numpy import vstack, array
from pylab import plot, show, savefig
import csv
import random
from scipy.cluster.vq import kmeans2, vq
import numpy_indexed as npi
import time
if __name__ == "__main__":
# read data as 2D array of data type 'np.float'
result = np.array(list(csv.reader(open("data-clustering-2.csv", "rb"), delimiter=","))).astype("float")
ti = []
colors = ['red', 'green', 'blue', 'cyan', 'orange']
X = result[0, :]
Y = result[1, :]
result = result.T
k = 0
while (k < 10):
start = time.time()
Ct = np.hstack(
(result, np.reshape(np.random.choice(range(0, 3), result.shape[0], replace=True), (result.shape[0], 1))))
meu = (npi.group_by(Ct[:, 2]).mean(Ct))[1][:, 0:2]
Converged = False
while Converged is False:
Converged = True
for j in range(0, Ct.shape[0]):
Cj = Ct[j, 2]
dmin = []
for i in range(0, 3):
Ct[j, 2] = i
G = (npi.group_by(Ct[:, 2])).split(Ct)
dist = 0
# print(G)
for p in range(0, 3):
t = (G[p][:, 0:2])
mi = np.reshape(np.mean(t, axis=0), (1, 2))
t = np.sum((t - mi) ** 2, axis=1)
dist = dist + np.sum(t, axis=0)
dmin.append(dist)
Cw = np.argmin(dmin)
if Cw != Cj:
Converged = False
Ct[j, 2] = Cw
meu = (npi.group_by(Ct[:, 2]).mean(Ct))[1][:, 0:2]
else:
Ct[j, 2] = Cj
end = time.time()
time_taken = end - start
ti.append(time_taken)
k = k + 1
print("time_taken")
print(sum(ti) / len(ti))
meu = np.hstack((meu, np.reshape(np.array(list(range(3))), (3, 1))))
cp = Ct
plt.title("Hartigan")
plt.xlim(xmin=np.min(Ct[:, 0]) - 1, xmax=np.max(1 + Ct[:, 0]))
plt.ylim(ymin=np.min(Ct[:, 1]) - 1, ymax=np.max(1 + Ct[:, 1]))
plt.scatter(Ct[:, 0], Ct[:, 1], c=[colors[i] for i in (Ct[:, 2]).astype(int)], s=5.5,
label='Points')
plt.scatter(meu[:, 0], meu[:, 1], c=[colors[i] for i in (meu[:, 2]).astype(int)], s=40,
marker='*', label='Centroids')
plt.savefig("Hartigan Clustering-2.pdf", facecolor='w', edgecolor='w',
papertype=None, format='pdf', transparent=False,
bbox_inches='tight', pad_inches=0.1)
plt.legend()
plt.show()
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _pass = _interopRequireDefault(require("./pass"));
var RenderPass = function (_Pass) {
(0, _inherits2["default"])(RenderPass, _Pass);
function RenderPass(gl) {
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
(0, _classCallCheck2["default"])(this, RenderPass);
return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(RenderPass).call(this, gl, Object.assign({
id: 'render-pass'
}, props)));
}
(0, _createClass2["default"])(RenderPass, [{
key: "_renderPass",
value: function _renderPass(_ref) {
var animationProps = _ref.animationProps;
var _this$props = this.props,
_this$props$models = _this$props.models,
models = _this$props$models === void 0 ? [] : _this$props$models,
drawParams = _this$props.drawParams;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = models[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var model = _step.value;
model.draw(Object.assign({}, drawParams, {
animationProps: animationProps
}));
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
}]);
return RenderPass;
}(_pass["default"]);
exports["default"] = RenderPass;
//# sourceMappingURL=render-pass.js.map |
import { dew as _toStringDewDew } from "./toString.dew.js";
var exports = {},
_dewExec = false;
export function dew() {
if (_dewExec) return exports;
_dewExec = true;
var toString = _toStringDewDew();
/**
* Replaces matches for `pattern` in `string` with `replacement`.
*
* **Note:** This method is based on
* [`String#replace`](https://mdn.io/String/replace).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to modify.
* @param {RegExp|string} pattern The pattern to replace.
* @param {Function|string} replacement The match replacement.
* @returns {string} Returns the modified string.
* @example
*
* _.replace('Hi Fred', 'Fred', 'Barney');
* // => 'Hi Barney'
*/
function replace() {
var args = arguments,
string = toString(args[0]);
return args.length < 3 ? string : string.replace(args[1], args[2]);
}
exports = replace;
return exports;
} |
import discord
from discord.ext import commands
import asyncio
from googletrans import Translator
class Translation(commands.Cog):
def __init__(self,client):
self.client = client
@commands.cooldown(1,5,commands.BucketType.user)
@commands.command()
async def trans(self, ctx):
"""translation"""
first_run = True
translation = ctx.message.content[7:]
while True:
if first_run:
embed = discord.Embed(color=0x19212d)
icon = "https://i.imgur.com/6zMLSah.png"
embed = discord.Embed(color=0x1ccc09)
embed.set_thumbnail(url=icon)
embed.set_author(name="Traduzir")
embed.set_footer(text="Athus V1.0")
embed.add_field(name="Texto", value=translation, inline=True)
first_run = False
msg = await ctx.send(embed=embed)
reactmoji = []
reactmoji.extend(['🇺🇸'])
reactmoji.append('🇧🇷')
reactmoji.append('🇻🇳')
reactmoji.append('🇯🇵')
reactmoji.append('🇦🇲')
reactmoji.append('🇿🇦')
reactmoji.append('🇦🇱')
reactmoji.append('🇦🇴')
#exit
reactmoji.append('❌')
for react in reactmoji:
await msg.add_reaction(react)
def check_react(reaction, user):
if reaction.message.id != msg.id:
return False
if user != ctx.message.author:
return False
if str(reaction.emoji) not in reactmoji:
return False
return True
try:
res, user = await self.client.wait_for('reaction_add', timeout=30.0, check=check_react)
except asyncio.TimeoutError:
return await msg.clear_reactions()
if user != ctx.message.author:
pass
elif '🇺🇸' in str(res.emoji):
country = 'en'
translator = Translator()
traduzido=translator.translate(translation, dest=country)
embed = discord.Embed(color=0x19212d)
icon = "https://i.imgur.com/6zMLSah.png"
embed = discord.Embed(color=0x1ccc09)
embed.set_thumbnail(url=icon)
embed.set_author(name="Traduzido")
embed.set_footer(text="Athus V1.0")
embed.add_field(name="Texto", value=traduzido.text, inline=True)
await msg.clear_reactions()
await msg.edit(embed=embed)
elif '🇧🇷' in str(res.emoji):
country = 'pt'
translator = Translator()
traduzido=translator.translate(translation, dest=country)
embed = discord.Embed(color=0x19212d)
icon = "https://i.imgur.com/6zMLSah.png"
embed = discord.Embed(color=0x1ccc09)
embed.set_thumbnail(url=icon)
embed.set_author(name="Traduzido")
embed.set_footer(text="Athus V1.0")
embed.add_field(name="Texto", value=traduzido.text, inline=True)
await msg.clear_reactions()
await msg.edit(embed=embed)
elif '🇻🇳' in str(res.emoji):
country = 'zh-tw'
translator = Translator()
traduzido=translator.translate(translation, dest=country)
embed = discord.Embed(color=0x19212d)
icon = "https://i.imgur.com/6zMLSah.png"
embed = discord.Embed(color=0x1ccc09)
embed.set_thumbnail(url=icon)
embed.set_author(name="Traduzido")
embed.set_footer(text="Athus V1.0")
embed.add_field(name="Texto", value=traduzido.text, inline=True)
await msg.clear_reactions()
await msg.edit(embed=embed)
elif '🇯🇵' in str(res.emoji):
country = 'ja'
translator = Translator()
traduzido=translator.translate(translation, dest=country)
embed = discord.Embed(color=0x19212d)
icon = "https://i.imgur.com/6zMLSah.png"
embed = discord.Embed(color=0x1ccc09)
embed.set_thumbnail(url=icon)
embed.set_author(name="Traduzido")
embed.set_footer(text="Athus V1.0")
embed.add_field(name="Texto", value=traduzido.text, inline=True)
await msg.clear_reactions()
await msg.edit(embed=embed)
elif '🇦🇲' in str(res.emoji):
country = 'hy'
translator = Translator()
traduzido=translator.translate(translation, dest=country)
embed = discord.Embed(color=0x19212d)
icon = "https://i.imgur.com/6zMLSah.png"
embed = discord.Embed(color=0x1ccc09)
embed.set_thumbnail(url=icon)
embed.set_author(name="Traduzido")
embed.set_footer(text="Athus V1.0")
embed.add_field(name="Texto", value=traduzido.text, inline=True)
await msg.clear_reactions()
await msg.edit(embed=embed)
elif '🇿🇦' in str(res.emoji):
country = 'af'
translator = Translator()
traduzido=translator.translate(translation, dest=country)
embed = discord.Embed(color=0x19212d)
icon = "https://i.imgur.com/6zMLSah.png"
embed = discord.Embed(color=0x1ccc09)
embed.set_thumbnail(url=icon)
embed.set_author(name="Traduzido")
embed.set_footer(text="Athus V1.0")
embed.add_field(name="Texto", value=traduzido.text, inline=True)
await msg.clear_reactions()
await msg.edit(embed=embed)
elif '🇦🇱' in str(res.emoji):
country = 'sq'
translator = Translator()
traduzido=translator.translate(translation, dest=country)
embed = discord.Embed(color=0x19212d)
icon = "https://i.imgur.com/6zMLSah.png"
embed = discord.Embed(color=0x1ccc09)
embed.set_thumbnail(url=icon)
embed.set_author(name="Traduzido")
embed.set_footer(text="Athus V1.0")
embed.add_field(name="Texto", value=traduzido.text, inline=True)
await msg.clear_reactions()
await msg.edit(embed=embed)
elif '🇦🇴' in str(res.emoji):
country = 'am'
translator = Translator()
traduzido=translator.translate(translation, dest=country)
embed = discord.Embed(color=0x19212d)
icon = "https://i.imgur.com/6zMLSah.png"
embed = discord.Embed(color=0x1ccc09)
embed.set_thumbnail(url=icon)
embed.set_author(name="Traduzido")
embed.set_footer(text="Athus V1.0")
embed.add_field(name="Texto", value=traduzido.text, inline=True)
await msg.clear_reactions()
await msg.edit(embed=embed)
elif '❌' in str(res.emoji):
await ctx.message.delete()
return await msg.delete()
self.client.counter += 1
def setup(client):
client.add_cog(Translation(client)) |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MAIN //
// Mapping from array constructors to data types...
var ctor2dtypes = {
'Float32Array': 'float32',
'Float64Array': 'float64',
'Array': 'generic',
'Int16Array': 'int16',
'Int32Array': 'int32',
'Int8Array': 'int8',
'Uint16Array': 'uint16',
'Uint32Array': 'uint32',
'Uint8Array': 'uint8',
'Uint8ClampedArray': 'uint8c'
};
// EXPORTS //
module.exports = ctor2dtypes;
|
# coding=utf-8
# Copyright 2018 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for TF Agents reinforce_agent."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
from absl.testing.absltest import mock
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
import tensorflow_probability as tfp
from tf_agents.agents.reinforce import reinforce_agent
from tf_agents.networks import actor_distribution_rnn_network
from tf_agents.networks import network
from tf_agents.networks import utils as network_utils
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import time_step as ts
from tf_agents.trajectories import trajectory
from tf_agents.utils import common
from tf_agents.utils import nest_utils
from tensorflow.python.util import nest # pylint:disable=g-direct-tensorflow-import # TF internal
class DummyActorNet(network.Network):
def __init__(self,
input_tensor_spec,
output_tensor_spec,
unbounded_actions=False,
stateful=False):
# When unbounded_actions=True, we skip the final tanh activation and the
# action shift and scale. This allows us to compute the actor and critic
# losses by hand more easily.
# If stateful=True, the network state has the same shape as
# `input_tensor_spec`. Otherwise it is empty.
state_spec = (tf.TensorSpec(input_tensor_spec.shape, tf.float32)
if stateful else ())
super(DummyActorNet, self).__init__(
input_tensor_spec=input_tensor_spec,
state_spec=state_spec,
name='DummyActorNet')
single_action_spec = tf.nest.flatten(output_tensor_spec)[0]
activation_fn = None if unbounded_actions else tf.nn.tanh
self._output_tensor_spec = output_tensor_spec
self._layers = [
tf.keras.layers.Dense(
single_action_spec.shape.num_elements() * 2,
activation=activation_fn,
kernel_initializer=tf.compat.v1.initializers.constant(
[[2, 1], [1, 1]]),
bias_initializer=tf.compat.v1.initializers.constant(5),
),
]
def call(self, observations, step_type, network_state):
del step_type
states = tf.cast(tf.nest.flatten(observations)[0], tf.float32)
for layer in self.layers:
states = layer(states)
single_action_spec = tf.nest.flatten(self._output_tensor_spec)[0]
actions, stdevs = states[..., 0], states[..., 1]
actions = tf.reshape(actions, [-1] + single_action_spec.shape.as_list())
stdevs = tf.reshape(stdevs, [-1] + single_action_spec.shape.as_list())
actions = tf.nest.pack_sequence_as(self._output_tensor_spec, [actions])
stdevs = tf.nest.pack_sequence_as(self._output_tensor_spec, [stdevs])
distribution = nest.map_structure_up_to(
self._output_tensor_spec, tfp.distributions.Normal, actions, stdevs)
return distribution, network_state
class DummyValueNet(network.Network):
def __init__(self, observation_spec, name=None, outer_rank=1):
super(DummyValueNet, self).__init__(observation_spec, (), 'DummyValueNet')
self._outer_rank = outer_rank
self._layers.append(
tf.keras.layers.Dense(
1,
kernel_initializer=tf.compat.v1.initializers.constant([2, 1]),
bias_initializer=tf.compat.v1.initializers.constant([5])))
def call(self, inputs, step_type=None, network_state=()):
del step_type
hidden_state = tf.cast(tf.nest.flatten(inputs), tf.float32)[0]
batch_squash = network_utils.BatchSquash(self._outer_rank)
hidden_state = batch_squash.flatten(hidden_state)
for layer in self.layers:
hidden_state = layer(hidden_state)
value_pred = tf.squeeze(batch_squash.unflatten(hidden_state), axis=-1)
return value_pred, network_state
class ReinforceAgentTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
super(ReinforceAgentTest, self).setUp()
tf.compat.v1.enable_resource_variables()
self._obs_spec = tensor_spec.TensorSpec([2], tf.float32)
self._time_step_spec = ts.time_step_spec(self._obs_spec)
self._action_spec = tensor_spec.BoundedTensorSpec([1], tf.float32, -1, 1)
def testCreateAgent(self):
reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=False),
optimizer=None,
)
def testCreateAgentWithValueNet(self):
reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=False),
value_network=DummyValueNet(self._obs_spec),
value_estimation_loss_coef=0.5,
optimizer=None,
)
def testPolicyGradientLoss(self):
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=None,
)
observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)
time_steps = ts.restart(observations, batch_size=2)
actions = tf.constant([[0], [1]], dtype=tf.float32)
actions_distribution = agent.collect_policy.distribution(
time_steps).action
returns = tf.constant([1.9, 1.0], dtype=tf.float32)
expected_loss = 10.983667373657227
loss = agent.policy_gradient_loss(
actions_distribution, actions, time_steps.is_last(), returns, 1)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_ = self.evaluate(loss)
self.assertAllClose(loss_, expected_loss)
def testPolicyGradientLossMultipleEpisodes(self):
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=None,
)
step_type = tf.constant(
[ts.StepType.FIRST, ts.StepType.LAST, ts.StepType.FIRST,
ts.StepType.LAST])
reward = tf.constant([0, 0, 0, 0], dtype=tf.float32)
discount = tf.constant([1, 1, 1, 1], dtype=tf.float32)
observations = tf.constant(
[[1, 2], [1, 2], [1, 2], [1, 2]], dtype=tf.float32)
time_steps = ts.TimeStep(step_type, reward, discount, observations)
actions = tf.constant([[0], [1], [2], [3]], dtype=tf.float32)
actions_distribution = agent.collect_policy.distribution(
time_steps).action
returns = tf.constant([1.9, 1.9, 1.0, 1.0], dtype=tf.float32)
expected_loss = 5.140229225158691
loss = agent.policy_gradient_loss(
actions_distribution, actions, time_steps.is_last(), returns, 2)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_ = self.evaluate(loss)
self.assertAllClose(loss_, expected_loss)
def testMaskingRewardSingleEpisodeRewardOnFirst(self):
# Test that policy_gradient_loss reacts correctly to rewards when there are:
# * A single MDP episode
# * Returns on the tf.StepType.FIRST transitions
#
# F, L, M = ts.StepType.{FIRST, MID, LAST} in the chart below.
#
# Experience looks like this:
# Trajectories: (F, L) -> (L, F)
# observation : [1, 2] [1, 2]
# action : [0] [1]
# reward : 3 0
# ~is_boundary: 1 0
# is_last : 1 0
# valid reward: 3*1 4*0
#
# The second action & reward should be masked out due to being on a
# boundary (step_type=(L, F)) transition.
#
# The expected_loss is > 0.0 in this case, only LAST should be excluded.
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=None,
)
step_type = tf.constant([ts.StepType.FIRST, ts.StepType.LAST])
reward = tf.constant([3, 4], dtype=tf.float32)
discount = tf.constant([1, 0], dtype=tf.float32)
observations = tf.constant([[1, 2], [1, 2]], dtype=tf.float32)
time_steps = ts.TimeStep(step_type, reward, discount, observations)
actions = tf.constant([[0], [1]], dtype=tf.float32)
actions_distribution = agent.collect_policy.distribution(
time_steps).action
returns = tf.constant([3.0, 0.0], dtype=tf.float32)
# Returns on the StepType.FIRST should be counted.
expected_loss = 10.8935775757
loss = agent.policy_gradient_loss(
actions_distribution, actions, time_steps.is_last(), returns, 1)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_ = self.evaluate(loss)
self.assertAllClose(loss_, expected_loss)
def testMaskingReturnSingleEpisodeRewardOnLast(self):
# Test that policy_gradient_loss reacts correctly to rewards when there are:
# * A single MDP episode
# * Returns on the tf.StepType.LAST transitions
#
# F, L, M = ts.StepType.{FIRST, MID, LAST} in the chart below.
#
# Experience looks like this:
# Trajectories: (F, L) -> (L, F)
# observation : [1, 2] [1, 2]
# action : [0] [1]
# reward : 0 3
# ~is_boundary: 1 0
# is_last : 1 0
# valid reward: 0*1 3*0
#
# The second action & reward should be masked out due to being on a
# boundary (step_type=(L, F)) transition. The first has a 0 reward.
#
# The expected_loss is 0.0 in this case.
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=None,
)
step_type = tf.constant([ts.StepType.FIRST, ts.StepType.LAST])
reward = tf.constant([0, 3], dtype=tf.float32)
discount = tf.constant([1, 0], dtype=tf.float32)
observations = tf.constant(
[[1, 2], [1, 2]], dtype=tf.float32)
time_steps = ts.TimeStep(step_type, reward, discount, observations)
actions = tf.constant([[0], [1]], dtype=tf.float32)
actions_distribution = agent.collect_policy.distribution(
time_steps).action
returns = tf.constant([0.0, 3.0], dtype=tf.float32)
# Returns on the StepType.LAST should not be counted.
expected_loss = 0.0
loss = agent.policy_gradient_loss(
actions_distribution, actions, time_steps.is_last(), returns, 1)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_ = self.evaluate(loss)
self.assertAllClose(loss_, expected_loss)
def testMaskingReturnMultipleEpisodesRewardOnFirst(self):
# Test that policy_gradient_loss reacts correctly to rewards when there are:
# * Multiple MDP episodes
# * Returns on the tf.StepType.FIRST transitions
#
# F, L, M = ts.StepType.{FIRST, MID, LAST} in the chart below.
#
# Experience looks like this:
# Trajectories: (F, L) -> (L, F) -> (F, L) -> (L, F)
# observation : [1, 2] [1, 2] [1, 2] [1, 2]
# action : [0] [1] [2] [3]
# reward : 3 0 4 0
# ~is_boundary: 1 0 1 0
# is_last : 1 0 1 0
# valid reward: 3*1 0*0 4*1 0*0
#
# The second & fourth action & reward should be masked out due to being on a
# boundary (step_type=(L, F)) transition.
#
# The expected_loss is > 0.0 in this case, only LAST should be excluded.
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=None,
)
step_type = tf.constant(
[ts.StepType.FIRST, ts.StepType.LAST, ts.StepType.FIRST,
ts.StepType.LAST])
reward = tf.constant([3, 0, 4, 0], dtype=tf.float32)
discount = tf.constant([1, 0, 1, 0], dtype=tf.float32)
observations = tf.constant(
[[1, 2], [1, 2], [1, 2], [1, 2]], dtype=tf.float32)
time_steps = ts.TimeStep(step_type, reward, discount, observations)
actions = tf.constant([[0], [1], [2], [3]], dtype=tf.float32)
actions_distribution = agent.collect_policy.distribution(
time_steps).action
returns = tf.constant([3.0, 0.0, 4.0, 0.0], dtype=tf.float32)
# Returns on the StepType.FIRST should be counted.
expected_loss = 12.2091741562
loss = agent.policy_gradient_loss(
actions_distribution, actions, time_steps.is_last(), returns, 2)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_ = self.evaluate(loss)
self.assertAllClose(loss_, expected_loss)
def testMaskingReturnMultipleEpisodesRewardOnLast(self):
# Test that policy_gradient_loss reacts correctly to returns when there are:
# * Multiple MDP episodes
# * Returns on the tf.StepType.LAST transitions
#
# F, L, M = ts.StepType.{FIRST, MID, LAST} in the chart below.
#
# Experience looks like this:
# Trajectories: (F, L) -> (L, F) -> (F, L) -> (L, F)
# observation : [1, 2] [1, 2] [1, 2] [1, 2]
# action : [0] [1] [2] [3]
# reward : 0 3 0 4
# ~is_boundary: 1 0 1 0
# is_last : 1 0 1 0
# valid reward: 0*1 3*0 0*1 4*0
#
# The second & fourth action & reward should be masked out due to being on a
# boundary (step_type=(L, F)) transition.
#
# The expected_loss is 0.0 in this case.
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=None,
)
step_type = tf.constant(
[ts.StepType.FIRST, ts.StepType.LAST, ts.StepType.FIRST,
ts.StepType.LAST])
reward = tf.constant([0, 3, 0, 4], dtype=tf.float32)
discount = tf.constant([1, 0, 1, 0], dtype=tf.float32)
observations = tf.constant(
[[1, 2], [1, 2], [1, 2], [1, 2]], dtype=tf.float32)
time_steps = ts.TimeStep(step_type, reward, discount, observations)
actions = tf.constant([[0], [1], [2], [3]], dtype=tf.float32)
actions_distribution = agent.collect_policy.distribution(
time_steps).action
returns = tf.constant([0.0, 3.0, 0.0, 4.0], dtype=tf.float32)
# Returns on the StepType.LAST should not be counted.
expected_loss = 0.0
loss = agent.policy_gradient_loss(
actions_distribution, actions, time_steps.is_last(), returns, 2)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_ = self.evaluate(loss)
self.assertAllClose(loss_, expected_loss)
@parameterized.parameters(
([[[0.8, 0.2]]], [1],),
([[[0.8, 0.2]], [[0.3, 0.7]]], [0.5, 0.5],),
)
def testEntropyLoss(self, probs, weights):
probs = tf.convert_to_tensor(probs)
distribution = tfp.distributions.Categorical(probs=probs)
shape = probs.shape.as_list()
action_spec = tensor_spec.TensorSpec(shape[2:-1], dtype=tf.int32)
expected = tf.reduce_mean(
-tf.reduce_mean(distribution.entropy()) * weights)
actual = reinforce_agent._entropy_loss(
distribution, action_spec, weights)
self.assertAlmostEqual(self.evaluate(actual), self.evaluate(expected),
places=4)
def testValueEstimationLoss(self):
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=False),
value_network=DummyValueNet(self._obs_spec),
value_estimation_loss_coef=0.5,
optimizer=None,
)
observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)
time_steps = ts.restart(observations, batch_size=2)
returns = tf.constant([1.9, 1.0], dtype=tf.float32)
value_preds, _ = agent._value_network(time_steps.observation,
time_steps.step_type)
expected_loss = 123.20500
loss = agent.value_estimation_loss(
value_preds, returns, 1)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_ = self.evaluate(loss)
self.assertAllClose(loss_, expected_loss)
def testTrainMaskingRewardSingleBanditEpisode(self):
# Test that train reacts correctly to experience when there is only a
# single Bandit episode. Bandit episodes are encoded differently than
# MDP episodes. They have only a single transition with
# step_type=StepType.FIRST and next_step_type=StepType.LAST.
#
# F, L, M = ts.StepType.{FIRST, MID, LAST} in the chart below.
#
# Experience looks like this:
# Trajectories: (F, L)
# observation : [1, 2]
# action : [0]
# reward : 3
# ~is_boundary: 0
# is_last : 1
# valid reward: 3*1
#
# The single bandit transition is valid and not masked.
#
# The expected_loss is > 0.0 in this case, matching the expected_loss of the
# testMaskingRewardSingleEpisodeRewardOnFirst policy_gradient_loss test.
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=tf.compat.v1.train.AdamOptimizer(0.001),
use_advantage_loss=False,
normalize_returns=False,
)
step_type = tf.constant([ts.StepType.FIRST])
next_step_type = tf.constant([ts.StepType.LAST])
reward = tf.constant([3], dtype=tf.float32)
discount = tf.constant([0], dtype=tf.float32)
observations = tf.constant([[1, 2]], dtype=tf.float32)
actions = tf.constant([[0]], dtype=tf.float32)
experience = nest_utils.batch_nested_tensors(trajectory.Trajectory(
step_type, observations, actions, (), next_step_type, reward, discount))
# Rewards should be counted.
expected_loss = 10.8935775757
if tf.executing_eagerly():
loss = lambda: agent.train(experience)
else:
loss = agent.train(experience)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_info = self.evaluate(loss)
self.assertAllClose(loss_info.loss, expected_loss)
def testTrainMaskingRewardMultipleBanditEpisodes(self):
# Test that train reacts correctly to experience when there are multiple
# Bandit episodes. Bandit episodes are encoded differently than
# MDP episodes. They (each) have only a single transition with
# step_type=StepType.FIRST and next_step_type=StepType.LAST. This test
# helps ensure that LAST->FIRST->LAST transitions are handled correctly.
#
# F, L, M = ts.StepType.{FIRST, MID, LAST} in the chart below.
#
# Experience looks like this:
# Trajectories: (F, L) -> (F, L)
# observation : [1, 2] [1, 2]
# action : [0] [2]
# reward : 3 4
# ~is_boundary: 0 0
# is_last : 1 1
# valid reward: 3*1 4*1
#
# All bandit transitions are valid and none are masked.
#
# The expected_loss is > 0.0 in this case, matching the expected_loss of the
# testMaskingRewardMultipleEpisodesRewardOnFirst policy_gradient_loss test.
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=tf.compat.v1.train.AdamOptimizer(0.001),
use_advantage_loss=False,
normalize_returns=False,
)
step_type = tf.constant([ts.StepType.FIRST, ts.StepType.FIRST])
next_step_type = tf.constant([ts.StepType.LAST, ts.StepType.LAST])
reward = tf.constant([3, 4], dtype=tf.float32)
discount = tf.constant([0, 0], dtype=tf.float32)
observations = tf.constant([[1, 2], [1, 2]], dtype=tf.float32)
actions = tf.constant([[0], [2]], dtype=tf.float32)
experience = nest_utils.batch_nested_tensors(trajectory.Trajectory(
step_type, observations, actions, (), next_step_type, reward, discount))
# Rewards on the StepType.FIRST should be counted.
expected_loss = 12.2091741562
if tf.executing_eagerly():
loss = lambda: agent.train(experience)
else:
loss = agent.train(experience)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_info = self.evaluate(loss)
self.assertAllClose(loss_info.loss, expected_loss)
def testTrainMaskingRewardSingleEpisodeRewardOnFirst(self):
# Test that train reacts correctly to experience when there are:
# * A single MDP episode
# * Rewards on the tf.StepType.FIRST transitions
#
# F, L, M = ts.StepType.{FIRST, MID, LAST} in the chart below.
#
# Experience looks like this:
# Trajectories: (F, L) -> (L, F)
# observation : [1, 2] [1, 2]
# action : [0] [1]
# reward : 3 4
# ~is_boundary: 1 0
# is_last : 1 0
# valid reward: 3*1 4*0
#
# The second action & reward should be masked out due to being on a
# boundary (step_type=(L, F)) transition.
#
# The expected_loss is > 0.0 in this case, matching the expected_loss of the
# testMaskingRewardSingleEpisodeRewardOnFirst policy_gradient_loss test.
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=tf.compat.v1.train.AdamOptimizer(0.001),
use_advantage_loss=False,
normalize_returns=False,
)
step_type = tf.constant([ts.StepType.FIRST, ts.StepType.LAST])
next_step_type = tf.constant([ts.StepType.LAST, ts.StepType.FIRST])
reward = tf.constant([3, 4], dtype=tf.float32)
discount = tf.constant([1, 0], dtype=tf.float32)
observations = tf.constant([[1, 2], [1, 2]], dtype=tf.float32)
actions = tf.constant([[0], [1]], dtype=tf.float32)
experience = nest_utils.batch_nested_tensors(trajectory.Trajectory(
step_type, observations, actions, (), next_step_type, reward, discount))
# Rewards on the StepType.FIRST should be counted.
expected_loss = 10.8935775757
if tf.executing_eagerly():
loss = lambda: agent.train(experience)
else:
loss = agent.train(experience)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_info = self.evaluate(loss)
self.assertAllClose(loss_info.loss, expected_loss)
def testTrainMaskingRewardSingleEpisodeRewardOnLast(self):
# Test that train reacts correctly to experience when there are:
# * A single MDP episode
# * Rewards on the tf.StepType.LAST transitions
#
# F, L, M = ts.StepType.{FIRST, MID, LAST} in the chart below.
#
# Experience looks like this:
# Trajectories: (F, L) -> (L, F)
# observation : [1, 2] [1, 2]
# action : [0] [1]
# reward : 0 3
# ~is_boundary: 1 0
# is_last : 1 0
# valid reward: 0*1 3*0
#
# The second action & reward should be masked out due to being on a
# boundary (step_type=(L, F)) transition. The first has a 0 reward.
#
# The expected_loss is = 0.0 in this case.
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=tf.compat.v1.train.AdamOptimizer(0.001),
use_advantage_loss=False,
normalize_returns=False,
)
step_type = tf.constant([ts.StepType.FIRST, ts.StepType.LAST])
next_step_type = tf.constant([ts.StepType.LAST, ts.StepType.FIRST])
reward = tf.constant([0, 3], dtype=tf.float32)
discount = tf.constant([1, 0], dtype=tf.float32)
observations = tf.constant([[1, 2], [1, 2]], dtype=tf.float32)
actions = tf.constant([[0], [1]], dtype=tf.float32)
experience = nest_utils.batch_nested_tensors(trajectory.Trajectory(
step_type, observations, actions, (), next_step_type, reward, discount))
# Rewards on the StepType.LAST should not be counted.
expected_loss = 0.0
if tf.executing_eagerly():
loss = lambda: agent.train(experience)
else:
loss = agent.train(experience)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_info = self.evaluate(loss)
self.assertAllClose(loss_info.loss, expected_loss)
def testTrainMaskingRewardMultipleEpisodesRewardOnFirst(self):
# Test that train reacts correctly to experience when there are:
# * Multiple MDP episodes
# * Rewards on the tf.StepType.FIRST transitions
#
# F, L, M = ts.StepType.{FIRST, MID, LAST} in the chart below.
#
# Experience looks like this:
# Trajectories: (F, L) -> (L, F) -> (F, L) -> (L, F)
# observation : [1, 2] [1, 2] [1, 2] [1, 2]
# action : [0] [1] [2] [3]
# reward : 3 0 4 0
# ~is_boundary: 1 0 1 0
# is_last : 1 0 1 0
# valid reward: 3*1 0*0 4*1 0*0
#
# The second & fourth action & reward should be masked out due to being on a
# boundary (step_type=(L, F)) transition.
#
# The expected_loss is > 0.0 in this case, matching the expected_loss of the
# testMaskingRewardMultipleEpisodesRewardOnFirst policy_gradient_loss test.
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=tf.compat.v1.train.AdamOptimizer(0.001),
use_advantage_loss=False,
normalize_returns=False,
)
step_type = tf.constant([ts.StepType.FIRST, ts.StepType.LAST,
ts.StepType.FIRST, ts.StepType.LAST])
next_step_type = tf.constant([ts.StepType.LAST, ts.StepType.FIRST,
ts.StepType.LAST, ts.StepType.FIRST])
reward = tf.constant([3, 0, 4, 0], dtype=tf.float32)
discount = tf.constant([1, 0, 1, 0], dtype=tf.float32)
observations = tf.constant(
[[1, 2], [1, 2], [1, 2], [1, 2]], dtype=tf.float32)
actions = tf.constant([[0], [1], [2], [3]], dtype=tf.float32)
experience = nest_utils.batch_nested_tensors(trajectory.Trajectory(
step_type, observations, actions, (), next_step_type, reward, discount))
# Rewards on the StepType.FIRST should be counted.
expected_loss = 12.2091741562
if tf.executing_eagerly():
loss = lambda: agent.train(experience)
else:
loss = agent.train(experience)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_info = self.evaluate(loss)
self.assertAllClose(loss_info.loss, expected_loss)
def testTrainMaskingPartialEpisodeMultipleEpisodesRewardOnFirst(self):
# Test that train reacts correctly to experience when there are:
# * Multiple MDP episodes
# * Rewards on the tf.StepType.FIRST transitions
# * Partial episode at end of experience
#
# F, L, M = ts.StepType.{FIRST, MID, LAST} in the chart below.
#
# Experience looks like this:
# Trajectories: (F, L) -> (L, F) -> (F, M) -> (M, M)
# observation : [1, 2] [1, 2] [1, 2] [1, 2]
# action : [0] [1] [2] [3]
# reward : 3 0 4 0
# ~is_boundary: 1 0 1 1
# is_last : 1 0 0 0
# valid reward: 3*1 0*0 4*0 0*0
#
# The second action & reward should be masked out due to being on a
# boundary (step_type=(L, F)) transition. The third & fourth transitions
# should get masked out for everything due to it being an incomplete episode
# (notice there is no trailing step_type=(F,L)).
#
# The expected_loss is > 0.0 in this case, matching the expected_loss of the
# testMaskingRewardSingleEpisodeRewardOnFirst policy_gradient_loss test,
# because the partial second episode should be masked out.
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=tf.compat.v1.train.AdamOptimizer(0.001),
use_advantage_loss=False,
normalize_returns=False,
)
step_type = tf.constant([ts.StepType.FIRST, ts.StepType.LAST,
ts.StepType.FIRST, ts.StepType.MID])
next_step_type = tf.constant([ts.StepType.LAST, ts.StepType.FIRST,
ts.StepType.MID, ts.StepType.MID])
reward = tf.constant([3, 0, 4, 0], dtype=tf.float32)
discount = tf.constant([1, 0, 1, 0], dtype=tf.float32)
observations = tf.constant(
[[1, 2], [1, 2], [1, 2], [1, 2]], dtype=tf.float32)
actions = tf.constant([[0], [1], [2], [3]], dtype=tf.float32)
experience = nest_utils.batch_nested_tensors(trajectory.Trajectory(
step_type, observations, actions, (), next_step_type, reward, discount))
# Rewards on the StepType.FIRST should be counted.
expected_loss = 10.8935775757
if tf.executing_eagerly():
loss = lambda: agent.train(experience)
else:
loss = agent.train(experience)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_info = self.evaluate(loss)
self.assertAllClose(loss_info.loss, expected_loss)
def testTrainMaskingRewardMultipleEpisodesRewardOnLast(self):
# Test that train reacts correctly to experience when there are:
# * Multiple MDP episodes
# * Rewards on the tf.StepType.LAST transitions
#
# F, L, M = ts.StepType.{FIRST, MID, LAST} in the chart below.
#
# Experience looks like this:
# Trajectories: (F, L) -> (L, F) -> (F, L) -> (L, F)
# observation : [1, 2] [1, 2] [1, 2] [1, 2]
# action : [0] [1] [2] [3]
# reward : 0 3 0 4
# ~is_boundary: 1 0 1 0
# is_last : 1 0 1 0
# valid reward: 0*1 3*0 0*1 4*0
#
# The second & fourth action & reward should be masked out due to being on a
# boundary (step_type=(L, F)) transition.
#
# The expected_loss is = 0.0 in this case.
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=True),
optimizer=tf.compat.v1.train.AdamOptimizer(0.001),
use_advantage_loss=False,
normalize_returns=False,
)
step_type = tf.constant([ts.StepType.FIRST, ts.StepType.LAST,
ts.StepType.FIRST, ts.StepType.LAST])
next_step_type = tf.constant([ts.StepType.LAST, ts.StepType.FIRST,
ts.StepType.LAST, ts.StepType.FIRST])
reward = tf.constant([0, 3, 0, 4], dtype=tf.float32)
discount = tf.constant([1, 0, 1, 0], dtype=tf.float32)
observations = tf.constant(
[[1, 2], [1, 2], [1, 2], [1, 2]], dtype=tf.float32)
actions = tf.constant([[0], [1], [2], [3]], dtype=tf.float32)
experience = nest_utils.batch_nested_tensors(trajectory.Trajectory(
step_type, observations, actions, (), next_step_type, reward, discount))
# Rewards on the StepType.LAST should be counted.
expected_loss = 0.0
if tf.executing_eagerly():
loss = lambda: agent.train(experience)
else:
loss = agent.train(experience)
self.evaluate(tf.compat.v1.global_variables_initializer())
loss_info = self.evaluate(loss)
self.assertAllClose(loss_info.loss, expected_loss)
def testPolicy(self):
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=False),
optimizer=None,
)
observations = tf.constant([[1, 2]], dtype=tf.float32)
time_steps = ts.restart(observations, batch_size=2)
actions = agent.policy.action(time_steps).action
self.assertEqual(actions.shape.as_list(), [1, 1])
self.evaluate(tf.compat.v1.global_variables_initializer())
action_values = self.evaluate(actions)
tf.nest.map_structure(
lambda v, s: self.assertAllInRange(v, s.minimum, s.maximum),
action_values, self._action_spec)
@parameterized.parameters(
(False,),
(True,),
)
def testGetInitialPolicyState(self, stateful):
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=False,
stateful=stateful),
optimizer=None,
)
observations = tf.constant([[1, 2]], dtype=tf.float32)
time_steps = ts.restart(observations, batch_size=3)
initial_state = reinforce_agent._get_initial_policy_state(
agent.collect_policy, time_steps)
if stateful:
self.assertAllEqual(self.evaluate(initial_state),
self.evaluate(tf.zeros((3, 2), dtype=tf.float32)))
else:
self.assertEqual(initial_state, ())
def testTrainWithRnn(self):
actor_net = actor_distribution_rnn_network.ActorDistributionRnnNetwork(
self._obs_spec,
self._action_spec,
input_fc_layer_params=None,
output_fc_layer_params=None,
conv_layer_params=None,
lstm_size=(40,))
counter = common.create_variable('test_train_counter')
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=actor_net,
optimizer=tf.compat.v1.train.AdamOptimizer(0.001),
train_step_counter=counter
)
batch_size = 5
observations = tf.constant(
[[[1, 2], [3, 4], [5, 6]]] * batch_size, dtype=tf.float32)
time_steps = ts.TimeStep(
step_type=tf.constant([[1, 1, 2]] * batch_size, dtype=tf.int32),
reward=tf.constant([[1] * 3] * batch_size, dtype=tf.float32),
discount=tf.constant([[1] * 3] * batch_size, dtype=tf.float32),
observation=observations)
actions = tf.constant([[[0], [1], [1]]] * batch_size, dtype=tf.float32)
experience = trajectory.Trajectory(
time_steps.step_type, observations, actions, (),
time_steps.step_type, time_steps.reward, time_steps.discount)
# Force variable creation.
agent.policy.variables()
if tf.executing_eagerly():
loss = lambda: agent.train(experience)
else:
loss = agent.train(experience)
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertEqual(self.evaluate(counter), 0)
self.evaluate(loss)
self.assertEqual(self.evaluate(counter), 1)
@parameterized.parameters(
(False,), (True,)
)
def testWithAdvantageFn(self, with_value_network):
advantage_fn = mock.Mock(
side_effect=lambda returns, _: returns)
value_network = (DummyValueNet(self._obs_spec) if with_value_network
else None)
agent = reinforce_agent.ReinforceAgent(
self._time_step_spec,
self._action_spec,
actor_network=DummyActorNet(
self._obs_spec, self._action_spec, unbounded_actions=False),
value_network=value_network,
advantage_fn=advantage_fn,
optimizer=None,
)
step_type = tf.constant([[ts.StepType.FIRST, ts.StepType.LAST,
ts.StepType.FIRST, ts.StepType.LAST]])
next_step_type = tf.constant([[ts.StepType.LAST, ts.StepType.FIRST,
ts.StepType.LAST, ts.StepType.FIRST]])
reward = tf.constant([[0, 0, 0, 0]], dtype=tf.float32)
discount = tf.constant([[1, 1, 1, 1]], dtype=tf.float32)
observations = tf.constant(
[[[1, 2], [1, 2], [1, 2], [1, 2]]], dtype=tf.float32)
actions = tf.constant([[[0], [1], [2], [3]]], dtype=tf.float32)
experience = trajectory.Trajectory(
step_type, observations, actions, (), next_step_type, reward, discount)
agent.total_loss(experience, reward, None)
advantage_fn.assert_called_once()
if __name__ == '__main__':
tf.test.main()
|
// 12.4.2017 mko
// Berechnung des Konfigurierten Sortiertermes
$(document).ready(function () {
$("#btnSave").click(function () {
let AppFolder = $("#AppFolder").attr("value");
let rpnFName = $("#rpnFName").attr("value");
let ControllerName = $("#ControllerName").attr("value");
let pnWithoutFunction = $("#pnWithoutFunction").attr("value");
let desc = $("#SortDescending").prop('checked');
let ParamTag = $("#ParamTag").attr("value");
let pn = pnWithoutFunction + ' ' + rpnFName + ' ' + ParamTag + ' ' + (desc ? "desc" : "asc");
let uri = AppFolder + ControllerName + '/Index' + '?pn=' + encodeURI(pn);
//window.location.href = uri;
window.location.assign(uri);
});
});
|
"""Utilities for writing code that runs on Python 2 and 3"""
# Copyright (c) 2010-2015 Benjamin Peterson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import functools
import itertools
import operator
import sys
import types
__author__ = "Benjamin Peterson <[email protected]>"
__version__ = "1.9.0"
# Useful for very coarse version differentiation.
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
integer_types = int,
class_types = type,
text_type = str
binary_type = bytes
MAXSIZE = sys.maxsize
else:
string_types = str,
integer_types = (int, int)
class_types = (type, type)
text_type = str
binary_type = str
if sys.platform.startswith("java"):
# Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)
else:
# It's possible to have sizeof(long) != sizeof(Py_ssize_t).
class X(object):
def __len__(self):
return 1 << 31
try:
len(X())
except OverflowError:
# 32-bit
MAXSIZE = int((1 << 31) - 1)
else:
# 64-bit
MAXSIZE = int((1 << 63) - 1)
del X
def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc
def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name]
class _LazyDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result) # Invokes __set__.
try:
# This is a bit ugly, but it avoids running this again by
# removing this descriptor.
delattr(obj.__class__, self.name)
except AttributeError:
pass
return result
class MovedModule(_LazyDescr):
def __init__(self, name, old, new=None):
super(MovedModule, self).__init__(name)
if PY3:
if new is None:
new = name
self.mod = new
else:
self.mod = old
def _resolve(self):
return _import_module(self.mod)
def __getattr__(self, attr):
_module = self._resolve()
value = getattr(_module, attr)
setattr(self, attr, value)
return value
class _LazyModule(types.ModuleType):
def __init__(self, name):
super(_LazyModule, self).__init__(name)
self.__doc__ = self.__class__.__doc__
def __dir__(self):
attrs = ["__doc__", "__name__"]
attrs += [attr.name for attr in self._moved_attributes]
return attrs
# Subclasses should override this
_moved_attributes = []
class MovedAttribute(_LazyDescr):
def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
super(MovedAttribute, self).__init__(name)
if PY3:
if new_mod is None:
new_mod = name
self.mod = new_mod
if new_attr is None:
if old_attr is None:
new_attr = name
else:
new_attr = old_attr
self.attr = new_attr
else:
self.mod = old_mod
if old_attr is None:
old_attr = name
self.attr = old_attr
def _resolve(self):
module = _import_module(self.mod)
return getattr(module, self.attr)
class _SixMetaPathImporter(object):
"""
A meta path importer to import six.moves and its submodules.
This class implements a PEP302 finder and loader. It should be compatible
with Python 2.5 and all existing versions of Python3
"""
def __init__(self, six_module_name):
self.name = six_module_name
self.known_modules = {}
def _add_module(self, mod, *fullnames):
for fullname in fullnames:
self.known_modules[self.name + "." + fullname] = mod
def _get_module(self, fullname):
return self.known_modules[self.name + "." + fullname]
def find_module(self, fullname, path=None):
if fullname in self.known_modules:
return self
return None
def __get_module(self, fullname):
try:
return self.known_modules[fullname]
except KeyError:
raise ImportError("This loader does not know module " + fullname)
def load_module(self, fullname):
try:
# in case of a reload
return sys.modules[fullname]
except KeyError:
pass
mod = self.__get_module(fullname)
if isinstance(mod, MovedModule):
mod = mod._resolve()
else:
mod.__loader__ = self
sys.modules[fullname] = mod
return mod
def is_package(self, fullname):
"""
Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)
"""
return hasattr(self.__get_module(fullname), "__path__")
def get_code(self, fullname):
"""Return None
Required, if is_package is implemented"""
self.__get_module(fullname) # eventually raises ImportError
return None
get_source = get_code # same as get_code
_importer = _SixMetaPathImporter(__name__)
class _MovedItems(_LazyModule):
"""Lazy loading of moved objects"""
__path__ = [] # mark as package
_moved_attributes = [
MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
MovedAttribute("intern", "__builtin__", "sys"),
MovedAttribute("map", "itertools", "builtins", "imap", "map"),
MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
MovedAttribute("reduce", "__builtin__", "functools"),
MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),
MovedAttribute("StringIO", "StringIO", "io"),
MovedAttribute("UserDict", "UserDict", "collections"),
MovedAttribute("UserList", "UserList", "collections"),
MovedAttribute("UserString", "UserString", "collections"),
MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
MovedModule("builtins", "__builtin__"),
MovedModule("configparser", "ConfigParser"),
MovedModule("copyreg", "copy_reg"),
MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"),
MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
MovedModule("http_cookies", "Cookie", "http.cookies"),
MovedModule("html_entities", "htmlentitydefs", "html.entities"),
MovedModule("html_parser", "HTMLParser", "html.parser"),
MovedModule("http_client", "httplib", "http.client"),
MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),
MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
MovedModule("cPickle", "cPickle", "pickle"),
MovedModule("queue", "Queue"),
MovedModule("reprlib", "repr"),
MovedModule("socketserver", "SocketServer"),
MovedModule("_thread", "thread", "_thread"),
MovedModule("tkinter", "Tkinter"),
MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
MovedModule("tkinter_colorchooser", "tkColorChooser",
"tkinter.colorchooser"),
MovedModule("tkinter_commondialog", "tkCommonDialog",
"tkinter.commondialog"),
MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
MovedModule("tkinter_font", "tkFont", "tkinter.font"),
MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
"tkinter.simpledialog"),
MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
MovedModule("winreg", "_winreg"),
]
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr)
if isinstance(attr, MovedModule):
_importer._add_module(attr, "moves." + attr.name)
del attr
_MovedItems._moved_attributes = _moved_attributes
moves = _MovedItems(__name__ + ".moves")
_importer._add_module(moves, "moves")
class Module_six_moves_urllib_parse(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_parse"""
_urllib_parse_moved_attributes = [
MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
MovedAttribute("urljoin", "urlparse", "urllib.parse"),
MovedAttribute("urlparse", "urlparse", "urllib.parse"),
MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
MovedAttribute("quote", "urllib", "urllib.parse"),
MovedAttribute("quote_plus", "urllib", "urllib.parse"),
MovedAttribute("unquote", "urllib", "urllib.parse"),
MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
MovedAttribute("urlencode", "urllib", "urllib.parse"),
MovedAttribute("splitquery", "urllib", "urllib.parse"),
MovedAttribute("splittag", "urllib", "urllib.parse"),
MovedAttribute("splituser", "urllib", "urllib.parse"),
MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),
MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),
MovedAttribute("uses_params", "urlparse", "urllib.parse"),
MovedAttribute("uses_query", "urlparse", "urllib.parse"),
MovedAttribute("uses_relative", "urlparse", "urllib.parse"),
]
for attr in _urllib_parse_moved_attributes:
setattr(Module_six_moves_urllib_parse, attr.name, attr)
del attr
Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
"moves.urllib_parse", "moves.urllib.parse")
class Module_six_moves_urllib_error(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_error"""
_urllib_error_moved_attributes = [
MovedAttribute("URLError", "urllib2", "urllib.error"),
MovedAttribute("HTTPError", "urllib2", "urllib.error"),
MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
]
for attr in _urllib_error_moved_attributes:
setattr(Module_six_moves_urllib_error, attr.name, attr)
del attr
Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
"moves.urllib_error", "moves.urllib.error")
class Module_six_moves_urllib_request(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_request"""
_urllib_request_moved_attributes = [
MovedAttribute("urlopen", "urllib2", "urllib.request"),
MovedAttribute("install_opener", "urllib2", "urllib.request"),
MovedAttribute("build_opener", "urllib2", "urllib.request"),
MovedAttribute("pathname2url", "urllib", "urllib.request"),
MovedAttribute("url2pathname", "urllib", "urllib.request"),
MovedAttribute("getproxies", "urllib", "urllib.request"),
MovedAttribute("Request", "urllib2", "urllib.request"),
MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
MovedAttribute("FileHandler", "urllib2", "urllib.request"),
MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
MovedAttribute("urlretrieve", "urllib", "urllib.request"),
MovedAttribute("urlcleanup", "urllib", "urllib.request"),
MovedAttribute("URLopener", "urllib", "urllib.request"),
MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
]
for attr in _urllib_request_moved_attributes:
setattr(Module_six_moves_urllib_request, attr.name, attr)
del attr
Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
"moves.urllib_request", "moves.urllib.request")
class Module_six_moves_urllib_response(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_response"""
_urllib_response_moved_attributes = [
MovedAttribute("addbase", "urllib", "urllib.response"),
MovedAttribute("addclosehook", "urllib", "urllib.response"),
MovedAttribute("addinfo", "urllib", "urllib.response"),
MovedAttribute("addinfourl", "urllib", "urllib.response"),
]
for attr in _urllib_response_moved_attributes:
setattr(Module_six_moves_urllib_response, attr.name, attr)
del attr
Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
"moves.urllib_response", "moves.urllib.response")
class Module_six_moves_urllib_robotparser(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_robotparser"""
_urllib_robotparser_moved_attributes = [
MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
]
for attr in _urllib_robotparser_moved_attributes:
setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
del attr
Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
"moves.urllib_robotparser", "moves.urllib.robotparser")
class Module_six_moves_urllib(types.ModuleType):
"""Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
__path__ = [] # mark as package
parse = _importer._get_module("moves.urllib_parse")
error = _importer._get_module("moves.urllib_error")
request = _importer._get_module("moves.urllib_request")
response = _importer._get_module("moves.urllib_response")
robotparser = _importer._get_module("moves.urllib_robotparser")
def __dir__(self):
return ['parse', 'error', 'request', 'response', 'robotparser']
_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),
"moves.urllib")
def add_move(move):
"""Add an item to six.moves."""
setattr(_MovedItems, move.name, move)
def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,))
if PY3:
_meth_func = "__func__"
_meth_self = "__self__"
_func_closure = "__closure__"
_func_code = "__code__"
_func_defaults = "__defaults__"
_func_globals = "__globals__"
else:
_meth_func = "im_func"
_meth_self = "im_self"
_func_closure = "func_closure"
_func_code = "func_code"
_func_defaults = "func_defaults"
_func_globals = "func_globals"
try:
advance_iterator = next
except NameError:
def advance_iterator(it):
return it.__next__()
next = advance_iterator
try:
callable = callable
except NameError:
def callable(obj):
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
if PY3:
def get_unbound_function(unbound):
return unbound
create_bound_method = types.MethodType
Iterator = object
else:
def get_unbound_function(unbound):
return unbound.__func__
def create_bound_method(func, obj):
return types.MethodType(func, obj, obj.__class__)
class Iterator(object):
def __next__(self):
return type(self).__next__(self)
callable = callable
_add_doc(get_unbound_function,
"""Get the function out of a possibly unbound function""")
get_method_function = operator.attrgetter(_meth_func)
get_method_self = operator.attrgetter(_meth_self)
get_function_closure = operator.attrgetter(_func_closure)
get_function_code = operator.attrgetter(_func_code)
get_function_defaults = operator.attrgetter(_func_defaults)
get_function_globals = operator.attrgetter(_func_globals)
if PY3:
def iterkeys(d, **kw):
return iter(d.keys(**kw))
def itervalues(d, **kw):
return iter(d.values(**kw))
def iteritems(d, **kw):
return iter(d.items(**kw))
def iterlists(d, **kw):
return iter(d.lists(**kw))
viewkeys = operator.methodcaller("keys")
viewvalues = operator.methodcaller("values")
viewitems = operator.methodcaller("items")
else:
def iterkeys(d, **kw):
return iter(d.iterkeys(**kw))
def itervalues(d, **kw):
return iter(d.itervalues(**kw))
def iteritems(d, **kw):
return iter(d.iteritems(**kw))
def iterlists(d, **kw):
return iter(d.iterlists(**kw))
viewkeys = operator.methodcaller("viewkeys")
viewvalues = operator.methodcaller("viewvalues")
viewitems = operator.methodcaller("viewitems")
_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
_add_doc(itervalues, "Return an iterator over the values of a dictionary.")
_add_doc(iteritems,
"Return an iterator over the (key, value) pairs of a dictionary.")
_add_doc(iterlists,
"Return an iterator over the (key, [values]) pairs of a dictionary.")
if PY3:
def b(s):
return s.encode("latin-1")
def u(s):
return s
chr = chr
if sys.version_info[1] <= 1:
def int2byte(i):
return bytes((i,))
else:
# This is about 2x faster than the implementation above on 3.2+
int2byte = operator.methodcaller("to_bytes", 1, "big")
byte2int = operator.itemgetter(0)
indexbytes = operator.getitem
iterbytes = iter
import io
StringIO = io.StringIO
BytesIO = io.BytesIO
_assertCountEqual = "assertCountEqual"
_assertRaisesRegex = "assertRaisesRegex"
_assertRegex = "assertRegex"
else:
def b(s):
return s
# Workaround for standalone backslash
def u(s):
return str(s.replace(r'\\', r'\\\\'), "unicode_escape")
chr = chr
int2byte = chr
def byte2int(bs):
return ord(bs[0])
def indexbytes(buf, i):
return ord(buf[i])
iterbytes = functools.partial(itertools.imap, ord)
import io
StringIO = BytesIO = io.StringIO
_assertCountEqual = "assertItemsEqual"
_assertRaisesRegex = "assertRaisesRegexp"
_assertRegex = "assertRegexpMatches"
_add_doc(b, """Byte literal""")
_add_doc(u, """Text literal""")
def assertCountEqual(self, *args, **kwargs):
return getattr(self, _assertCountEqual)(*args, **kwargs)
def assertRaisesRegex(self, *args, **kwargs):
return getattr(self, _assertRaisesRegex)(*args, **kwargs)
def assertRegex(self, *args, **kwargs):
return getattr(self, _assertRegex)(*args, **kwargs)
if PY3:
exec_ = getattr(moves.builtins, "exec")
def reraise(tp, value, tb=None):
if value is None:
value = tp()
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
else:
def exec_(_code_, _globs_=None, _locs_=None):
"""Execute code in a namespace."""
if _globs_ is None:
frame = sys._getframe(1)
_globs_ = frame.f_globals
if _locs_ is None:
_locs_ = frame.f_locals
del frame
elif _locs_ is None:
_locs_ = _globs_
exec("""exec _code_ in _globs_, _locs_""")
exec_("""def reraise(tp, value, tb=None):
raise tp, value, tb
""")
if sys.version_info[:2] == (3, 2):
exec_("""def raise_from(value, from_value):
if from_value is None:
raise value
raise value from from_value
""")
elif sys.version_info[:2] > (3, 2):
exec_("""def raise_from(value, from_value):
raise value from from_value
""")
else:
def raise_from(value, from_value):
raise value
print_ = getattr(moves.builtins, "print", None)
if print_ is None:
def print_(*args, **kwargs):
"""The new-style print function for Python 2.4 and 2.5."""
fp = kwargs.pop("file", sys.stdout)
if fp is None:
return
def write(data):
if not isinstance(data, str):
data = str(data)
# If the file has an encoding, encode unicode with it.
if (isinstance(fp, file) and
isinstance(data, str) and
fp.encoding is not None):
errors = getattr(fp, "errors", None)
if errors is None:
errors = "strict"
data = data.encode(fp.encoding, errors)
fp.write(data)
want_unicode = False
sep = kwargs.pop("sep", None)
if sep is not None:
if isinstance(sep, str):
want_unicode = True
elif not isinstance(sep, str):
raise TypeError("sep must be None or a string")
end = kwargs.pop("end", None)
if end is not None:
if isinstance(end, str):
want_unicode = True
elif not isinstance(end, str):
raise TypeError("end must be None or a string")
if kwargs:
raise TypeError("invalid keyword arguments to print()")
if not want_unicode:
for arg in args:
if isinstance(arg, str):
want_unicode = True
break
if want_unicode:
newline = str("\n")
space = str(" ")
else:
newline = "\n"
space = " "
if sep is None:
sep = space
if end is None:
end = newline
for i, arg in enumerate(args):
if i:
write(sep)
write(arg)
write(end)
if sys.version_info[:2] < (3, 3):
_print = print_
def print_(*args, **kwargs):
fp = kwargs.get("file", sys.stdout)
flush = kwargs.pop("flush", False)
_print(*args, **kwargs)
if flush and fp is not None:
fp.flush()
_add_doc(reraise, """Reraise an exception.""")
if sys.version_info[0:2] < (3, 4):
def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
def wrapper(f):
f = functools.wraps(wrapped, assigned, updated)(f)
f.__wrapped__ = wrapped
return f
return wrapper
else:
wraps = functools.wraps
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a dummy
# metaclass for one level of class instantiation that replaces itself with
# the actual metaclass.
class metaclass(meta):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
# Complete the moves implementation.
# This code is at the end of this module to speed up module loading.
# Turn this module into a package.
__path__ = [] # required for PEP 302 and PEP 451
__package__ = __name__ # see PEP 366 @ReservedAssignment
if globals().get("__spec__") is not None:
__spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
# Remove other six meta path importers, since they cause problems. This can
# happen if six is removed from sys.modules and then reloaded. (Setuptools does
# this for some reason.)
if sys.meta_path:
for i, importer in enumerate(sys.meta_path):
# Here's some real nastiness: Another "instance" of the six module might
# be floating around. Therefore, we can't use isinstance() to check for
# the six meta path importer, since the other six instance will have
# inserted an importer with different class.
if (type(importer).__name__ == "_SixMetaPathImporter" and
importer.name == __name__):
del sys.meta_path[i]
break
del i, importer
# Finally, add the importer to the meta path import hook.
sys.meta_path.append(_importer)
|
import React from 'react';
import SortColumn, { SortByDirection } from '../../SortColumn';
import { css } from '@patternfly/react-styles';
import styles from '@patternfly/patternfly/components/Table/table.css';
import buttonStyles from '@patternfly/patternfly/components/Button/button.css';
export default (label, { columnIndex, column, property }) => {
const {
extraParams: { sortBy, onSort }
} = column;
const extraData = {
columnIndex,
column,
property
};
const isSortedBy = sortBy && columnIndex === sortBy.index;
function sortClicked(event) {
let reversedDirection;
if (!isSortedBy) {
reversedDirection = SortByDirection.asc;
} else {
reversedDirection = sortBy.direction === SortByDirection.asc ? SortByDirection.desc : SortByDirection.asc;
}
onSort && onSort(event, columnIndex, reversedDirection, extraData);
}
return {
className: css(styles.tableSort, isSortedBy && styles.modifiers.selected),
'aria-sort': isSortedBy ? `${sortBy.direction}ending` : 'none',
children: (
<SortColumn
isSortedBy={isSortedBy}
sortDirection={isSortedBy ? sortBy.direction : ''}
onSort={sortClicked}
className={css(buttonStyles.button, buttonStyles.modifiers.plain)}
>
{label}
</SortColumn>
)
};
};
|
//
// Tests autosplit locations with force : true, for small collections
//
(function() {
'use strict';
var st = new ShardingTest(
{shards: 1, mongos: 1, other: {chunkSize: 1, mongosOptions: {noAutoSplit: ""}}});
var mongos = st.s0;
var admin = mongos.getDB("admin");
var config = mongos.getDB("config");
var shardAdmin = st.shard0.getDB("admin");
var coll = mongos.getCollection("foo.bar");
assert.commandWorked(admin.runCommand({enableSharding: coll.getDB() + ""}));
assert.commandWorked(admin.runCommand({shardCollection: coll + "", key: {_id: 1}}));
assert.commandWorked(admin.runCommand({split: coll + "", middle: {_id: 0}}));
jsTest.log("Insert a bunch of data into the low chunk of a collection," +
" to prevent relying on stats.");
var data128k = "x";
for (var i = 0; i < 7; i++)
data128k += data128k;
var bulk = coll.initializeUnorderedBulkOp();
for (var i = 0; i < 1024; i++) {
bulk.insert({_id: -(i + 1)});
}
assert.writeOK(bulk.execute());
jsTest.log("Insert 32 docs into the high chunk of a collection");
bulk = coll.initializeUnorderedBulkOp();
for (var i = 0; i < 32; i++) {
bulk.insert({_id: i});
}
assert.writeOK(bulk.execute());
jsTest.log("Split off MaxKey chunk...");
assert.commandWorked(admin.runCommand({split: coll + "", middle: {_id: 32}}));
jsTest.log("Keep splitting chunk multiple times...");
st.printShardingStatus();
for (var i = 0; i < 5; i++) {
assert.commandWorked(admin.runCommand({split: coll + "", find: {_id: 0}}));
st.printShardingStatus();
}
// Make sure we can't split further than 5 (2^5) times
assert.commandFailed(admin.runCommand({split: coll + "", find: {_id: 0}}));
var chunks = config.chunks.find({'min._id': {$gte: 0, $lt: 32}}).sort({min: 1}).toArray();
printjson(chunks);
// Make sure the chunks grow by 2x (except the first)
var nextSize = 1;
for (var i = 0; i < chunks.size; i++) {
assert.eq(coll.count({_id: {$gte: chunks[i].min._id, $lt: chunks[i].max._id}}), nextSize);
if (i != 0)
nextSize += nextSize;
}
st.stop();
})();
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import nodemailer from 'nodemailer';
import { Action, ActionResult } from '../';
export const EMAIL_ACTION_ID = 'xpack-notifications-email';
/**
* Email Action enables generic sending of emails, when configured.
*/
export class EmailAction extends Action {
/**
* Create a new Action capable of sending emails.
*
* @param {Object} server Kibana server object.
* @param {Object} options Configuration options for Nodemailer.
* @param {Object} defaults Default fields used when sending emails.
* @param {Object} _nodemailer Exposed for tests.
*/
constructor({ server, options, defaults = { }, _nodemailer = nodemailer }) {
super({ server, id: EMAIL_ACTION_ID, name: 'Email' });
this.transporter = _nodemailer.createTransport(options, defaults);
this.defaults = defaults;
}
getMissingFields(notification) {
const missingFields = [];
if (!Boolean(this.defaults.to) && !Boolean(notification.to)) {
missingFields.push({
field: 'to',
name: 'To',
type: 'email',
});
}
if (!Boolean(this.defaults.from) && !Boolean(notification.from)) {
missingFields.push({
field: 'from',
name: 'From',
type: 'email',
});
}
if (!Boolean(notification.subject)) {
missingFields.push({
field: 'subject',
name: 'Subject',
type: 'text',
});
}
if (!Boolean(notification.markdown)) {
missingFields.push({
field: 'markdown',
name: 'Body',
type: 'markdown',
});
}
return missingFields;
}
async doPerformHealthCheck() {
// this responds with a boolean 'true' response, otherwise throws an Error
const response = await this.transporter.verify();
return new ActionResult({
message: `Email action SMTP configuration has been verified.`,
response: {
verified: response
},
});
}
async doPerformAction(notification) {
// Note: This throws an Error upon failure
const response = await this.transporter.sendMail({
// email routing
from: notification.from,
to: notification.to,
cc: notification.cc,
bcc: notification.bcc,
// email content
subject: notification.subject,
html: notification.markdown,
text: notification.markdown,
});
return new ActionResult({
message: `Sent email for '${notification.subject}'.`,
response,
});
}
}
|
var path = require('path');
module.exports = {
mode: 'production',
context: path.join(__dirname, '/dist'),
entry: './client.js',
output: {
path: path.join(__dirname, '/browser'),
filename: 'client.js',
library: 'SubscriptionsTransportWs'
}
};
|
"""
Print out Py-ART version information.
This file can also be run as a script to report on dependencies before a
build: python pyart/_debug_info.py
"""
from __future__ import print_function
import os
import sys
def _debug_info(stream=None):
"""
Print out version and status information for debugging.
This file can be run as a script from the source directory to report on
dependecies before a build using: **python pyart/_debug_info.py**.
Parameters
----------
stream : file-like object
Stream to print the information to, None prints to sys.stdout.
"""
if stream is None:
stream = sys.stdout
# remove the current path from the import search path
# if this is not done ./io is found and not the std library io module.
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir in sys.path:
sys.path.remove(current_dir)
try:
import pyart
pyart_version = pyart.__version__
except:
pyart_version = "MISSING"
try:
import platform
python_version = platform.python_version()
except:
python_version = "MISSING"
try:
import numpy
numpy_version = numpy.__version__
except:
numpy_version = "MISSING"
try:
import numpy
numpy_version = numpy.__version__
except:
numpy_version = "MISSING"
try:
import scipy
scipy_version = scipy.__version__
except:
scipy_version = "MISSING"
try:
import matplotlib
matplotlib_version = matplotlib.__version__
except:
matplotlib_version = "MISSING"
try:
import netCDF4
netCDF4_version = netCDF4.__version__
except:
netCDF4_version = "MISSING"
try:
rsl_version = pyart.io._rsl_interface._RSL_VERSION_STR
except:
rsl_version = "MISSING"
try:
import cylp
cylp_available = "Available"
except:
cylp_available = "MISSING"
try:
import glpk
glpk_version = "%i.%i" % (glpk.env.version)
except:
glpk_version = "MISSING"
try:
import cvxopt.info
cvxopt_version = cvxopt.info.version
except:
cvxopt_version = "MISSING"
try:
from mpl_toolkits import basemap
basemap_version = basemap.__version__
except:
basemap_version = "MISSING"
try:
import nose
nose_version = nose.__version__
except:
nose_version = "MISSING"
print("Py-ART version:", pyart_version, file=stream)
print("", file=stream)
print("---- Dependencies ----", file=stream)
print("Python version:", python_version, file=stream)
print("NumPy version:", numpy_version, file=stream)
print("SciPy version:", scipy_version, file=stream)
print("matplotlib version:", matplotlib_version, file=stream)
print("netCDF4 version:", netCDF4_version, file=stream)
print("", file=stream)
print("---- Optional dependencies ----", file=stream)
print("TRMM RSL version:", rsl_version, file=stream)
print("CyLP:", cylp_available, file=stream)
print("PyGLPK version:", glpk_version, file=stream)
print("CVXOPT version:", cvxopt_version, file=stream)
print("basemap version:", basemap_version, file=stream)
print("nose version:", nose_version, file=stream)
if __name__ == "__main__":
_debug_info()
|
/**
* @category saltcorn-data
* @module models/user
* @subcategory models
*/
const db = require("../db");
const bcrypt = require("bcryptjs");
const { contract, is } = require("contractis");
const { v4: uuidv4 } = require("uuid");
const dumbPasswords = require("dumb-passwords");
const validator = require("email-validator");
/**
* @param {object} o
* @returns {*}
*/
const safeUserFields = (o) => {
const {
email,
password,
language,
_attributes,
api_token,
verification_token,
verified_on,
disabled,
id,
reset_password_token,
reset_password_expiry,
role_id,
...rest
} = o;
return rest;
};
/**
* User
* @category saltcorn-data
*/
class User {
/**
* User constructor
* @param {object} o
*/
constructor(o) {
this.email = o.email;
this.password = o.password;
this.language = o.language;
this._attributes =
typeof o._attributes === "string"
? JSON.parse(o._attributes)
: o._attributes || {};
this.api_token = o.api_token;
this.verification_token = o.verification_token;
this.verified_on = ["string", "number"].includes(typeof o.verified_on)
? new Date(o.verified_on)
: o.verified_on;
this.disabled = !!o.disabled;
this.id = o.id ? +o.id : o.id;
this.reset_password_token = o.reset_password_token || null;
this.reset_password_expiry =
(typeof o.reset_password_expiry === "string" &&
o.reset_password_expiry.length > 0) ||
typeof o.reset_password_expiry === "number"
? new Date(o.reset_password_expiry)
: o.reset_password_expiry || null;
this.role_id = o.role_id ? +o.role_id : 8;
Object.assign(this, safeUserFields(o));
contract.class(this);
}
/**
* Get bcrypt hash for Password
* @param pw - password string
* @returns {Promise<string>}
*/
static async hashPassword(pw) {
return await bcrypt.hash(pw, 10);
}
/**
* Check password
* @param pw - password string
* @returns {boolean}
*/
checkPassword(pw) {
return bcrypt.compareSync(pw, this.password);
}
/**
* Change password
* @param newpw - new password string
* @param expireToken - if true than force reset password token
* @returns {Promise<void>} no result
*/
async changePasswordTo(newpw, expireToken) {
const password = await User.hashPassword(newpw);
this.password = password;
const upd = { password };
if (expireToken) upd.reset_password_token = null;
await db.update("users", upd, this.id);
}
/**
* Find or Create User
* @param k
* @param v
* @param {object} [uo = {}]
* @returns {Promise<{session_object: {_attributes: {}}, _attributes: {}}|User|*|boolean|{error: string}|User>}
*/
static async findOrCreateByAttribute(k, v, uo = {}) {
const u = await User.findOne({ _attributes: { json: [k, v] } });
if (u) return u;
else {
const { getState } = require("../db/state");
const email_mask = getState().getConfig("email_mask");
if (email_mask && uo.email) {
const { check_email_mask } = require("./config");
if (!check_email_mask(uo.email)) {
return false;
}
}
const new_user_form = getState().getConfig("new_user_form");
if (new_user_form) {
// cannot create user, return pseudo-user
const pseudoUser = { ...uo, _attributes: { [k]: v } };
return { ...pseudoUser, session_object: pseudoUser };
} else {
const extra = {};
if (!uo.password) extra.password = User.generate_password();
return await User.create({ ...uo, ...extra, _attributes: { [k]: v } });
}
}
}
/**
* Create user
* @param uo - user object
* @returns {Promise<{error: string}|User>}
*/
static async create(uo) {
const { email, password, passwordRepeat, role_id, ...rest } = uo;
const u = new User({ email, password, role_id });
if (User.unacceptable_password_reason(u.password))
return {
error:
"Password not accepted: " +
User.unacceptable_password_reason(u.password),
};
const hashpw = await User.hashPassword(u.password);
const ex = await User.findOne({ email: u.email });
if (ex) return { error: `User with this email already exists` };
const id = await db.insert("users", {
email: u.email,
password: hashpw,
role_id: u.role_id,
...rest,
});
u.id = id;
return u;
}
/**
* Create session object for user
* @type {{role_id: number, language, id, email, tenant: *}}
*/
get session_object() {
const so = {
email: this.email,
id: this.id,
role_id: this.role_id,
language: this.language,
tenant: db.getTenantSchema(),
};
Object.assign(so, safeUserFields(this));
return so;
}
/**
* Authenticate User
* @param uo - user object
* @returns {Promise<boolean|User>}
*/
static async authenticate(uo) {
const { password, ...uoSearch } = uo;
const urows = await User.find(uoSearch, { limit: 2 });
if (urows.length !== 1) return false;
const [urow] = urows;
if (urow.disabled) return false;
const cmp = urow.checkPassword(password || "");
if (cmp) return new User(urow);
else return false;
}
/**
* Find users list
* @param where - where object
* @param selectopts - select options
* @returns {Promise<User[]>}
*/
static async find(where, selectopts) {
const us = await db.select("users", where, selectopts);
return us.map((u) => new User(u));
}
/**
* Find one user
* @param where - where object
* @returns {Promise<User|*>}
*/
static async findOne(where) {
const u = await db.selectMaybeOne("users", where);
return u ? new User(u) : u;
}
/**
* Check that user table is not empty in database
* @deprecated use method count()
* @returns {Promise<boolean>} true if there are users in db
*/
static async nonEmpty() {
const res = await db.count("users");
return res > 0;
}
/**
* Delete user based on session object
* @returns {Promise<void>}
*/
async delete() {
const schema = db.getTenantSchemaPrefix();
this.destroy_sessions();
await db.query(`delete FROM ${schema}users WHERE id = $1`, [this.id]);
}
/**
* Set language for User in database
* @param language
* @returns {Promise<void>}
*/
async set_language(language) {
await this.update({ language });
}
/**
* Update User
* @param row
* @returns {Promise<void>}
*/
async update(row) {
await db.update("users", row, this.id);
}
/**
* Get new reset token
* @returns {Promise<*|string>}
*/
async getNewResetToken() {
const reset_password_token_uuid = uuidv4();
const reset_password_expiry = new Date();
reset_password_expiry.setDate(new Date().getDate() + 1);
const reset_password_token = await bcrypt.hash(
reset_password_token_uuid,
10
);
await db.update(
"users",
{ reset_password_token, reset_password_expiry },
this.id
);
return reset_password_token_uuid;
}
/**
* Add new API token to user
* @returns {Promise<string>}
*/
async getNewAPIToken() {
const api_token = uuidv4();
await db.update("users", { api_token }, this.id);
this.api_token = api_token;
return api_token;
}
/**
* Remove API token for user
* @returns {Promise<string>}
*/
async removeAPIToken() {
const api_token = null;
await db.update("users", { api_token }, this.id);
this.api_token = api_token;
return api_token;
}
/**
* Validate password
* @param pw
* @returns {string}
*/
static unacceptable_password_reason(pw) {
if (typeof pw !== "string") return "Not a string";
if (pw.length < 8) return "Too short";
if (dumbPasswords.check(pw)) return "Too common";
}
/**
* Validate email
* @param email
* @returns {boolean}
*/
// TBD that validation works
static valid_email(email) {
return validator.validate(email);
}
/**
* Verification with token
* @param email - email sting
* @param verification_token - verification token string
* @returns {Promise<{error: string}|boolean>} true if verification passed, error string if not
*/
static async verifyWithToken({ email, verification_token }) {
if (
typeof verification_token !== "string" ||
typeof email !== "string" ||
verification_token.length < 10 ||
!email
)
return { error: "Invalid token" };
const u = await User.findOne({ email, verification_token });
if (!u) return { error: "Invalid token" };
return await u.set_to_verified();
}
/**
* @returns {Promise<boolean>}
*/
async set_to_verified() {
const upd = { verified_on: new Date() };
const { getState } = require("../db/state");
const elevate_verified = +getState().getConfig("elevate_verified");
if (elevate_verified)
upd.role_id = Math.min(elevate_verified, this.role_id);
await db.update("users", upd, this.id);
Object.assign(this, upd);
const Trigger = require("./trigger");
Trigger.emitEvent("UserVerified", null, this, this);
return true;
}
/**
* Reset password using token
* @param email - email address string
* @param reset_password_token - reset password token string
* @param password
* @returns {Promise<{error: string}|{success: boolean}>}
*/
static async resetPasswordWithToken({
email,
reset_password_token,
password,
}) {
if (
typeof reset_password_token !== "string" ||
typeof email !== "string" ||
reset_password_token.length < 10
)
return {
error: "Invalid token or invalid token length or incorrect email",
};
const u = await User.findOne({ email });
if (u && new Date() < u.reset_password_expiry && u.reset_password_token) {
const match = bcrypt.compareSync(
reset_password_token,
u.reset_password_token
);
if (match) {
if (User.unacceptable_password_reason(password))
return {
error:
"Password not accepted: " +
User.unacceptable_password_reason(password),
};
await u.changePasswordTo(password, true);
return { success: true };
} else return { error: "User not found or expired token" };
} else {
return { error: "User not found or expired token" };
}
}
/**
* Count users in database
* @param where
* @returns {Promise<number>}
*/
// TBD I think that method is simular to notEmppty() but more powerfull.
// TBD use some rules for naming of methods - e.g. this method will have name count_users or countUsers because of methods relay on roles in this class
static async count(where) {
return await db.count("users", where || {});
}
/**
* Get available roles
* @returns {Promise<*>}
*/
static async get_roles() {
const rs = await db.select("_sc_roles", {}, { orderBy: "id" });
return rs;
}
/**
* Generate password
* @returns {string}
*/
static generate_password() {
const candidate = is.str.generate().split(" ").join("");
// TBD low performance impact - un
if (candidate.length < 10) return User.generate_password();
else return candidate;
}
/**
* @returns {Promise<void>}
*/
async destroy_sessions() {
if (!db.isSQLite) {
const schema = db.getTenantSchema();
await db.query(
`delete from _sc_session
where sess->'passport'->'user'->>'id' = $1
and sess->'passport'->'user'->>'tenant' = $2`,
[`${this.id}`, schema]
);
}
}
/**
* @param {object} req
*/
relogin(req) {
req.login(this.session_object, function (err) {
if (err) req.flash("danger", err);
});
}
}
User.contract = {
variables: {
id: is.maybe(is.posint),
email: is.str,
//password: is.str,
disabled: is.bool,
language: is.maybe(is.str),
_attributes: is.maybe(is.obj({})),
role_id: is.posint,
reset_password_token: is.maybe(
is.and(
is.str,
is.sat((s) => s.length > 10)
)
),
reset_password_expiry: is.maybe(is.class("Date")),
},
methods: {
delete: is.fun([], is.promise(is.undefined)),
destroy_sessions: is.fun([], is.promise(is.undefined)),
changePasswordTo: is.fun(is.str, is.promise(is.undefined)),
checkPassword: is.fun(is.str, is.bool),
},
static_methods: {
find: is.fun(is.maybe(is.obj()), is.promise(is.array(is.class("User")))),
findOne: is.fun(is.obj(), is.promise(is.maybe(is.class("User")))),
nonEmpty: is.fun([], is.promise(is.bool)),
hashPassword: is.fun(is.str, is.promise(is.str)),
authenticate: is.fun(
is.objVals(is.str),
is.promise(is.or(is.class("User"), is.eq(false)))
),
verifyWithToken: is.fun(
is.obj({ email: is.str, verification_token: is.str }),
is.promise(is.any)
),
resetPasswordWithToken: is.fun(
is.obj({ email: is.str, reset_password_token: is.str, password: is.str }),
is.promise(is.any)
),
create: is.fun(
is.obj({ email: is.str }),
is.promise(is.or(is.obj({ error: is.str }), is.class("User")))
),
get_roles: is.fun(
[],
is.promise(is.array(is.obj({ id: is.posint, role: is.str })))
),
},
};
module.exports = User;
|
let hist = Array()
let hist_id = 0
let prev_command = ""
///// Firebase parameters /////
const database = firebase.database();
const provider = new firebase.auth.GoogleAuthProvider();
//provider.addScope('https://www.googleapis.com/auth/plus.login');
const userLogin = { name: "hackntu" }
const emailregex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
/* new var and config [Start] */
let commands = [];
// window.commands = commands;
Vue.config.debug = true
Vue.config.devtools = true
/* new var and config [End] */
let Prompt = {
template: `
<div :id="promptId" class="cmd">
<span id="p-h">{{ name }}@taipei</span>
<span id="p-t"> {{ time }}</span>
<span id="p-d" > {{ dir }} </span>
<span id="p-s">$</span >
<span id="p-text">{{ text }}</span >
<template id="control" v-if="control">
<span id="_front" >{{front}}</span><span id="cursor">{{cursorText}}</span ><span id="_back">{{back}}</span >
<input @keyup.stop.prevent="keyup($event)" type="text" id="command" v-model="input"></input>
</template>
</div >
`,
created() {
this.time = new Date().toTimeString().substring(0, 5)
console.log("Prompted.")
},
data() {
return {
// hr: '',
// min: '',
dir: '~',
time: '10:00', //debug
input: '123456', //test
cursorIndex: 0,
}
},
props: {
control: Boolean,
text: String,
index: Number,
},
watch: {
cursorIndex() {
if (this.cursorIndex > 0)
this.cursorIndex = 0
if (-this.cursorIndex > this.input.length)
this.cursorIndex = -this.input.length
},
},
computed: {
name: () => userLogin.name,
promptId: () => 'prompt-' + this.index,
front() {
return ((this.cursorIndex < 0) ? this.input.slice(0, this.cursorIndex) : this.input)
},
cursorText() {
return ((this.cursorIndex < 0) ? this.input.substr((this.cursorIndex), 1) : ' ')
},
back() {
return ((this.cursorIndex < -1) ? this.input.slice(this.cursorIndex + 1) : '')
},
},
methods: {
moveCursor(dir) {
if (dir === 'left')
this.cursorIndex -= 1
if (dir === 'right')
this.cursorIndex += 1
},
enter() {
console.log("Enter here again")
commands.push({ 'text': this.input }); // need content
// if (this.input.length == 0)
// return;
this.$parent.run(this.input)
this.input = '' //clean input
this.cursorIndex = 0
},
keyup(e) {
switch (e.which) {
case 37: // Left
this.moveCursor('left')
break;
case 39: // Right
this.moveCursor('right')
break;
case 13: // Enter
this.enter()
break;
default:
break;
}
},
}
}
let Prompts = new Vue({
el: '#prompts',
template: `
<div id="console">
<template v-for="(command, index) in commands">
<prompt :index="index + 1" :text="command.text"></prompt>
</template>
<prompt :index="0" :control="control"></prompt>
</div>
`,
components: {
Prompt,
},
created() {
// Blinks the cursor
setInterval(function() {
if ($('#cursor').css('background-color') == 'rgb(255, 255, 255)') {
$('#cursor').css('background-color', 'transparent')
} else {
$('#cursor').css('background-color', 'white')
}
}, 500)
$('#command').focus()
$(document).keydown(function(e) {
$('#command').focus();
})
},
data() {
return {
dir: '~',
control: true,
}
},
computed: {
name: () => userLogin.name,
commands: () => commands,
},
methods: {
run(command) {
this.control = false
console.log("Get command:", command)
for (let prop in law) {
if (law.hasOwnProperty(prop) && law[prop].reg.test(command)) {
law[prop].exec(command)
return;
}
}
this.done()
},
done() {
this.$nextTick(function() {
this.control = true
})
},
}
});
/*
function prompt(dir = '~') {
let date = new Date()
let hr = date.getHours().toString()
if (date.getHours() < 10)
hr = "0" + hr
let min = date.getMinutes().toString()
if (date.getMinutes() < 10)
min = "0" + min
$('#console').append('<div id="prompt" class="cmd"><span id="p-h">' + userLogin.name + '@taipei</span> <span id="p-t">' +
hr + ':' + min + '</span> ' +
'<span id="p-d">' + dir + '</span> <span id="p-s">$</span> <span id="control">' +
'<span id="_front"></span><span id="cursor"></span>' +
'<input type="text" id="command"></input><span id="_back"></span></span></div>')
$('#command').focus()
console.log("Prompted.")
}
*/
$(function() {
// prompt()
$("#greeting-typed-1").typed({
stringsElement: $('#greeting-1'),
showCursor: false,
typeSpeed: 10,
callback: function() {
$("#greeting-typed-2").typed({
stringsElement: $('#greeting-2'),
showCursor: false,
typeSpeed: 10,
callback: function() {
//prompt();
}
})
}
});
});
/*
$(document).keyup(function(e) {
let front = $('#_front').text()
let back = $('#_back').text()
if (e.which == 37) { // Left
if (back.length > 0) {
$('#_front').text(front.slice(0, -1))
$('#_back').text(front.slice(-1) + back)
}
} else if (e.which == 38) { // Up
if (hist_id > 0) {
$('#_front').text(hist[hist_id - 1])
$('#_back').text("")
}
if (hist_id == hist.length) {
prev_command = front + back
}
hist_id = Math.max(hist_id - 1, 0);
} else if (e.which == 39) { // Right
if (back.length > 0) {
$('#_front').text(front + back[0])
$('#_back').text(back.slice(1))
}
} else if (e.which == 40) { // Down
if (hist_id < hist.length - 1) {
$('#_front').text(hist[hist_id + 1])
$('#_back').text("")
} else { // Fill in previous command.
$('#_front').text(prev_command)
$('#_back').text("")
}
hist_id = Math.min(hist_id + 1, hist.length)
} else if (e.which == 13) { // Enter
console.log("Enter here again")
let com = front + back
// Remove old control & rename line id
$('#control').remove()
$('#prompt').append('<span>' + com + '</span>')
$('#prompt').attr('id', 'line-' + hist_id)
prev_command = ""
if (com.length == 0)
return;
runcommand(com)
hist.push(com)
hist_id = hist.length
} else if (e.which == 8) { // BackSpace
$('#_front').text(front.slice(0, -1))
e.preventDefault();
} else {
$('#_front').text(front + $('#command').val())
// console.log("Get input:", $('#command').val())
$('#command').val("")
}
})
*/
/*
$(document).keydown(function(e) {
$('#command').focus();
})
// Blinks the cursor
setInterval(function() {
if ($('#cursor').css('background-color') == 'rgb(255, 255, 255)') {
$('#cursor').css('background-color', 'transparent')
} else {
$('#cursor').css('background-color', 'white')
}
}, 500)
*/
var law = {
bye: {
reg: /^bye$/,
exec: function() {
if (confirm("Ready to say goodbye?")) {
setInterval(function() {
window.open('about:blank','_self');
}, 500)
}
doneCommand()
}
},
contact: {
reg: /^contact$/,
exec: function() {
function loadUserMeta(meta, column, regex) {
return new Promise((resolve, reject) => {
$('#console').append('<div class="interactive cmd">' + column +
': <input type="text" id="meta" class="text"></input></div>')
$('#meta').focus().keyup(function(e) {
// Avoids enter been interpreted by document event handler.
e.stopPropagation();
if (e.which == 13) {
if (regex.test($('#meta').val())) {
meta[column] = $('#meta').val()
console.log("Load!!!!!", $('#meta').val())
resolve(meta)
$('#meta').attr('id', '');
} else {
$('#console').append('<div class="error cmd">Illegal input of ' + column + '</div>')
reject("Illegal input")
}
}
})
})
};
loadUserMeta({}, "name", /^.*$/).then(obj => {
return loadUserMeta(obj, "email", emailregex)
}).then(obj => {
return loadUserMeta(obj, "quote", /^.*$/)
}).then(obj => { // Done loading user data
console.log(obj)
database.ref().child('contact').push().set(obj);
doneCommand()
}).catch(error => {
console.log(error)
doneCommand()
})
}
},
sudo: {
reg: /^sudo$/,
exec: loginGoogle
},
login: {
reg: /^login$/,
exec: loginGoogle
},
cat: {
reg: /^cat.*$/,
exec: function(command) {
ascii['cat'].forEach((line, idx, array) => {
if (idx === 3) {
let sentence = command.split(' ').slice(1).join(' ')
$('#console').append('<div class="cmd">'+line+' Meow: "'+sentence+'"</div>')
} else {
$('#console').append('<div class="cmd">'+line+'</div>')
}
})
doneCommand()
}
},
dog: {
reg: /^dog.*$/,
exec: function(command) {
let target = "<div class='cmd'><pre>"
ascii['dog'].forEach((line, idx, array) => {
target += line
if (idx === 3) {
target += ' ' + command.split(' ').slice(1).join(' ')
}
target += '\n'
})
target += "</pre></div>"
$('#console').append(target)
doneCommand()
}
}
}
function enterSecret() {
$("#console").append('<div class="sudo cmd">Enter password: ' +
'<input type="password" id="password"></input></div>')
$('#password').focus().keyup(function(e) {
if (e.which == 13) {
alert("Password:" + $('#password').val())
doneCommand()
}
})
}
function loginGoogle() {
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
console.log("Login:", user)
$('#console').append('<div class="cmd">Welcome, <span id="p-h">' + user.displayName + '</span></div>')
userLogin.name = user.displayName
userLogin.email = user.email
doneCommand()
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
console.log(errorCode, errorMessage)
$('#console').append('<div class="error cmd"><span id="p-d">Error! </span>' +
errorMessage + '</div>')
doneCommand()
});
}
function doneCommand() {
// prompt()
Prompts.done()
}
/*
function runcommand(command) {
console.log("Get command:", command)
for (let prop in law) {
if (law.hasOwnProperty(prop) && law[prop].reg.test(command)) {
law[prop].exec(command)
return;
}
}
doneCommand()
}
*/
var ascii = {
cat: [" /\\ ___ /\\"
," ( o o ) "
," \\ >#< /"
," / \\ "
," / \\ ^ "
,"| | //"
," \\ / // "
," /// /// --"],
dog: [ " ,:'/ _... ",
" // ( `\"\"-.._.' ",
" \\| / 6\\___ /",
" | 6 4 ",
" | / \\",
" \\_ .--' ",
" (_\'---\'`) ",
" / `\'---`() ",
" ,\' | ",
" , .\'` | ",
" )\ _.-\' ; ",
" / | .\'` _ / ",
" /` / .\' '. , | ",
" / / / \ ; | | ",
" | \ | | .| | | ",
" \ `\"| /.-\' | | | ",
" '-..-\ _.;.._ | |.;-. ",
" \ <`.._ )) | .;-. )) ",
" (__. ` ))-\' \_ ))' ",
" `\'--\"` jgs `\"\"\"` "
]
};
|
/**
* @author Richard Davey <[email protected]>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Calculate the distance between two sets of coordinates (points).
*
* @function Phaser.Math.Distance.Between
* @since 3.0.0
*
* @param {number} x1 - The x coordinate of the first point.
* @param {number} y1 - The y coordinate of the first point.
* @param {number} x2 - The x coordinate of the second point.
* @param {number} y2 - The y coordinate of the second point.
*
* @return {number} The distance between each point.
*/
var DistanceBetween = function (x1, y1, x2, y2)
{
var dx = x1 - x2;
var dy = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
};
module.exports = DistanceBetween;
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Riccardo Malpica Galassi, Sapienza University, Roma, Italy
"""
import numpy as np
from .ThermoKinetics import CanteraThermoKinetics
class CanteraCSP(CanteraThermoKinetics):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.jacobiantype = 'full'
self.rtol = 1.0e-2
self.atol = 1.0e-8
self._rhs = []
self._jac = []
self._evals = []
self._Revec = []
self._Levec = []
self._f = []
self._tau = []
self._nUpdates = 0
self._changed = False
@property
def jacobiantype(self):
return self._jacobiantype
@jacobiantype.setter
def jacobiantype(self,value):
if value == 'full':
self.nv = self.n_species + 1
self._jacobiantype = value
elif value == 'kinetic' or value == 'constrained':
self.nv = self.n_species
self._jacobiantype = value
else:
raise ValueError("Invalid jacobian type --> %s" %value)
@property
def rtol(self):
return self._rtol
@rtol.setter
def rtol(self,value):
self._rtol = value
@property
def atol(self):
return self._atol
@atol.setter
def atol(self,value):
self._atol = value
@property
def rhs(self):
return self._rhs
@property
def jac(self):
return self._jac
@property
def evals(self):
return self._evals
@property
def Revec(self):
return self._Revec
@property
def Levec(self):
return self._Levec
@property
def f(self):
return self._f
@property
def tau(self):
return self._tau
@property
def nUpdates(self):
return self._nUpdates
def __setattr__(self, key, value):
if key != '_changed':
self._changed = True
super().__setattr__(key, value)
def is_changed(self):
return self._changed
def update_kernel(self):
if self.jacobiantype == 'full':
self._evals,self._Revec,self._Levec,self._f = self.kernel()
elif self.jacobiantype == 'constrained':
self._evals,self._Revec,self._Levec,self._f = self.kernel_constrained_jac()
elif self.jacobiantype == 'kinetic':
self._evals,self._Revec,self._Levec,self._f = self.kernel_kinetic_only()
self._tau = timescales(self.evals)
self._changed = False
def get_kernel(self):
"""Retrieves the stored CSP kernel.
If any attributes changed before latest query, kernel is recomputed"""
if self.is_changed():
self.update_kernel()
self._changed = False
return [self.evals,self.Revec,self.Levec,self.f]
def calc_exhausted_modes(self, **kwargs):
"""Computes number of exhausted modes (M).
Optional arguments are rtol and atol for the calculation of M.
If not provided, uses default or previously set values"""
rtol = self.rtol
atol = self.atol
for key, value in kwargs.items():
if (key == 'rtol'):
rtol = value
elif (key == 'atol'):
atol = value
else:
raise ValueError("unknown argument --> %s" %key)
if self.is_changed():
self.update_kernel()
self._changed = False
M = findM(self.n_elements,self.stateYT(),self.evals,self.Revec,self.tau,self.f,rtol,atol)
return M
def calc_TSR(self,**kwargs):
"""Computes number of exhausted modes (M) and the TSR.
Optional arguments are rtol and atol for the calculation of M.
If not provided, uses default or previously set values.
The calculated value of M can be retrieved by passing
the optional argument getM=True"""
getM = False
rtol = self.rtol
atol = self.atol
for key, value in kwargs.items():
if (key == 'rtol'):
rtol = value
elif (key == 'atol'):
atol = value
elif (key == 'getM'):
getM = value
else:
raise ValueError("unknown argument --> %s" %key)
if self.is_changed():
self.update_kernel()
self._changed = False
M = findM(self.n_elements,self.stateYT(),self.evals,self.Revec,self.tau,self.f,rtol,atol)
TSR, weights = findTSR(self.n_elements,self.rhs,self.evals,self.Revec,self.f,M)
if getM:
return [TSR, M]
else:
return TSR
def calc_TSRindices(self,**kwargs):
"""Computes number of exhausted modes (M), the TSR and its indices.
Optional argument is type, which can be timescale or amplitude.
Default value is amplitude.
Other optional arguments are rtol and atol for the calculation of M.
If not provided, uses default or previously set values.
The calculated value of M can be retrieved by passing
the optional argument getM=True"""
getM = False
useTPI = False
rtol = self.rtol
atol = self.atol
for key, value in kwargs.items():
if (key == 'rtol'):
rtol = value
elif (key == 'atol'):
atol = value
elif (key == 'getM'):
getM = value
elif (key == 'type'):
if(value == 'timescale'):
useTPI = True
elif(value != 'amplitude'):
raise ValueError("unknown type --> %s" %value)
else:
raise ValueError("unknown argument --> %s" %key)
if self.is_changed():
self.update_kernel()
self._changed = False
Smat = self.generalized_Stoich_matrix
rvec = self.R_vector
M = findM(self.n_elements,self.stateYT(),self.evals,self.Revec,self.tau,self.f,rtol,atol)
TSR, weights = findTSR(self.n_elements,self.rhs,self.evals,self.Revec,self.f,M)
TSRidx = TSRindices(weights, self.evals)
if (useTPI):
JacK = self.jac_contribution()
CSPidx = CSP_timescale_participation_indices(self.n_reactions, JacK, self.evals, self.Revec, self.Levec)
else:
CSPidx = CSP_amplitude_participation_indices(self.Levec, Smat, rvec)
TSRind = TSR_participation_indices(TSRidx, CSPidx)
if getM:
return TSR, TSRind, M
else:
return TSR, TSRind
def calc_CSPindices(self,**kwargs):
"""Computes number of exhausted modes (M) and the CSP Indices.
Optional arguments are rtol and atol for the calculation of M.
If not provided, uses default or previously set values.
The calculated value of M can be retrieved by passing
the optional argument getM=True"""
getM = False
getAPI = False
getImpo = False
getspeciestype = False
getTPI = False
API = None
Ifast = None
Islow = None
species_type = None
TPI = None
rtol = self.rtol
atol = self.atol
for key, value in kwargs.items():
if (key == 'rtol'):
rtol = value
elif (key == 'atol'):
atol = value
elif (key == 'getM'):
getM = value
elif (key == 'API'):
getAPI = value
elif (key == 'Impo'):
getImpo = value
elif (key == 'species_type'):
getspeciestype = value
elif (key == 'TPI'):
getTPI = value
else:
raise ValueError("unknown argument --> %s" %key)
if self.is_changed():
self.update_kernel()
self._changed = False
M = findM(self.n_elements,self.stateYT(),self.evals,self.Revec,self.tau,self.f,rtol,atol)
Smat = self.generalized_Stoich_matrix
rvec = self.R_vector
if getAPI: API = CSP_amplitude_participation_indices(self.Levec, Smat, rvec)
if getImpo: Ifast,Islow = CSP_importance_indices(self.Revec,self.Levec,M,Smat,rvec)
if getspeciestype:
pointers = CSP_pointers(self.Revec,self.Levec)
species_type = classify_species(self.stateYT(), self.rhs, pointers, M)
if getTPI:
JacK = self.jac_contribution()
TPI = CSP_timescale_participation_indices(self.n_reactions, JacK, self.evals, self.Revec, self.Levec)
if getM:
return [API, TPI, Ifast, Islow, species_type, M]
else:
return [API, TPI, Ifast, Islow, species_type]
def calc_extended_TSR(self,**kwargs):
"""Computes number of Extended exhausted modes (Mext) and the extended TSR.
Caller must provide either a diffusion rhs with the keywork rhs_diffYT
or a convection rhs with the keywork rhs_convYT, or both.
Optional arguments are rtol and atol for the calculation of Mext.
If not provided, uses default or previously set values.
The calculated value of Mext can be retrieved by passing
the optional argument getMext=True"""
if self.is_changed():
self.update_kernel()
self._changed = False
nv=len(self.Revec)
getMext = False
rtol = self.rtol
atol = self.atol
rhs_convYT = np.zeros(nv)
rhs_diffYT = np.zeros(nv)
for key, value in kwargs.items():
if (key == 'rtol'):
rtol = value
elif (key == 'atol'):
atol = value
elif (key == 'getMext'):
getMext = value
elif (key == 'conv'):
rhs_convYT = value
elif (key == 'diff'):
rhs_diffYT = value
else:
raise ValueError("unknown argument --> %s" %key)
if(len(rhs_convYT)!=nv):
raise ValueError("Check dimension of Convection rhs. Should be %d", nv)
if(len(rhs_diffYT)!=nv):
raise ValueError("Check dimension of Diffusion rhs. Should be %d", nv)
Smat = self.generalized_Stoich_matrix
rvec = self.R_vector
rhs_ext, h, Smat_ext, rvec_ext = add_transport(self.rhs,self.Levec,Smat,rvec,rhs_convYT,rhs_diffYT)
Mext = findM(self.n_elements,self.stateYT(),self.evals,self.Revec,self.tau,h,rtol,atol)
TSR_ext, weights_ext = findTSR(self.n_elements,rhs_ext,self.evals,self.Revec,h,Mext)
if getMext:
return [TSR_ext, Mext]
else:
return TSR_ext
def calc_extended_TSRindices(self,**kwargs):
"""Computes number of Extended exhausted modes (Mext), the extended TSR and its indices.
Caller must provide either a diffusion rhs with the keywork rhs_diffYT
or a convection rhs with the keywork rhs_convYT, or both.
Other optional arguments are rtol and atol for the calculation of Mext.
If not provided, uses default or previously set values.
The calculated value of Mext can be retrieved by passing
the optional argument getMext=True"""
if self.is_changed():
self.update_kernel()
self._changed = False
getMext = False
nv=len(self.Revec)
rtol = self.rtol
atol = self.atol
rhs_convYT = np.zeros(nv)
rhs_diffYT = np.zeros(nv)
for key, value in kwargs.items():
if (key == 'rtol'):
rtol = value
elif (key == 'atol'):
atol = value
elif (key == 'getMext'):
getMext = value
elif (key == 'conv'):
rhs_convYT = value
elif (key == 'diff'):
rhs_diffYT = value
else:
raise ValueError("unknown argument --> %s" %key)
if(len(rhs_convYT)!=nv):
raise ValueError("Check dimension of Convection rhs. Should be %d", nv)
if(len(rhs_diffYT)!=nv):
raise ValueError("Check dimension of Diffusion rhs. Should be %d", nv)
Smat = self.generalized_Stoich_matrix
rvec = self.R_vector
rhs_ext, h, Smat_ext, rvec_ext = add_transport(self.rhs,self.Levec,Smat,rvec,rhs_convYT,rhs_diffYT)
Mext = findM(self.n_elements,self.stateYT(),self.evals,self.Revec,self.tau,h,rtol,atol)
TSR_ext, weights_ext = findTSR(self.n_elements,rhs_ext,self.evals,self.Revec,h,Mext)
TSRidx = TSRindices(weights_ext, self.evals)
CSPidx = CSP_amplitude_participation_indices(self.Levec, Smat_ext, rvec_ext)
TSRind_ext = TSR_participation_indices(TSRidx, CSPidx)
if getMext:
return TSR_ext, TSRind_ext, Mext
else:
return TSR_ext, TSRind_ext
""" ~~~~~~~~~~~~ KERNEL ~~~~~~~~~~~~~
"""
def kernel(self):
"""Computes CSP kernel. Its dimension is Nspecies + 1.
Returns [evals,Revec,Levec,amplitudes].
Input must be an instance of the CSPCantera class"""
#self.nv = self.n_species + 1
self._rhs = self.source.copy()
self._jac = self.jacobian.copy()
#eigensystem
evals,Revec,Levec = eigsys(self.jac)
self.clean_conserved(evals)
f = np.matmul(Levec,self.rhs)
self._nUpdates = self._nUpdates + 1
#rotate eigenvectors such that amplitudes are positive
Revec,Levec,f = evec_pos_ampl(Revec,Levec,f)
return[evals,Revec,Levec,f]
def kernel_kinetic_only(self):
"""Computes kinetic kernel. Its dimension is Nspecies.
Returns [evals,Revec,Levec,amplitudes].
Input must be an instance of the CSPCantera class"""
#self.nv = self.n_species
self._rhs = self.source.copy()[:self.nv]
self._jac = self.jacKinetic().copy()
#eigensystem
evals,Revec,Levec = eigsys(self.jac)
self.clean_conserved(evals)
f = np.matmul(Levec,self.rhs)
self._nUpdates = self._nUpdates + 1
#rotate eigenvectors such that amplitudes are positive
Revec,Levec,f = evec_pos_ampl(Revec,Levec,f)
return[evals,Revec,Levec,f]
def kernel_constrained_jac(self):
"""Computes constrained (to enthalpy) kernel. Its dimension is Nspecies .
Returns [evals,Revec,Levec,amplitudes].
Input must be an instance of the CSPCantera class"""
#self.nv = self.n_species
self._rhs = self.source.copy()[:self.nv]
kineticjac = self.jacKinetic()
thermaljac = self.jacThermal()
self._jac = kineticjac - thermaljac
#eigensystem
evals,Revec,Levec = eigsys(self.jac)
self.clean_conserved(evals)
f = np.matmul(Levec,self.rhs)
self._nUpdates = self._nUpdates + 1
#rotate eigenvectors such that amplitudes are positive
Revec,Levec,f = evec_pos_ampl(Revec,Levec,f)
return[evals,Revec,Levec,f]
def clean_conserved(self,evals):
"""Zero-out conserved modes eigenvalues"""
i = self.nv-self.n_elements
evals[i:] = 0.0
""" ~~~~~~~~~~~~ EXHAUSTED MODES ~~~~~~~~~~~~~
"""
def findM(n_elements,stateYT,evals,Revec,tau,f,rtol,atol):
nv = len(Revec)
nEl = n_elements
#nconjpairs = sum(1 for x in self.eval.imag if x != 0)/2
imPart = evals.imag!=0
nModes = nv - nEl #removing conserved modes
ewt = setEwt(stateYT,rtol,atol)
delw = np.zeros(nv)
for j in range(nModes-1): #loop over eligible modes (last excluded)
taujp1 = tau[j+1] #timescale of next (slower) mode
Aj = Revec[j] #this mode right evec
fj = f[j] #this mode amplitued
lamj = evals[j].real #this mode eigenvalue (real part)
for i in range(nv):
Aji = Aj[i] #i-th component of this mode Revec
delw[i] = delw[i] + modeContribution(Aji,fj,taujp1,lamj) #contribution of j-th mode to i-th var
if np.abs(delw[i]) > ewt[i]:
if j==0:
M = 0
else:
M = j-1 if (imPart[j] and imPart[j-1] and evals[j].real==evals[j-1].real) else j #if j is the second of a pair, move back by 2
return M
#print("All modes are exhausted")
M = nModes - 1 #if criterion is never verified, all modes are exhausted. Leave 1 active mode.
return M
def setEwt(y,rtol,atol):
ewt = [rtol * absy + atol if absy >= 1.0e-6 else absy + atol for absy in np.absolute(y)]
return ewt
def modeContribution(a,f,tau,lam):
delwMi = a*f*(np.exp(tau*lam) - 1)/lam if lam != 0.0 else 0.0
return delwMi
""" ~~~~~~~~~~~~~~ TSR ~~~~~~~~~~~~~~~~
"""
def findTSR(n_elements,rhs,evals,Revec,f,M):
n = len(Revec)
nEl = n_elements
#deal with amplitudes of cmplx conjugates
fvec = f.copy()
imPart = evals.imag!=0
for i in range(1,n):
if (imPart[i] and imPart[i-1] and evals[i].real==evals[i-1].real):
fvec[i] = np.sqrt(fvec[i]**2 + fvec[i-1]**2)
fvec[i-1] = fvec[i]
fnorm = fvec / np.linalg.norm(rhs)
#deal with zero-eigenvalues (if any)
fvec[evals==0.0] = 0.0
weights = fnorm**2
weights[0:M] = 0.0 #excluding fast modes
weights[n-nEl:n] = 0.0 #excluding conserved modes
normw = np.sum(weights)
weights = weights / normw if normw > 0 else np.zeros(n)
TSR = np.sum([weights[i] * np.sign(evals[i].real) * np.abs(evals[i]) for i in range(n)])
return [TSR, weights]
def TSRindices(weights, evals):
"""Ns array containing participation index of mode i to TSR"""
n = len(weights)
Index = np.zeros((n))
norm = np.sum([weights[i] * np.abs(evals[i]) for i in range(n)])
for i in range(n):
Index[i] = weights[i] * np.abs(evals[i])
Index[i] = Index[i]/norm if norm > 1e-10 else 0.0
return Index
def TSR_participation_indices(TSRidx, CSPidx):
"""2Nr array containing participation index of reaction k to TSR"""
Index = np.matmul(np.transpose(CSPidx),np.abs(TSRidx))
norm = np.sum(np.abs(Index))
Index = Index/norm if norm > 0 else Index*0.0
return Index
""" ~~~~~~~~~~~~ EIGEN FUNC ~~~~~~~~~~~~~
"""
def eigsys(jac):
"""Returns eigensystem (evals, Revec, Levec). Input must be a 2D array.
Both Revec (since it is transposed) and Levec (naturally) contain row vectors,
such that an eigenvector can be retrieved using R/Levec[index,:] """
#ncons = len(jac) - np.linalg.matrix_rank(jac)
evals, Revec = np.linalg.eig(jac)
#sort
idx = np.argsort(abs(evals))[::-1]
evals = evals[idx]
Revec = Revec[:,idx]
#zero-out conserved eigenvalues (last ncons)
#evals[-ncons:] = 0.0
#adjust complex conjugates
cmplx = Revec.imag.any(axis=0) #boolean indexing of complex eigenvectors (cols)
icmplx = np.flatnonzero(cmplx) #indexes of complex eigenvectors
for i in icmplx[::2]:
re = (Revec[:,i]+Revec[:,i+1])/2.0
im = (Revec[:,i]-Revec[:,i+1])/(2.0j)
Revec[:,i] = re
Revec[:,i+1] = im
Revec = Revec.real #no need to carry imaginary part anymore
#compute left eigenvectors, amplitudes
try:
Levec = np.linalg.inv(Revec)
except:
print('Warning: looks like the R martrix is singular (rank[R] = %i).' %np.linalg.matrix_rank(Revec))
print(' Kernel is zeroed-out.')
return[np.zeros(len(jac)),np.zeros((len(jac),len(jac))),np.zeros((len(jac),len(jac)))]
#transpose Revec
Revec = np.transpose(Revec)
return[evals,Revec,Levec]
def evec_pos_ampl(Revec,Levec,f):
"""changes sign to eigenvectors based on sign of corresponding mode amplitude."""
idx = np.flatnonzero(f < 0)
Revec[idx,:] = - Revec[idx,:]
Levec[idx,:] = - Levec[idx,:]
f[idx] = -f[idx]
return[Revec,Levec,f]
def timescales(evals):
tau = [1.0/abslam if abslam > 0 else 1e+20 for abslam in np.absolute(evals)]
return np.array(tau)
""" ~~~~~~~~~~~~ INDEXES FUNC ~~~~~~~~~~~~~
"""
def CSPIndices(Proj, Smat, rvec):
"""Returns a Nv x 2Nr matrix of indexes, computed as Proj S r """
ns = Smat.shape[0]
nr = Smat.shape[1]
Index = np.zeros((ns,nr))
for i in range(ns):
Proj_i = Proj[i,:]
Index[i,:] = CSPIndices_one_var(Proj_i, Smat, rvec)
#np.sum(abs(Index),axis=1) check: a n-long array of ones
return Index
def CSPIndices_one_var(Proj_i, Smat, rvec):
"""Given the i-th row of the projector, computes 2Nr indexes of reactions to variable i.
Proj_i must be a nv-long array. Returns a 2Nr-long array"""
nr = Smat.shape[1]
PS = np.matmul(Proj_i,Smat)
Index = np.multiply(PS,rvec)
norm = np.sum(abs(Index))
if norm != 0.0:
Index = Index/norm
else:
Index = np.zeros((nr))
#np.sum(abs(Index),axis=1) check: a n-long array of ones
return Index
def CSP_amplitude_participation_indices(B, Smat, rvec):
"""Ns x 2Nr array containing participation index of reaction k to variable i"""
API = CSPIndices(B, Smat, rvec)
return API
def CSP_importance_indices(A,B,M,Smat,rvec):
"""Ns x 2Nr array containing fast/slow importance index of reaction k to variable i"""
fastProj = np.matmul(np.transpose(A[0:M]),B[0:M])
Ifast = CSPIndices(fastProj, Smat, rvec)
slowProj = np.matmul(np.transpose(A[M:]),B[M:])
Islow = CSPIndices(slowProj, Smat, rvec)
return [Ifast,Islow]
def CSP_pointers(A,B):
nv = A.shape[0]
pointers = np.array([[np.transpose(A)[spec,mode]*B[mode,spec] for spec in range(nv)] for mode in range(nv)])
return pointers
def classify_species(stateYT, rhs, pointers, M):
"""species classification
"""
n = len(stateYT)
ytol = 1e-20
rhstol = 1e-13
sort = np.absolute(np.sum(pointers[:,:M],axis=1)).argsort()[::-1]
species_type = np.full(n,'slow',dtype=object)
species_type[sort[0:M]] = 'fast'
species_type[-1] = 'slow' #temperature is always slow
for i in range(n-1):
if (stateYT[i] < ytol and abs(rhs[i]) < rhstol): species_type[i] = 'trace'
return species_type
def CSP_participation_to_one_timescale(i, nr, JacK, evals, A, B):
imPart = evals.imag!=0
if(imPart[i] and imPart[i-1] and evals[i].real==evals[i-1].real): i = i-1 #if the second of a complex pair, shift back the index by 1
Index = np.zeros(2*nr)
norm = 0.0
if(imPart[i]):
for k in range(2*nr):
Index[k] = 0.5 * ( np.matmul(np.matmul(B[i],JacK[k]),np.transpose(A)[:,i]) -
np.matmul(np.matmul(B[i+1],JacK[k]),np.transpose(A)[:,i+1]))
norm = norm + abs(Index[k])
else:
for k in range(2*nr):
Index[k] = np.matmul(np.matmul(B[i],JacK[k]),np.transpose(A)[:,i])
norm = norm + abs(Index[k])
for k in range(2*nr):
Index[k] = Index[k]/norm if (norm != 0.0) else 0.0
return Index
def CSP_timescale_participation_indices(nr, JacK, evals, A, B):
"""Ns x 2Nr array containing TPI of reaction k to variable i"""
nv = A.shape[0]
TPI = np.zeros((nv,2*nr))
for i in range(nv):
TPI[i] = CSP_participation_to_one_timescale(i, nr, JacK, evals, A, B)
return TPI
def CSPtiming(gas):
import time
ns = gas.n_species
randY = np.random.dirichlet(np.ones(ns),size=1)
gas.TP = 1000,101325.0
gas.Y = randY
gas.constP = 101325.0
gas.jacobiantype='full'
gas.rtol=1.0e-3
gas.atol=1.0e-10
starttime = time.time()
gas.update_kernel()
endtime = time.time()
timekernel = endtime - starttime
starttime = time.time()
M = gas.calc_exhausted_modes()
endtime = time.time()
timeM = endtime - starttime
starttime = time.time()
TSR = gas.calc_TSR()
endtime = time.time()
timeTSR = endtime - starttime
starttime = time.time()
api, tpi, ifast, islow, species_type = gas.calc_CSPindices(API=True,Impo=False,species_type=False,TPI=False)
endtime = time.time()
timeAPI = endtime - starttime
starttime = time.time()
api, tpi, ifast, islow, species_type = gas.calc_CSPindices(API=False,Impo=True,species_type=False,TPI=False)
endtime = time.time()
timeImpo = endtime - starttime
starttime = time.time()
api, tpi, ifast, islow, species_type = gas.calc_CSPindices(API=False,Impo=False,species_type=True,TPI=False)
endtime = time.time()
timeclassify = endtime - starttime
starttime = time.time()
api, tpi, ifast, islow, species_type = gas.calc_CSPindices(API=False,Impo=False,species_type=False,TPI=True)
endtime = time.time()
timeTPI = endtime - starttime
print ('Time Kernel: %10.3e' %timekernel)
print ('Time findM: %10.3e' %timeM)
print ('Time TSR: %10.3e' %timeTSR)
print ('Time API indexes: %10.3e' %timeAPI)
print ('Time Imp indexes: %10.3e' %timeImpo)
print ('Time TPI indexes: %10.3e' %timeTPI)
print ('Time class specs: %10.3e' %timeclassify)
print ('*** all times in seconds')
""" ~~~~~~~~~~~ EXTENDED FUNC ~~~~~~~~~~~~
"""
def add_transport(rhs,Levec,Smat,rvec,rhs_convYT,rhs_diffYT):
nv=len(Levec)
nr=Smat.shape[1]
rhs_ext = rhs + rhs_convYT + rhs_diffYT
h = np.matmul(Levec,rhs_ext)
Smat_ext = np.zeros((nv,nr+2*nv))
Smat_ext[:,0:nr] = Smat
Smat_ext[:,nr:nr+nv] = np.eye(nv)
Smat_ext[:,nr+nv:nr+2*nv] = np.eye(nv)
rvec_ext = np.zeros((nr+2*nv))
rvec_ext[0:nr] = rvec
rvec_ext[nr:nr+nv] = rhs_convYT
rvec_ext[nr+nv:nr+2*nv] = rhs_diffYT
#splitrhs_ext = np.dot(Smat_ext,rvec_ext)
#checksplitrhs = np.isclose(rhs_ext, splitrhs_ext, rtol=1e-6, atol=0, equal_nan=False)
#if(np.any(checksplitrhs == False)):
# raise ValueError('Mismatch between numerical extended RHS and S.r')
return rhs_ext, h, Smat_ext, rvec_ext
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tf = require("@tensorflow/tfjs-core");
var common_1 = require("../common");
function boxPredictionLayer(x, params) {
return tf.tidy(function () {
var batchSize = x.shape[0];
var boxPredictionEncoding = tf.reshape(common_1.convLayer(x, params.box_encoding_predictor), [batchSize, -1, 1, 4]);
var classPrediction = tf.reshape(common_1.convLayer(x, params.class_predictor), [batchSize, -1, 3]);
return {
boxPredictionEncoding: boxPredictionEncoding,
classPrediction: classPrediction
};
});
}
exports.boxPredictionLayer = boxPredictionLayer;
//# sourceMappingURL=boxPredictionLayer.js.map |
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.nipplejs=e()}}(function(){function e(){}function t(e,i){return this.identifier=i.identifier,this.position=i.position,this.frontPosition=dataoptions.frontPosition,this.collection=e,this.defaults={size:100,threshold:.1,color:"white",fadeTime:250,restJoystick:!0,restOpacity:.5,mode:"dynamic",zone:document.body,lockX:!1,lockY:!1},this.config(i),"dynamic"===this.options.mode&&(this.options.restOpacity=0),this.id=t.id,t.id+=1,this.buildEl().stylize(),this.instance={el:this.ui.el,on:this.on.bind(this),off:this.off.bind(this),show:this.show.bind(this),hide:this.hide.bind(this),add:this.addToDom.bind(this),remove:this.removeFromDom.bind(this),destroy:this.destroy.bind(this),resetDirection:this.resetDirection.bind(this),computeDirection:this.computeDirection.bind(this),trigger:this.trigger.bind(this),position:this.position,frontPosition:this.frontPosition,ui:this.ui,identifier:this.identifier,id:this.id,options:this.options},this.instance}function i(e,t){var n=this;return n.nipples=[],n.idles=[],n.actives=[],n.ids=[],n.pressureIntervals={},n.manager=e,n.id=i.id,i.id+=1,n.defaults={zzz:!1,maxNumberOfNipples:10,mode:"dynamic",position:{top:0,left:0},catchDistance:200,size:100,threshold:.1,color:"white",fadeTime:250,restJoystick:!0,restOpacity:.5,lockX:!1,lockY:!1},n.config(t),"static"!==n.options.mode&&"semi"!==n.options.mode||(n.options.multitouch=!1),n.options.multitouch||(n.options.maxNumberOfNipples=1),n.updateBox(),n.prepareNipples(),n.bindings(),n.begin(),n.nipples}function n(e){var t=this;t.ids={},t.index=0,t.collections=[],t.config(e),t.prepareCollections();var i;return c.bindEvt(window,"resize",function(e){clearTimeout(i),i=setTimeout(function(){var e,i=c.getScroll();t.collections.forEach(function(t){t.forEach(function(t){e=t.el.getBoundingClientRect(),t.position={x:i.x+e.left,y:i.y+e.top}})})},100)}),t.collections}var o,r=!!("ontouchstart"in window),s=!!window.PointerEvent,d=!!window.MSPointerEvent,a={touch:{start:"touchstart",move:"touchmove",end:"touchend, touchcancel"},mouse:{start:"mousedown",move:"mousemove",end:"mouseup"},pointer:{start:"pointerdown",move:"pointermove",end:"pointerup, pointercancel"},MSPointer:{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}},p={};s?o=a.pointer:d?o=a.MSPointer:r?(o=a.touch,p=a.mouse):o=a.mouse;var c={};c.distance=function(e,t){var i=t.x-e.x,n=t.y-e.y;return Math.sqrt(i*i+n*n)},c.angle=function(e,t){var i=t.x-e.x,n=t.y-e.y;return c.degrees(Math.atan2(n,i))},c.findCoord=function(e,t,i){var n={x:0,y:0};return i=c.radians(i),n.x=e.x-t*Math.cos(i),n.y=e.y-t*Math.sin(i),n},c.radians=function(e){return e*(Math.PI/180)},c.degrees=function(e){return e*(180/Math.PI)},c.bindEvt=function(e,t,i){for(var n,o=t.split(/[ ,]+/g),r=0;r<o.length;r+=1)n=o[r],e.addEventListener?e.addEventListener(n,i,!1):e.attachEvent&&e.attachEvent(n,i)},c.unbindEvt=function(e,t,i){for(var n,o=t.split(/[ ,]+/g),r=0;r<o.length;r+=1)n=o[r],e.removeEventListener?e.removeEventListener(n,i):e.detachEvent&&e.detachEvent(n,i)},c.trigger=function(e,t,i){var n=new CustomEvent(t,i);e.dispatchEvent(n)},c.prepareEvent=function(e){return e.preventDefault(),e.type.match(/^touch/)?e.changedTouches:e},c.getScroll=function(){return{x:void 0!==window.pageXOffset?window.pageXOffset:(document.documentElement||document.body.parentNode||document.body).scrollLeft,y:void 0!==window.pageYOffset?window.pageYOffset:(document.documentElement||document.body.parentNode||document.body).scrollTop}},c.applyPosition=function(e,t){t.top||t.right||t.bottom||t.left?(e.style.top=t.top,e.style.right=t.right,e.style.bottom=t.bottom,e.style.left=t.left):(e.style.left=t.x+"px",e.style.top=t.y+"px")},c.getTransitionStyle=function(e,t,i){var n=c.configStylePropertyObject(e);for(var o in n)if(n.hasOwnProperty(o))if("string"==typeof t)n[o]=t+" "+i;else{for(var r="",s=0,d=t.length;s<d;s+=1)r+=t[s]+" "+i+", ";n[o]=r.slice(0,-2)}return n},c.getVendorStyle=function(e,t){var i=c.configStylePropertyObject(e);for(var n in i)i.hasOwnProperty(n)&&(i[n]=t);return i},c.configStylePropertyObject=function(e){var t={};return t[e]="",["webkit","Moz","o"].forEach(function(i){t[i+e.charAt(0).toUpperCase()+e.slice(1)]=""}),t},c.extend=function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i]);return e},c.safeExtend=function(e,t){var i={};for(var n in e)e.hasOwnProperty(n)&&t.hasOwnProperty(n)?i[n]=t[n]:e.hasOwnProperty(n)&&(i[n]=e[n]);return i},c.map=function(e,t){if(e.length)for(var i=0,n=e.length;i<n;i+=1)t(e[i]);else t(e)},e.prototype.on=function(e,t){var i,n=this,o=e.split(/[ ,]+/g);n._handlers_=n._handlers_||{};for(var r=0;r<o.length;r+=1)i=o[r],n._handlers_[i]=n._handlers_[i]||[],n._handlers_[i].push(t);return n},e.prototype.off=function(e,t){var i=this;return i._handlers_=i._handlers_||{},void 0===e?i._handlers_={}:void 0===t?i._handlers_[e]=null:i._handlers_[e]&&i._handlers_[e].indexOf(t)>=0&&i._handlers_[e].splice(i._handlers_[e].indexOf(t),1),i},e.prototype.trigger=function(e,t){var i,n=this,o=e.split(/[ ,]+/g);n._handlers_=n._handlers_||{};for(var r=0;r<o.length;r+=1)i=o[r],n._handlers_[i]&&n._handlers_[i].length&&n._handlers_[i].forEach(function(e){e.call(n,{type:i,target:n},t)})},e.prototype.config=function(e){var t=this;t.options=t.defaults||{},e&&(t.options=c.safeExtend(t.options,e))},e.prototype.bindEvt=function(e,t){var i=this;return i._domHandlers_=i._domHandlers_||{},i._domHandlers_[t]=function(){"function"==typeof i["on"+t]?i["on"+t].apply(i,arguments):console.warn('[WARNING] : Missing "on'+t+'" handler.')},c.bindEvt(e,o[t],i._domHandlers_[t]),p[t]&&c.bindEvt(e,p[t],i._domHandlers_[t]),i},e.prototype.unbindEvt=function(e,t){var i=this;return i._domHandlers_=i._domHandlers_||{},c.unbindEvt(e,o[t],i._domHandlers_[t]),p[t]&&c.unbindEvt(e,p[t],i._domHandlers_[t]),delete i._domHandlers_[t],this},t.prototype=new e,t.constructor=t,t.id=0,t.prototype.destroy=function(){clearTimeout(this.removeTimeout),clearTimeout(this.showTimeout),clearTimeout(this.restTimeout),this.trigger("destroyed",this.instance),this.removeFromDom(),this.off()},t.prototype.restPosition=function(e){var t=this;t.frontPosition={x:0,y:0};var i=t.options.fadeTime+"ms",n={};n.front=c.getTransitionStyle("transition",["top","left"],i);var o={front:{}};o.front={left:t.frontPosition.x+"px",top:t.frontPosition.y+"px"},t.applyStyles(n),t.applyStyles(o),t.restTimeout=setTimeout(function(){"function"==typeof e&&e.call(t),t.restCallback()},t.options.fadeTime)},t.prototype.restCallback=function(){var e=this,t={};t.front=c.getTransitionStyle("transition","none",""),e.applyStyles(t),e.trigger("rested",e.instance)},t.prototype.resetDirection=function(){this.direction={x:!1,y:!1,angle:!1}},t.prototype.computeDirection=function(e){var t,i,n,o=e.angle.radian,r=Math.PI/4,s=Math.PI/2;if(o>r&&o<3*r&&!e.lockX?t="up":o>-r&&o<=r&&!e.lockY?t="left":o>3*-r&&o<=-r&&!e.lockX?t="down":e.lockY||(t="right"),e.lockY||(i=o>-s&&o<s?"left":"right"),e.lockX||(n=o>0?"up":"down"),e.force>this.options.threshold){var d={};for(var a in this.direction)this.direction.hasOwnProperty(a)&&(d[a]=this.direction[a]);var p={};this.direction={x:i,y:n,angle:t},e.direction=this.direction;for(var a in d)d[a]===this.direction[a]&&(p[a]=!0);if(p.x&&p.y&&p.angle)return e;p.x&&p.y||this.trigger("plain",e),p.x||this.trigger("plain:"+i,e),p.y||this.trigger("plain:"+n,e),p.angle||this.trigger("dir dir:"+t,e)}return e},i.prototype=new e,i.constructor=i,i.id=0,i.prototype.prepareNipples=function(){var e=this,t=e.nipples;t.on=e.on.bind(e),t.off=e.off.bind(e),t.options=e.options,t.destroy=e.destroy.bind(e),t.ids=e.ids,t.id=e.id,t.processOnMove=e.processOnMove.bind(e),t.processOnEnd=e.processOnEnd.bind(e),t.get=function(e){if(void 0===e)return t[0];for(var i=0,n=t.length;i<n;i+=1)if(t[i].identifier===e)return t[i];return!1}},i.prototype.bindings=function(){var e=this;e.bindEvt(e.options.zone,"start"),e.options.zone.style.touchAction="none",e.options.zone.style.msTouchAction="none"},i.prototype.begin=function(){var e=this,t=e.options;if("static"===t.mode){var i=e.createNipple(t.position,e.manager.getIdentifier());i.add(),e.idles.push(i)}},i.prototype.createNipple=function(e,i){var n=this,o=c.getScroll(),r=n.options;if(e.x&&e.y)({x:e.x-(o.x+n.box.left),y:e.y-(o.y+n.box.top)});else if(e.top||e.right||e.bottom||e.left){var s=document.createElement("DIV");s.style.display="hidden",s.style.top=e.top,s.style.right=e.right,s.style.bottom=e.bottom,s.style.left=e.left,s.style.position="absolute",r.zone.appendChild(s);var d=s.getBoundingClientRect();r.zone.removeChild(s),e,e={x:d.left+o.x,y:d.top+o.y}}var a=new t(n,{color:r.color,size:r.size,threshold:r.threshold,fadeTime:r.fadeTime,restJoystick:r.restJoystick,restOpacity:r.restOpacity,mode:r.mode,identifier:i,position:e,zone:r.zone,frontPosition:{x:0,y:0}});return n.nipples.push(a),n.trigger("added "+a.identifier+":added",a),n.manager.trigger("added "+a.identifier+":added",a),n.bindNipple(a),a},i.prototype.updateBox=function(){var e=this;e.box=e.options.zone.getBoundingClientRect()},i.prototype.bindNipple=function(e){var t,i=this,n=function(e,n){t=e.type+" "+n.id+":"+e.type,i.trigger(t,n)};e.on("destroyed",i.onDestroyed.bind(i)),e.on("shown hidden rested dir plain",n),e.on("dir:up dir:right dir:down dir:left",n),e.on("plain:up plain:right plain:down plain:left",n)},i.prototype.pressureFn=function(e,t,i){var n=this,o=0;clearInterval(n.pressureIntervals[i]),n.pressureIntervals[i]=setInterval(function(){var i=e.force||e.pressure||e.webkitForce||0;i!==o&&(t.trigger("pressure",i),n.trigger("pressure "+t.identifier+":pressure",i),o=i)}.bind(n),100)},i.prototype.onstart=function(e){var t=this,i=t.options;e=c.prepareEvent(e),t.updateBox();var n=function(e){t.actives.length<i.maxNumberOfNipples&&t.processOnStart(e)};return c.map(e,n),t.manager.bindDocument(),!1},i.prototype.processOnStart=function(e){var t,i=this,n=i.options,o=i.manager.getIdentifier(e),r=e.force||e.pressure||e.webkitForce||0,s={x:e.pageX,y:e.pageY},d=i.getOrCreate(o,s);d.identifier!==o&&i.manager.removeIdentifier(d.identifier),d.identifier=o;var a=function(t){t.trigger("start",t),i.trigger("start "+t.id+":start",t),t.show(),r>0&&i.pressureFn(e,t,t.identifier),i.processOnMove(e)};if((t=i.idles.indexOf(d))>=0&&i.idles.splice(t,1),i.actives.push(d),i.ids.push(d.identifier),"semi"!==n.mode)a(d);else{if(!(c.distance(s,d.position)<=n.catchDistance))return d.destroy(),void i.processOnStart(e);a(d)}return d},i.prototype.getOrCreate=function(e,t){var i,n=this,o=n.options;return/(semi|static)/.test(o.mode)?(i=n.idles[0])?(n.idles.splice(0,1),i):"semi"===o.mode?n.createNipple(t,e):(console.warn("Coudln't find the needed nipple."),!1):i=n.createNipple(t,e)},i.prototype.processOnMove=function(e){var t=this,i=t.options,n=t.manager.getIdentifier(e),o=t.nipples.get(n);if(!o)return console.error("Found zombie joystick with ID "+n),void t.manager.removeIdentifier(n);o.identifier=n;var r=o.options.size/2,s={x:e.pageX,y:e.pageY},d=c.distance(s,o.position),a=c.angle(s,o.position),p=c.radians(a),l=d/r;d>r&&(d=r,s=c.findCoord(o.position,d,a));var f=s.x-o.position.x,u=s.y-o.position.y;i.lockX&&(u=0),i.lockY&&(f=0),o.frontPosition={x:f,y:u};var h={identifier:o.identifier,position:s,force:l,pressure:e.force||e.pressure||e.webkitForce||0,distance:d,angle:{radian:p,degree:a},instance:o,lockX:i.lockX,lockY:i.lockY};h=o.computeDirection(h),h.angle={radian:c.radians(180-a),degree:180-a},o.trigger("move",h),t.trigger("move "+o.id+":move",h)},i.prototype.processOnEnd=function(e){var t=this,i=t.options,n=t.manager.getIdentifier(e),o=t.nipples.get(n),r=t.manager.removeIdentifier(o.identifier);o&&(clearInterval(t.pressureIntervals[o.identifier]),o.resetDirection(),o.trigger("end",o),t.trigger("end "+o.id+":end",o),t.ids.indexOf(o.identifier)>=0&&t.ids.splice(t.ids.indexOf(o.identifier),1),t.actives.indexOf(o)>=0&&t.actives.splice(t.actives.indexOf(o),1),/(semi|static)/.test(i.mode)?t.idles.push(o):t.nipples.indexOf(o)>=0&&t.nipples.splice(t.nipples.indexOf(o),1),t.manager.unbindDocument(),/(semi|static)/.test(i.mode)&&(t.manager.ids[r.id]=r.identifier))},i.prototype.onDestroyed=function(e,t){var i=this;i.nipples.indexOf(t)>=0&&i.nipples.splice(i.nipples.indexOf(t),1),i.actives.indexOf(t)>=0&&i.actives.splice(i.actives.indexOf(t),1),i.idles.indexOf(t)>=0&&i.idles.splice(i.idles.indexOf(t),1),i.ids.indexOf(t.identifier)>=0&&i.ids.splice(i.ids.indexOf(t.identifier),1),i.manager.removeIdentifier(t.identifier),i.manager.unbindDocument()},i.prototype.destroy=function(){var e=this;e.unbindEvt(e.options.zone,"start"),e.nipples.forEach(function(e){e.destroy()});for(var t in e.pressureIntervals)e.pressureIntervals.hasOwnProperty(t)&&clearInterval(e.pressureIntervals[t]);e.trigger("destroyed",e.nipples),e.manager.unbindDocument(),e.off()},n.prototype=new e,n.constructor=n,n.prototype.prepareCollections=function(){var e=this;e.collections.create=e.create.bind(e),e.collections.on=e.on.bind(e),e.collections.off=e.off.bind(e),e.collections.destroy=e.destroy.bind(e),e.collections.get=function(t){var i;return e.collections.every(function(e){return!(i=e.get(t))}),i}},n.prototype.create=function(e){return this.createCollection(e)},n.prototype.createCollection=function(e){var t=this,n=new i(t,e);return t.bindCollection(n),t.collections.push(n),n},n.prototype.bindCollection=function(e){var t,i=this,n=function(e,n){t=e.type+" "+n.id+":"+e.type,i.trigger(t,n)};e.on("destroyed",i.onDestroyed.bind(i)),e.on("shown hidden rested dir plain",n),e.on("dir:up dir:right dir:down dir:left",n),e.on("plain:up plain:right plain:down plain:left",n)},n.prototype.bindDocument=function(){var e=this;e.binded||(e.bindEvt(document,"move").bindEvt(document,"end"),e.binded=!0)},n.prototype.unbindDocument=function(e){var t=this;Object.keys(t.ids).length&&!0!==e||(t.unbindEvt(document,"move").unbindEvt(document,"end"),t.binded=!1)},n.prototype.getIdentifier=function(e){var t;return e?void 0===(t=void 0===e.identifier?e.pointerId:e.identifier)&&(t=this.latest||0):t=this.index,void 0===this.ids[t]&&(this.ids[t]=this.index,this.index+=1),this.latest=t,this.ids[t]},n.prototype.removeIdentifier=function(e){var t={};for(var i in this.ids)if(this.ids[i]===e){t.id=i,t.identifier=this.ids[i],delete this.ids[i];break}return t},n.prototype.onmove=function(e){return this.onAny("move",e),!1},n.prototype.onend=function(e){return this.onAny("end",e),!1},n.prototype.oncancel=function(e){return this.onAny("end",e),!1},n.prototype.onAny=function(e,t){var i,n=this,o="processOn"+e.charAt(0).toUpperCase()+e.slice(1);t=c.prepareEvent(t);var r=function(e,t,i){i.ids.indexOf(t)>=0&&(i[o](e),e._found_=!0)},s=function(e){i=n.getIdentifier(e),c.map(n.collections,r.bind(null,e,i)),e._found_||n.removeIdentifier(i)};return c.map(t,s),!1},n.prototype.destroy=function(){var e=this;e.unbindDocument(!0),e.ids={},e.index=0,e.collections.forEach(function(e){e.destroy()}),e.off()},n.prototype.onDestroyed=function(e,t){var i=this;if(i.collections.indexOf(t)<0)return!1;i.collections.splice(i.collections.indexOf(t),1)};var l=new n;return{create:function(e){return l.create(e)},factory:l}}); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _stringWithLength = require('./string-with-length.generator');
Object.keys(_stringWithLength).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _stringWithLength[key];
}
});
});
var _personalData = require('./personalData.generator');
Object.keys(_personalData).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _personalData[key];
}
});
}); |
/**
* Welcome to your Workbox-powered service worker!
*
* You'll need to register this file in your web app and you should
* disable HTTP caching for this file too.
* See https://goo.gl/nhQhGp
*
* The rest of the code is auto-generated. Please don't update this file
* directly; instead, make changes to your Workbox build configuration
* and re-run your build process.
* See https://goo.gl/2aRDsh
*/
importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
workbox.core.skipWaiting();
workbox.core.clientsClaim();
/**
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
* See https://goo.gl/S9QRab
*/
self.__precacheManifest = [
{
"url": "android-chrome-192x192.0fcebb82.png",
"revision": "71c32dc8b4da4840d61a1796a2bc230b"
},
{
"url": "android-chrome-512x512.ae40f73d.png",
"revision": "8bf8012c4f4ae251d660b4739171b7ed"
},
{
"url": "apple-touch-icon-120x120-precomposed.044c6f3f.png",
"revision": "a6e447e90b691da286286ab18849adac"
},
{
"url": "apple-touch-icon-120x120.044c6f3f.png",
"revision": "a6e447e90b691da286286ab18849adac"
},
{
"url": "apple-touch-icon-precomposed.fdeabd24.png",
"revision": "de5e22b15cf20cb0d586a036d714ee3f"
},
{
"url": "apple-touch-icon.fdeabd24.png",
"revision": "de5e22b15cf20cb0d586a036d714ee3f"
},
{
"url": "certificate.1e3570bc.pdf",
"revision": "623cac53a40c141642b22bf50fe14628"
},
{
"url": "confidentialite.2f395007.js",
"revision": "fdaad1887614bbc6822d8a5abb2234ff"
},
{
"url": "confidentialite.daef9682.css",
"revision": "9caf330c4bbb593fbc8d2eb58a9e085c"
},
{
"url": "confidentialite.html",
"revision": "4bce5357393a4b0e58eee0842ffa7e8d"
},
{
"url": "favicon-16x16.a4687270.png",
"revision": "652605ae0182d51781ab0be639ad2bda"
},
{
"url": "favicon-32x32.623384d0.png",
"revision": "674c9c4ef1e4c7ea9de1218ee0bfd0cf"
},
{
"url": "index.html",
"revision": "717a9a9a16b984000cc6e4539c49e936"
},
{
"url": "logo_dnum_dark.0fe33c5b.svg",
"revision": "da8bdc57d4f231585216c53da752d00a"
},
{
"url": "logo_dnum.19ebc682.svg",
"revision": "3a41bfa41e4671414da29db168c37d66"
},
{
"url": "main.26b14001.js",
"revision": "80920b563c1f746ea1d101a6f62a8c60"
},
{
"url": "main.31fdc5e2.js",
"revision": "382ce23520ff206b81f17bf12bad787c"
},
{
"url": "main.61387d31.js",
"revision": "f2ab86a88b51e1e07dc6f703efb93652"
},
{
"url": "main.daef9682.css",
"revision": "7d236ed06e460d3f2096e07384bbc079"
},
{
"url": "marianne-bold-webfont.1505950c.woff2",
"revision": "e67f6cefe32cc39f909e605c8d6337a9"
},
{
"url": "marianne-bold-webfont.7424dbde.woff",
"revision": "0bcc99dd4adfb78e11098fedfe531cbb"
},
{
"url": "marianne-regular-webfont.0a959359.woff",
"revision": "89f4f2326c77429e98693cf83703face"
},
{
"url": "marianne-regular-webfont.daa94941.woff2",
"revision": "d2c09e5f58d8360f541e2a8726c33587"
},
{
"url": "MIN_Interieur_RVB_dark.0e5ee525.svg",
"revision": "345794cee228a40837ab654184cd2c96"
},
{
"url": "MIN_Interieur_RVB.124e26ea.svg",
"revision": "6823b6d87f43d208b17ff81e178f9ae9"
},
{
"url": "safari-pinned-tab.1551797e.svg",
"revision": "f53452e6ac8760f12bab91672e91d39b"
},
{
"url": "./",
"revision": "a1ca98525a5046713bfb5f2cbf458e89"
}
].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
workbox.routing.registerNavigationRoute(workbox.precaching.getCacheKeyForURL("/index.html"));
|
import React, { Component } from 'react';
import {Icon } from 'antd';
import './style/style.less';
export default class Card extends Component {
constructor(props) {
super(props);
this.state={
flag:false,
};
}
render() {
const {title,icon,more,className} = this.props;
let flag = this.state.flag;
if(more){
flag=true;
}
return (
<div className={`card1 ${className?className:''}`}>
<div className="title">
<span><img className="img" src={icon} /></span>
<span className="s1">{title}</span>
{flag?<span><a className="s21 a-style1">更多<Icon type="double-right" /></a></span>:''}
</div>
<div className="content">
{this.props.children}
</div>
</div>
);
}
}
|
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
module.exports = {
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: [
'index.ts',
'/node_modules/'
],
// An object that configures minimum threshold enforcement for coverage results
coverageThreshold: {
global: {
'branches': 70,
'functions': 70,
'lines': 70,
'statements': 70
}
},
// An array of file extensions your modules use
moduleFileExtensions: [
'js',
'json',
'jsx',
'ts',
'tsx',
'node'
],
// The test environment that will be used for testing
testEnvironment: 'node',
// The glob patterns Jest uses to detect test files
testMatch: [
'**/src/**/__tests__/**/*.[jt]s?(x)',
'**/src/**/?(*.)+(spec|test).[tj]s?(x)'
],
// A map from regular expressions to paths to transformers
transform: {
'\\.(ts)$': 'ts-jest'
}
}
|
module.exports = {
env: {
browser: true,
es6: true,
},
extends: [
'airbnb',
'airbnb/hooks',
'plugin:prettier/recommended',
'prettier/react',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 2018,
sourceType: 'module',
},
plugins: ['react'],
rules: {
'prettier/prettier': 'error',
'jsx-a11y/label-has-associated-control': [
'error',
{
required: {
some: ['nesting', 'id'],
},
},
],
'no-underscore-dangle': [2, { allow: ['_id', '_groups'] }],
},
};
|
var destinos = [], categorias = [], perfiles = [];
var exp = undefined;
function addElement (array, element){
if (!$.isArray(array)){
return false;
}
array.push(element);
}
function deleteElement (array, element){
if (!$.isArray(array)){
return false;
}else {
if (array.length == 0){
return false;
}
}
$.each(array, function(index, value){
if (value == element){
array.splice(index, 1);
return;
}
});
}
function change (object, array, element){
if (!$(object).is(':checked')){
deleteElement (array, element);
}else{
addElement (array, element);
}
console.log(array);
}
|
(async () => {
const gameID = prompt('Please enter the game set ID you are playing: ');
const GetAnswers = await fetch(`https://api.blooket.com/api/games?gameId=${gameID}`, {
headers: {
"accept": "application/json, text/plain, */*",
"accept-language": "en-US,en;q=0.9",
"content-type": "application/json;charset=UTF-8",
},
method: 'GET'
});
const Answers = await GetAnswers.json();
Answers.questions.forEach(question => {
console.log(`Q: ${question.question} A: ${question.correctAnswers.join(', ')}`);
});
})();
|
/*
Copyright (c) Uber Technologies, Inc.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
// @flow
import * as React from 'react';
import { Block } from '../../block/index.js';
import { Button } from '../../button/index.js';
import { ProgressSteps, NumberedStep } from '../index.js';
export class Scenario extends React.Component<{}, { current: number }> {
state = { current: 0 };
render() {
return (
<ProgressSteps current={this.state.current}>
<NumberedStep title="Create Account">
<Block data-e2e="content-1" font="font400">
Here is some step content
</Block>
<Button data-e2e="button-next" onClick={() => this.setState({ current: 1 })}>
Next
</Button>
</NumberedStep>
<NumberedStep title="Verify Payment">
<Block data-e2e="content-2" font="font400">
Here is some more content
</Block>
<Button data-e2e="button-previous" onClick={() => this.setState({ current: 0 })}>
Previous
</Button>
<Button onClick={() => this.setState({ current: 2 })}>Next</Button>
</NumberedStep>
<NumberedStep title="Add Payment Method">
<Block data-e2e="content-3" font="font400">
Here too!
</Block>
<Button onClick={() => this.setState({ current: 1 })}>Previous</Button>
</NumberedStep>
</ProgressSteps>
);
}
}
|