text:
import mock

from rally import exceptions
from rally.plugins.openstack.scenarios.heat import utils
from tests.unit import test

HEAT_UTILS = "rally.plugins.openstack.scenarios.heat.utils"

CONF = utils.CONF

class HeatScenarioTestCase(test.ScenarioTestCase):
    def setUp(self):
        super(HeatScenarioTestCase, self).setUp()
        self.stack = mock.Mock()
        self.scenario = utils.HeatScenario(self.context)
        self.default_template = "heat_template_version: 2013-05-23"
        self.dummy_parameters = {"dummy_param": "dummy_key"}
        self.dummy_files = ["dummy_file.yaml"]
        self.dummy_environment = {"dummy_env": "dummy_env_value"}
        self.default_output_key = "dummy_output_key"

    def test_list_stacks(self):
        scenario = utils.HeatScenario(self.context)
        return_stacks_list = scenario._list_stacks()
        self.clients("heat").stacks.list.assert_called_once_with()
        self.assertEqual(list(self.clients("heat").stacks.list.return_value),
                         return_stacks_list)
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.list_stacks")

    def test_create_stack(self):
        self.clients("heat").stacks.create.return_value = {
            "stack": {"id": "test_id"}
        }
        self.clients("heat").stacks.get.return_value = self.stack
        return_stack = self.scenario._create_stack(self.default_template,
                                                   self.dummy_parameters,
                                                   self.dummy_files,
                                                   self.dummy_environment)
        args, kwargs = self.clients("heat").stacks.create.call_args
        self.assertIn(self.dummy_parameters, kwargs.values())
        self.assertIn(self.default_template, kwargs.values())
        self.assertIn(self.dummy_files, kwargs.values())
        self.assertIn(self.dummy_environment, kwargs.values())
        self.mock_wait_for.mock.assert_called_once_with(
            self.stack,
            update_resource=self.mock_get_from_manager.mock.return_value,
            ready_statuses=["CREATE_COMPLETE"],
            failure_statuses=["CREATE_FAILED"],
            check_interval=CONF.benchmark.heat_stack_create_poll_interval,
            timeout=CONF.benchmark.heat_stack_create_timeout)
        self.mock_get_from_manager.mock.assert_called_once_with()
        self.assertEqual(self.mock_wait_for.mock.return_value, return_stack)
        self._test_atomic_action_timer(self.scenario.atomic_actions(),
                                       "heat.create_stack")

    def test_update_stack(self):
        self.clients("heat").stacks.update.return_value = None
        scenario = utils.HeatScenario(self.context)
        scenario._update_stack(self.stack, self.default_template,
                               self.dummy_parameters, self.dummy_files,
                               self.dummy_environment)
        args, kwargs = self.clients("heat").stacks.update.call_args
        self.assertIn(self.dummy_parameters, kwargs.values())
        self.assertIn(self.default_template, kwargs.values())
        self.assertIn(self.dummy_files, kwargs.values())
        self.assertIn(self.dummy_environment, kwargs.values())
        self.assertIn(self.stack.id, args)
        self.mock_wait_for.mock.assert_called_once_with(
            self.stack,
            update_resource=self.mock_get_from_manager.mock.return_value,
            ready_statuses=["UPDATE_COMPLETE"],
            failure_statuses=["UPDATE_FAILED"],
            check_interval=CONF.benchmark.heat_stack_update_poll_interval,
            timeout=CONF.benchmark.heat_stack_update_timeout)
        self.mock_get_from_manager.mock.assert_called_once_with()
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.update_stack")

    def test_check_stack(self):
        scenario = utils.HeatScenario(self.context)
        scenario._check_stack(self.stack)
        self.clients("heat").actions.check.assert_called_once_with(
            self.stack.id)
        self.mock_wait_for.mock.assert_called_once_with(
            self.stack,
            update_resource=self.mock_get_from_manager.mock.return_value,
            ready_statuses=["CHECK_COMPLETE"],
            failure_statuses=["CHECK_FAILED"],
            check_interval=CONF.benchmark.heat_stack_check_poll_interval,
            timeout=CONF.benchmark.heat_stack_check_timeout)
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.check_stack")

    def test_delete_stack(self):
        scenario = utils.HeatScenario(self.context)
        scenario._delete_stack(self.stack)
        self.stack.delete.assert_called_once_with()
        self.mock_wait_for_status.mock.assert_called_once_with(
            self.stack,
            ready_statuses=["DELETE_COMPLETE"],
            failure_statuses=["DELETE_FAILED"],
            check_deletion=True,
            update_resource=self.mock_get_from_manager.mock.return_value,
            check_interval=CONF.benchmark.heat_stack_delete_poll_interval,
            timeout=CONF.benchmark.heat_stack_delete_timeout)
        self.mock_get_from_manager.mock.assert_called_once_with()
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.delete_stack")

    def test_suspend_stack(self):
        scenario = utils.HeatScenario(self.context)
        scenario._suspend_stack(self.stack)
        self.clients("heat").actions.suspend.assert_called_once_with(
            self.stack.id)
        self.mock_wait_for.mock.assert_called_once_with(
            self.stack,
            update_resource=self.mock_get_from_manager.mock.return_value,
            ready_statuses=["SUSPEND_COMPLETE"],
            failure_statuses=["SUSPEND_FAILED"],
            check_interval=CONF.benchmark.heat_stack_suspend_poll_interval,
            timeout=CONF.benchmark.heat_stack_suspend_timeout)
        self.mock_get_from_manager.mock.assert_called_once_with()
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.suspend_stack")

    def test_resume_stack(self):
        scenario = utils.HeatScenario(self.context)
        scenario._resume_stack(self.stack)
        self.clients("heat").actions.resume.assert_called_once_with(
            self.stack.id)
        self.mock_wait_for.mock.assert_called_once_with(
            self.stack,
            update_resource=self.mock_get_from_manager.mock.return_value,
            ready_statuses=["RESUME_COMPLETE"],
            failure_statuses=["RESUME_FAILED"],
            check_interval=CONF.benchmark.heat_stack_resume_poll_interval,
            timeout=CONF.benchmark.heat_stack_resume_timeout)
        self.mock_get_from_manager.mock.assert_called_once_with()
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.resume_stack")

    def test_snapshot_stack(self):
        scenario = utils.HeatScenario(self.context)
        scenario._snapshot_stack(self.stack)
        self.clients("heat").stacks.snapshot.assert_called_once_with(
            self.stack.id)
        self.mock_wait_for.mock.assert_called_once_with(
            self.stack,
            update_resource=self.mock_get_from_manager.mock.return_value,
            ready_statuses=["SNAPSHOT_COMPLETE"],
            failure_statuses=["SNAPSHOT_FAILED"],
            check_interval=CONF.benchmark.heat_stack_snapshot_poll_interval,
            timeout=CONF.benchmark.heat_stack_snapshot_timeout)
        self.mock_get_from_manager.mock.assert_called_once_with()
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.snapshot_stack")

    def test_restore_stack(self):
        scenario = utils.HeatScenario(self.context)
        scenario._restore_stack(self.stack, "dummy_id")
        self.clients("heat").stacks.restore.assert_called_once_with(
            self.stack.id, "dummy_id")
        self.mock_wait_for.mock.assert_called_once_with(
            self.stack,
            update_resource=self.mock_get_from_manager.mock.return_value,
            ready_statuses=["RESTORE_COMPLETE"],
            failure_statuses=["RESTORE_FAILED"],
            check_interval=CONF.benchmark.heat_stack_restore_poll_interval,
            timeout=CONF.benchmark.heat_stack_restore_timeout)
        self.mock_get_from_manager.mock.assert_called_once_with()
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.restore_stack")

    def test__count_instances(self):
        self.clients("heat").resources.list.return_value = [
            mock.Mock(resource_type="OS::Nova::Server"),
            mock.Mock(resource_type="OS::Nova::Server"),
            mock.Mock(resource_type="OS::Heat::AutoScalingGroup")]
        scenario = utils.HeatScenario(self.context)
        self.assertEqual(scenario._count_instances(self.stack), 2)
        self.clients("heat").resources.list.assert_called_once_with(
            self.stack.id,
            nested_depth=1)

    def test__scale_stack(self):
        scenario = utils.HeatScenario(self.context)
        scenario._count_instances = mock.Mock(side_effect=[3, 3, 2])
        scenario._stack_webhook = mock.Mock()

        scenario._scale_stack(self.stack, "test_output_key", -1)

        scenario._stack_webhook.assert_called_once_with(self.stack,
                                                        "test_output_key")
        self.mock_wait_for.mock.assert_called_once_with(
            self.stack,
            is_ready=mock.ANY,
            failure_statuses=["UPDATE_FAILED"],
            update_resource=self.mock_get_from_manager.mock.return_value,
            timeout=CONF.benchmark.heat_stack_scale_timeout,
            check_interval=CONF.benchmark.heat_stack_scale_poll_interval)
        self.mock_get_from_manager.mock.assert_called_once_with()

        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.scale_with_test_output_key")

    @mock.patch("requests.post")
    def test_stack_webhook(self, mock_post):
        scenario = utils.HeatScenario(self.context)
        stack = mock.Mock(outputs=[
            {"output_key": "output1", "output_value": "url1"},
            {"output_key": "output2", "output_value": "url2"}])

        scenario._stack_webhook(stack, "output1")
        mock_post.assert_called_with("url1")
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.output1_webhook")

    @mock.patch("requests.post")
    def test_stack_webhook_invalid_output_key(self, mock_post):
        scenario = utils.HeatScenario(self.context)
        stack = mock.Mock()
        stack.outputs = [{"output_key": "output1", "output_value": "url1"},
                         {"output_key": "output2", "output_value": "url2"}]

        self.assertRaises(exceptions.InvalidConfigException,
                          scenario._stack_webhook, stack, "bogus")

    def test_stack_show_output(self):
        scenario = utils.HeatScenario(self.context)
        scenario._stack_show_output(self.stack, self.default_output_key)
        self.clients("heat").stacks.output_show.assert_called_once_with(
            self.stack.id, self.default_output_key)
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.show_output")

    def test_stack_show_output_via_API(self):
        scenario = utils.HeatScenario(self.context)
        scenario._stack_show_output_via_API(
            self.stack, self.default_output_key)
        self.clients("heat").stacks.get.assert_called_once_with(
            stack_id=self.stack.id)
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.show_output_via_API")

    def test_stack_list_output(self):
        scenario = utils.HeatScenario(self.context)
        scenario._stack_list_output(self.stack)
        self.clients("heat").stacks.output_list.assert_called_once_with(
            self.stack.id)
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.list_output")

    def test_stack_list_output_via_API(self):
        scenario = utils.HeatScenario(self.context)
        scenario._stack_list_output_via_API(self.stack)
        self.clients("heat").stacks.get.assert_called_once_with(
            stack_id=self.stack.id)
        self._test_atomic_action_timer(scenario.atomic_actions(),
                                       "heat.list_output_via_API")

