Best JavaScript code snippet using storybook-root
dense_features_test.py
Source:dense_features_test.py
...42 @test_util.run_in_graph_and_eager_modes()43 def test_retrieving_input(self):44 features = {'a': [0.]}45 dense_features = df.DenseFeatures(fc.numeric_column('a'))46 inputs = self.evaluate(dense_features(features))47 self.assertAllClose([[0.]], inputs)48 def test_reuses_variables(self):49 with context.eager_mode():50 sparse_input = sparse_tensor.SparseTensor(51 indices=((0, 0), (1, 0), (2, 0)),52 values=(0, 1, 2),53 dense_shape=(3, 3))54 # Create feature columns (categorical and embedding).55 categorical_column = fc.categorical_column_with_identity(56 key='a', num_buckets=3)57 embedding_dimension = 258 def _embedding_column_initializer(shape, dtype, partition_info=None):59 del shape # unused60 del dtype # unused61 del partition_info # unused62 embedding_values = (63 (1, 0), # id 064 (0, 1), # id 165 (1, 1)) # id 266 return embedding_values67 embedding_column = fc.embedding_column(68 categorical_column,69 dimension=embedding_dimension,70 initializer=_embedding_column_initializer)71 dense_features = df.DenseFeatures([embedding_column])72 features = {'a': sparse_input}73 inputs = dense_features(features)74 variables = dense_features.variables75 # Sanity check: test that the inputs are correct.76 self.assertAllEqual([[1, 0], [0, 1], [1, 1]], inputs)77 # Check that only one variable was created.78 self.assertEqual(1, len(variables))79 # Check that invoking dense_features on the same features does not create80 # additional variables81 _ = dense_features(features)82 self.assertEqual(1, len(variables))83 self.assertIs(variables[0], dense_features.variables[0])84 def test_dense_feature_with_partitioner(self):85 with context.eager_mode():86 sparse_input = sparse_tensor.SparseTensor(87 indices=((0, 0), (1, 0), (2, 0), (3, 0)),88 values=(0, 1, 3, 2),89 dense_shape=(4, 4))90 # Create feature columns (categorical and embedding).91 categorical_column = fc.categorical_column_with_identity(92 key='a', num_buckets=4)93 embedding_dimension = 294 def _embedding_column_initializer(shape, dtype, partition_info=None):95 offset = partition_info._var_offset[0]96 del shape # unused97 del dtype # unused98 if offset == 0:99 embedding_values = (100 (1, 0), # id 0101 (0, 1)) # id 1102 else:103 embedding_values = (104 (1, 1), # id 2105 (2, 2)) # id 3106 return embedding_values107 embedding_column = fc.embedding_column(108 categorical_column,109 dimension=embedding_dimension,110 initializer=_embedding_column_initializer)111 dense_features = df.DenseFeatures(112 [embedding_column],113 partitioner=partitioned_variables.fixed_size_partitioner(2))114 features = {'a': sparse_input}115 inputs = dense_features(features)116 variables = dense_features.variables117 # Sanity check: test that the inputs are correct.118 self.assertAllEqual([[1, 0], [0, 1], [2, 2], [1, 1]], inputs)119 # Check that only one variable was created.120 self.assertEqual(2, len(variables))121 # Check that invoking dense_features on the same features does not create122 # additional variables123 _ = dense_features(features)124 self.assertEqual(2, len(variables))125 self.assertIs(variables[0], dense_features.variables[0])126 self.assertIs(variables[1], dense_features.variables[1])127 def test_feature_column_dense_features_gradient(self):128 with context.eager_mode():129 sparse_input = sparse_tensor.SparseTensor(130 indices=((0, 0), (1, 0), (2, 0)),131 values=(0, 1, 2),132 dense_shape=(3, 3))133 # Create feature columns (categorical and embedding).134 categorical_column = fc.categorical_column_with_identity(135 key='a', num_buckets=3)136 embedding_dimension = 2137 def _embedding_column_initializer(shape, dtype, partition_info=None):138 del shape # unused139 del dtype # unused140 del partition_info # unused141 embedding_values = (142 (1, 0), # id 0143 (0, 1), # id 1144 (1, 1)) # id 2145 return embedding_values146 embedding_column = fc.embedding_column(147 categorical_column,148 dimension=embedding_dimension,149 initializer=_embedding_column_initializer)150 dense_features = df.DenseFeatures([embedding_column])151 features = {'a': sparse_input}152 def scale_matrix():153 matrix = dense_features(features)154 return 2 * matrix155 # Sanity check: Verify that scale_matrix returns the correct output.156 self.assertAllEqual([[2, 0], [0, 2], [2, 2]], scale_matrix())157 # Check that the returned gradient is correct.158 grad_function = backprop.implicit_grad(scale_matrix)159 grads_and_vars = grad_function()160 indexed_slice = grads_and_vars[0][0]161 gradient = grads_and_vars[0][0].values162 self.assertAllEqual([0, 1, 2], indexed_slice.indices)163 self.assertAllEqual([[2, 2], [2, 2], [2, 2]], gradient)164 def test_raises_if_empty_feature_columns(self):165 with self.assertRaisesRegexp(ValueError,166 'feature_columns must not be empty'):167 df.DenseFeatures(feature_columns=[])(features={})168 def test_should_be_dense_column(self):169 with self.assertRaisesRegexp(ValueError, 'must be a .*DenseColumn'):170 df.DenseFeatures(feature_columns=[171 fc.categorical_column_with_hash_bucket('wire_cast', 4)172 ])(173 features={174 'a': [[0]]175 })176 def test_does_not_support_dict_columns(self):177 with self.assertRaisesRegexp(178 ValueError, 'Expected feature_columns to be iterable, found dict.'):179 df.DenseFeatures(feature_columns={'a': fc.numeric_column('a')})(180 features={181 'a': [[0]]182 })183 def test_bare_column(self):184 with ops.Graph().as_default():185 features = features = {'a': [0.]}186 net = df.DenseFeatures(fc.numeric_column('a'))(features)187 self.evaluate(variables_lib.global_variables_initializer())188 self.evaluate(lookup_ops.tables_initializer())189 self.assertAllClose([[0.]], self.evaluate(net))190 def test_column_generator(self):191 with ops.Graph().as_default():192 features = features = {'a': [0.], 'b': [1.]}193 columns = (fc.numeric_column(key) for key in features)194 net = df.DenseFeatures(columns)(features)195 self.evaluate(variables_lib.global_variables_initializer())196 self.evaluate(lookup_ops.tables_initializer())197 self.assertAllClose([[0., 1.]], self.evaluate(net))198 def test_raises_if_duplicate_name(self):199 with self.assertRaisesRegexp(200 ValueError, 'Duplicate feature column name found for columns'):201 df.DenseFeatures(202 feature_columns=[fc.numeric_column('a'),203 fc.numeric_column('a')])(204 features={205 'a': [[0]]206 })207 def test_one_column(self):208 price = fc.numeric_column('price')209 with ops.Graph().as_default():210 features = {'price': [[1.], [5.]]}211 net = df.DenseFeatures([price])(features)212 self.evaluate(variables_lib.global_variables_initializer())213 self.evaluate(lookup_ops.tables_initializer())214 self.assertAllClose([[1.], [5.]], self.evaluate(net))215 def test_multi_dimension(self):216 price = fc.numeric_column('price', shape=2)217 with ops.Graph().as_default():218 features = {'price': [[1., 2.], [5., 6.]]}219 net = df.DenseFeatures([price])(features)220 self.evaluate(variables_lib.global_variables_initializer())221 self.evaluate(lookup_ops.tables_initializer())222 self.assertAllClose([[1., 2.], [5., 6.]], self.evaluate(net))223 def test_compute_output_shape(self):224 price1 = fc.numeric_column('price1', shape=2)225 price2 = fc.numeric_column('price2', shape=4)226 with ops.Graph().as_default():227 features = {228 'price1': [[1., 2.], [5., 6.]],229 'price2': [[3., 4., 5., 6.], [7., 8., 9., 10.]]230 }231 dense_features = df.DenseFeatures([price1, price2])232 self.assertEqual((None, 6), dense_features.compute_output_shape((None,)))233 net = dense_features(features)234 self.evaluate(variables_lib.global_variables_initializer())235 self.evaluate(lookup_ops.tables_initializer())236 self.assertAllClose([[1., 2., 3., 4., 5., 6.], [5., 6., 7., 8., 9., 10.]],237 self.evaluate(net))238 def test_raises_if_shape_mismatch(self):239 price = fc.numeric_column('price', shape=2)240 with ops.Graph().as_default():241 features = {'price': [[1.], [5.]]}242 with self.assertRaisesRegexp(243 Exception,244 r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'):245 df.DenseFeatures([price])(features)246 def test_reshaping(self):247 price = fc.numeric_column('price', shape=[1, 2])248 with ops.Graph().as_default():249 features = {'price': [[[1., 2.]], [[5., 6.]]]}250 net = df.DenseFeatures([price])(features)251 self.evaluate(variables_lib.global_variables_initializer())252 self.evaluate(lookup_ops.tables_initializer())253 self.assertAllClose([[1., 2.], [5., 6.]], self.evaluate(net))254 def test_multi_column(self):255 price1 = fc.numeric_column('price1', shape=2)256 price2 = fc.numeric_column('price2')257 with ops.Graph().as_default():258 features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}259 net = df.DenseFeatures([price1, price2])(features)260 self.evaluate(variables_lib.global_variables_initializer())261 self.evaluate(lookup_ops.tables_initializer())262 self.assertAllClose([[1., 2., 3.], [5., 6., 4.]], self.evaluate(net))263 def test_cols_to_output_tensors(self):264 price1 = fc.numeric_column('price1', shape=2)265 price2 = fc.numeric_column('price2')266 with ops.Graph().as_default():267 cols_dict = {}268 features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}269 dense_features = df.DenseFeatures([price1, price2])270 net = dense_features(features, cols_dict)271 self.evaluate(variables_lib.global_variables_initializer())272 self.evaluate(lookup_ops.tables_initializer())273 self.assertAllClose([[1., 2.], [5., 6.]],274 self.evaluate(cols_dict[price1]))275 self.assertAllClose([[3.], [4.]], self.evaluate(cols_dict[price2]))276 self.assertAllClose([[1., 2., 3.], [5., 6., 4.]], self.evaluate(net))277 def test_column_order(self):278 price_a = fc.numeric_column('price_a')279 price_b = fc.numeric_column('price_b')280 with ops.Graph().as_default():281 features = {282 'price_a': [[1.]],283 'price_b': [[3.]],284 }...
dense_features_v2_test.py
Source:dense_features_v2_test.py
...41 @test_util.run_in_graph_and_eager_modes()42 def test_retrieving_input(self):43 features = {'a': [0.]}44 dense_features = df.DenseFeatures(fc.numeric_column('a'))45 inputs = self.evaluate(dense_features(features))46 self.assertAllClose([[0.]], inputs)47 def test_reuses_variables(self):48 with context.eager_mode():49 sparse_input = sparse_tensor.SparseTensor(50 indices=((0, 0), (1, 0), (2, 0)),51 values=(0, 1, 2),52 dense_shape=(3, 3))53 # Create feature columns (categorical and embedding).54 categorical_column = fc.categorical_column_with_identity(55 key='a', num_buckets=3)56 embedding_dimension = 257 def _embedding_column_initializer(shape, dtype, partition_info=None):58 del shape # unused59 del dtype # unused60 del partition_info # unused61 embedding_values = (62 (1, 0), # id 063 (0, 1), # id 164 (1, 1)) # id 265 return embedding_values66 embedding_column = fc.embedding_column(67 categorical_column,68 dimension=embedding_dimension,69 initializer=_embedding_column_initializer)70 dense_features = df.DenseFeatures([embedding_column])71 features = {'a': sparse_input}72 inputs = dense_features(features)73 variables = dense_features.variables74 # Sanity check: test that the inputs are correct.75 self.assertAllEqual([[1, 0], [0, 1], [1, 1]], inputs)76 # Check that only one variable was created.77 self.assertEqual(1, len(variables))78 # Check that invoking dense_features on the same features does not create79 # additional variables80 _ = dense_features(features)81 self.assertEqual(1, len(variables))82 self.assertIs(variables[0], dense_features.variables[0])83 def test_feature_column_dense_features_gradient(self):84 with context.eager_mode():85 sparse_input = sparse_tensor.SparseTensor(86 indices=((0, 0), (1, 0), (2, 0)),87 values=(0, 1, 2),88 dense_shape=(3, 3))89 # Create feature columns (categorical and embedding).90 categorical_column = fc.categorical_column_with_identity(91 key='a', num_buckets=3)92 embedding_dimension = 293 def _embedding_column_initializer(shape, dtype, partition_info=None):94 del shape # unused95 del dtype # unused96 del partition_info # unused97 embedding_values = (98 (1, 0), # id 099 (0, 1), # id 1100 (1, 1)) # id 2101 return embedding_values102 embedding_column = fc.embedding_column(103 categorical_column,104 dimension=embedding_dimension,105 initializer=_embedding_column_initializer)106 dense_features = df.DenseFeatures([embedding_column])107 features = {'a': sparse_input}108 def scale_matrix():109 matrix = dense_features(features)110 return 2 * matrix111 # Sanity check: Verify that scale_matrix returns the correct output.112 self.assertAllEqual([[2, 0], [0, 2], [2, 2]], scale_matrix())113 # Check that the returned gradient is correct.114 grad_function = backprop.implicit_grad(scale_matrix)115 grads_and_vars = grad_function()116 indexed_slice = grads_and_vars[0][0]117 gradient = grads_and_vars[0][0].values118 self.assertAllEqual([0, 1, 2], indexed_slice.indices)119 self.assertAllEqual([[2, 2], [2, 2], [2, 2]], gradient)120 def test_dense_feature_with_training_arg(self):121 price1 = fc.numeric_column('price1', shape=2)122 price2 = fc.numeric_column('price2')123 # Monkey patch the second numeric column to simulate a column that has124 # different behavior by mode.125 def training_aware_get_dense_tensor(transformation_cache,126 state_manager,127 training=None):128 return transformation_cache.get(price2, state_manager, training=training)129 def training_aware_transform_feature(transformation_cache,130 state_manager,131 training=None):132 input_tensor = transformation_cache.get(133 price2.key, state_manager, training=training)134 if training:135 return input_tensor * 10.0136 else:137 return input_tensor * 20.0138 price2.get_dense_tensor = training_aware_get_dense_tensor139 price2.transform_feature = training_aware_transform_feature140 with ops.Graph().as_default():141 features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}142 train_mode = df.DenseFeatures([price1, price2])(features, training=True)143 predict_mode = df.DenseFeatures([price1, price2144 ])(features, training=False)145 self.evaluate(variables_lib.global_variables_initializer())146 self.evaluate(lookup_ops.tables_initializer())147 self.assertAllClose([[1., 2., 30.], [5., 6., 40.]],148 self.evaluate(train_mode))149 self.assertAllClose([[1., 2., 60.], [5., 6., 80.]],150 self.evaluate(predict_mode))151 def test_raises_if_empty_feature_columns(self):152 with self.assertRaisesRegexp(ValueError,153 'feature_columns must not be empty'):154 df.DenseFeatures(feature_columns=[])(features={})155 def test_should_be_dense_column(self):156 with self.assertRaisesRegexp(ValueError, 'must be a .*DenseColumn'):157 df.DenseFeatures(feature_columns=[158 fc.categorical_column_with_hash_bucket('wire_cast', 4)159 ])(160 features={161 'a': [[0]]162 })163 def test_does_not_support_dict_columns(self):164 with self.assertRaisesRegexp(165 ValueError, 'Expected feature_columns to be iterable, found dict.'):166 df.DenseFeatures(feature_columns={'a': fc.numeric_column('a')})(167 features={168 'a': [[0]]169 })170 def test_bare_column(self):171 with ops.Graph().as_default():172 features = features = {'a': [0.]}173 net = df.DenseFeatures(fc.numeric_column('a'))(features)174 self.evaluate(variables_lib.global_variables_initializer())175 self.evaluate(lookup_ops.tables_initializer())176 self.assertAllClose([[0.]], self.evaluate(net))177 def test_column_generator(self):178 with ops.Graph().as_default():179 features = features = {'a': [0.], 'b': [1.]}180 columns = (fc.numeric_column(key) for key in features)181 net = df.DenseFeatures(columns)(features)182 self.evaluate(variables_lib.global_variables_initializer())183 self.evaluate(lookup_ops.tables_initializer())184 self.assertAllClose([[0., 1.]], self.evaluate(net))185 def test_raises_if_duplicate_name(self):186 with self.assertRaisesRegexp(187 ValueError, 'Duplicate feature column name found for columns'):188 df.DenseFeatures(189 feature_columns=[fc.numeric_column('a'),190 fc.numeric_column('a')])(191 features={192 'a': [[0]]193 })194 def test_one_column(self):195 price = fc.numeric_column('price')196 with ops.Graph().as_default():197 features = {'price': [[1.], [5.]]}198 net = df.DenseFeatures([price])(features)199 self.evaluate(variables_lib.global_variables_initializer())200 self.evaluate(lookup_ops.tables_initializer())201 self.assertAllClose([[1.], [5.]], self.evaluate(net))202 def test_multi_dimension(self):203 price = fc.numeric_column('price', shape=2)204 with ops.Graph().as_default():205 features = {'price': [[1., 2.], [5., 6.]]}206 net = df.DenseFeatures([price])(features)207 self.evaluate(variables_lib.global_variables_initializer())208 self.evaluate(lookup_ops.tables_initializer())209 self.assertAllClose([[1., 2.], [5., 6.]], self.evaluate(net))210 def test_compute_output_shape(self):211 price1 = fc.numeric_column('price1', shape=2)212 price2 = fc.numeric_column('price2', shape=4)213 with ops.Graph().as_default():214 features = {215 'price1': [[1., 2.], [5., 6.]],216 'price2': [[3., 4., 5., 6.], [7., 8., 9., 10.]]217 }218 dense_features = df.DenseFeatures([price1, price2])219 self.assertEqual((None, 6), dense_features.compute_output_shape((None,)))220 net = dense_features(features)221 self.evaluate(variables_lib.global_variables_initializer())222 self.evaluate(lookup_ops.tables_initializer())223 self.assertAllClose([[1., 2., 3., 4., 5., 6.], [5., 6., 7., 8., 9., 10.]],224 self.evaluate(net))225 def test_raises_if_shape_mismatch(self):226 price = fc.numeric_column('price', shape=2)227 with ops.Graph().as_default():228 features = {'price': [[1.], [5.]]}229 with self.assertRaisesRegexp(230 Exception,231 r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'):232 df.DenseFeatures([price])(features)233 def test_reshaping(self):234 price = fc.numeric_column('price', shape=[1, 2])235 with ops.Graph().as_default():236 features = {'price': [[[1., 2.]], [[5., 6.]]]}237 net = df.DenseFeatures([price])(features)238 self.evaluate(variables_lib.global_variables_initializer())239 self.evaluate(lookup_ops.tables_initializer())240 self.assertAllClose([[1., 2.], [5., 6.]], self.evaluate(net))241 def test_multi_column(self):242 price1 = fc.numeric_column('price1', shape=2)243 price2 = fc.numeric_column('price2')244 with ops.Graph().as_default():245 features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}246 net = df.DenseFeatures([price1, price2])(features)247 self.evaluate(variables_lib.global_variables_initializer())248 self.evaluate(lookup_ops.tables_initializer())249 self.assertAllClose([[1., 2., 3.], [5., 6., 4.]], self.evaluate(net))250 def test_cols_to_output_tensors(self):251 price1 = fc.numeric_column('price1', shape=2)252 price2 = fc.numeric_column('price2')253 with ops.Graph().as_default():254 cols_dict = {}255 features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]}256 dense_features = df.DenseFeatures([price1, price2])257 net = dense_features(features, cols_dict)258 self.evaluate(variables_lib.global_variables_initializer())259 self.evaluate(lookup_ops.tables_initializer())260 self.assertAllClose([[1., 2.], [5., 6.]],261 self.evaluate(cols_dict[price1]))262 self.assertAllClose([[3.], [4.]], self.evaluate(cols_dict[price2]))263 self.assertAllClose([[1., 2., 3.], [5., 6., 4.]], self.evaluate(net))264 def test_column_order(self):265 price_a = fc.numeric_column('price_a')266 price_b = fc.numeric_column('price_b')267 with ops.Graph().as_default():268 features = {269 'price_a': [[1.]],270 'price_b': [[3.]],271 }...
dungeon.js
Source:dungeon.js
1/**2 * @class Floor3 * @augments RPG.Cells.BaseCell4 */5RPG.Cells.Corridor = OZ.Singleton().extend(RPG.Cells.BaseCell);6RPG.Cells.Corridor.visual = { desc:"floor section", ch:".", image:"corridor", color:"#ccc" };78/**9 * @class Road10 * @augments RPG.Cells.BaseCell11 */12RPG.Cells.Road = OZ.Singleton().extend(RPG.Cells.BaseCell);13RPG.Cells.Road.visual = { desc:"road", ch:".", image:"road", color:"#963" };1415/**16 * @class Grass17 * @augments RPG.Cells.BaseCell18 */19RPG.Cells.Grass = OZ.Singleton().extend(RPG.Cells.BaseCell);20RPG.Cells.Grass.visual = { desc:"grass", ch:".", image:"grass", color:"#693" };2122/**23 * @class Water24 * @augments RPG.Cells.BaseCell25 */26RPG.Cells.Water = OZ.Singleton().extend(RPG.Cells.BaseCell);27RPG.Cells.Water.visual = { desc:"water", ch:"=", image:"water", color:"#009" };28RPG.Cells.Water.prototype.init = function() {29 this.parent();30 this._water = true;31}3233RPG.Cells.Water.prototype.entering = function(being) {34 var canSee = RPG.Game.pc.canSee(being.getCoords());35 if (canSee) {36 var verb = RPG.Misc.verb("wade", being);37 var s = RPG.Misc.format("Splash Splash! %A %s into the water.", being, verb);38 RPG.UI.buffer.message(s); 39 } else {40 RPG.UI.buffer.message("You hear some splashing.");41 }42}4344/**45 * @class Deep Water46 * @augments RPG.Cells.BaseCell47 */48RPG.Cells.DeepWater = OZ.Singleton().extend(RPG.Cells.Water);49RPG.Cells.DeepWater.visual = { desc:"deep water", ch:"~", image:"deepwater", color:"#009" };50RPG.Cells.DeepWater.prototype._blocks = RPG.BLOCKS_MOVEMENT;515253/**54 * @class Wall55 * @augments RPG.Cells.BaseCell56 */57RPG.Cells.Wall = OZ.Singleton().extend(RPG.Cells.BaseCell);58RPG.Cells.Wall.visual = { desc:"solid wall", ch:"#", image:"wall", color:"#666" };59RPG.Cells.Wall.prototype._blocks = RPG.BLOCKS_LIGHT;6061/**62 * @class Fake wall63 * @augments RPG.Cells.Wall64 */65RPG.Cells.Wall.Fake = OZ.Singleton().extend(RPG.Cells.Wall);66RPG.Cells.Wall.Fake.prototype.init = function() {67 this.parent();68 this._fake = true;69}7071/**72 * @class Tree73 * @augments RPG.Features.BaseFeature74 */75RPG.Features.Tree = OZ.Class().extend(RPG.Features.BaseFeature);76RPG.Features.Tree.visual = { desc:"tree", ch:"T", image:"tree", color:"#093" }77RPG.Features.Tree.prototype._blocks = RPG.BLOCKS_ITEMS;7879/**80 * @class Altar feature81 * @augments RPG.Features.BaseFeature82 */83RPG.Features.Altar = OZ.Class().extend(RPG.Features.BaseFeature);84RPG.Features.Altar.visual = { desc:"altar", image:"altar", ch:"\u00B1", color:"#fff"};8586/**87 * @class Bench feature88 * @augments RPG.Features.BaseFeature89 */90RPG.Features.Bench = OZ.Class().extend(RPG.Features.BaseFeature);91RPG.Features.Bench.visual = { desc:"bench", image:"bench", ch:"|", color:"#963"};92RPG.Features.Bench.prototype._blocks = RPG.BLOCKS_MOVEMENT;9394/**95 * @class Signpost feature96 * @augments RPG.Features.BaseFeature97 */98RPG.Features.Signpost = OZ.Class().extend(RPG.Features.BaseFeature);99RPG.Features.Signpost.visual = { image:"signpost", ch:"\u2142", color:"#666"};100RPG.Features.Signpost.prototype.init = function(label) {101 this.parent();102 this._label = label;103}104RPG.Features.Signpost.prototype.describe = function() {105 return "signpost labeled '" + this._label + "'";106}107108/**109 * @class Generic trap110 * @augments RPG.Features.BaseFeature111 */112RPG.Features.Trap = OZ.Class().extend(RPG.Features.BaseFeature);113RPG.Features.Trap.factory.frequency = 0;114RPG.Features.Trap.visual = { ch:"^" }115RPG.Features.Trap.prototype.init = function() {116 this.parent();117 this._damage = null;118}119120RPG.Features.Trap.prototype.entering = function(being) {121 this.parent(being);122 being.trapEncounter(this);123}124125RPG.Features.Trap.prototype.setOff = function(being) {126}127128RPG.Features.Trap.prototype.getDamage = function() {129 return this._damage;130}131132/**133 * @class Teleport trap134 * @augments RPG.Features.Trap135 */136RPG.Features.Trap.Teleport = OZ.Class().extend(RPG.Features.Trap);137RPG.Features.Trap.Teleport.visual = { desc:"teleport trap", image:"trap-teleport", color:"#3c3" }138139RPG.Features.Trap.Teleport.prototype.setOff = function(being) {140 var c = this._map.getFreeCoords();141 being.teleport(c);142}143144/**145 * @class Pit trap146 * @augments RPG.Features.Trap147 */148RPG.Features.Trap.Pit = OZ.Class().extend(RPG.Features.Trap);149RPG.Features.Trap.Pit.visual = { desc:"pit trap", image:"trap-pit", color:"#963" }150151RPG.Features.Trap.Pit.prototype.init = function() {152 this.parent();153 this._damage = new RPG.RandomValue(3, 1);154}155156RPG.Features.Trap.Pit.prototype.setOff = function(being) {157 var canSee = RPG.Game.pc.canSee(this._coords);158159 if (canSee) {160 var verb = RPG.Misc.verb("fall", being);161 var s = RPG.Misc.format("%A %s into a pit!", being, verb);162 RPG.UI.buffer.message(s);163 }164165 var dmg = RPG.Rules.getTrapDamage(being, this);166 being.adjustStat(RPG.STAT_HP, -dmg);167 168 if (!being.isAlive() && canSee && being != RPG.Game.pc) {169 var s = RPG.Misc.format("%The suddenly collapses!", being);170 RPG.UI.buffer.message(s);171 }172173}174175/**176 * @class Flash trap177 * @augments RPG.Features.Trap178 */179RPG.Features.Trap.Flash = OZ.Class().extend(RPG.Features.Trap);180RPG.Features.Trap.Flash.visual = { desc:"flash trap", image:"trap-flash", color:"#ff0" }181182RPG.Features.Trap.Flash.prototype.setOff = function(being) {183 var canSee = RPG.Game.pc.canSee(this._coords);184185 var blindness = new RPG.Effects.Blindness(5);186 being.addEffect(blindness);187188 if (canSee) {189 var s = RPG.Misc.format("%A %is blinded by a light flash!", being);190 RPG.UI.buffer.message(s);191 }192}193194/**195 * @class Abstract destroyable feature196 * @augments RPG.Features.BaseFeature197 * @augments RPG.Features.IDamageReceiver198 */199RPG.Features.Destroyable = OZ.Class().extend(RPG.Features.BaseFeature)200 .implement(RPG.Misc.IDamageReceiver);201202RPG.Features.Destroyable.factory.frequency = 0;203RPG.Features.Destroyable.prototype.damage = function(amount) {204 this._hp -= amount;205 if (!this.isAlive()) { this._destroy(); }206}207RPG.Features.Destroyable.prototype.isAlive = function() {208 return this._hp > 0;209}210211/**212 * This being just destroyed this feature213 * @param {RPG.Beings.BaseBeing} being214 */215RPG.Features.Destroyable.prototype._destroy = function() {216 this._map.setFeature(null, this._coords); 217}218219/**220 * @class Tombstone feature221 * @augments RPG.Features.Destroyable222 */223RPG.Features.Tombstone = OZ.Class().extend(RPG.Features.Destroyable);224RPG.Features.Tombstone.visual = { desc:"tombstone", image:"tombstone", ch:"\u2020", color:"#666"};225RPG.Features.Tombstone.prototype._blocks = RPG.BLOCKS_MOVEMENT;226RPG.Features.Tombstone.prototype.init = function() {227 this.parent();228 this._hp = 4;229}230RPG.Features.Tombstone.prototype._destroy = function() {231 this.parent();232 var undead = RPG.Factories.undead.getInstance(this._map.getDanger());233 RPG.Game.getEngine().addActor(undead);234 this._map.setBeing(undead, this._coords);235}236237/**238 * @class Door239 * @augments RPG.Features.Destroyable240 */241RPG.Features.Door = OZ.Class().extend(RPG.Features.Destroyable);242RPG.Features.Door.visual = { color:"#963" }243RPG.Features.Door.prototype.init = function() {244 this.parent();245 this._hp = 4;246 this._closed = null;247 this._locked = null;248 this.open();249}250251RPG.Features.Door.prototype.getVisualProperty = function(name) {252 var result = this.parent(name);253 if (this._closed) {254 var data = {255 ch: "+",256 desc: "closed door",257 image: "door-closed"258 };259 } else {260 var data = {261 ch: "/",262 desc: "open door",263 image: "door-open"264 };265 }266 return data[name] || this.parent(name);267}268269RPG.Features.Door.prototype.lock = function() {270 this.close();271 this._locked = true;272 return this;273}274275RPG.Features.Door.prototype.close = function() {276 this._closed = true;277 this._locked = false;278 this._blocks = RPG.BLOCKS_LIGHT;279 if (this._map && this._map.isActive() && RPG.Game.pc.canSee(this._coords)) { 280 RPG.Game.pc.coordsChanged(this._coords);281 RPG.Game.pc.updateVisibility(); 282 }283 return this;284}285286RPG.Features.Door.prototype.open = function() {287 this._closed = false;288 this._locked = false;289 this._blocks = RPG.BLOCKS_NOTHING;290 if (this._map && this._map.isActive() && RPG.Game.pc.canSee(this._coords)) { 291 RPG.Game.pc.coordsChanged(this._coords);292 RPG.Game.pc.updateVisibility(); 293 }294 return this;295}296297RPG.Features.Door.prototype.unlock = function() {298 this._locked = false;299 return this;300}301302RPG.Features.Door.prototype.isClosed = function() {303 return this._closed;304}305306RPG.Features.Door.prototype.isLocked = function() {307 return this._locked;308}309RPG.Features.Door.prototype._destroy = function() {310 this.parent();311 if (RPG.Game.pc.canSee(this._coords)) { RPG.Game.pc.updateVisibility(); }312}313314/**315 * @class Stained glass window, random shiny color. When destroyed, damages stuff around.316 * @augments RPG.Features.Destroyable317 * @augments RPG.Features.IActor318 * @augments RPG.Features.IDamageDealer319 */320RPG.Features.StainedGlassWindow = OZ.Class().extend(RPG.Features.Destroyable)321 .implement(RPG.IActor)322 .implement(RPG.Misc.IDamageDealer);323324RPG.Features.StainedGlassWindow.visual = { desc:"stained glass window", image:"stained-glass-window", ch:"=" };325RPG.Features.StainedGlassWindow.prototype._blocks = RPG.BLOCKS_MOVEMENT;326RPG.Features.StainedGlassWindow.prototype._hit = new RPG.RandomValue(8, 5);327RPG.Features.StainedGlassWindow.prototype._damage = new RPG.RandomValue(2, 1);328RPG.Features.StainedGlassWindow.prototype.init = function() { 329 this.parent();330 this._hp = 3;331 this._color = ["red","green","blue","yellow","magenta","cyan"].random(); 332}333RPG.Features.StainedGlassWindow.prototype.getColor = function() { 334 return this._color;335}336RPG.Features.StainedGlassWindow.prototype._destroy = function() {337 this.parent();338 RPG.Game.getEngine().addActor(this);339}340/**341 * @see RPG.IActor#getSpeed342 */343RPG.Features.StainedGlassWindow.prototype.getSpeed = function() {344 return 1/0;345}346/**347 * @see RPG.IActor#yourTurn348 * Damage surrounding beings349 */350RPG.Features.StainedGlassWindow.prototype.yourTurn = function() {351 var coords = this._map.getCoordsInCircle(this._coords, 1);352 for (var i=0;i<coords.length;i++) {353 var b = this._map.getBeing(coords[i]);354 if (!b) { continue; }355 var combat = new RPG.Combat(this, b).execute();356 357 if (!combat.wasHit()) {358 var verb = RPG.Misc.verb("evade", b);359 var s = RPG.Misc.format("%The %s the falling glass.", b, verb);360 RPG.UI.buffer.message(s);361 continue;362 }363 364 var verb = (combat.wasKill() ? "killed" : "wounded");365 var s = RPG.Misc.format("%The %is %s by the falling glass!", b, b, verb);366 RPG.UI.buffer.message(s);367 }368369 RPG.Game.getEngine().removeActor(this);370 return RPG.ACTION_TIME;371}372373374/**375 * @class Basic level connector376 * @augments RPG.Features.BaseFeature377 */378RPG.Features.Connector = OZ.Class().extend(RPG.Features.BaseFeature);379380RPG.Features.Connector.prototype.init = function() {381 this.parent();382 this._target = null;383}384385RPG.Features.Connector.prototype.enter = function(being) {386 var target = this.getTarget();387388 if (target) { /* move being to other map */389 var map = target.getMap();390 var coords = target.getCoords();391 map.setBeing(being, coords);392 return RPG.ACTION_TIME;393 } else {394 return RPG.ACTION_NO_TIME;395 }396}397398/**399 * @param {RPG.Features.Connector} target400 */401RPG.Features.Connector.prototype.setTarget = function(target) {402 this._target = target;403 return this;404}405406/**407 * @returns {RPG.Features.Connector || null}408 */409RPG.Features.Connector.prototype.getTarget = function() {410 if (!this._target) { RPG.Game.getStory().staircaseCallback(this); }/* ask story to generate some */411 return this._target;412}413414/**415 * @class Connector in "down" direction416 * @augments RPG.Features.Connector417 */418RPG.Features.Connector.Entry = OZ.Class().extend(RPG.Features.Connector);419RPG.Features.Connector.Entry.visual = { ch:">" };420421/**422 * @class Connector in "up" direction423 * @augments RPG.Features.Connector424 */425RPG.Features.Connector.Exit = OZ.Class().extend(RPG.Features.Connector);426RPG.Features.Connector.Exit.visual = { ch:"<" };427428/**429 * @class Staircase down430 * @augments RPG.Features.Connector.Entry431 */432RPG.Features.StaircaseDown = OZ.Class().extend(RPG.Features.Connector.Entry);433RPG.Features.StaircaseDown.visual = { desc:"staircase leading down", image:"staircase-down", color:"#ccc" }434435/**436 * @class Staircase up437 * @augments RPG.Features.Connector.Exit438 */439RPG.Features.StaircaseUp = OZ.Class().extend(RPG.Features.Connector.Exit);440RPG.Features.StaircaseUp.visual = { desc:"staircase leading up", image:"staircase-up", color:"#ccc" }441442/**443 * @class Road in "up" direction444 * @augments RPG.Features.Connector445 */446RPG.Features.RoadExit = OZ.Class().extend(RPG.Features.Connector.Exit);447RPG.Features.RoadExit.visual = { desc:"road leading away", image:"road-away", color:"#963" };448449/**450 * @class Road in "down" direction451 * @augments RPG.Features.Connector452 */453RPG.Features.RoadEntry = OZ.Class().extend(RPG.Features.Connector.Entry);454RPG.Features.RoadEntry.visual = { desc:"road leading further", image:"road-further", color:"#963" };455456/**457 * @class Set of cells with tutorial messages458 * @augments RPG.Areas.BaseArea459 */460RPG.Areas.Tutorial = OZ.Class().extend(RPG.Areas.BaseArea);461RPG.Areas.Tutorial.prototype._messages = {};462RPG.Areas.Tutorial.prototype.init = function() {463 this.parent();464 this._visited = {};465}466RPG.Areas.Tutorial.prototype.getCoords = function() {467 var all = [];468 for (var p in this._messages) { 469 if (p in this._visited) { continue; }470 all.push(RPG.Coords.fromString(p)); 471 }472 return all;473}474475RPG.Areas.Tutorial.prototype.entering = function(being) {476 this.parent(being);477 if (being != RPG.Game.pc) { return; }478 var id = being.getCoords().toString();479 480 if (id in this._visited) { return; } /* already seen */481 482 /* showing tutorial for the first time? */483 var first = true;484 for (var p in this._visited) { first = false; }485 486 if (first) {487 var text = this._messages[id];488 text += "<br/><br/>";489 text += "Do you want to continue seeing these tutorial tips?";490 491 var yes = function() { /* want to see */492 this._visited[id] = 1;493 }494 495 var no = function() { /* do not want to see, mark all as visited */496 for (var id in this._messages) { this._visited[id] = 1; }497 }498 499 RPG.UI.confirm(text, "Tutorial", yes.bind(this), no.bind(this));500 501 } else {502 this._visited[id] = 1;503 RPG.UI.alert(this._messages[id], "Tutorial");504 }505}506507/**508 * @class Shop area509 * @augments RPG.Areas.Room510 */511RPG.Areas.Shop = OZ.Class().extend(RPG.Areas.Room);512RPG.Areas.Shop.prototype.init = function(corner1, corner2) {513 this.parent(corner1, corner2);514 this._modifiers[RPG.FEAT_MAX_MANA] = -1e6; /* in shops, there is no mana .) */515 this._door = null;516 this._welcome = "You entered a shop.";517}518519RPG.Areas.Shop.prototype.setMap = function(map) {520 this.parent(map);521522 var c = new RPG.Coords(0, 0);523 for (var i=this._corner1.x-1; i<=this._corner2.x+1; i++) {524 for (var j=this._corner1.y-1; j<=this._corner2.y+1; j++) {525 if (i >= this._corner1.x && i <= this._corner2.x && j >= this._corner1.y && j <= this._corner2.y) { continue; }526 c.x = i;527 c.y = j;528 if (this._map.blocks(RPG.BLOCKS_MOVEMENT, c)) { continue; }529 530 if (this._door) { throw new Error("Shop cannot have >1 doors"); }531 this._door = c.clone();532 }533 }534 535 if (!this._door) { throw new Error("Shop without doors"); }536}537538RPG.Areas.Shop.prototype.getDoor = function() {539 return this._door;540}541542RPG.Areas.Shop.prototype.setShopkeeper = function(being) {543 this._map.setBeing(being, this._door);544 var ai = new RPG.AI.Shopkeeper(being, this);545 being.setAI(ai);546}
...
highlight-test.js
Source:highlight-test.js
1/*2* Copyright 2017, GeoSolutions Sas.3* All rights reserved.4*5* This source code is licensed under the BSD-style license found in the6* LICENSE file in the root directory of this source tree.7*/8import expect from 'expect';9import {10 selectedFeatures,11 filteredspatialObject,12 filteredspatialObjectCoord,13 filteredGeometry,14 filteredSpatialObjectId,15 filteredSpatialObjectCrs,16 filteredspatialObjectType,17 filteredFeatures,18 highlighedFeatures19} from '../highlight';20const idFt1 = "idFt1";21const idFt2 = "idFt2";22const modeEdit = "edit";23let feature1 = {24 type: "Feature",25 geometry: {26 type: "Point",27 coordinates: [1, 2]28 },29 id: idFt1,30 properties: {31 someProp: "someValue"32 }33};34let feature2 = {35 type: "Feature",36 geometry: {37 type: "Point",38 coordinates: [1, 2]39 },40 id: idFt2,41 properties: {42 someProp: "someValue"43 }44};45let feature3 = [{46 type: "Feature",47 geometry: {48 type: 'Polygon',49 coordinates: [ [ 0.000008983152841195214, 0.000017966305681987637 ] ]50 },51 style: {52 fillColor: '#FFFFFF',53 fillOpacity: '0.2',54 color: '#ffcc33'55 },56 id: 'spatial_object'57}];58const initialState = {59 featuregrid: {60 mode: modeEdit,61 select: [feature1, feature2],62 changes: [feature2],63 showFilteredObject: true,64 open: true65 },66 highlight: {67 featuresPath: "featuregrid.select"68 },69 query: {70 filterObj: {71 spatialField: {72 geometry: {73 type: 'Polygon',74 coordinates: [[ 1, 2]],75 projection: 'EPSG:3857',76 id: 'spatial_object'77 }78 }79 }80 }81};82describe('Test highlight selectors', () => {83 it('test if there are some selected features', () => {84 const features = selectedFeatures(initialState);85 expect(features).toExist();86 expect(features.length).toBe(2);87 });88 it('test if there are not some selected features', () => {89 initialState.featuregrid.select = [];90 const features = selectedFeatures(initialState);91 expect(features).toExist();92 expect(features.length).toBe(0);93 });94 it('test filteredspatialObject', () => {95 const spatialObject = initialState.query.filterObj.spatialField;96 const features = filteredspatialObject(initialState);97 expect(features).toExist();98 expect(features).toBe(spatialObject);99 });100 it('test filteredspatialObject with empty state', () => {101 expect(filteredspatialObject({})).toBe(undefined);102 });103 it('test filteredGeometry', () => {104 const geometry = initialState.query.filterObj.spatialField.geometry;105 const features = filteredGeometry(initialState);106 expect(features).toExist();107 expect(features).toBe(geometry);108 });109 it('test filteredspatialObjectCoord', () => {110 const coordinates = initialState.query.filterObj.spatialField.geometry.coordinates;111 const features = filteredspatialObjectCoord(initialState);112 expect(features).toExist();113 expect(features).toBe(coordinates);114 });115 it('test filteredSpatialObjectId', () => {116 const geometryId = initialState.query.filterObj.spatialField.geometry.id;117 const features = filteredSpatialObjectId(initialState);118 expect(features).toExist();119 expect(features).toBe(geometryId);120 });121 it('test filteredSpatialObjectCrs', () => {122 const geometryCrs = initialState.query.filterObj.spatialField.geometry.projection;123 const features = filteredSpatialObjectCrs(initialState);124 expect(features).toExist();125 expect(features).toBe(geometryCrs);126 });127 it('test filteredspatialObjectType', () => {128 const geometryType = initialState.query.filterObj.spatialField.geometry.type;129 const features = filteredspatialObjectType(initialState);130 expect(features).toExist();131 expect(features).toBe(geometryType);132 });133 it('test filteredFeatures', () => {134 const features = filteredFeatures(initialState);135 expect(features).toExist();136 expect(features).toEqual(feature3);137 });138 it('test highlighedFeatures', () => {139 const features = highlighedFeatures(initialState);140 const featuresSelected = initialState.featuregrid.select;141 const combinedFeatures = [...featuresSelected, ...feature3];142 expect(features).toExist();143 expect(features).toEqual(combinedFeatures);144 });...
performanceWorm.py
Source:performanceWorm.py
1import matplotlib2matplotlib.use('Agg')3import matplotlib.pyplot as plt4import numpy as np5def cal_tempo_and_velocity_by_beat(features, note_locations=None, momentum=0.8):6 tempos = []7 velocities = []8 prev_beat = 09 tempo_saved = 010 num_added = 011 max_velocity = 012 velocity_saved = 013 num_notes = len(features)14 for i in range(num_notes):15 feat = features[i]16 if note_locations:17 cur_note_tempo = feat[0]18 cur_note_vel = feat[1]19 cur_beat = note_locations[i].beat20 else:21 if feat.qpm is None:22 continue23 else:24 cur_note_tempo = feat.qpm25 cur_note_vel = feat.velocity26 cur_beat = feat.note_location.beat27 if cur_beat > prev_beat and num_added > 0:28 tempo = tempo_saved / num_added29 velocity = (velocity_saved / num_added + max_velocity) / 230 if len(tempos)> 0:31 tempo = tempos[-1] * momentum + tempo * (1-momentum)32 velocity = velocities[-1] * momentum + velocity * (1 - momentum)33 tempos.append(tempo)34 velocities.append(velocity)35 tempo_saved = 036 num_added = 037 max_velocity = 038 velocity_saved = 039 tempo_saved += 10 ** cur_note_tempo40 velocity_saved += cur_note_vel41 num_added += 142 max_velocity = max(max_velocity, cur_note_vel)43 prev_beat = cur_beat44 if num_added > 0:45 tempo = tempo_saved / num_added46 tempos.append(tempo)47 velocities.append(max_velocity)48 return tempos, velocities49def plot_performance_worm(features, save_name='images/performance_worm.png'):50 tempos, velocities = cal_tempo_and_velocity_by_beat(features)51 num_beat = len(tempos)52 plt.figure(figsize=(10, 7))53 color = 'green'54 for i in range(num_beat):55 ratio = i / num_beat56 alpha = 0.05+ratio*0.857 plt.plot(tempos[i], velocities[i], markersize=(7 + 7*ratio), marker='o', color=color, alpha=alpha)58 if i > 0:59 plt.plot(tempos[i-1:i+1], velocities[i-1:i+1], color=color, alpha=alpha)60 plt.savefig(save_name)61 plt.close()62def plot_normalized_feature(features_list, save_name='feature_test.png'):63 plt.figure(figsize=(12, 7))64 num_beat = len(features_list[0])65 for features in features_list:66 features = np.asarray(features)67 normalized_features = features / np.mean(features)68 # for i in range(1,num_beat):69 # feat = normalized_features[i]70 plt.plot(range(num_beat), normalized_features)71 plt.savefig(save_name)72 plt.close()73def plot_human_model_features_compare(features_list, save_name='feature_test.png'):74 plt.figure(figsize=(12, 7))75 num_beat = len(features_list[0])76 num_performance = len(features_list)77 for i in range(num_performance-1):78 features = features_list[i]79 features = np.asarray(features)80 normalized_features = features / np.mean(features)81 # for i in range(1,num_beat):82 # feat = normalized_features[i]83 plt.plot(range(num_beat), normalized_features, color='gray')84 model_features = np.asarray(features_list[-1])85 normalized_features = model_features / np.mean(model_features)86 plt.plot(range(num_beat), normalized_features, color='red')87 plt.savefig(save_name)88 plt.close()89def plot_model_features_compare(features_list, num_models=4, save_name='feature_test.png'):90 plt.figure(figsize=(12, 6))91 matplotlib.rcParams.update({'font.size': 20})92 plt.xlabel('Beat Index')93 plt.ylabel('Relative Tempo')94 num_beat = len(features_list[0])95 num_performance = len(features_list)96 code = ('ISGN', 'BL', 'HAN', 'G-HAN')97 for i in range(num_performance-num_models):98 features = features_list[i]99 features = np.asarray(features)100 normalized_features = features / np.mean(features)101 # for i in range(1,num_beat):102 # feat = normalized_features[i]103 if i == 0:104 plt.plot(range(num_beat), normalized_features, color='gray', label='Human')105 else:106 plt.plot(range(num_beat), normalized_features, color='gray')107 for i in range(num_models):108 model_features = np.asarray(features_list[-num_models + i])109 normalized_features = model_features / np.mean(model_features)110 plt.plot(range(num_beat), normalized_features, label=code[i], linewidth=2.0)111 plt.legend()112 plt.savefig(save_name)...
index.js
Source:index.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.createRegExpFeaturePlugin = createRegExpFeaturePlugin;6var _regexpuCore = require("regexpu-core");7var _features = require("./features");8var _util = require("./util");9var _core = require("@babel/core");10var _helperAnnotateAsPure = require("@babel/helper-annotate-as-pure");11function pullFlag(node, flag) {12 node.flags = node.flags.replace(flag, "");13}14const version = "7.14.5".split(".").reduce((v, x) => v * 1e5 + +x, 0);15const versionKey = "@babel/plugin-regexp-features/version";16function createRegExpFeaturePlugin({17 name,18 feature,19 options = {}20}) {21 return {22 name,23 pre() {24 var _file$get;25 const {26 file27 } = this;28 const features = (_file$get = file.get(_features.featuresKey)) != null ? _file$get : 0;29 let newFeatures = (0, _features.enableFeature)(features, _features.FEATURES[feature]);30 const {31 useUnicodeFlag,32 runtime = true33 } = options;34 if (useUnicodeFlag === false) {35 newFeatures = (0, _features.enableFeature)(newFeatures, _features.FEATURES.unicodeFlag);36 }37 if (newFeatures !== features) {38 file.set(_features.featuresKey, newFeatures);39 }40 if (!runtime) {41 file.set(_features.runtimeKey, false);42 }43 if (!file.has(versionKey) || file.get(versionKey) < version) {44 file.set(versionKey, version);45 }46 },47 visitor: {48 RegExpLiteral(path) {49 var _file$get2;50 const {51 node52 } = path;53 const {54 file55 } = this;56 const features = file.get(_features.featuresKey);57 const runtime = (_file$get2 = file.get(_features.runtimeKey)) != null ? _file$get2 : true;58 const regexpuOptions = (0, _util.generateRegexpuOptions)(node, features);59 if (regexpuOptions === null) {60 return;61 }62 const namedCaptureGroups = {};63 if (regexpuOptions.namedGroup) {64 regexpuOptions.onNamedGroup = (name, index) => {65 namedCaptureGroups[name] = index;66 };67 }68 node.pattern = _regexpuCore(node.pattern, node.flags, regexpuOptions);69 if (regexpuOptions.namedGroup && Object.keys(namedCaptureGroups).length > 0 && runtime && !isRegExpTest(path)) {70 const call = _core.types.callExpression(this.addHelper("wrapRegExp"), [node, _core.types.valueToNode(namedCaptureGroups)]);71 (0, _helperAnnotateAsPure.default)(call);72 path.replaceWith(call);73 }74 if ((0, _features.hasFeature)(features, _features.FEATURES.unicodeFlag)) {75 pullFlag(node, "u");76 }77 if ((0, _features.hasFeature)(features, _features.FEATURES.dotAllFlag)) {78 pullFlag(node, "s");79 }80 }81 }82 };83}84function isRegExpTest(path) {85 return path.parentPath.isMemberExpression({86 object: path.node,87 computed: false88 }) && path.parentPath.get("property").isIdentifier({89 name: "test"90 });...
Using AI Code Generation
1import { features } from 'storybook-root-decorator';2import { features } from 'storybook-root-decorator';3import { features } from 'storybook-root-decorator';4import { features } from 'storybook-root-decorator';5import { features } from 'storybook-root-decorator';6import { features } from 'storybook-root-decorator';7import { features } from 'storybook-root-decorator';8import { features } from 'storybook-root-decorator';9import { features } from 'storybook-root-decorator';10import { features } from 'storybook-root-decorator';11import { features } from 'storybook-root-decorator';12import { features } from 'storybook-root-decorator';13import { features } from 'storybook-root-decorator';14import { features } from 'storybook-root-decorator';15import { features } from 'storybook-root-decorator';16import { features } from 'storybook-root-decorator';17import { features } from 'storybook-root-decorator';18import { features } from '
Using AI Code Generation
1import { features } from 'storybook-root-elements';2import { features } from 'storybook-root-elements';3import { features } from 'storybook-root-elements';4import { features } from 'storybook-root-elements';5import { features } from 'storybook-root-elements';6import { features } from 'storybook-root-elements';7import { features } from 'storybook-root-elements';8import { features } from 'storybook-root-elements';9import { features } from 'storybook-root-elements';10import { features } from 'storybook-root-elements';11import { features } from 'storybook-root-elements';12import { features } from 'storybook-root-elements';13import { features } from 'storybook-root-elements';14import { features } from 'storybook-root-elements';15import { features } from 'storybook-root-elements';16import { features } from 'storybook-root-elements';17import { features } from 'storybook-root-elements';18import { features } from 'storybook-root-elements';19import { features } from 'storybook-root-elements';20import { features } from 'storybook-root-elements';
Using AI Code Generation
1import { features } from 'storybook-root-decorator';2import { storiesOf } from '@storybook/react';3import { withInfo } from '@storybook/addon-info';4import Button from './Button';5features('Button', module, storiesOf, [withInfo]);6storiesOf('Button', module)7 .add('with text', () => <Button>Hello Button</Button>)8 .add('with some emoji', () => (9 ));10features('Button', module, storiesOf, [withInfo]);11storiesOf('Button', module)12 .add('with text', () => <Button>Hello Button</Button>)13 .add('with some emoji', () => (14 ));15features('Button', module, storiesOf, [withInfo]);16storiesOf('Button', module)17 .add('with text', () => <Button>Hello Button</Button>)18 .add('with some emoji', () => (19 ));20features('Button', module, storiesOf, [withInfo]);21storiesOf('Button', module)22 .add('with text', () => <Button>Hello Button</Button>)23 .add('with some emoji', () => (24 ));25features('Button', module, storiesOf, [withInfo]);26storiesOf('Button', module)27 .add('with text', () => <Button>Hello Button</Button>)28 .add('with some emoji', () => (
Using AI Code Generation
1import { addDecorator, configure } from "@storybook/react";2import { features } from "storybook-root-decorator";3addDecorator(features);4function loadStories() {5 require("../stories/Welcome.js");6}7configure(loadStories, module);8import React from "react";9import { storiesOf } from "@storybook/react";10storiesOf("Welcome", module).add("to Storybook", () => (11));12import React from "react";13import { storiesOf } from "@storybook/react";14storiesOf("Welcome", module).add("to Storybook", () => (15));16import React from "react";17import { storiesOf } from "@storybook/react";18storiesOf("Welcome", module).add("to Storybook", () => (19));20import React from "react";21import { storiesOf } from "@storybook/react";22storiesOf("Welcome", module).add("to Storybook", () => (23));24import React from "react";25import { storiesOf } from "@storybook/react";26storiesOf("Welcome", module).add("to Storybook", () => (27));28import React from "react";29import { storiesOf } from "@storybook/react";30storiesOf("Welcome", module).add("to Storybook", () => (31));32import React from "react";33import { storiesOf } from "@storybook/react";34storiesOf("Welcome", module).add("to Storybook", () => (35));36import React from "react";37import { storiesOf } from "@storybook/react";38storiesOf("Welcome", module).add("to Storybook", () => (
Using AI Code Generation
1import { features } from 'storybook-root-decorator';2features('MyComponent');3features('MyComponent', { /* options */ });4features('MyComponent', { /* options */ }, { /* context */ });5features('MyComponent', { /* options */ }, { /* context */ }, { /* options */ });6features('MyComponent', { /* options */ }, { /* context */ }, { /* options */ }, { /* options */ });7features('MyComponent', { /* options */ }, { /* context */ }, { /* options */ }, { /* options */ }, { /* options */ });8features('MyComponent', { /* options */ }, { /* context */ }, { /* options */ }, { /* options */ }, { /* options */ }, { /* options */ });9features('MyComponent', { /* options */ }, { /* context */ }, { /* options */ }, { /* options */ }, { /* options */ }, { /* options */ }, { /* options */ });10features('MyComponent', { /* options */ }, { /* context */ }, { /* options */ }, { /* options */ }, { /* options */ }, { /* options */ }, { /* options */ }, { /* options */ });11features('MyComponent'
Using AI Code Generation
1import { features } from 'storybook-root-decorator';2const myFeature = features('myFeature');3myFeature.add('my story', () => <div>My story</div>);4myFeature.add('another story', () => <div>Another story</div>);5myFeature.add('a third story', () => <div>A third story</div>);6import 'storybook-root-decorator/register';7import { features } from 'storybook-root-decorator';8export default features('myFeature');9import { addDecorator } from '@storybook/react';10import features from './features';11addDecorator(features);12const path = require('path');13module.exports = ({ config }) => {14 config.module.rules.push({15 include: path.resolve(__dirname, '../'),16 loader: require.resolve('babel-loader'),17 options: {18 require.resolve('@babel/preset-env'),19 {20 targets: {21 },22 },23 require.resolve('@babel/preset-react'),24 },25 });26 return config;27};28import 'storybook-root-decorator/register';29import { addDecorator } from '@storybook/react';30import features from './features';31addDecorator(features);32const path = require('path');33module.exports = ({ config }) => {34 config.module.rules.push({35 include: path.resolve(__dirname, '../'),36 loader: require.resolve('babel-loader'),37 options: {38 require.resolve('@babel/preset-env'),39 {40 targets: {41 },42 },43 require.resolve('@babel/preset-react'),44 },45 });46 return config;47};
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!