text:
"""Tests for lite.py functionality related to MLIR-TFLite converter."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from absl.testing import parameterized
import numpy as np

from tensorflow.lite.python import lite
from tensorflow.lite.python import lite_constants
from tensorflow.lite.python.interpreter import Interpreter
from tensorflow.python import keras
from tensorflow.python.client import session
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_spec
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import rnn
from tensorflow.python.ops import rnn_cell_impl
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training.tracking import tracking

class TFLiteMLIRTest(test_util.TensorFlowTestCase):
  """Base case for testing MLIR-based TFLite converter."""

  def _evaluateTFLiteModel(self, tflite_model, input_data):
    """Evaluates the model on the `input_data`."""
    interpreter = Interpreter(model_content=tflite_model)
    interpreter.allocate_tensors()

    input_details = interpreter.get_input_details()
    output_details = interpreter.get_output_details()

    for input_tensor, tensor_data in zip(input_details, input_data):
      interpreter.set_tensor(input_tensor['index'], tensor_data.numpy())
    interpreter.invoke()
    return [
        interpreter.get_tensor(details['index']) for details in output_details
    ]

  def _getSimpleVariableModel(self):
    root = tracking.AutoTrackable()
    root.v1 = variables.Variable(3.)
    root.v2 = variables.Variable(2.)
    root.f = def_function.function(lambda x: root.v1 * root.v2 * x)
    return root

class FromSessionTest(TFLiteMLIRTest):

  def testFloat(self):
    with ops.Graph().as_default():
      in_tensor = array_ops.placeholder(
          shape=[1, 16, 16, 3], dtype=dtypes.float32)
      out_tensor = in_tensor + in_tensor
      sess = session.Session()

    # Convert model and ensure model is not None.
    converter = lite.TFLiteConverter.from_session(sess, [in_tensor],
                                                  [out_tensor])
    converter.experimental_enable_mlir_converter = True
    tflite_model = converter.convert()

    # Check values from converted model.
    interpreter = Interpreter(model_content=tflite_model)
    interpreter.allocate_tensors()

    input_details = interpreter.get_input_details()
    self.assertEqual(1, len(input_details))
    self.assertEqual('Placeholder', input_details[0]['name'])
    self.assertEqual(np.float32, input_details[0]['dtype'])
    self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())
    self.assertEqual((0., 0.), input_details[0]['quantization'])

    output_details = interpreter.get_output_details()
    self.assertEqual(1, len(output_details))
    self.assertEqual('add', output_details[0]['name'])
    self.assertEqual(np.float32, output_details[0]['dtype'])
    self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())
    self.assertEqual((0., 0.), output_details[0]['quantization'])

  def testString(self):
    with ops.Graph().as_default():
      in_tensor = array_ops.placeholder(shape=[4], dtype=dtypes.string)
      out_tensor = array_ops.reshape(in_tensor, shape=[2, 2])
      sess = session.Session()

    # Convert model and ensure model is not None.
    converter = lite.TFLiteConverter.from_session(sess, [in_tensor],
                                                  [out_tensor])
    converter.experimental_enable_mlir_converter = True
    tflite_model = converter.convert()

    # Check values from converted model.
    interpreter = Interpreter(model_content=tflite_model)
    interpreter.allocate_tensors()

    input_details = interpreter.get_input_details()
    self.assertEqual(1, len(input_details))
    self.assertEqual('Placeholder', input_details[0]['name'])
    self.assertEqual(np.string_, input_details[0]['dtype'])
    self.assertTrue(([4] == input_details[0]['shape']).all())

    output_details = interpreter.get_output_details()
    self.assertEqual(1, len(output_details))
    self.assertEqual('Reshape', output_details[0]['name'])
    self.assertEqual(np.string_, output_details[0]['dtype'])
    self.assertTrue(([2, 2] == output_details[0]['shape']).all())

  def testQuantization(self):
    with ops.Graph().as_default():
      in_tensor_1 = array_ops.placeholder(
          shape=[1, 16, 16, 3], dtype=dtypes.float32, name='inputA')
      in_tensor_2 = array_ops.placeholder(
          shape=[1, 16, 16, 3], dtype=dtypes.float32, name='inputB')
      out_tensor = array_ops.fake_quant_with_min_max_args(
          in_tensor_1 + in_tensor_2, min=0., max=1., name='output')
      sess = session.Session()

    # Convert model and ensure model is not None.
    converter = lite.TFLiteConverter.from_session(sess,
                                                  [in_tensor_1, in_tensor_2],
                                                  [out_tensor])
    converter.experimental_enable_mlir_converter = True
    converter.inference_type = lite_constants.QUANTIZED_UINT8
    converter.quantized_input_stats = {
        'inputA': (0., 1.),
        'inputB': (0., 1.)
    }  # mean, std_dev
    tflite_model = converter.convert()

    # Check values from converted model.
    interpreter = Interpreter(model_content=tflite_model)
    interpreter.allocate_tensors()

    input_details = interpreter.get_input_details()
    self.assertEqual(2, len(input_details))
    self.assertEqual('inputA', input_details[0]['name'])
    self.assertEqual(np.uint8, input_details[0]['dtype'])
    self.assertTrue(([1, 16, 16, 3] == input_details[0]['shape']).all())
    self.assertEqual((1., 0.),
                     input_details[0]['quantization'])  # scale, zero_point

    self.assertEqual('inputB', input_details[1]['name'])
    self.assertEqual(np.uint8, input_details[1]['dtype'])
    self.assertTrue(([1, 16, 16, 3] == input_details[1]['shape']).all())
    self.assertEqual((1., 0.),
                     input_details[1]['quantization'])  # scale, zero_point

    output_details = interpreter.get_output_details()
    self.assertEqual(1, len(output_details))
    self.assertEqual('output', output_details[0]['name'])
    self.assertEqual(np.uint8, output_details[0]['dtype'])
    self.assertTrue(([1, 16, 16, 3] == output_details[0]['shape']).all())
    self.assertGreater(output_details[0]['quantization'][0], 0)  # scale

  def testScalarValid(self):
    # Construct a graph using a scalar (empty shape) input.
    with ops.Graph().as_default():
      in_tensor = array_ops.placeholder(dtype=dtypes.float32, shape=[])
      out_tensor = in_tensor + in_tensor
      sess = session.Session()

    # Test conversion with the scalar input shape.
    converter = lite.TFLiteConverter.from_session(sess, [in_tensor],
                                                  [out_tensor])
    converter.experimental_enable_mlir_converter = True
    tflite_model = converter.convert()

    # Check values from converted model.
    interpreter = Interpreter(model_content=tflite_model)
    interpreter.allocate_tensors()

    input_details = interpreter.get_input_details()
    self.assertEqual(1, len(input_details))
    self.assertEqual('Placeholder', input_details[0]['name'])
    self.assertEqual(np.float32, input_details[0]['dtype'])
    self.assertEqual(len(input_details[0]['shape']), 0)

    output_details = interpreter.get_output_details()
    self.assertEqual(1, len(output_details))
    self.assertEqual('add', output_details[0]['name'])
    self.assertEqual(np.float32, output_details[0]['dtype'])
    self.assertEqual(len(output_details[0]['shape']), 0)

    # Validate inference using the scalar inputs/outputs.
    test_input = np.array(4.0, dtype=np.float32)
    expected_output = np.array(8.0, dtype=np.float32)
    interpreter.set_tensor(input_details[0]['index'], test_input)
    interpreter.invoke()

    output_data = interpreter.get_tensor(output_details[0]['index'])
    self.assertTrue((expected_output == output_data).all())

  def testPostTrainingQuantize(self):
    self.skipTest('b/124315492')
    np.random.seed(0)
    with ops.Graph().as_default():
      # We need the tensor to have more than 1024 elements for quantize_weights
      # to kick in. Thus, the [33, 33] shape.
      in_tensor_1 = array_ops.placeholder(
          shape=[33, 33], dtype=dtypes.float32, name='inputA')
      in_tensor_2 = constant_op.constant(
          np.random.uniform(low=-10., high=10., size=(33, 33)),
          shape=[33, 33],
          dtype=dtypes.float32,
          name='inputB')
      out_tensor = math_ops.matmul(in_tensor_1, in_tensor_2, name='output')
      sess = session.Session()

    # Convert float model.
    float_converter = lite.TFLiteConverter.from_session(sess, [in_tensor_1],
                                                        [out_tensor])
    float_converter.experimental_enable_mlir_converter = True
    float_tflite = float_converter.convert()

    # Convert quantized weights model.
    quantized_converter = lite.TFLiteConverter.from_session(
        sess, [in_tensor_1], [out_tensor])
    quantized_converter.experimental_enable_mlir_converter = True
    quantized_converter.optimizations = [lite.Optimize.DEFAULT]
    quantized_tflite = quantized_converter.convert()

    # Ensure that the quantized weights tflite model is smaller.
    self.assertLess(len(quantized_tflite), len(float_tflite))

  @test_util.run_in_graph_and_eager_modes
  def testFunctions(self):
    """Tests tf.function in 1.X."""

    @def_function.function
    def plus_placeholder(x, placeholder):
      return x + placeholder

    with ops.Graph().as_default():
      placeholder = array_ops.placeholder(
          dtype=dtypes.float32, shape=[1], name='input')
      variable_node = variables.Variable(1.0, name='variable_node')
      defun_node = plus_placeholder(variable_node, placeholder)
      output_node = math_ops.multiply(defun_node, 2.0, name='output_node')

      # Initialize variables in the model.
      sess = session.Session()
      sess.run(variables.variables_initializer([variable_node]))

    # Convert model and ensure model is not None.
    converter = lite.TFLiteConverter.from_session(sess, [placeholder],
                                                  [output_node])
    converter.experimental_enable_mlir_converter = True
    tflite_model = converter.convert()

    # Check values from converted model.
    interpreter = Interpreter(model_content=tflite_model)
    interpreter.allocate_tensors()

    input_details = interpreter.get_input_details()
    self.assertEqual(1, len(input_details))
    self.assertEqual('input', input_details[0]['name'])
    self.assertEqual(np.float32, input_details[0]['dtype'])
    self.assertTrue(([1] == input_details[0]['shape']).all())
    self.assertEqual((0., 0.), input_details[0]['quantization'])

    output_details = interpreter.get_output_details()
    self.assertEqual(1, len(output_details))
    self.assertEqual('output_node', output_details[0]['name'])
    self.assertEqual(np.float32, output_details[0]['dtype'])
    self.assertTrue(([1] == output_details[0]['shape']).all())
    self.assertEqual((0., 0.), output_details[0]['quantization'])

class FromConcreteFunctionTest(TFLiteMLIRTest):

  @test_util.run_v2_only
  def testFloat(self):
    root = self._getSimpleVariableModel()
    input_data = constant_op.constant(1., shape=[1])
    concrete_func = root.f.get_concrete_function(input_data)

    # Convert model.
    converter = lite.TFLiteConverterV2.from_concrete_functions([concrete_func])
    converter.experimental_enable_mlir_converter = True
    tflite_model = converter.convert()

    # Check values from converted model.
    expected_value = root.f(input_data)
    actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])
    self.assertEqual(expected_value.numpy(), actual_value)

  @test_util.run_v2_only
  def testControlFlow(self):
    input_data = {
        'x': constant_op.constant([1., 2.], shape=[1, 2]),
        'b': constant_op.constant(True)
    }

    weights = variables.Variable([[0.1, 0.2], [0.3, 0.4]], dtype=dtypes.float32)

    def true_fn(x):
      return math_ops.matmul(x, weights)

    def false_fn(x):
      return math_ops.add(x, weights)

    @def_function.function(input_signature=[
        tensor_spec.TensorSpec(shape=[1, 2], dtype=dtypes.float32),
        tensor_spec.TensorSpec(shape=(), dtype=dtypes.bool)
    ])
    def model(x, b):
      return control_flow_ops.cond(
          b, true_fn=lambda: true_fn(x), false_fn=lambda: false_fn(x))

    concrete_func = model.get_concrete_function()

    # Convert model.
    converter = lite.TFLiteConverterV2.from_concrete_functions([concrete_func])
    converter.experimental_enable_mlir_converter = True
    tflite_model = converter.convert()

    # Check values from converted model.
    expected_value = concrete_func(**input_data)
    actual_value = self._evaluateTFLiteModel(
        tflite_model, [input_data['x'], input_data['b']])[0]
    np.testing.assert_almost_equal(expected_value.numpy(), actual_value)

  @test_util.run_v2_only
  def testStaticRnn(self):
    input_data = constant_op.constant(
        np.array(np.random.random_sample((3, 10)), dtype=np.float32))

    cell = rnn_cell_impl.LSTMCell(10)

    @def_function.function(input_signature=[
        tensor_spec.TensorSpec(shape=[3, 10], dtype=dtypes.float32)
    ])
    def model(x):
      seq = array_ops.split(x, 3, 0)
      return rnn.static_rnn(
          cell, seq, dtype=dtypes.float32, sequence_length=[1])

    concrete_func = model.get_concrete_function()

    # Convert model.
    converter = lite.TFLiteConverterV2.from_concrete_functions([concrete_func])
    converter.experimental_enable_mlir_converter = True
    tflite_model = converter.convert()

    # Check values from converted model.
    expected_value = concrete_func(input_data)[0]
    actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])
    for expected, actual in zip(expected_value, actual_value):
      np.testing.assert_almost_equal(expected.numpy(), actual)

  @test_util.run_v2_only
  def testLoop(self):
    input_data = constant_op.constant([1., 2., 3., 4.], shape=[2, 2])

    weights = variables.Variable([[0.1, 0.2], [0.3, 0.4]], dtype=dtypes.float32)

    def condition(x):
      return math_ops.reduce_sum(x) < 100

    def body(x):
      return math_ops.add(x, weights)

    @def_function.function(input_signature=[
        tensor_spec.TensorSpec(shape=[2, 2], dtype=dtypes.float32)
    ])
    def model(x):
      return control_flow_ops.while_loop(condition, body, [x])

    concrete_func = model.get_concrete_function()

    # Convert model.
    converter = lite.TFLiteConverterV2.from_concrete_functions([concrete_func])
    converter.experimental_enable_mlir_converter = True
    tflite_model = converter.convert()

    # Check values from converted model.
    expected_value = concrete_func(input_data)
    actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])[0]
    np.testing.assert_almost_equal(expected_value.numpy(), actual_value)

  @test_util.run_v2_only
  def testDynamicRnn(self):
    input_data = constant_op.constant(
        np.array(np.random.random_sample((3, 10, 10)), dtype=np.float32))

    cell = rnn_cell_impl.LSTMCell(10)

    @def_function.function(input_signature=[
        tensor_spec.TensorSpec(shape=[3, 10, 10], dtype=dtypes.float32)
    ])
    def model(x):
      return rnn.dynamic_rnn(cell, x, dtype=dtypes.float32)

    concrete_func = model.get_concrete_function()

    # Convert model.
    converter = lite.TFLiteConverterV2.from_concrete_functions([concrete_func])
    converter.experimental_enable_mlir_converter = True
    tflite_model = converter.convert()

    # Check values from converted model.
    expected_value = concrete_func(input_data)
    actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])
    for expected, actual in zip(expected_value, actual_value):
      if isinstance(expected, ops.EagerTensor):
        expected = expected.numpy()
      else:
        expected = expected.c.numpy()
      np.testing.assert_almost_equal(expected, actual)

  @test_util.run_v2_only
  def testKerasLSTM(self):
    input_data = constant_op.constant(
        np.array(np.random.random_sample((10, 10, 10)), dtype=np.float32))

    model = keras.models.Sequential(
        [keras.layers.LSTM(units=10, input_shape=(10, 10))])

    run_model = def_function.function(model.__call__)
    concrete_func = run_model.get_concrete_function(
        tensor_spec.TensorSpec((10, 10, 10), dtype=dtypes.float32))

    # Convert model.
    converter = lite.TFLiteConverterV2.from_concrete_functions([concrete_func])
    converter.experimental_enable_mlir_converter = True
    tflite_model = converter.convert()

    # Check values from converted model.
    expected_value = concrete_func(input_data)
    actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])[0]
    np.testing.assert_almost_equal(expected_value, actual_value)

class FromKerasModelTest(TFLiteMLIRTest, parameterized.TestCase):

  @parameterized.named_parameters(('LSTM', keras.layers.LSTM),
                                  ('SimpleRNN', keras.layers.SimpleRNN),
                                  ('GRU', keras.layers.GRU))
  @test_util.run_v2_only
  def testKerasRNN(self, rnn_layer):
    # This test case is similar to `FromConcreteFunctionTest.testKerasLSTM`
    # above, but it's more concise to pass the Keras model directly.
    # This relies on TFLiteConverter to rewrite unknown batch size to 1. The
    # model will fail if resizing the input to non-1 batch size.
    input_data = constant_op.constant(
        np.array(np.random.random_sample((1, 10, 10)), dtype=np.float32))

    model = keras.models.Sequential([rnn_layer(units=10, input_shape=(10, 10))])

    # Convert model.
    converter = lite.TFLiteConverterV2.from_keras_model(model)
    converter.experimental_enable_mlir_converter = True
    tflite_model = converter.convert()
    actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])[0]

    # Check values from converted model.
    expected_value = model.predict(input_data)

    np.testing.assert_almost_equal(expected_value, actual_value, decimal=5)

class TestFlexMode(TFLiteMLIRTest):

  def testSession(self):
    with ops.Graph().as_default():
      in_tensor = array_ops.placeholder(
          shape=[1, 16, 16, 3], dtype=dtypes.float32)
      out_tensor = in_tensor + in_tensor
      sess = session.Session()

    # Convert model and ensure model is not None.
    converter = lite.TFLiteConverter.from_session(sess, [in_tensor],
                                                  [out_tensor])
    converter.experimental_enable_mlir_converter = True
    converter.target_spec.supported_ops = set([lite.OpsSet.SELECT_TF_OPS])
    tflite_model = converter.convert()

    # Ensures the model contains TensorFlow ops.
    # TODO(nupurgarg): Check values once there is a Python delegate interface.
    interpreter = Interpreter(model_content=tflite_model)
    with self.assertRaises(RuntimeError) as error:
      interpreter.allocate_tensors()
    self.assertIn(
        'Regular TensorFlow ops are not supported by this interpreter.',
        str(error.exception))

  @test_util.run_v2_only
  def testConcreteFunc(self):
    input_data = constant_op.constant(1., shape=[1])
    root = tracking.AutoTrackable()
    root.v1 = variables.Variable(3.)
    root.v2 = variables.Variable(2.)
    root.f = def_function.function(lambda x: root.v1 * root.v2 * x)
    concrete_func = root.f.get_concrete_function(input_data)

    # Convert model.
    converter = lite.TFLiteConverterV2.from_concrete_functions([concrete_func])
    converter.experimental_enable_mlir_converter = True
    converter.target_spec.supported_ops = set([lite.OpsSet.SELECT_TF_OPS])
    tflite_model = converter.convert()

    # Ensures the model contains TensorFlow ops.
    # TODO(nupurgarg): Check values once there is a Python delegate interface.
    interpreter = Interpreter(model_content=tflite_model)
    with self.assertRaises(RuntimeError) as error:
      interpreter.allocate_tensors()
    self.assertIn(
        'Regular TensorFlow ops are not supported by this interpreter.',
        str(error.exception))

if __name__ == '__main__':
  test.main()


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Collections.Generic;
using Azure.Core;

namespace Azure.AI.TextAnalytics
{
    internal static class ClientOptionsExtensions
    {
        public static void ConfigureLogging(this ClientOptions clientOptions)
        {
            IList<string> loggedHeaderNames = clientOptions.Diagnostics.LoggedHeaderNames;
            loggedHeaderNames.Add("Operation-Location");
            loggedHeaderNames.Add("x-envoy-upstream-service-time");
            loggedHeaderNames.Add("apim-request-id");
            loggedHeaderNames.Add("Strict-Transport-Security");
            loggedHeaderNames.Add("x-content-type-options");

            clientOptions.Diagnostics.LoggedQueryParameters.Add("jobId");
            clientOptions.Diagnostics.LoggedQueryParameters.Add("$top");
            clientOptions.Diagnostics.LoggedQueryParameters.Add("$skip");
            clientOptions.Diagnostics.LoggedQueryParameters.Add("showStats");
            clientOptions.Diagnostics.LoggedQueryParameters.Add("model-version");
            clientOptions.Diagnostics.LoggedQueryParameters.Add("domain");
            clientOptions.Diagnostics.LoggedQueryParameters.Add("stringIndexType");
            clientOptions.Diagnostics.LoggedQueryParameters.Add("piiCategories");
            clientOptions.Diagnostics.LoggedQueryParameters.Add("opinionMining");

            clientOptions.Diagnostics.LoggedQueryParameters.Add("top");
            clientOptions.Diagnostics.LoggedQueryParameters.Add("skip");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
continue = {
	images = {
		background = "assets/images/load_background.png",
		selector = "assets/images/load_selector.png",
	},
}


text:
@interface MessagesViewController () <IMCollectionViewControllerDelegate>

@property(nonatomic, strong) IMImojiSession* session;

@end

@implementation MessagesViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    if (!self.session) {
        [[ImojiSDK sharedInstance] setClientId:[[NSUUID alloc] initWithUUIDString:@"748cddd4-460d-420a-bd42-fcba7f6c031b"]
                                      apiToken:@"U2FsdGVkX1/yhkvIVfvMcPCALxJ1VHzTt8FPZdp1vj7GIb+fsdzOjyafu9MZRveo7ebjx1+SKdLUvz8aM6woAw=="];
        self.session = [IMImojiSession imojiSession];
    }

    [self loadStickerView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Conversation Handling

-(void)didBecomeActiveWithConversation:(MSConversation *)conversation {

}

-(void)willResignActiveWithConversation:(MSConversation *)conversation {
    // Called when the extension is about to move from the active to inactive state.
    // This will happen when the user dissmises the extension, changes to a different
    // conversation or quits Messages.

    // Use this method to release shared resources, save user data, invalidate timers,
    // and store enough state information to restore your extension to its current state
    // in case it is terminated later.
}

-(void)didReceiveMessage:(MSMessage *)message conversation:(MSConversation *)conversation {
    // Called when a message arrives that was generated by another instance of this
    // extension on a remote device.

    // Use this method to trigger UI updates in response to the message.
}

-(void)didStartSendingMessage:(MSMessage *)message conversation:(MSConversation *)conversation {
    // Called when the user taps the send button.
}

-(void)didCancelSendingMessage:(MSMessage *)message conversation:(MSConversation *)conversation {
    // Called when the user deletes the message without sending it.

    // Use this to clean up state related to the deleted message.
}

-(void)willTransitionToPresentationStyle:(MSMessagesAppPresentationStyle)presentationStyle {
    // Called before the extension transitions to a new presentation style.

    // Use this method to prepare for the change in presentation style.
}

-(void)didTransitionToPresentationStyle:(MSMessagesAppPresentationStyle)presentationStyle {
    // Called after the extension transitions to a new presentation style.

    // Use this method to finalize any behaviors associated with the change in presentation style.
}

- (void)loadStickerView {
    for (UIViewController *child in self.childViewControllers) {
        [child willMoveToParentViewController:nil];
        [child.view removeFromSuperview];
        [child removeFromParentViewController];
    }

    IMCollectionViewController* stickerController = [[IMCollectionViewController alloc] initWithSession:self.session];
    stickerController.collectionViewControllerDelegate = self;

    // shows the sticker cells as MSStickerView's, allowing users to drag and drop them onto their conversations
    stickerController.collectionView.loadUsingStickerViews = YES;

    // load larger, non-bordered stickers
    stickerController.collectionView.renderingOptions = [IMImojiObjectRenderingOptions optionsWithRenderSize:IMImojiObjectRenderSize320 borderStyle:IMImojiObjectBorderStyleNone];

    [self addChildViewController:stickerController];

    [self.view addSubview:stickerController.view];
    stickerController.view.frame = self.view.bounds;

    [stickerController.view.leftAnchor constraintEqualToAnchor:self.view.leftAnchor].active = YES;
    [stickerController.view.rightAnchor constraintEqualToAnchor:self.view.rightAnchor].active = YES;
    [stickerController.view.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
    [stickerController.view.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor].active = YES;

    stickerController.searchView.userInteractionEnabled = YES;

    [stickerController didMoveToParentViewController:self];

    [stickerController.collectionView loadImojiCategoriesWithOptions:[IMCategoryFetchOptions optionsWithClassification:IMImojiSessionCategoryClassificationTrending]];
}

- (void)userDidSelectImoji:(IMImojiObject *)imoji fromCollectionView:(IMCollectionView *)collectionView {
    if (self.activeConversation) {
        IMImojiObjectRenderingOptions *renderingOptions;
        if (imoji.supportsAnimation) {
            renderingOptions = [IMImojiObjectRenderingOptions optionsWithAnimationAndRenderSize:IMImojiObjectRenderSize320];
        } else {
            renderingOptions = [IMImojiObjectRenderingOptions optionsWithRenderSize:IMImojiObjectRenderSize320 borderStyle:IMImojiObjectBorderStyleSticker];
        }

        [self.session renderImojiAsMSSticker:imoji
                                     options:renderingOptions
                                    callback:^(NSObject * _Nullable msStickerObject, NSError * _Nullable error) {
                                        if (error) {
                                            NSLog(@":( looks like we got an error %@", error);
                                        } else {
                                            [self.activeConversation insertSticker:(MSSticker*) msStickerObject
                                                                 completionHandler:^(NSError * _Nullable insertError) {
                                                                     if (insertError) {
                                                                         NSLog(@":( looks like we got another terrible error %@", insertError);
                                                                     }
                                                                 }];
                                        }
                                    }];
    }
}

@end


text:
#pragma checksum "..\..\..\Windows\FactionsGameLobbyPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "C0CEADB54D66D59496CE0B49BB0055DD"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18408
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms.Integration;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;

namespace LegendaryClient.Windows {

    /// <summary>
    /// FactionsGameLobbyPage
    /// </summary>
    public partial class FactionsGameLobbyPage : System.Windows.Controls.Page, System.Windows.Markup.IComponentConnector {

        #line 57 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label GameName;

        #line default
        #line hidden

        #line 59 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Button QuitGameButton;

        #line default
        #line hidden

        #line 62 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label LeftTeamLabel;

        #line default
        #line hidden

        #line 64 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.ListView BlueTeamListView;

        #line default
        #line hidden

        #line 75 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label RightTeamLabel;

        #line default
        #line hidden

        #line 77 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.ListView PurpleTeamListView;

        #line default
        #line hidden

        #line 90 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.ListView WhitelistListView;

        #line default
        #line hidden

        #line 109 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.ListView InviteListView;

        #line default
        #line hidden

        #line 122 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Button SwitchTeamsButton;

        #line default
        #line hidden

        #line 124 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Button StartGameButton;

        #line default
        #line hidden

        #line 127 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.RichTextBox ChatText;

        #line default
        #line hidden

        #line 136 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.TextBox ChatTextBox;

        #line default
        #line hidden

        #line 138 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Button ChatButton;

        #line default
        #line hidden

        #line 144 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.ListView SpectatorListView;

        #line default
        #line hidden

        #line 157 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label MapLabel;

        #line default
        #line hidden

        #line 160 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label ModeLabel;

        #line default
        #line hidden

        #line 163 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label TypeLabel;

        #line default
        #line hidden

        #line 166 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
        internal System.Windows.Controls.Label SizeLabel;

        #line default
        #line hidden

        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Uri resourceLocater = new System.Uri("/LegendaryClient;component/windows/factionsgamelobbypage.xaml", System.UriKind.Relative);

            #line 1 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
            System.Windows.Application.LoadComponent(this, resourceLocater);

            #line default
            #line hidden
        }

        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
        void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
            switch (connectionId)
            {
            case 1:
            this.GameName = ((System.Windows.Controls.Label)(target));
            return;
            case 2:
            this.QuitGameButton = ((System.Windows.Controls.Button)(target));

            #line 60 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
            this.QuitGameButton.Click += new System.Windows.RoutedEventHandler(this.QuitGameButton_Click);

            #line default
            #line hidden
            return;
            case 3:
            this.LeftTeamLabel = ((System.Windows.Controls.Label)(target));
            return;
            case 4:
            this.BlueTeamListView = ((System.Windows.Controls.ListView)(target));
            return;
            case 5:
            this.RightTeamLabel = ((System.Windows.Controls.Label)(target));
            return;
            case 6:
            this.PurpleTeamListView = ((System.Windows.Controls.ListView)(target));
            return;
            case 7:
            this.WhitelistListView = ((System.Windows.Controls.ListView)(target));
            return;
            case 8:
            this.InviteListView = ((System.Windows.Controls.ListView)(target));
            return;
            case 9:

            #line 120 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
            ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Invite_Click);

            #line default
            #line hidden
            return;
            case 10:
            this.SwitchTeamsButton = ((System.Windows.Controls.Button)(target));

            #line 123 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
            this.SwitchTeamsButton.Click += new System.Windows.RoutedEventHandler(this.SwitchTeamsButton_Click);

            #line default
            #line hidden
            return;
            case 11:
            this.StartGameButton = ((System.Windows.Controls.Button)(target));

            #line 125 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
            this.StartGameButton.Click += new System.Windows.RoutedEventHandler(this.StartGameButton_Click);

            #line default
            #line hidden
            return;
            case 12:
            this.ChatText = ((System.Windows.Controls.RichTextBox)(target));
            return;
            case 13:
            this.ChatTextBox = ((System.Windows.Controls.TextBox)(target));
            return;
            case 14:
            this.ChatButton = ((System.Windows.Controls.Button)(target));

            #line 140 "..\..\..\Windows\FactionsGameLobbyPage.xaml"
            this.ChatButton.Click += new System.Windows.RoutedEventHandler(this.ChatButton_Click);

            #line default
            #line hidden
            return;
            case 15:
            this.SpectatorListView = ((System.Windows.Controls.ListView)(target));
            return;
            case 16:
            this.MapLabel = ((System.Windows.Controls.Label)(target));
            return;
            case 17:
            this.ModeLabel = ((System.Windows.Controls.Label)(target));
            return;
            case 18:
            this.TypeLabel = ((System.Windows.Controls.Label)(target));
            return;
            case 19:
            this.SizeLabel = ((System.Windows.Controls.Label)(target));
            return;
            }
            this._contentLoaded = true;
        }
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.07.27 at 08:11:57 PM EEST
//

package eu.datex2.schema._1_0._1_0;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 * The status of traffic conditions on a specific section or at a specific point on the road network.
 *
 *
Java class for TrafficStatusValue complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="TrafficStatusValue">
 *   <complexContent>
 *     <extension base="{http://datex2.eu/schema/1_0/1_0}BasicDataValue">
 *       <sequence>
 *         <element name="trafficStatus" type="{http://datex2.eu/schema/1_0/1_0}TrafficStatusEnum" minOccurs="0"/>
 *         <element name="trafficTrendType" type="{http://datex2.eu/schema/1_0/1_0}TrafficTrendTypeEnum" minOccurs="0"/>
 *         <element name="trafficStatusValueExtension" type="{http://datex2.eu/schema/1_0/1_0}ExtensionType" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TrafficStatusValue", propOrder = {
    "trafficStatus",
    "trafficTrendType",
    "trafficStatusValueExtension"
})
public class TrafficStatusValue
    extends BasicDataValue
{

    protected TrafficStatusEnum trafficStatus;
    protected TrafficTrendTypeEnum trafficTrendType;
    protected ExtensionType trafficStatusValueExtension;

    /**
     * Gets the value of the trafficStatus property.
     *
     * @return
     *     possible object is
     *     {@link TrafficStatusEnum }
     *
     */
    public TrafficStatusEnum getTrafficStatus() {
        return trafficStatus;
    }

    /**
     * Sets the value of the trafficStatus property.
     *
     * @param value
     *     allowed object is
     *     {@link TrafficStatusEnum }
     *
     */
    public void setTrafficStatus(TrafficStatusEnum value) {
        this.trafficStatus = value;
    }

    /**
     * Gets the value of the trafficTrendType property.
     *
     * @return
     *     possible object is
     *     {@link TrafficTrendTypeEnum }
     *
     */
    public TrafficTrendTypeEnum getTrafficTrendType() {
        return trafficTrendType;
    }

    /**
     * Sets the value of the trafficTrendType property.
     *
     * @param value
     *     allowed object is
     *     {@link TrafficTrendTypeEnum }
     *
     */
    public void setTrafficTrendType(TrafficTrendTypeEnum value) {
        this.trafficTrendType = value;
    }

    /**
     * Gets the value of the trafficStatusValueExtension property.
     *
     * @return
     *     possible object is
     *     {@link ExtensionType }
     *
     */
    public ExtensionType getTrafficStatusValueExtension() {
        return trafficStatusValueExtension;
    }

    /**
     * Sets the value of the trafficStatusValueExtension property.
     *
     * @param value
     *     allowed object is
     *     {@link ExtensionType }
     *
     */
    public void setTrafficStatusValueExtension(ExtensionType value) {
        this.trafficStatusValueExtension = value;
    }

}


text:
set auto_increment_increment=1;

source data.config.sql;
source data.button.sql;
source data.game.sql;
source data.player.sql;
source data.stats.sql;
source data.forum.sql;


text:
package ru.radiant.anormacro.sql

import anorm._
import ru.radiant.anormacro.ConnSource

//   utils
trait Selector {

  //
  def selectOn[A](sql: String, parser: RowParser[A],
                  params: (scala.Any, anorm.ParameterValue[_])*) (implicit cs: ConnSource) : List[A]
  = cs.withConnection { implicit c =>
      SQL(sql).on(params :_*).as(parser *)
  }

  def select[A](sql: String, parser: RowParser[A],
                params: anorm.ParameterValue[_]*) (implicit cs: ConnSource) : List[A]
  = cs.withConnection { implicit c =>
      SQL(sql).onParams(params :_*).as(parser *)
  }

  def selectOne[A](sql: String, parser: RowParser[A],
                   params: anorm.ParameterValue[_]*) (implicit cs: ConnSource) : Option[A]
  = cs.withConnection { implicit c =>
      SQL(sql).onParams(params :_*).as(parser.singleOpt)
  }

  /*
    JDBC (so am anorm) can't use PredefinedStatement for list of values of the one parameter.
    For example, can't just write: WHERE blabla IN ({list})
    so we have to create 'formal'  parameter list, like: WHERE blabla IN (listValue0, listValue1, .., listValueN)
  */

  //  def valuesList(prefix: String, values: Any*): (String, Seq[(String, anorm.ParameterValue[_])]) = {
  //    val paramsList = for ( i <- 0 until values.size ) yield (prefix + i)
  //    val where = "{"+paramsList.mkString("},{")+"}"
  //    val anormValues  = values.map(toParameterValue(_))
  //    val valuesMap = paramsList.zip(anormValues)
  //
  //    (where, valuesMap)
  //  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
CiaoJava
</TITLE>

<META NAME="keywords" CONTENT="CiaoJava package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

CiaoJava

Classes

PLAtom

PLConnection

PLFloat

PLGoal

PLInteger

PLJavaServer

PLList

PLServerSocket

PLString

PLStructure

PLTerm

PLVariable

Exceptions

PLException

PLGoalException


text:
An IBM WebSphere Application Server Network Deployment deployment manager image can be built by extending the Network Deployment install image.

The Dockerfile takes the values for the following variables at build time:
* CELL_NAME (optional, default is 'DefaultCell01') - cell name
* NODE_NAME (optional, default is 'DefaultNode01') - node name
* PROFILE_NAME (optional, default is 'Dmgr01') - profile name
* HOST_NAME (optional, default is 'dmgr') - host name

The Dockerfile takes the following actions:

1. Uses the `websphere-traditional:nd-install` install image as a base image
2. Creates a deployment manager profile
3. Exposes the required ports
4. Copies the startup script to the image
5. When the container is started the deployment manager is started

## Building the IBM WebSphere Application Server Network Deployment traditional deployment manager image

1. Clone this repository
3. Build the `websphere-traditional:nd-install` install image following the [install build instructions](../install/README.md), if not built already
3. Move to the directory `network-deployment/dmgr`
4. Build the deployment manager image by using:

    ```bash
    docker build -t websphere-traditional:dmgr .
    ```

## Running the IBM WebSphere Application Server Network Deployment traditional deployment manager image

1. Create a docker network for the Network Deployment cell topology by using:

   ```bash
   docker network create <network-name>
   ```
   This command creates a user defined bridge network, to create an overlay network, see [Get started with multi-host networking docker documentation](https://docs.docker.com/engine/userguide/networking/get-started-overlay/).

   Example:

   ```bash
   docker network create cell-network
   ```

2. Run the deployment manager image by using:

   ```bash
   docker run --name <container-name> -h <container-name> --net=<network-name> \
    -p 9060:9060 -d websphere-traditional:dmgr
   ```

   Example:

   ```bash
   docker run --name dmgr -h dmgr --net=cell-network  -p 9060:9060 -d \
    websphere-traditional:dmgr
   ```


text:
/*
 * RecursivePropagate.cpp
 *
 *  Created on: Dec 11, 2014
 *      Author: Philipp
 */

#include "intervals/RecursivePropagate.h"
#define USEQUEUE

#include "intervals/DownwardPropagator.h"
#include "intervals/SetParents.h"
#include "intervals/TermList.h"
#include "intervals/UpwardPropagator.h"

//#define RecPropDEBUG

namespace alica
{
	namespace reasoner
	{
		namespace intervalpropagation
		{

			RecursivePropagate::RecursivePropagate()
			{
				changed = make_shared<TermList>();

				dp = make_shared<DownwardPropagator>();
				dp->changed = this->changed;
				up = make_shared<UpwardPropagator>();
				up->changed = this->changed;
				sp = make_shared<SetParents>();
			}

			RecursivePropagate::~RecursivePropagate()
			{
				// TODO Auto-generated destructor stub
			}

			bool RecursivePropagate::propagate(shared_ptr<Term> term)
			{
				//for(int i=0; i<2; i++) {
				this->changed->clear();
				term->accept(shared_from_this());
#ifdef RecPropDEBUG
				cout << "Queued Terms: " << endl;
				shared_ptr<Term> asd = this->changed->first;
				while (asd != nullptr)
				{
					cout << asd->toString() << endl;
					asd = asd->next;
				}
				cout << "------------------------------------" << endl;
#endif
				/*
				 foreach(Term q in this->changed) {
				 q->accept(this->sp);
				 }
				 while(this->changed.Count > 0) {
				 Term cur = this->changed->dequeue();
				 cur->accept(this->dp);
				 cur->accept(this->up);
				 }*/

				shared_ptr<Term> cur = this->changed->first;
				while (cur != nullptr)
				{
					cur->accept(this->sp);
					cur = cur->next;
				}

				cur = this->changed->dequeue();
				while (cur != nullptr)
				{
					cur->accept(this->dp);
					cur->accept(this->up);
					cur = this->changed->dequeue();
				}

				//}
				/*cur = this->changed->first;
				 while(cur!=null) {
				 cur->accept(this->dp);
				 //Term next = cur->next;

				 if(cur->accept(this->up)) {
				 /*Term prev = cur.Prev;
				 this->changed.MoveToEnd(cur);
				 if (prev == nullptr) cur = this->changed->first;
				 else cur = prev->next;*/
				//cur = cur->next;
				//	}
				//	cur = cur->next;
				//}
				//*/
			}

			void RecursivePropagate::addToQueue(shared_ptr<Term> t)
			{
				if (!this->changed->contains(t))
					this->changed->enqueue(t);
			}

			int RecursivePropagate::visit(shared_ptr<Abs> abs)
			{
				addToQueue(abs);
				abs->arg->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<And> and_)
			{
				addToQueue(and_);
				and_->left->accept(shared_from_this());
				and_->right->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Atan2> atan2)
			{
				addToQueue(atan2);
				atan2->left->accept(shared_from_this());
				atan2->right->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Constant> constant)
			{
				//	return false;
			}

			int RecursivePropagate::visit(shared_ptr<ConstPower> intPower)
			{
				addToQueue(intPower);
				intPower->base->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<ConstraintUtility> cu)
			{
				addToQueue(cu);
				cu->constraint->accept(shared_from_this());
				cu->utility->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Cos> cos)
			{
				addToQueue(cos);
				cos->arg->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Exp> exp)
			{
				addToQueue(exp);
				exp->arg->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Gp> gp)
			{
				throw "Not implemented yet";
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<LinSigmoid> sigmoid)
			{
				addToQueue(sigmoid);
				sigmoid->arg->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Log> log)
			{
				addToQueue(log);
				log->arg->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<LTConstraint> constraint)
			{
				addToQueue(constraint);
				constraint->left->accept(shared_from_this());
				constraint->right->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<LTEConstraint> constraint)
			{
				addToQueue(constraint);
				constraint->left->accept(shared_from_this());
				constraint->right->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Max> max)
			{
				addToQueue(max);
				max->left->accept(shared_from_this());
				max->right->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Min> min)
			{
				addToQueue(min);
				min->left->accept(shared_from_this());
				min->right->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Or> or_)
			{
				addToQueue(or_);
				or_->left->accept(shared_from_this());
				or_->right->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Product> product)
			{
				addToQueue(product);
				product->left->accept(shared_from_this());
				product->right->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Reification> reif)
			{
				addToQueue(reif);
				reif->condition->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Sigmoid> sigmoid)
			{
				addToQueue(sigmoid);
				sigmoid->arg->accept(shared_from_this());
				sigmoid->mid->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Sin> sin)
			{
				addToQueue(sin);
				sin->arg->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Sum> sum)
			{
				addToQueue(sum);
				for (shared_ptr<Term> t : sum->terms)
				{
					t->accept(shared_from_this());
				}
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<TermPower> power)
			{
				addToQueue(power);
				power->base->accept(shared_from_this());
				power->exponent->accept(shared_from_this());
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Variable> var)
			{
				addToQueue(var);
				//return true;
			}

			int RecursivePropagate::visit(shared_ptr<Zero> zero)
			{
				//	return false;
			}

		} /* namespace intervalpropagation */
	} /* namespace reasoner */
} /* namespace alica */


text:
import * as foo from "foo";
var foo;


text:
var gulp = require('gulp');
var gutil = require('gulp-util');
var webpack = require('webpack');

var webpackConfig = require('./webpack.config.js');
var webpackBuildConfig = require('./webpack.build.config.js');

gulp.task('webpack_dev', function(callback) {

  webpack(webpackConfig, function(err, stats) {
    if (err) throw new gutil.PluginError('webpack', err);
    gutil.log('[webpack]', stats.toString({}));
    callback();
  });
});

gulp.task('webpack', function(callback) {

  webpack(webpackBuildConfig, function(err, stats) {
    if (err) throw new gutil.PluginError('webpack', err);
    gutil.log('[webpack]', stats.toString({}));
    callback();
  });
});

gulp.task('build', ['webpack'], function() {
  return gulp.src('./index.js')
  	.pipe(gulp.dest('build'))
  	.on('end', function() {
  		process.exit(1);
  	})
  	.on('error', function() {
  		process.exit(1);
  	});
});

// 本地开发
gulp.task('default', ['webpack_dev']);
// 发布
gulp.task('pub', ['build']);


text:
<!DOCTYPE html>

        <title>Testpage for Typesetting Code Plugins for tinyMCE</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Example 1

        <textarea></textarea>


text:
/* eslint max-len: 0 */

import isNumber from "lodash/isNumber";
import * as t from "babel-types";
import * as n from "../node";

export function UnaryExpression(node: Object) {
  if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof") {
    this.word(node.operator);
    this.space();
  } else {
    this.token(node.operator);
  }

  this.print(node.argument, node);
}

export function DoExpression(node: Object) {
  this.word("do");
  this.space();
  this.print(node.body, node);
}

export function ParenthesizedExpression(node: Object) {
  this.token("(");
  this.print(node.expression, node);
  this.token(")");
}

export function UpdateExpression(node: Object) {
  if (node.prefix) {
    this.token(node.operator);
    this.print(node.argument, node);
  } else {
    this.print(node.argument, node);
    this.token(node.operator);
  }
}

export function ConditionalExpression(node: Object) {
  this.print(node.test, node);
  this.space();
  this.token("?");
  this.space();
  this.print(node.consequent, node);
  this.space();
  this.token(":");
  this.space();
  this.print(node.alternate, node);
}

export function NewExpression(node: Object, parent: Object) {
  this.word("new");
  this.space();
  this.print(node.callee, node);
  if (node.arguments.length === 0 && this.format.minified &&
      !t.isCallExpression(parent, { callee: node }) &&
      !t.isMemberExpression(parent) &&
      !t.isNewExpression(parent)) return;

  this.token("(");
  this.printList(node.arguments, node);
  this.token(")");
}

export function SequenceExpression(node: Object) {
  this.printList(node.expressions, node);
}

export function ThisExpression() {
  this.word("this");
}

export function Super() {
  this.word("super");
}

export function Decorator(node: Object) {
  this.token("@");
  this.print(node.expression, node);
  this.newline();
}

function commaSeparatorNewline() {
  this.token(",");
  this.newline();

  if (!this.endsWith("\n")) this.space();
}

export function CallExpression(node: Object) {
  this.print(node.callee, node);

  this.token("(");

  let isPrettyCall = node._prettyCall;

  let separator;
  if (isPrettyCall) {
    separator = commaSeparatorNewline;
    this.newline();
    this.indent();
  }

  this.printList(node.arguments, node, { separator });

  if (isPrettyCall) {
    this.newline();
    this.dedent();
  }

  this.token(")");
}

export function Import() {
  this.word("import");
}

function buildYieldAwait(keyword: string) {
  return function (node: Object) {
    this.word(keyword);

    if (node.delegate) {
      this.token("*");
    }

    if (node.argument) {
      this.space();
      let terminatorState = this.startTerminatorless();
      this.print(node.argument, node);
      this.endTerminatorless(terminatorState);
    }
  };
}

export let YieldExpression = buildYieldAwait("yield");
export let AwaitExpression = buildYieldAwait("await");

export function EmptyStatement() {
  this.semicolon(true /* force */);
}

export function ExpressionStatement(node: Object) {
  this.print(node.expression, node);
  this.semicolon();
}

export function AssignmentPattern(node: Object) {
  this.print(node.left, node);
  if (node.left.optional) this.token("?");
  this.print(node.left.typeAnnotation, node);
  this.space();
  this.token("=");
  this.space();
  this.print(node.right, node);
}

export function AssignmentExpression(node: Object, parent: Object) {
  // Somewhere inside a for statement `init` node but doesn't usually
  // needs a paren except for `in` expressions: `for (a in b ? a : b;;)`
  let parens = this.inForStatementInitCounter && node.operator === "in" &&
               !n.needsParens(node, parent);

  if (parens) {
    this.token("(");
  }

  this.print(node.left, node);

  this.space();
  if (node.operator === "in" || node.operator === "instanceof") {
    this.word(node.operator);
  } else {
    this.token(node.operator);
  }
  this.space();

  this.print(node.right, node);

  if (parens) {
    this.token(")");
  }
}

export function BindExpression(node: Object) {
  this.print(node.object, node);
  this.token("::");
  this.print(node.callee, node);
}

export {
  AssignmentExpression as BinaryExpression,
  AssignmentExpression as LogicalExpression
};

export function MemberExpression(node: Object) {
  this.print(node.object, node);

  if (!node.computed && t.isMemberExpression(node.property)) {
    throw new TypeError("Got a MemberExpression for MemberExpression property");
  }

  let computed = node.computed;
  if (t.isLiteral(node.property) && isNumber(node.property.value)) {
    computed = true;
  }

  if (computed) {
    this.token("[");
    this.print(node.property, node);
    this.token("]");
  } else {
    this.token(".");
    this.print(node.property, node);
  }
}

export function MetaProperty(node: Object) {
  this.print(node.meta, node);
  this.token(".");
  this.print(node.property, node);
}


text:
package org.elasticsearch.ingest.common;

public class LowercaseProcessorFactoryTests extends AbstractStringProcessorFactoryTestCase {
    @Override
    protected AbstractStringProcessor.Factory newFactory() {
        return new LowercaseProcessor.Factory();
    }
}


text:
require 'spec_helper'

describe FeedlyApi::Client do
  let(:auth_token) { ENV['FEEDLY_TOKEN']   || 'GREATE_AUTH_TOKEN' }
  let(:user_id)    { ENV['FEEDLY_USER_ID'] || '00000000-000-NOT-VALID-a29b6679bb3c' }
  let(:client)     { FeedlyApi::Client.new auth_token }

  describe '#new' do
    before :each do
      FeedlyApi.stub(:get).and_return(File.read(File.join('spec', 'fixtures', 'profile.json')))
    end

    it 'creates Client object with given token' do
      client = FeedlyApi::Client.new auth_token
      expect(client.auth_token).to eq auth_token
    end

    it 'saves user_id' do
      expect(client.user_id).to eq user_id
    end
  end

  describe '#get_user_profile' do
    # rewrite for more accurancy
    it 'returns user info' do
      FeedlyApi.stub(:get).and_return(File.read(File.join('spec', 'fixtures', 'profile.json')))
      expect(client.get_user_profile[:client]).to eq 'feedly'
    end
  end

  describe '#get_feed_info' do
    it 'retrievs basic feed info' do
      FeedlyApi.stub(:get).and_return(File.read(File.join('spec', 'fixtures', 'feed_info.json')))
      feed_info = client.get_feed_info('feed/https://www.eff.org/rss/updates.xml')
      expect(feed_info[:website]).to eq 'https://www.eff.org/rss/updates.xml'
    end
  end

  describe '#get_subscriptions' do
    it 'retrievs user subscriptions' do
      FeedlyApi.stub(:get).and_return(File.read(File.join('spec', 'fixtures', 'subscriptions.json')))
      expect(client.get_subscriptions.size).to eq 3
    end
  end

  describe '#get_feed_contents' do
    it 'retrievs feed contents' do
      FeedlyApi.stub(:get).and_return(File.read(File.join('spec', 'fixtures', 'feed_contents_20.json')))
      feed_contents = client.get_feed_contents('feed/https://www.eff.org/rss/updates.xml')
      expect(feed_contents[:items].size).to eq 20
    end

    it 'retrievs custom number of feed items' do
      FeedlyApi.stub(:get).and_return(File.read(File.join('spec', 'fixtures', 'feed_contents_10.json')))
      feed_contents = client.get_feed_contents('feed/https://www.eff.org/rss/updates.xml', {count: 10})
      expect(feed_contents[:items].size).to eq 10
    end

    it 'returns feed items in custom order'

    it 'returns unred only feed items'
  end

  describe '#get_tag_contents' do
    it 'retrievs content for specific tag' do
      FeedlyApi.stub(:get).and_return(File.read(File.join('spec', 'fixtures', 'tagged.json')))
      feed_contents = client.get_tag_contents('global.saved')
      expect(feed_contents[:items].size).to eq 1
    end

    # Update fixture for more items with tags
    # it 'retrievs custom number of feed items for specific tag' do
    #   feed_contents = client.get_tag_contents('global.saved', {count: 10})
    #   expect(feed_contents[:items].size).to eq 10
    # end
  end

  describe '#get_category_contents' do
    it 'retrievs content for custom category_id' do
      FeedlyApi.stub(:get).and_return(File.read(File.join('spec', 'fixtures', 'uncategoriezed.json')))
      feed_contents = client.get_category_contents('global.uncategorized')
      expect(feed_contents[:items].size).to eq 16
    end

    it 'retrievs custom number of feed items for specific category_id' do
      FeedlyApi.stub(:get).and_return(File.read(File.join('spec', 'fixtures', 'uncategoriezed_10.json')))
      feed_contents = client.get_category_contents('global.uncategorized', {count: 10})
      expect(feed_contents[:items].size).to eq 10
    end
  end

  describe '#get_markers' do
    it 'returns unred counts for all feeds' do
      FeedlyApi.stub(:get).and_return(File.read(File.join('spec', 'fixtures', 'markers.json')))
      expect(client.get_markers[:unreadcounts].last[:count]).to eq 16
    end
  end
end


text:
package org.trustedanalytics.user.common;

import org.apache.commons.lang.StringUtils;

public class UserPasswordValidator implements PasswordValidator {

    private static int DEFAULT_MIN_PASSWORD_LENGTH = 6;

    public UserPasswordValidator() {
    }

    public UserPasswordValidator(int minPasswordLength) {
        this.DEFAULT_MIN_PASSWORD_LENGTH = minPasswordLength;
    }

    @Override
    public void validate(String password) {

        if(StringUtils.isBlank(password)) {
            throw new EmptyPasswordException("Password cannot be empty.");
        }

        if(password.length() < this.DEFAULT_MIN_PASSWORD_LENGTH) {
            throw new TooShortPasswordException("Password should consist of minimum " +
                    this.DEFAULT_MIN_PASSWORD_LENGTH + " characters.");
        }
    }

}


text:
<?php
namespace Asar;

use \Asar\Template\TemplateInterface;

/**
 */
class TemplateSimpleRenderer {

  function renderTemplate(
    $template, $vars,
    $layout = null
  ) {
    if (!$template instanceof TemplateInterface) {
      return null;
    }
    $output = $template->render($vars);
    if (
      !$template->getConfig('no_layout') &&
      $layout instanceof TemplateInterface
    ) {
      $output = $layout->render($this->extractLayoutVars($output, $template));
    }
    return $output;
  }

  private function extractLayoutVars($content, $tpl) {
    $others = $tpl->getLayoutVars();
    if (is_array($others)) {
      return array_merge(array('content' => $content), $others);
    }
    return array('content' => $content);
  }

}


text:
package xyz.openmodloader.event.impl;

import xyz.openmodloader.OpenModLoader;
import xyz.openmodloader.event.Event;

public class InputEvent extends Event {

    /**
     * An event fired whenever the mouse is pressed.
     */
    public static class Mouse extends InputEvent {

        /**
         * The mouse button that was pressed.
         *
         * @see #getButton()
         */
        private final int button;

        public Mouse(int button) {
            this.button = button;
        }

        public int getButton() {
            return button;
        }

        public static boolean handle(int button) {
            InputEvent.Mouse event = new InputEvent.Mouse(button);
            return OpenModLoader.getEventBus().post(event);
        }
    }

    /**
     * An event fired when a key is pressed.
     */
    public static class Keyboard extends InputEvent {

        /**
         * The character corresponding to the key pressed.
         *
         * @see #getCharacter()
         */
        private final char character;

        /**
         * The code for the key pressed.
         *
         * @see #getKey()
         */
        private final int key;

        public Keyboard(char character, int key) {
            this.character = character;
            this.key = key;
        }

        public char getCharacter() {
            return character;
        }

        public int getKey() {
            return key;
        }

        public static boolean handle() {
            if (org.lwjgl.input.Keyboard.getEventKeyState()) {
                int keyCode = org.lwjgl.input.Keyboard.getEventKey() == 0 ? org.lwjgl.input.Keyboard.getEventCharacter() + 256 : org.lwjgl.input.Keyboard.getEventKey();
                xyz.openmodloader.event.impl.InputEvent.Keyboard event = new xyz.openmodloader.event.impl.InputEvent.Keyboard(org.lwjgl.input.Keyboard.getEventCharacter(), keyCode);
                return OpenModLoader.getEventBus().post(event);
            }
            return true;
        }
    }

    @Override
    public boolean isCancelable() {
        return true;
    }
}


text:
module Azure::AzureStack::Mgmt::V2017_06_01
  module Models
    #
    # Data disk image.
    #
    class DataDiskImage

      include MsRestAzure

      # @return [Integer] The LUN.
      attr_accessor :lun

      # @return [String] SAS key for source blob.
      attr_accessor :source_blob_sas_uri

      #
      # Mapper for DataDiskImage class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'DataDiskImage',
          type: {
            name: 'Composite',
            class_name: 'DataDiskImage',
            model_properties: {
              lun: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'lun',
                type: {
                  name: 'Number'
                }
              },
              source_blob_sas_uri: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'sourceBlobSasUri',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
/*
 * var.c
 *
 * Simple linked list to hold a list of variables containing of an identifier
 * and a value (both on long).
 *
 * Tom René Hennig
 */

/******************************************************************************
 *                              INCLUDE SECTION
 */

#include <stdio.h>
#include <stdlib.h>

#include "var.h"

/******************************************************************************
 *                           FUNCTION DEFINITIONS
 */

/*
 * Add a variable to the list returning the list (necessary to allocate a new
 * listin case it was emtpy). If the identifier is already allocated nothing
 * is modified.
 * ARGS     list - list handle to add variable to
 *          id   - identifier of new variable
 * RETURN   possibly new handle of the list
 */
VariableList addVariable(VariableList list, long id)
{
    Variable *tmp = list;

    // Allocate new list if necessary
    if (list == NULL) {
        tmp = malloc(sizeof(Variable));
        if (tmp == NULL) {
            fprintf(stderr, "ERROR: unable to allocate memory\n");
            exit(EXIT_FAILURE);
        }
        tmp->id = id;
        tmp->value = 0;
        tmp->next = NULL;
        return tmp;
    }

    // Walk till the end of the list and check whether the new identifier is
    // already in the list
    while (tmp->next != NULL) {
        if (tmp->id == id) {
            fprintf(stderr, "WARNING: tried to double allocate variable");
            return list;
        }
        tmp = tmp->next;
    }

    // Allocate new element at the end of the list
    tmp->next = malloc(sizeof(Variable));
    if (tmp->next == NULL) {
        fprintf(stderr, "ERROR: unable to allocate memory\n");
        exit(EXIT_FAILURE);
    }
    tmp = tmp->next;
    tmp->id = id;
    tmp->value = 0;
    tmp->next = NULL;
    return list;
}

/*
 * Look up value of given identifier, add new variable to the list and
 * initialize it to zero, if it is not yet allocated.
 * WARNING: cannot add variables to an empty list!
 * ARGS     list - list to search for identifier
 *          id   - identifier of variable to be searched for
 * RETURN   value of the searched variable (0 if it has not been allocated yet)
 */
long getValue(VariableList list, long id)
{
    Variable *tmp = list;

    // input check
    if (list == NULL) {
        fprintf(stderr, "ERROR: unable to obtain value from empty variable list\n");
        exit(EXIT_FAILURE);
    }

    // walk through the list and search identifier
    do {
        if (tmp->id == id)
            return tmp->value;
        tmp = tmp->next;
    } while (tmp != NULL);

    // add identifier to list if is not already there
    addVariable(list, id);
    return 0;
}

/*
 * Set the value of an variable in the given list, allocates a new variable
 * if necessary.
 * WARNING: cannot add variables to an empty list!
 * ARGS     list  - list to modify the value of variable identifier
 *          id    - identifier to search for
 *          value - new value of variable identifier
 */
void setValue(VariableList list, long id, long value)
{
    Variable *tmp = list;

    // input check
    if (list == NULL) {
        fprintf(stderr, "ERROR: unable to set value of an empty variable list\n");
        exit(EXIT_FAILURE);
    }

    // walk through the list and search identifier
    do {
        if (tmp->id == id) {
            tmp->value = value;
            return;
        }
        tmp = tmp->next;
    } while (tmp != NULL);

    // add identifier to list if is not already there
    list = addVariable(list, id);
    setValue(list, id, value);
}


text:
#import <Foundation/Foundation.h>
#import "TiUtils.h"
#import "ApplicationDefaults.h"

@implementation ApplicationDefaults

+ (NSMutableDictionary*) copyDefaults
{
	NSMutableDictionary * _property = [[NSMutableDictionary alloc] init];

	[_property setObject:[TiUtils stringValue:@"Z6nJlKyKPxF873Im7gYFps48rHuBNeZ1"] forKey:@"acs-oauth-secret-production"];
	[_property setObject:[TiUtils stringValue:@"NUf1DOQZm5HLVF0FxmnYgiedR9vR9BZ0"] forKey:@"acs-oauth-key-production"];
	[_property setObject:[TiUtils stringValue:@"yZJajMnNN5W1x3GpuiPCFiGCuPxx6yRu"] forKey:@"acs-api-key-production"];
	[_property setObject:[TiUtils stringValue:@"siRfGlrtDi3G3TUwBUhzRto9b9E6girU"] forKey:@"acs-oauth-secret-development"];
	[_property setObject:[TiUtils stringValue:@"zsIr4akpq4UxCibqqaHYG6hjonbs1kOV"] forKey:@"acs-oauth-key-development"];
	[_property setObject:[TiUtils stringValue:@"KsqH1UXvmrGbKJdPzNq3cVSWQIRCZOXW"] forKey:@"acs-api-key-development"];
	[_property setObject:[TiUtils stringValue:@"system"] forKey:@"ti.ui.defaultunit"];
	return _property;
}

+ (NSDictionary*) launchUrl {
    static BOOL launched = NO;
    if (!launched) {
        launched = YES;
        return nil;
    } else { return nil;}
}

@end


text:
<title>DOM tests -- CSS2 interface</title>

Text inside div a

Text inside div b

Text inside div c


text:
module ChapterOne
  module One

    # Implement an algorithm to determine if a string has all unique characters
    def unique_chars?(s)
      existing_vals = []
      ascii_vals = s.bytes
      result = true
      ascii_vals.each do |v|
        existing_vals[v] == 1 ? result = false : existing_vals[v] = 1
      end

      result
    end

  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace HIPHttpApi
{
    internal struct StatusResponseJson
    {
        public bool Success { get; set; }
        public HIPHttpApi.StatusResponseJson.Result Result { get; set; }
    }

    namespace HIPHttpApi.StatusResponseJson
    {
        internal struct Result
        {
            [JsonConverter(typeof(UnixTimeConverter))]
            public DateTime SystemTime { get; set; }
            public int UpTime { get; set; }
        }
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

#if HAS_IOPERATION

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;

namespace Analyzer.Utilities.Extensions
{
    internal static class OperationBlockAnalysisContextExtension
    {
#pragma warning disable RS1012 // Start action has no registered actions.
        public static bool IsMethodNotImplementedOrSupported(this OperationBlockStartAnalysisContext context)
#pragma warning restore RS1012 // Start action has no registered actions.
        {
            // Note that VB method bodies with 1 action have 3 operations.
            // The first is the actual operation, the second is a label statement, and the third is a return
            // statement. The last two are implicit in these scenarios.

            var operationBlocks = context.OperationBlocks.WhereAsArray(operation => !operation.IsOperationNoneRoot());

            IBlockOperation? methodBlock = null;
            if (operationBlocks.Length == 1 && operationBlocks[0].Kind == OperationKind.Block)
            {
                methodBlock = (IBlockOperation)operationBlocks[0];
            }
            else if (operationBlocks.Length > 1)
            {
                foreach (var block in operationBlocks)
                {
                    if (block.Kind == OperationKind.Block)
                    {
                        methodBlock = (IBlockOperation)block;
                        break;
                    }
                }
            }

            if (methodBlock != null)
            {
                static bool IsSingleStatementBody(IBlockOperation body)
                {
                    return body.Operations.Length == 1 ||
                        (body.Operations.Length == 3 && body.Syntax.Language == LanguageNames.VisualBasic &&
                         body.Operations[1] is ILabeledOperation labeledOp && labeledOp.IsImplicit &&
                         body.Operations[2] is IReturnOperation returnOp && returnOp.IsImplicit);
                }

                if (IsSingleStatementBody(methodBlock) &&
                    methodBlock.Operations[0].GetTopmostExplicitDescendants() is { } descendants &&
                    descendants.Length == 1 &&
                    descendants[0] is IThrowOperation throwOperation &&
                    throwOperation.GetThrownExceptionType() is ITypeSymbol createdExceptionType)
                {
                    if (Equals(context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotImplementedException), createdExceptionType.OriginalDefinition)
                        || Equals(context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotSupportedException), createdExceptionType.OriginalDefinition))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
    }
}

#endif


text:
'use strict';

/**
 * @return {object}
 */
module.exports = {
  ELEMENT: 'childName',
  MODIFIER: 'theme',
  NAME: 'className'
};


text:
# RabbitMQ tutorial - "Hello World!" SUPPRESS-RHS

## Introduction

<xi:include href="site/tutorials/tutorials-help.xml.inc"/>
<xi:include href="site/tutorials/tutorials-intro.xml.inc"/>

## "Hello World"
### (using the Bunny Ruby Client)

In this part of the tutorial we'll write two small programs in Ruby; a
producer (sender) that sends a single message, and a consumer (receiver) that receives
messages and prints them out.  We'll gloss over some of the detail in
the [Bunny](http://rubybunny.info) API, concentrating on this very simple thing just to get
started. It's a "Hello World" of messaging.

In the diagram below, "P" is our producer and "C" is our consumer. The
box in the middle is a queue - a message buffer that RabbitMQ keeps
on behalf of the consumer.

   [|||] -> (C)" height="60" />

> #### The Bunny client library
>
> RabbitMQ speaks multiple protocols. This tutorial uses AMQP 0-9-1, which is an open,
> general-purpose protocol for messaging. There are a number of clients
> for RabbitMQ in [many different
> languages](http://rabbitmq.com/devtools.html). We'll
> use the [Bunny](http://rubybunny.info), the most popular Ruby client, in this tutorial.
>
> First, install Bunny using [Rubygems](http://rubygems.org):
>
>

> gem install bunny --version ">= 2.13.0"
>

Now we have Bunny installed, we can write some
code.

### Sending

   [|||]" height="100" />

We'll call our message producer `send.rb` and our message consumer
`receive.rb`.  The producer will connect to RabbitMQ, send a single message,
then exit.

In
[`send.rb`](https://github.com/rabbitmq/rabbitmq-tutorials/blob/main/ruby/send.rb),
we need to require the library first:

#!/usr/bin/env ruby
require 'bunny'

then connect to RabbitMQ server

connection = Bunny.new
connection.start

The connection abstracts the socket connection, and takes care of
protocol version negotiation and authentication and so on for us. Here
we connect to a broker on the local machine with all default settings.

If we wanted to connect to a broker on a different
machine we'd simply specify its name or IP address using the `:hostname`
option:

connection = Bunny.new(hostname: 'rabbit.local')
connection.start

Next we create a channel, which is where most of the API for getting
things done resides:

channel = connection.create_channel

To send, we must declare a queue for us to send to; then we can publish a message
to the queue:

queue = channel.queue('hello')

channel.default_exchange.publish('Hello World!', routing_key: queue.name)
puts " [x] Sent 'Hello World!'"

Declaring a queue is idempotent - it will only be created if it doesn't
exist already. The message content is a byte array, so you can encode
whatever you like there.

Lastly, we close the connection:

connection.close

[Here's the whole send.rb script](https://github.com/rabbitmq/rabbitmq-tutorials/blob/main/ruby/send.rb).

> #### Sending doesn't work!
>
> If this is your first time using RabbitMQ and you don't see the "Sent"
> message then you may be left scratching your head wondering what could
> be wrong. Maybe the broker was started without enough free disk space
> (by default it needs at least 200 MB free) and is therefore refusing to
> accept messages. Check the broker logfile to confirm and reduce the
> limit if necessary. The  href="https://www.rabbitmq.com/configure.html#config-items">configuration
> file documentation will show you how to set disk_free_limit.

### Receiving

That's it for our producer. Our consumer is listening for messages from
RabbitMQ, so unlike the producer which publishes a single message, we'll
keep the consumer running to listen for messages and print them out.

   (C)" height="100" />

The code (in [`receive.rb`](https://github.com/rabbitmq/rabbitmq-tutorials/blob/main/ruby/receive.rb)) has the same require as `send`:

#!/usr/bin/env ruby
require 'bunny'

Setting up is the same as the producer; we open a connection and a
channel, and declare the queue from which we're going to consume.
Note this matches up with the queue that `send` publishes to.

connection = Bunny.new
connection.start

channel = connection.create_channel
queue = channel.queue('hello')

Note that we declare the queue here, as well. Because we might start
the consumer before the producer, we want to make sure the queue exists
before we try to consume messages from it.

We're about to tell the server to deliver us the messages from the
queue. Since it will push us messages asynchronously, we provide a
callback that will be executed when RabbitMQ pushes messages to
our consumer. This is what `Bunny::Queue#subscribe` does.

begin
  puts ' [*] Waiting for messages. To exit press CTRL+C'
  queue.subscribe(block: true) do |_delivery_info, _properties, body|
    puts " [x] Received #{body}"
  end
rescue Interrupt => _
  connection.close

  exit(0)
end

`Bunny::Queue#subscribe` is used with the `:block` option that makes it
block the calling thread (we don't want the script to finish running immediately!).

[Here's the whole receive.rb script](https://github.com/rabbitmq/rabbitmq-tutorials/blob/main/ruby/receive.rb).

### Putting it all together

Now we can run both scripts. In a terminal, run the consumer (receiver):

ruby receive.rb

then, run the publisher (sender):

ruby send.rb

The consumer will print the message it gets from the producer via
RabbitMQ. The consumer will keep running, waiting for messages (Use Ctrl-C to stop it), so try running
the producer from another terminal.

> #### Listing queues
>
> You may wish to see what queues RabbitMQ has and how many
> messages are in them. You can do it (as a privileged user) using the `rabbitmqctl` tool:
>
>

> sudo rabbitmqctl list_queues
>

>
> On Windows, omit the sudo:
>

> rabbitmqctl.bat list_queues
>

Time to move on to [part 2](tutorial-two-ruby.html) and build a simple _work queue_.