class HeatScenarioNegativeTestCase(test.ScenarioTestCase):
    patch_task_utils = False

    def test_failed_create_stack(self):
        self.clients("heat").stacks.create.return_value = {
            "stack": {"id": "test_id"}
        }
        stack = mock.Mock()
        resource = mock.Mock()
        resource.stack_status = "CREATE_FAILED"
        stack.manager.get.return_value = resource
        self.clients("heat").stacks.get.return_value = stack
        scenario = utils.HeatScenario(context=self.context)
        ex = self.assertRaises(exceptions.GetResourceErrorStatus,
                               scenario._create_stack, "stack_name")
        self.assertIn("has CREATE_FAILED status", str(ex))

    def test_failed_update_stack(self):
        stack = mock.Mock()
        resource = mock.Mock()
        resource.stack_status = "UPDATE_FAILED"
        stack.manager.get.return_value = resource
        self.clients("heat").stacks.get.return_value = stack
        scenario = utils.HeatScenario(context=self.context)
        ex = self.assertRaises(exceptions.GetResourceErrorStatus,
                               scenario._update_stack, stack,
                               "heat_template_version: 2013-05-23")
        self.assertIn("has UPDATE_FAILED status", str(ex))


text:
using System;
using System.Text;

class ReverseStringD
{
    static void Main()
    {
        string aString = Console.ReadLine();
        Console.WriteLine(ReverseString(aString));

    }
    public static string ReverseString(string s)
    {
        StringBuilder sb = new StringBuilder(s.Length);
        for (int i = s.Length - 1; i >= 0; i--)
            sb.Append(s[i]);
        return sb.ToString();

    }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef INDIGOX_CLASSES_ATOM_HPP
#define INDIGOX_CLASSES_ATOM_HPP

#include <array>
#include <cstdint>
#include <iostream>
#include <memory>
#include <vector>

#include "../api.hpp"
#include "../utils/counter.hpp"

namespace indigox {

  // Related typedefs
  typedef std::vector<Bond_wp> AtomBonds;
  typedef AtomBonds::iterator AtomBondIterator;
  typedef AtomBonds::const_iterator const_AtomBondIterator;

  class Atom
  : public utils::CountableObject<Atom>,
  public std::enable_shared_from_this<Atom> {

  public:
    /// @name Initialisation methods.

    /// @brief Default constructor.
    Atom();

    /// @brief Normal constructor, links Atom to a Molecule.
    Atom(Molecule_p m);

    /// @brief Destructor
    ~Atom();

    /// @name Data retrival methods.

    /// @returns the element of this atom.
    Element_p GetElement() const;

    /// @returns the formal charge on this atom.
    Int GetFormalCharge() const;

    /// @returns the index of this atom.
    uid_t GetIndex() const;

    /// @returns the molecule this atom is part of.
    Molecule_p GetMolecule() const;

    /// @returns the name of this atom.
    String GetName() const;

    /// @returns the x coordinate of this atom.
    Float GetX() const;

    /// @returns the y coordinate of this atom.
    Float GetY() const;

    /// @returns the z coordinate of this atom.
    Float GetZ() const;

    /// @returns a string representation of this atom.
    String ToString();

    /// @name Data modification methods.

    /// @brief Sets the element of this atom.
    void SetElement(Element_p);
    void SetElement(String);
    void SetElement(Int);

    /// @brief Sets the formal charge on this atom.
    void SetFormalCharge(Int);

    /// @brief Sets the index of this atom.
    void SetIndex(uid_t);

    /// @brief Sets the molecule this atom is part of. Performs no bookkeeping.
    void SetMolecule(Molecule_p);

    /// @brief Sets the name of this atom.
    void SetName(String);

    /// @brief Sets the position of this atom
    void SetPosition(Float, Float, Float);

    /// @name Atom modification methods.

    /// @brief Adds a bond to this atom. Performs no bookkeeping.
    void AddBond(Bond_p);

    /// @brief Removes a bond from this atom. Performs no bookkeeping.
    void RemoveBond(Bond_p);

    void Clear();

    /// @name Iterator methods.

    /// @brief Sets the given iterator to the next position in bonds_.
    Bond_p Next(AtomBondIterator&);

    /// @brief Sets the given iterator to the start of bonds_.
    Bond_p Begin(AtomBondIterator&);

    /// @brief Sets the given iterator to the end of bonds_.
    AtomBondIterator BeginBond();
    AtomBondIterator EndBond();

  private:
    Molecule_wp mol_;
    Element_p element_;
    Int fc_ = 0;
    uid_t idx_ = 0;
    String name_ = "None";
    std::array<Float, 3> pos_ = {{0.0, 0.0, 0.0}};

    AtomBonds bonds_;

  };
}

#endif /* INDIGOX_CLASSES_ATOM_HPP */


text:
// Copyright (C) 2020 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.googlesource.gerrit.plugins.replication;

import static com.google.common.truth.Truth.assertThat;
import static com.googlesource.gerrit.plugins.replication.PushResultProcessing.NO_OP;

import com.google.gerrit.acceptance.TestPlugin;
import com.google.gerrit.acceptance.UseLocalDisk;
import com.google.gerrit.acceptance.WaitUtil;
import com.google.gerrit.entities.Project;
import com.google.gerrit.extensions.api.projects.BranchInput;
import com.googlesource.gerrit.plugins.replication.Destination.QueueInfo;
import com.googlesource.gerrit.plugins.replication.ReplicationConfig.FilterType;
import com.googlesource.gerrit.plugins.replication.ReplicationTasksStorage.ReplicateRefUpdate;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.eclipse.jgit.transport.URIish;
import org.junit.Test;

/**
 * The tests in this class aim to ensure events are correctly written and read from storage. They
 * typically do this by setting up replication destinations with long delays, performing actions
 * that are expected to write to storage, reloading the configuration (which should read from
 * storage), and then confirming the actions complete as expected.
 */
@UseLocalDisk
@TestPlugin(
    name = "replication",
    sysModule = "com.googlesource.gerrit.plugins.replication.ReplicationModule")
public class ReplicationStorageIT extends ReplicationStorageDaemon {

  @Test
  public void shouldCreateIndividualReplicationTasksForEveryRemoteUrlPair() throws Exception {
    List<String> replicaSuffixes = Arrays.asList("replica1", "replica2");
    createTestProject(project + "replica1");
    createTestProject(project + "replica2");

    setReplicationDestination("foo1", replicaSuffixes, ALL_PROJECTS, Integer.MAX_VALUE);
    setReplicationDestination("foo2", replicaSuffixes, ALL_PROJECTS, Integer.MAX_VALUE);
    reloadConfig();

    createChange();

    assertThat(listWaitingReplicationTasks("refs/changes/\\d*/\\d*/\\d*")).hasSize(4);
  }

  @Test
  public void shouldCreateOneReplicationTaskWhenSchedulingRepoFullSync() throws Exception {
    createTestProject(project + "replica");

    setReplicationDestination("foo", "replica", ALL_PROJECTS, Integer.MAX_VALUE);
    reloadConfig();

    plugin
        .getSysInjector()
        .getInstance(ReplicationQueue.class)
        .scheduleFullSync(project, null, new ReplicationState(NO_OP), false);

    assertThat(listWaitingReplicationTasks(Pattern.quote(PushOne.ALL_REFS))).hasSize(1);
  }

  @Test
  public void shouldFirePendingOnlyToIncompleteUri() throws Exception {
    String suffix1 = "replica1";
    String suffix2 = "replica2";
    String remote1 = "foo1";
    String remote2 = "foo2";
    setReplicationDestination(remote1, suffix1, ALL_PROJECTS, Integer.MAX_VALUE);
    setReplicationDestination(remote2, suffix2, ALL_PROJECTS, Integer.MAX_VALUE);
    reloadConfig();

    String changeRef = createChange().getPatchSet().refName();
    changeReplicationTasksForRemote(tasksStorage.streamWaiting(), changeRef, remote1)
        .forEach(
            (update) -> {
              try {
                UriUpdates uriUpdates = new TestUriUpdates(update);
                tasksStorage.start(uriUpdates);
                tasksStorage.finish(uriUpdates);
              } catch (URISyntaxException e) {
              }
            });
    reloadConfig();

    assertThat(waitingChangeReplicationTasksForRemote(changeRef, remote2).count()).isEqualTo(1);
    assertThat(waitingChangeReplicationTasksForRemote(changeRef, remote1).count()).isEqualTo(0);
  }

  @Test
  public void shouldFireAndCompletePendingOnlyToIncompleteUri() throws Exception {
    String suffix1 = "replica1";
    String suffix2 = "replica2";
    Project.NameKey target1 = createTestProject(project + suffix1);
    Project.NameKey target2 = createTestProject(project + suffix2);
    String remote1 = "foo1";
    String remote2 = "foo2";
    setReplicationDestination(remote1, suffix1, ALL_PROJECTS, Integer.MAX_VALUE);
    setReplicationDestination(remote2, suffix2, ALL_PROJECTS, Integer.MAX_VALUE);
    reloadConfig();

    String changeRef = createChange().getPatchSet().refName();
    changeReplicationTasksForRemote(tasksStorage.streamWaiting(), changeRef, remote1)
        .forEach(
            (update) -> {
              try {
                UriUpdates uriUpdates = new TestUriUpdates(update);
                tasksStorage.start(uriUpdates);
                tasksStorage.finish(uriUpdates);
              } catch (URISyntaxException e) {
              }
            });

    setReplicationDestination(remote1, suffix1, ALL_PROJECTS);
    setReplicationDestination(remote2, suffix2, ALL_PROJECTS);
    reloadConfig();

    assertThat(isPushCompleted(target2, changeRef, TEST_PUSH_TIMEOUT)).isEqualTo(true);
    assertThat(isPushCompleted(target1, changeRef, TEST_PUSH_TIMEOUT)).isEqualTo(false);
  }

  @Test
  public void shouldFirePendingChangeRefs() throws Exception {
    String suffix1 = "replica1";
    String suffix2 = "replica2";
    String remote1 = "foo1";
    String remote2 = "foo2";
    setReplicationDestination(remote1, suffix1, ALL_PROJECTS, Integer.MAX_VALUE);
    setReplicationDestination(remote2, suffix2, ALL_PROJECTS, Integer.MAX_VALUE);
    reloadConfig();

    String changeRef1 = createChange().getPatchSet().refName();
    String changeRef2 = createChange().getPatchSet().refName();
    reloadConfig();

    assertThat(waitingChangeReplicationTasksForRemote(changeRef1, remote1).count()).isEqualTo(1);
    assertThat(waitingChangeReplicationTasksForRemote(changeRef1, remote2).count()).isEqualTo(1);
    assertThat(waitingChangeReplicationTasksForRemote(changeRef2, remote1).count()).isEqualTo(1);
    assertThat(waitingChangeReplicationTasksForRemote(changeRef2, remote2).count()).isEqualTo(1);
  }

  @Test
  public void shouldFireAndCompletePendingChangeRefs() throws Exception {
    String suffix1 = "replica1";
    String suffix2 = "replica2";
    Project.NameKey target1 = createTestProject(project + suffix1);
    Project.NameKey target2 = createTestProject(project + suffix2);
    String remote1 = "foo1";
    String remote2 = "foo2";
    setReplicationDestination(remote1, suffix1, ALL_PROJECTS, Integer.MAX_VALUE);
    setReplicationDestination(remote2, suffix2, ALL_PROJECTS, Integer.MAX_VALUE);
    reloadConfig();

    String changeRef1 = createChange().getPatchSet().refName();
    String changeRef2 = createChange().getPatchSet().refName();
    Map<Project.NameKey, String> refsByProject = new HashMap<>();
    refsByProject.put(target1, changeRef1);
    refsByProject.put(target2, changeRef1);
    refsByProject.put(target1, changeRef2);
    refsByProject.put(target2, changeRef2);

    setReplicationDestination(remote1, suffix1, ALL_PROJECTS);
    setReplicationDestination(remote2, suffix2, ALL_PROJECTS);
    reloadConfig();

    // Wait for completion within the time 2 pushes should take because each remote only has 1
    // thread and needs to push 2 events
    assertThat(isPushCompleted(refsByProject, TEST_PUSH_TIMEOUT.plus(TEST_PUSH_TIMEOUT)))
        .isEqualTo(true);
  }

  @Test
  public void shouldMatchTemplatedUrl() throws Exception {
    createTestProject(project + "replica");

    setReplicationDestination("foo", "replica", ALL_PROJECTS, Integer.MAX_VALUE);
    reloadConfig();

    String urlMatch = gitPath.resolve("${name}" + "replica" + ".git").toString();
    String expectedURI = gitPath.resolve(project + "replica" + ".git").toString();

    plugin
        .getSysInjector()
        .getInstance(ReplicationQueue.class)
        .scheduleFullSync(project, urlMatch, new ReplicationState(NO_OP), false);

    assertThat(listWaiting()).hasSize(1);
    tasksStorage
        .streamWaiting()
        .forEach(
            (task) -> {
              assertThat(task.uri()).isEqualTo(expectedURI);
              assertThat(task.refs()).isEqualTo(Set.of(PushOne.ALL_REFS));
            });
  }

  @Test
  public void shouldMatchRealUrl() throws Exception {
    createTestProject(project + "replica");

    setReplicationDestination("foo", "replica", ALL_PROJECTS, Integer.MAX_VALUE);
    reloadConfig();

    String urlMatch = gitPath.resolve(project + "replica" + ".git").toString();
    String expectedURI = urlMatch;

    plugin
        .getSysInjector()
        .getInstance(ReplicationQueue.class)
        .scheduleFullSync(project, urlMatch, new ReplicationState(NO_OP), false);

    assertThat(listWaiting()).hasSize(1);
    tasksStorage
        .streamWaiting()
        .forEach(
            (task) -> {
              assertThat(task.uri()).isEqualTo(expectedURI);
              assertThat(task.refs()).isEqualTo(Set.of(PushOne.ALL_REFS));
            });
  }

  @Test
  public void shouldReplicateBranchDeletionWhenMirror() throws Exception {
    replicateBranchDeletion(true);
  }

  @Test
  public void shouldNotReplicateBranchDeletionWhenNotMirror() throws Exception {
    replicateBranchDeletion(false);
  }

  @Test
  public void shouldCleanupTasksAfterNewProjectReplication() throws Exception {
    setReplicationDestination("task_cleanup_project", "replica", ALL_PROJECTS);
    config.setInt("remote", "task_cleanup_project", "replicationRetry", 0);
    config.save();
    reloadConfig();
    assertThat(listRunning()).hasSize(0);
    Project.NameKey sourceProject = createTestProject("task_cleanup_project");

    WaitUtil.waitUntil(
        () -> nonEmptyProjectExists(Project.nameKey(sourceProject + "replica.git")),
        TEST_NEW_PROJECT_TIMEOUT);
    WaitUtil.waitUntil(() -> listRunning().size() == 0, TEST_TASK_FINISH_TIMEOUT);
  }

  @Test
  public void shouldCleanupBothTasksAndLocksAfterNewProjectReplication() throws Exception {
    setReplicationDestination("task_cleanup_locks_project", "replica", ALL_PROJECTS);
    config.setInt("remote", "task_cleanup_locks_project", "replicationRetry", 0);
    config.save();
    reloadConfig();
    assertThat(listRunning()).hasSize(0);
    Project.NameKey sourceProject = createTestProject("task_cleanup_locks_project");

    WaitUtil.waitUntil(
        () -> nonEmptyProjectExists(Project.nameKey(sourceProject + "replica.git")),
        TEST_NEW_PROJECT_TIMEOUT);
    WaitUtil.waitUntil(() -> isTaskCleanedUp(), TEST_TASK_FINISH_TIMEOUT);
  }

  @Test
  public void shouldCleanupBothTasksAndLocksAfterReplicationCancelledAfterMaxRetries()
      throws Exception {
    String projectName = "task_cleanup_locks_project_cancelled";
    String remoteDestination = "http://invalidurl:9090/";
    URIish urish = new URIish(remoteDestination + projectName + ".git");

    setReplicationDestination(projectName, "replica", Optional.of(projectName));
    // replace correct urls with invalid one to trigger retry
    config.setString("remote", projectName, "url", remoteDestination + "${name}.git");
    config.setInt("remote", projectName, "replicationMaxRetries", TEST_REPLICATION_MAX_RETRIES);
    config.save();
    reloadConfig();
    Destination destination =
        destinationCollection.getAll(FilterType.ALL).stream()
            .filter(dest -> dest.getProjects().contains(projectName))
            .findFirst()
            .get();

    createTestProject(projectName);

    WaitUtil.waitUntil(
        () -> isTaskRescheduled(destination.getQueueInfo(), urish), TEST_NEW_PROJECT_TIMEOUT);
    // replicationRetry is set to 1 minute which is the minimum value. That's why
    // should be safe to get the pushOne object from pending because it should be
    // here for one minute
    PushOne pushOp = destination.getQueueInfo().pending.get(urish);

    WaitUtil.waitUntil(() -> pushOp.wasCanceled(), MAX_RETRY_WITH_TOLERANCE_TIMEOUT);
    WaitUtil.waitUntil(() -> isTaskCleanedUp(), TEST_TASK_FINISH_TIMEOUT);
  }

  private void replicateBranchDeletion(boolean mirror) throws Exception {
    setReplicationDestination("foo", "replica", ALL_PROJECTS);
    reloadConfig();

    Project.NameKey targetProject = createTestProject(project + "replica");
    String branchToDelete = "refs/heads/todelete";
    String master = "refs/heads/master";
    BranchInput input = new BranchInput();
    input.revision = master;
    gApi.projects().name(project.get()).branch(branchToDelete).create(input);
    isPushCompleted(targetProject, branchToDelete, TEST_PUSH_TIMEOUT);

    setReplicationDestination("foo", "replica", ALL_PROJECTS, Integer.MAX_VALUE, mirror);
    reloadConfig();

    gApi.projects().name(project.get()).branch(branchToDelete).delete();

    assertThat(listWaitingReplicationTasks(branchToDelete)).hasSize(1);
  }

  private boolean isTaskRescheduled(QueueInfo queue, URIish uri) {
    PushOne pushOne = queue.pending.get(uri);
    return pushOne == null ? false : pushOne.isRetrying();
  }

  private boolean isTaskCleanedUp() {
    Path refUpdates = replicationConfig.getEventsDirectory().resolve("ref-updates");
    Path runningUpdates = refUpdates.resolve("running");
    try {
      return Files.list(runningUpdates).count() == 0;
    } catch (IOException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }

  private Stream<ReplicateRefUpdate> waitingChangeReplicationTasksForRemote(
      String changeRef, String remote) {
    return tasksStorage
        .streamWaiting()
        .filter(task -> task.refs().stream().anyMatch(ref -> changeRef.equals(ref)))
        .filter(task -> remote.equals(task.remote()));
  }

  private Stream<ReplicateRefUpdate> changeReplicationTasksForRemote(
      Stream<ReplicateRefUpdate> updates, String changeRef, String remote) {
    return updates
        .filter(task -> task.refs().stream().anyMatch(ref -> changeRef.equals(ref)))
        .filter(task -> remote.equals(task.remote()));
  }
}


text:
package com.bridgelabz.functionalProgram.programs;

import java.util.Scanner;

import com.bridgelabz.functionalProgram.utility.Utility;

public class Quadratic {
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		System.out.println("Enter the value of a : ");
		int a=scanner.nextInt();
		System.out.println("Enter the value of b : ");
		int b=scanner.nextInt();
		System.out.println("Enter the value of c : ");
		int c=scanner.nextInt();

		Utility.quadratic(a, b, c);
	}
}


text:
require File.expand_path('../../prepare',  __FILE__)

client = Hessian2::Client.new('http://127.0.0.1:8080/')

puts client.sleep('wrong', 'arguments')


text:
package com.google.devtools.intellij.protoeditor.lang.psi;

/** Implemented by proto literal elements. */
public interface PbLiteral extends PbElement, ProtoLiteral {}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['advancedoptions'] = 'Opciones avanzaes';
$string['allday'] = 'Tol día';
$string['calendar'] = 'Calendariu';
$string['calendarheading'] = 'Calendariu {$a}';
$string['clickhide'] = 'Calque pa esconder.';
$string['clickshow'] = 'Calque pa enseñar.';
$string['commontasks'] = 'Opciones';
$string['confirmeventdelete'] = '¿De verdá quier esborrar esti eventu?';
$string['course'] = 'Cursu';
$string['courseevent'] = 'Eventu del cursu';
$string['courseevents'] = 'Eventos del cursu';
$string['courses'] = 'Cursos';
$string['dayview'] = 'Eventos del día';
$string['daywithnoevents'] = 'Nun hai eventos nesti día.';
$string['default'] = 'Por defeutu.';
$string['deleteevent'] = 'Esborrar eventu.';
$string['deleteevents'] = 'Esborrar eventos.';
$string['detailedmonthview'] = 'Eventos del mes detallaos';
$string['durationminutes'] = 'Duración en minutos';
$string['durationnone'] = 'Ensin duración';
$string['durationuntil'] = 'Hasta';
$string['editevent'] = 'Editar eventu';
$string['errorbeforecoursestart'] = 'Nun pue definir un eventu enantes de la fecha d\'entamu del cursu.';
$string['errorinvaliddate'] = 'fecha inválida';
$string['errorinvalidminutes'] = 'Especifique la duración, en minutos, con un númberu énte 1 y 999.';
$string['errorinvalidrepeats'] = 'Especifique la cantidá d\'eventos con un númberu énte 1 y 99.';
$string['errornodescription'] = 'Necesita una descripción';
$string['errornoeventname'] = 'Necesita un nome';
$string['eventdate'] = 'Fecha';
$string['eventdescription'] = 'Descripción';
$string['eventduration'] = 'Duración';
$string['eventendtime'] = 'Hora final';
$string['eventinstanttime'] = 'Tiempu';
$string['eventkind'] = 'Tipu d\'eventu';
$string['eventname'] = 'Nome';
$string['eventnone'] = 'Ensin eventos';
$string['eventrepeat'] = 'Repeticiones';
$string['eventsall'] = 'Tolos eventos';
$string['eventsfor'] = 'Eventos {$a}';
$string['eventskey'] = 'Llave d\'eventos';
$string['eventsrelatedtocourses'] = 'Eventos relacionaos colos cursos';
$string['eventstarttime'] = 'Hora d\'entamu.';
$string['eventtime'] = 'Tiempu';
$string['eventview'] = 'Detalles del eventu';
$string['expired'] = 'Caducáu';
$string['explain_site_timeformat'] = 'Pue escoyer el formatu nel que van vese les hores (12 o 24) en tol sitiu. Si escueye la opción por defeutu, el formatu escoyeráse automáticamente acordies col idioma qu\'use. Esti axuste pue pasase per altu mediante les preferencies d\'usuariu.';
$string['export'] = 'Esportar';
$string['exportbutton'] = 'Esportar';
$string['exportcalendar'] = 'Esportar calendariu';
$string['for'] = 'pa';
$string['fri'] = 'Vi';
$string['friday'] = 'Vienres';
$string['generateurlbutton'] = 'Consiguir URL del calendariu';
$string['global'] = 'Global';
$string['globalevent'] = 'Eventu global';
$string['globalevents'] = 'Eventos globales';
$string['gotocalendar'] = 'Dir al calendariu';
$string['group'] = 'Grupu';
$string['groupevent'] = 'Eventu de grupu';
$string['groupevents'] = 'Eventos de grupu';
$string['hidden'] = 'escondíu';
$string['ical'] = 'iCal';
$string['iwanttoexport'] = 'Esportar';
$string['manyevents'] = 'Eventos {$a}';
$string['mon'] = 'Llu';
$string['monday'] = 'Llunes';
$string['monthlyview'] = 'Eventu del mes';
$string['monthnext'] = 'Prósimu mes';
$string['monththis'] = 'Esti mes';
$string['newevent'] = 'Eventu nuevu';
$string['noupcomingevents'] = 'Nun hai eventos cercanos';
$string['oneevent'] = '1 eventu';
$string['preferences'] = 'Preferencies';
$string['preferences_available'] = 'Les sos preferencies personales.';
$string['pref_lookahead'] = 'Ver prósimos eventos';
$string['pref_maxevents'] = 'Cantidá máxima d\'eventos prósimos';
$string['pref_persistflt'] = 'Remembrar la configuración del filtru';
$string['pref_startwday'] = 'Primer día de la selmana.';
$string['pref_timeformat'] = 'Formatu de hora.';
$string['quickdownloadcalendar'] = 'Descargar / soscribir al calendariu.';
$string['recentupcoming'] = 'Días recientes y prósimos 60.';
$string['repeateditall'] = 'Aplicar modificaciones en tolos eventos {$a} d\'esta serie repetida.';
$string['repeateditthis'] = 'Aplicar modificaciones namás nesti eventu.';
$string['repeatnone'] = 'Ensin repeticiones';
$string['repeatweeksl'] = 'Repetir selmanalmente, creando en conxuntu.';
$string['repeatweeksr'] = 'eventos';
$string['sat'] = 'Sa';
$string['saturday'] = 'Sábadu';
$string['shown'] = 'amosáu';
$string['spanningevents'] = 'Eventos en procesu';
$string['sun'] = 'Do';
$string['sunday'] = 'Domingu';
$string['thu'] = 'Xu';
$string['thursday'] = 'Xueves';
$string['timeformat_12'] = '12 hores (am/pm)';
$string['timeformat_24'] = '24 hores';
$string['today'] = 'Güei';
$string['tomorrow'] = 'Mañana';
$string['tt_deleteevent'] = 'Esborrar eventu';
$string['tt_editevent'] = 'Editar eventu';
$string['tt_hidecourse'] = 'Eventos de cursu amosaos (calque pa esconder)';
$string['tt_hideglobal'] = 'Eventos globales amosaos (calque pa esconder)';
$string['tt_hidegroups'] = 'Eventos de grupu amosaos (calque pa esconder)';
$string['tt_hideuser'] = 'Eventos d\'usuariu amosaos (calque pa esconder)';
$string['tt_showcourse'] = 'Eventos de cursu escondíos (calque p\'amosar)';
$string['tt_showglobal'] = 'Eventos globales escondíos (calque p\'amosar)';
$string['tt_showgroups'] = 'Eventos de grupu escondíos (calque p\'amosar)';
$string['tt_showuser'] = 'Eventos d\'usuariu escondíos (calque p\'amosar)';
$string['tue'] = 'Ma';
$string['tuesday'] = 'Martes';
$string['typecourse'] = 'Eventu de cursu';
$string['typegroup'] = 'Eventu de grupu';
$string['typesite'] = 'Eventu de sitiu';
$string['typeuser'] = 'Eventu d\'usuariu';
$string['upcomingevents'] = 'Eventos cercanos.';
$string['urlforical'] = 'URL pa esportar a iCalendar, pa soscribir al calendariu.';
$string['user'] = 'Usuariu';
$string['userevent'] = 'Eventu d\'usuariu';
$string['userevents'] = 'Eventos d\'usuariu';
$string['wed'] = 'Mie';
$string['wednesday'] = 'Miércoles';
$string['weeknext'] = 'La selmana que vien.';
$string['weekthis'] = 'Esta semana.';
$string['yesterday'] = 'Ayer';
$string['youcandeleteallrepeats'] = 'Esti eventu ye parte d\'una serie d\'eventos repetíos. Pue esborrar namás esti eventu, o tolos eventos {$a} de la serie d\'una sola vez.';


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Rssdp.Infrastructure
{
	/// <summary>
	/// Parses a string into a <see cref="System.Net.Http.HttpResponseMessage"/> or throws an exception.
	/// </summary>
	public sealed class HttpResponseParser : HttpParserBase<System.Net.Http.HttpResponseMessage>
	{

		#region Fields & Constants

		private static readonly string[] ContentHeaderNames = new string[]
				{
					"Allow", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Expires", "Last-Modified"
				};

		#endregion

		#region Public Methods

		/// <summary>
		/// Parses the specified data into a <see cref="System.Net.Http.HttpResponseMessage"/> instance.
		/// </summary>
		/// <param name="data">A string containing the data to parse.</param>
		/// <returns>A <see cref="System.Net.Http.HttpResponseMessage"/> instance containing the parsed data.</returns>
		public override HttpResponseMessage Parse(string data)
		{
			System.Net.Http.HttpResponseMessage retVal = null;
			try
			{
				retVal = new System.Net.Http.HttpResponseMessage();

				retVal.Content = Parse(retVal, retVal.Headers, data);

				return retVal;
			}
			catch
			{
				if (retVal != null)
					retVal.Dispose();

				throw;
			}
		}

		#endregion

		#region Overrides Methods

		/// <summary>
		/// Returns a boolean indicating whether the specified HTTP header name represents a content header (true), or a message header (false).
		/// </summary>
		/// <param name="headerName">A string containing the name of the header to return the type of.</param>
		/// <returns>A boolean, true if th specified header relates to HTTP content, otherwise false.</returns>
		protected override bool IsContentHeader(string headerName)
		{
			return ContentHeaderNames.Contains(headerName, StringComparer.OrdinalIgnoreCase);
		}

		/// <summary>
		/// Used to parse the first line of an HTTP request or response and assign the values to the appropriate properties on the <paramref name="message"/>.
		/// </summary>
		/// <param name="data">The first line of the HTTP message to be parsed.</param>
		/// <param name="message">Either a <see cref="System.Net.Http.HttpResponseMessage"/> or <see cref="System.Net.Http.HttpRequestMessage"/> to assign the parsed values to.</param>
		protected override void ParseStatusLine(string data, HttpResponseMessage message)
		{
			if (data == null) throw new ArgumentNullException("data");
			if (message == null) throw new ArgumentNullException("message");

			var parts = data.Split(' ');
			if (parts.Length < 3) throw new ArgumentException("data status line is invalid. Insufficient status parts.", "data");

			message.Version = ParseHttpVersion(parts[0].Trim());

			int statusCode = -1;
			if (!Int32.TryParse(parts[1].Trim(), out statusCode))
				throw new ArgumentException("data status line is invalid. Status code is not a valid integer.", "data");

			message.StatusCode = (HttpStatusCode)statusCode;
			message.ReasonPhrase = parts[2].Trim();
		}

		#endregion

	}
}


text:
'use strict';

var arrayToSentence = require('array-to-sentence');
var mapAsync = require('map-async');
var oneTime = require('one-time');
var which = require('which');

function isNotString(item) {
  return typeof item !== 'string';
}

module.exports = function multiwhich(cmds, options, cb) {
  if (!Array.isArray(cmds)) {
    throw new TypeError(
      String(cmds) +
      ' is not an array. Expected an array of executable names'
    );
  }

  if (cb === undefined) {
    cb = options;
    options = {};
  }

  var nonStringValues = cmds.filter(isNotString);
  if (nonStringValues.length !== 0) {
    var isPrural = nonStringValues.length > 1;
    throw new TypeError(
      arrayToSentence(nonStringValues) +
      ' ' +
      (isPrural ? 'are' : 'is') +
      ' not ' +
      (isPrural ? 'strings' : 'a string') +
      '. Expected every item in the array is a string of executable name.'
    );
  }

  if (typeof cb !== 'function') {
    throw new TypeError(
      String(cb) +
      ' is not a function. Expected a callback function of multiwhich.'
    );
  }

  mapAsync(cmds, function iterator(cmd, index, done) {
    which(cmd, options, done);
  }, oneTime(cb));
};


text:
package com.mars.secure.rest.webapp.archetype.shiro.modules;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.authz.aop.AuthenticatedAnnotationMethodInterceptor;
import org.apache.shiro.authz.aop.GuestAnnotationMethodInterceptor;
import org.apache.shiro.authz.aop.PermissionAnnotationMethodInterceptor;
import org.apache.shiro.authz.aop.RoleAnnotationMethodInterceptor;
import org.apache.shiro.authz.aop.UserAnnotationMethodInterceptor;

import com.google.inject.AbstractModule;
import com.google.inject.matcher.Matchers;

public class ShiroAnnotationsModule extends AbstractModule{

	@Override
	protected void configure() {
		bindInterceptor(Matchers.any(), Matchers.annotatedWith(RequiresRoles.class),
                new ShiroMethodInterceptor(new RoleAnnotationMethodInterceptor()));
        bindInterceptor(Matchers.any(), Matchers.annotatedWith(RequiresUser.class),
                new ShiroMethodInterceptor(new UserAnnotationMethodInterceptor()));
        bindInterceptor(Matchers.any(), Matchers.annotatedWith(RequiresPermissions.class),
                new ShiroMethodInterceptor(new PermissionAnnotationMethodInterceptor()));
        bindInterceptor(Matchers.any(), Matchers.annotatedWith(RequiresGuest.class),
                new ShiroMethodInterceptor(new GuestAnnotationMethodInterceptor()));
        bindInterceptor(Matchers.any(), Matchers.annotatedWith(RequiresAuthentication.class),
                new ShiroMethodInterceptor(new AuthenticatedAnnotationMethodInterceptor()));
	}

}


text:
<!doctype html>

    <title>Lunch Checker</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles/bootstrap.min.css">

Lunch Checker

             <input id="lunch-menu" type="text" ng-model="menu"
             placeholder="list comma separated dishes you usually have for lunch"
             class="form-control">

             <button class="btn btn-default" ng-click="checkLunch();">Check If Too Much</button>

           {{message}}


text:
package pages;

import Utils.VerifyUtils;
import org.openqa.selenium.By;

/**
 * Created by shop on 15/09/2015.
 */
public class MensSectionPage extends BasePage {

    public void MenssectionpageOpened(){
        VerifyUtils.True("Men",driver.findElement(By.cssSelector("h1.category_title")).isDisplayed());
    }
}


text:
[![Code Climate](https://codeclimate.com/github/bc-maia/projeto-final-una/badges/gpa.svg)](https://codeclimate.com/github/bc-maia/projeto-final-una)
## Desenvolvimento de Software - UNA - Projeto Final
___

### Professor
>Roberto Oliveira

### Aluno
>B. Maia

### Curso
>Análise e Desenvolvimento de Sistemas

### Metas do Projeto
- Desenvolvimento de uma aplicação Web MVC orientada aos patterns de BDD & TDD

- Planejamento de Testing e BugTracking

- Implementação de testes unitários e funcionais

- Análise estática de código

### Natureza do produto final
>Software

### Último Update
>25-Maio-2016 (Douglas Adams approves this!)

### Web-Workspace & Container
>https://projeto-una-ror-bcmaia.c9users.io

___

Para executar o projeto você deverá:
--------------------------------------

1. Executar a gem bundle e instalar dependências do projeto

   `bundle install`

2. Migrar o banco de dados

   `rake db:migrate`

3. Iniciar o servidor

   `rails server`


text:
package org.example.domain;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * Customer entity bean.
 */
@Entity
@Table(name="be_customer")
public class Customer extends BaseModel {

  /**
   * Convenience Finder for 'active record' style.
   */
  public static final Finder<Long,Customer> find = new Finder<>(Long.class, Customer.class);

  boolean inactive;

  @Column(length=100)
  String name;

  LocalDate registered;

  @Column(length=1000)
  String comments;

  @ManyToOne(cascade=CascadeType.ALL)
  Address billingAddress;

  @ManyToOne(cascade=CascadeType.ALL)
  Address shippingAddress;

  @OneToMany(mappedBy="customer", cascade=CascadeType.PERSIST)
  List<Contact> contacts;

  public boolean isInactive() {
    return inactive;
  }

  public void setInactive(boolean inactive) {
    this.inactive = inactive;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public LocalDate getRegistered() {
    return registered;
  }

  public void setRegistered(LocalDate registered) {
    this.registered = registered;
  }

  public String getComments() {
    return comments;
  }

  public void setComments(String comments) {
    this.comments = comments;
  }

  public Address getBillingAddress() {
    return billingAddress;
  }

  public void setBillingAddress(Address billingAddress) {
    this.billingAddress = billingAddress;
  }

  public Address getShippingAddress() {
    return shippingAddress;
  }

  public void setShippingAddress(Address shippingAddress) {
    this.shippingAddress = shippingAddress;
  }

  public List<Contact> getContacts() {
    return contacts;
  }

  public void setContacts(List<Contact> contacts) {
    this.contacts = contacts;
  }

  /**
   * Helper method to add a contact to the customer.
   */
  public void addContact(Contact contact) {
    if (contacts == null) {
      contacts = new ArrayList<>();
    }
    // setting the customer is automatically done when Ebean does
    // a cascade save from customer to contacts.
    contact.setCustomer(this);
    contacts.add(contact);
  }

}


text:
Some utility script.

* createdemo.sh create all VMs for my typical demos
* destroydemo.sh destroys all VMs for my typical demos


text:
package java8professional.chapter08.streams;

import java.io.*;

public class ByteStreamsAndCharacterStreams {

    // abstract ones
    InputStream inputStream;
    OutputStream outputStream;
    Reader reader;
    Writer writer;

    // low-level
    FileInputStream fileInputStream;
    FileOutputStream fileOutputStream;
    FileReader fileReader;
    FileWriter fileWriter;

    // high-level
    BufferedInputStream bufferedInputStream;
    BufferedOutputStream bufferedOutputStream;
    BufferedReader bufferedReader;
    BufferedWriter bufferedWriter;

    // serialize and deserialize objects
    ObjectInputStream objectInputStream;
    ObjectOutputStream objectOutputStream;

    // read characters from an input stream
    InputStreamReader inputStreamReader;
    OutputStreamWriter outputStreamWriter;

    // write characters to an output stream
    PrintStream printStream;
    PrintWriter printWriter;

}


text:
package de.jpaw.bonaparte.hazelcast;

import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.jpaw.bonaparte.core.BonaPortable;
import de.jpaw.bonaparte.core.BonaPortableClass;
import de.jpaw.xenums.init.ReflectionsPackageCache;

public abstract class AbstractScanner<T extends BonaPortable> {
    protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractScanner.class);

    abstract void addBClass(BonaPortableClass<T> bclass);

    protected void scanPackage(String packageName, Class<T> interfaceType) {
        scanPackage(interfaceType, ReflectionsPackageCache.get(packageName));
    }

    public void scanPackage(Class<T> interfaceType, Reflections ... reflections) {
        for (int i = 0; i < reflections.length; ++i) {
            for (Class<? extends T> cls : reflections[i].getSubTypesOf(interfaceType)) {
                try {
                    BonaPortableClass<T> bclass = (BonaPortableClass<T>) cls.getMethod("class$BonaPortableClass").invoke(null);
                    if (bclass.getFactoryId() != 0 && bclass.getId() != 0)
                        addBClass(bclass);
                } catch (Exception e) {
                    LOGGER.warn("Cannot obtain BonaPortableClass for {}: {}", cls.getCanonicalName(), e.getMessage());
                }
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>

CSS Class

		text text text text text text text text text
		text text text text text text text text text
		text text text text text text text text text
		text text text text text text text text text


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.addthis.hydra.minion;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import java.util.Collections;
import java.util.Optional;
import java.util.stream.Stream;

import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;

import com.addthis.basis.util.LessBytes;

import com.addthis.maljson.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class LogUtils {
    private static final Logger log = LoggerFactory.getLogger(LogUtils.class);

    /** Streams task log files from newest to oldest. The returned Stream should be closed. */
    public static Stream<Path> streamTaskLogsByName(JobTask task) throws IOException {
        Path logDir = task.logDir.toPath();
        return Files.list(logDir)
                    .filter(path -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS))
                    .sorted(Collections.reverseOrder());
    }

    public static Optional<Path> getNthNewestLog(JobTask task, int runsAgo, String suffix) throws IOException {
        // short circuit for the most common case
        if (runsAgo == 0) {
            if ("err".equals(suffix)) {
                return Optional.of(task.logErr.toPath());
            } else if ("out".equals(suffix)) {
                return Optional.of(task.logOut.toPath());
            }
        }
        try (Stream<Path> paths = streamTaskLogsByName(task)
                .filter(path -> path.toString().endsWith(suffix))
                .skip(runsAgo)) {
            return paths.findFirst();
        }
    }

    public static JSONObject readLogLines(JobTask task, int startOffset, int lines, int runsAgo, String suffix) {
        try {
            Optional<Path> logFile = getNthNewestLog(task, runsAgo, suffix);
            if (!logFile.isPresent()) {
                log.info("no log file found for task {}, {} runs ago, with suffix {}", task, runsAgo, suffix);
                return new JSONObject();
            }
            return readLogLines(logFile.get().toFile(), startOffset, lines);
        } catch (Exception ex) {
            log.warn("exception while trying to serve task logs via http", ex);
            return new JSONObject();
        }
    }

    public static JSONObject readLogLines(File file, int startOffset, int lines) {
        JSONObject json = new JSONObject();
        String content = "";
        long off = 0;
        long endOffset = 0;
        int linesRead = 0;
        int bytesRead = 0;
        try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
            long len = raf.length();
            //if startoffset is negative, tail the content
            if (startOffset < 0 || startOffset > len) {
                off = len;
                while (lines > 0 && --off >= 0) {
                    raf.seek(off);
                    if (off == 0 || raf.read() == '\n') {
                        lines--;
                        linesRead++;
                    }
                }
                bytesRead = (int) (len - off);
                byte[] buf = new byte[bytesRead];
                raf.read(buf);
                content = LessBytes.toString(buf);
                endOffset = len;
            } else if (len > 0 && startOffset < len) {
                off = startOffset;
                while (lines > 0 && off < len) {
                    raf.seek(off++);
                    if (raf.read() == '\n') {
                        lines--;
                        linesRead++;
                    }
                }
                bytesRead = (int) (off - startOffset);
                byte[] buf = new byte[bytesRead];
                raf.seek(startOffset);
                raf.read(buf);
                content = LessBytes.toString(buf);
                endOffset = off;
            } else if (startOffset == len) {
                endOffset = len;
                linesRead = 0;
                content = "";
            }
            json.put("offset", endOffset);
            json.put("lines", linesRead);
            json.put("lastModified", file.lastModified());
            json.put("out", content);
        } catch (Exception e) {
            log.warn("", e);
        }
        return json;
    }

    public static String tail(File file, int lines) {
        try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
            long len = raf.length();
            if (len <= 0) {
                return "";
            }
            long off = len;
            while (lines > 0 && --off >= 0) {
                raf.seek(off);
                if (off == 0 || raf.read() == '\n') {
                    lines--;
                }
            }
            byte[] buf = new byte[(int) (len - off)];
            raf.read(buf);
            return LessBytes.toString(buf);
        } catch (Exception e) {
            log.warn("", e);
        }
        return "";
    }

    public static String head(File file, int lines) {
        try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
            long len = raf.length();
            if (len <= 0) {
                return "";
            }
            long off = 0;
            while (lines > 0 && off < len) {
                raf.seek(off++);
                if (raf.read() == '\n') {
                    lines--;
                }
            }
            byte[] buf = new byte[(int) off];
            raf.seek(0);
            raf.read(buf);
            return LessBytes.toString(buf);
        } catch (Exception e) {
            log.warn("", e);
        }
        return "";
    }

    private LogUtils() {}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />

    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
    />
    <meta
      name="description"
      content="Sample photogrammetry and classification datasets both rendered with 3D Tiles."
    />
    <meta name="cesium-sandcastle-labels" content="Showcases, 3D Tiles" />
    <title>Cesium Demo</title>

Loading...


text:
layout: post
title: 2º Hackathon Campinas - 8/Jul/17

---

<iframe width="560" height="315" src="https://www.youtube.com/embed/7Am4Oy739qY?rel=0" frameborder="0" allowfullscreen></iframe>

https://hackathon.ima.sp.gov.br/


text:
require "active_support/core_ext/hash/except"
require "active_support/core_ext/module/introspection"
require "active_support/core_ext/module/redefine_method"
require "active_support/core_ext/module/delegation"

module ActiveModel
  class Name
    include Comparable

    attr_accessor :singular, :plural, :element, :collection,
      :singular_route_key, :route_key, :param_key, :i18n_key,
      :name

    alias_method :cache_key, :collection

    ##
    # :method: ==
    #
    # :call-seq:
    #   ==(other)
    #
    # Equivalent to <tt>String#==</tt>. Returns +true+ if the class name and
    # +other+ are equal, otherwise +false+.
    #
    #   class BlogPost
    #     extend ActiveModel::Naming
    #   end
    #
    #   BlogPost.model_name == 'BlogPost'  # => true
    #   BlogPost.model_name == 'Blog Post' # => false

    ##
    # :method: ===
    #
    # :call-seq:
    #   ===(other)
    #
    # Equivalent to <tt>#==</tt>.
    #
    #   class BlogPost
    #     extend ActiveModel::Naming
    #   end
    #
    #   BlogPost.model_name === 'BlogPost'  # => true
    #   BlogPost.model_name === 'Blog Post' # => false

    ##
    # :method: <=>
    #
    # :call-seq:
    #   <=>(other)
    #
    # Equivalent to <tt>String#<=></tt>.
    #
    #   class BlogPost
    #     extend ActiveModel::Naming
    #   end
    #
    #   BlogPost.model_name <=> 'BlogPost'  # => 0
    #   BlogPost.model_name <=> 'Blog'      # => 1
    #   BlogPost.model_name <=> 'BlogPosts' # => -1

    ##
    # :method: =~
    #
    # :call-seq:
    #   =~(regexp)
    #
    # Equivalent to <tt>String#=~</tt>. Match the class name against the given
    # regexp. Returns the position where the match starts or +nil+ if there is
    # no match.
    #
    #   class BlogPost
    #     extend ActiveModel::Naming
    #   end
    #
    #   BlogPost.model_name =~ /Post/ # => 4
    #   BlogPost.model_name =~ /\d/   # => nil

    ##
    # :method: !~
    #
    # :call-seq:
    #   !~(regexp)
    #
    # Equivalent to <tt>String#!~</tt>. Match the class name against the given
    # regexp. Returns +true+ if there is no match, otherwise +false+.
    #
    #   class BlogPost
    #     extend ActiveModel::Naming
    #   end
    #
    #   BlogPost.model_name !~ /Post/ # => false
    #   BlogPost.model_name !~ /\d/   # => true

    ##
    # :method: eql?
    #
    # :call-seq:
    #   eql?(other)
    #
    # Equivalent to <tt>String#eql?</tt>. Returns +true+ if the class name and
    # +other+ have the same length and content, otherwise +false+.
    #
    #   class BlogPost
    #     extend ActiveModel::Naming
    #   end
    #
    #   BlogPost.model_name.eql?('BlogPost')  # => true
    #   BlogPost.model_name.eql?('Blog Post') # => false

    ##
    # :method: match?
    #
    # :call-seq:
    #   match?(regexp)
    #
    # Equivalent to <tt>String#match?</tt>. Match the class name against the
    # given regexp. Returns +true+ if there is a match, otherwise +false+.
    #
    #   class BlogPost
    #     extend ActiveModel::Naming
    #   end
    #
    #   BlogPost.model_name.match?(/Post/) # => true
    #   BlogPost.model_name.match?(/\d/) # => false

    ##
    # :method: to_s
    #
    # :call-seq:
    #   to_s()
    #
    # Returns the class name.
    #
    #   class BlogPost
    #     extend ActiveModel::Naming
    #   end
    #
    #   BlogPost.model_name.to_s # => "BlogPost"

    ##
    # :method: to_str
    #
    # :call-seq:
    #   to_str()
    #
    # Equivalent to +to_s+.
    delegate :==, :===, :<=>, :=~, :"!~", :eql?, :match?, :to_s,
             :to_str, :as_json, to: :name

    # Returns a new ActiveModel::Name instance. By default, the +namespace+
    # and +name+ option will take the namespace and name of the given class
    # respectively.
    # Use +locale+ argument for singularize and pluralize model name.
    #
    #   module Foo
    #     class Bar
    #     end
    #   end
    #
    #   ActiveModel::Name.new(Foo::Bar).to_s
    #   # => "Foo::Bar"
    def initialize(klass, namespace = nil, name = nil, locale = :en)
      @name = name || klass.name

      raise ArgumentError, "Class name cannot be blank. You need to supply a name argument when anonymous class given" if @name.blank?

      @unnamespaced = @name.delete_prefix("#{namespace.name}::") if namespace
      @klass        = klass
      @singular     = _singularize(@name)
      @plural       = ActiveSupport::Inflector.pluralize(@singular, locale)
      @uncountable  = @plural == @singular
      @element      = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(@name))
      @human        = ActiveSupport::Inflector.humanize(@element)
      @collection   = ActiveSupport::Inflector.tableize(@name)
      @param_key    = (namespace ? _singularize(@unnamespaced) : @singular)
      @i18n_key     = @name.underscore.to_sym

      @route_key          = (namespace ? ActiveSupport::Inflector.pluralize(@param_key, locale) : @plural.dup)
      @singular_route_key = ActiveSupport::Inflector.singularize(@route_key, locale)
      @route_key << "_index" if @uncountable
    end

    # Transform the model name into a more human format, using I18n. By default,
    # it will underscore then humanize the class name.
    #
    #   class BlogPost
    #     extend ActiveModel::Naming
    #   end
    #
    #   BlogPost.model_name.human # => "Blog post"
    #
    # Specify +options+ with additional translating options.
    def human(options = {})
      return @human if i18n_keys.empty? || i18n_scope.empty?

      key, *defaults = i18n_keys
      defaults << options[:default] if options[:default]
      defaults << MISSING_TRANSLATION

      translation = I18n.translate(key, scope: i18n_scope, count: 1, **options, default: defaults)
      translation = @human if translation == MISSING_TRANSLATION
      translation
    end

    def uncountable?
      @uncountable
    end

    private
      MISSING_TRANSLATION = -(2**60) # :nodoc:

      def _singularize(string)
        ActiveSupport::Inflector.underscore(string).tr("/", "_")
      end

      def i18n_keys
        @i18n_keys ||= if @klass.respond_to?(:lookup_ancestors)
          @klass.lookup_ancestors.map { |klass| klass.model_name.i18n_key }
        else
          []
        end
      end

      def i18n_scope
        @i18n_scope ||= @klass.respond_to?(:i18n_scope) ? [@klass.i18n_scope, :models] : []
      end
  end

  # == Active \Model \Naming
  #
  # Creates a +model_name+ method on your object.
  #
  # To implement, just extend ActiveModel::Naming in your object:
  #
  #   class BookCover
  #     extend ActiveModel::Naming
  #   end
  #
  #   BookCover.model_name.name   # => "BookCover"
  #   BookCover.model_name.human  # => "Book cover"
  #
  #   BookCover.model_name.i18n_key              # => :book_cover
  #   BookModule::BookCover.model_name.i18n_key  # => :"book_module/book_cover"
  #
  # Providing the functionality that ActiveModel::Naming provides in your object
  # is required to pass the \Active \Model Lint test. So either extending the
  # provided method below, or rolling your own is required.
  module Naming
    def self.extended(base) # :nodoc:
      base.silence_redefinition_of_method :model_name
      base.delegate :model_name, to: :class
    end

    # Returns an ActiveModel::Name object for module. It can be
    # used to retrieve all kinds of naming-related information
    # (See ActiveModel::Name for more information).
    #
    #   class Person
    #     extend ActiveModel::Naming
    #   end
    #
    #   Person.model_name.name     # => "Person"
    #   Person.model_name.class    # => ActiveModel::Name
    #   Person.model_name.singular # => "person"
    #   Person.model_name.plural   # => "people"
    def model_name
      @_model_name ||= begin
        namespace = module_parents.detect do |n|
          n.respond_to?(:use_relative_model_naming?) && n.use_relative_model_naming?
        end
        ActiveModel::Name.new(self, namespace)
      end
    end

    # Returns the plural class name of a record or class.
    #
    #   ActiveModel::Naming.plural(post)             # => "posts"
    #   ActiveModel::Naming.plural(Highrise::Person) # => "highrise_people"
    def self.plural(record_or_class)
      model_name_from_record_or_class(record_or_class).plural
    end

    # Returns the singular class name of a record or class.
    #
    #   ActiveModel::Naming.singular(post)             # => "post"
    #   ActiveModel::Naming.singular(Highrise::Person) # => "highrise_person"
    def self.singular(record_or_class)
      model_name_from_record_or_class(record_or_class).singular
    end

    # Identifies whether the class name of a record or class is uncountable.
    #
    #   ActiveModel::Naming.uncountable?(Sheep) # => true
    #   ActiveModel::Naming.uncountable?(Post)  # => false
    def self.uncountable?(record_or_class)
      model_name_from_record_or_class(record_or_class).uncountable?
    end

    # Returns string to use while generating route names. It differs for
    # namespaced models regarding whether it's inside isolated engine.
    #
    #   # For isolated engine:
    #   ActiveModel::Naming.singular_route_key(Blog::Post) # => "post"
    #
    #   # For shared engine:
    #   ActiveModel::Naming.singular_route_key(Blog::Post) # => "blog_post"
    def self.singular_route_key(record_or_class)
      model_name_from_record_or_class(record_or_class).singular_route_key
    end

    # Returns string to use while generating route names. It differs for
    # namespaced models regarding whether it's inside isolated engine.
    #
    #   # For isolated engine:
    #   ActiveModel::Naming.route_key(Blog::Post) # => "posts"
    #
    #   # For shared engine:
    #   ActiveModel::Naming.route_key(Blog::Post) # => "blog_posts"
    #
    # The route key also considers if the noun is uncountable and, in
    # such cases, automatically appends _index.
    def self.route_key(record_or_class)
      model_name_from_record_or_class(record_or_class).route_key
    end

    # Returns string to use for params names. It differs for
    # namespaced models regarding whether it's inside isolated engine.
    #
    #   # For isolated engine:
    #   ActiveModel::Naming.param_key(Blog::Post) # => "post"
    #
    #   # For shared engine:
    #   ActiveModel::Naming.param_key(Blog::Post) # => "blog_post"
    def self.param_key(record_or_class)
      model_name_from_record_or_class(record_or_class).param_key
    end

    def self.model_name_from_record_or_class(record_or_class) # :nodoc:
      if record_or_class.respond_to?(:to_model)
        record_or_class.to_model.model_name
      else
        record_or_class.model_name
      end
    end
    private_class_method :model_name_from_record_or_class
  end
end


text:
var page = (function() {

  function update() {
    var body = helper.e("body");
    var modal = (body.dataset.modal == "true");
    var prompt = (body.dataset.prompt == "true");
    var menu = (body.dataset.menuOpen == "true");
    var select = (body.dataset.characterSelectOpen == "true");
    if (modal || prompt || menu || select) {
      helper.addClass(body, "is-scrolll-disabled");
    } else {
      helper.removeClass(body, "is-scrolll-disabled");
    };
  };

  function lock() {
    var body = helper.e("body");
    helper.addClass(body, "is-scrolll-disabled");
  };

  function unlock() {
    var body = helper.e("body");
    helper.removeClass(body, "is-scrolll-disabled");
  };

  // exposed methods
  return {
    lock: lock,
    unlock: unlock,
    update: update
  };

})();


text:
'use strict';

/**
 * The Operations Management Suite (OMS) status response
 *
 */
class ClusterMonitoringResponse {
  /**
   * Create a ClusterMonitoringResponse.
   * @property {boolean} [clusterMonitoringEnabled] The status of the
   * Operations Management Suite (OMS) on the HDInsight cluster.
   * @property {string} [workspaceId] The workspace ID of the Operations
   * Management Suite (OMS) on the HDInsight cluster.
   */
  constructor() {
  }

  /**
   * Defines the metadata of ClusterMonitoringResponse
   *
   * @returns {object} metadata of ClusterMonitoringResponse
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ClusterMonitoringResponse',
      type: {
        name: 'Composite',
        className: 'ClusterMonitoringResponse',
        modelProperties: {
          clusterMonitoringEnabled: {
            required: false,
            serializedName: 'clusterMonitoringEnabled',
            type: {
              name: 'Boolean'
            }
          },
          workspaceId: {
            required: false,
            serializedName: 'workspaceId',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ClusterMonitoringResponse;


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import 'bootstrap/dist/css/bootstrap.css';
import 'c3/c3.css';

import '../styles/styles.scss';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthModule } from './auth/auth.module';
import { BlogModule } from './blog/blog.module';
import { CalendarModule } from './calendar/calendar.module';
import { ChartModule } from './chart/chart.module';
import { CodemirrorModule } from './codemirror/codemirror.module';
import { CoreModule } from './core/core.module';
import { DashboardModule } from './dashboard/dashboard.module';
import { EditorModule } from './editor/editor.module';
import {
  FileUtilitiesModule,
} from './file-utilities/file-utilities.module';
import { FontModule } from './font/font.module';
import { FormModule } from './form/form.module';
import { GalleryModule } from './gallery/gallery.module';
import { GridModule } from './grid/grid.module';
import {
  InteractiveTimelineModule,
} from './interactive-timeline/interactive-timeline.module';
import { MailboxModule } from './mailbox/mailbox.module';
import { MapModule } from './map/map.module';
import { PanelModule } from './panel/panel.module';
import { PaymentModule } from './payment/payment.module';
import { SocialModule } from './social/social.module';
import {
  StaticTimelineModule,
} from './static-timeline/static-timeline.module';
import { TableModule } from './table/table.module';
import { UIElementModule } from './ui-element/ui-element.module';
import { UserViewModule } from './user-view/user-view.module';

@NgModule({
  imports: [
    BrowserModule,
    CoreModule,
    DashboardModule,
    MailboxModule,
    GalleryModule,
    SocialModule,
    BlogModule,
    PanelModule,
    ChartModule,
    CodemirrorModule,
    MapModule,
    EditorModule,
    UIElementModule,
    FormModule,
    TableModule,
    GridModule,
    CalendarModule,
    FontModule,
    PaymentModule,
    FileUtilitiesModule,
    InteractiveTimelineModule,
    StaticTimelineModule,
    AuthModule,
    UserViewModule,
    AppRoutingModule,
  ],

  declarations: [
    AppComponent,
  ],

  bootstrap: [
    AppComponent,
  ],
})
export class AppModule {
}


text:
package io.netty.handler.codec.socks;

import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;

public class SocksAuthResponseDecoderTest {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksAuthResponseDecoderTest.class);

    private static void testSocksAuthResponseDecoderWithDifferentParams(SocksAuthStatus authStatus) {
        logger.debug("Testing SocksAuthResponseDecoder with authStatus: " + authStatus);
        SocksAuthResponse msg = new SocksAuthResponse(authStatus);
        SocksAuthResponseDecoder decoder = new SocksAuthResponseDecoder();
        EmbeddedChannel embedder = new EmbeddedChannel(decoder);
        SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
        msg = embedder.readInbound();
        assertSame(msg.authStatus(), authStatus);
        assertNull(embedder.readInbound());
    }

    @Test
    public void testSocksCmdResponseDecoder() {
        for (SocksAuthStatus authStatus: SocksAuthStatus.values()) {
            testSocksAuthResponseDecoderWithDifferentParams(authStatus);
        }
    }
}