text:
"""
Tests for Bolt and BatchingBolt classes
"""

from __future__ import absolute_import, print_function, unicode_literals

import itertools
import json
import logging
import time
import unittest
from io import BytesIO, StringIO

try:
    from unittest import mock
    from unittest.mock import patch
except ImportError:
    import mock
    from mock import patch

from six.moves import range

from streamparse.storm import BatchingBolt, Bolt, Component, Tuple

log = logging.getLogger(__name__)

class BoltTests(unittest.TestCase):

    def setUp(self):
        self.tup_dict = {'id': 14,
                         'comp': 'some_spout',
                         'stream': 'default',
                         'task': 'some_bolt',
                         'tuple': [1, 2, 3]}
        tup_json = "{}\nend\n".format(json.dumps(self.tup_dict))
        self.tup = Tuple(self.tup_dict['id'], self.tup_dict['comp'],
                         self.tup_dict['stream'], self.tup_dict['task'],
                         self.tup_dict['tuple'],)
        self.bolt = Bolt(input_stream=StringIO(tup_json),
                         output_stream=BytesIO())
        self.bolt.initialize({}, {})

    @patch.object(Bolt, 'send_message', autospec=True)
    def test_emit(self, send_message_mock):
        # A basic emit
        self.bolt.emit([1, 2, 3], need_task_ids=False)
        send_message_mock.assert_called_with(self.bolt, {'command': 'emit',
                                                         'anchors': [],
                                                         'tuple': [1, 2, 3],
                                                         'need_task_ids': False})

        # Emit with stream and anchors
        self.bolt.emit([1, 2, 3], stream='foo', anchors=[4, 5],
                       need_task_ids=False)
        send_message_mock.assert_called_with(self.bolt, {'command': 'emit',
                                                         'stream': 'foo',
                                                         'anchors': [4, 5],
                                                         'tuple': [1, 2, 3],
                                                         'need_task_ids': False})

        # Emit as a direct task
        self.bolt.emit([1, 2, 3], direct_task='other_bolt')
        send_message_mock.assert_called_with(self.bolt, {'command': 'emit',
                                                         'anchors': [],
                                                         'tuple': [1, 2, 3],
                                                         'task': 'other_bolt'})

    @patch.object(Bolt, 'send_message', autospec=True)
    def test_ack(self, send_message_mock):
        # ack an ID
        self.bolt.ack(42)
        send_message_mock.assert_called_with(self.bolt, {'command': 'ack',
                                                         'id': 42})

        # ack a Tuple
        self.bolt.ack(self.tup)
        send_message_mock.assert_called_with(self.bolt, {'command': 'ack',
                                                         'id': 14})

    @patch.object(Bolt, 'send_message', autospec=True)
    def test_fail(self, send_message_mock):
        # fail an ID
        self.bolt.fail(42)
        send_message_mock.assert_called_with(self.bolt, {'command': 'fail',
                                                         'id': 42})

        # fail a Tuple
        self.bolt.ack(self.tup)
        send_message_mock.assert_called_with(self.bolt, {'command': 'ack',
                                                         'id': 14})

    @patch.object(Bolt, 'process', autospec=True)
    @patch.object(Bolt, 'ack', autospec=True)
    def test_run(self, ack_mock, process_mock):
        self.bolt._run()
        process_mock.assert_called_with(self.bolt, self.tup)
        self.assertListEqual(self.bolt._current_tups, [])

    @patch.object(Bolt, 'process', autospec=True)
    @patch.object(Bolt, 'ack', autospec=True)
    def test_auto_ack_on(self, ack_mock, process_mock):
        # test auto-ack on (the default)
        self.bolt._run()
        ack_mock.assert_called_with(self.bolt, self.tup)

    @patch.object(Bolt, 'process', autospec=True)
    @patch.object(Bolt, 'ack', autospec=True)
    def test_auto_ack_off(self, ack_mock, process_mock):
        self.bolt.auto_ack = False
        self.bolt._run()
        # Assert that this wasn't called, and print out what it was called with
        # otherwise.
        self.assertListEqual(ack_mock.call_args_list, [])

    @patch.object(Bolt, 'send_message', autospec=True)
    def test_auto_anchor(self, send_message_mock):
        self.bolt._current_tups = [self.tup]
        # Test auto-anchor on (the default)
        self.bolt.emit([1, 2, 3], need_task_ids=False)
        send_message_mock.assert_called_with(self.bolt, {'command': 'emit',
                                                         'anchors': [14],
                                                         'tuple': [1, 2, 3],
                                                         'need_task_ids': False})

        # Test auto-anchor off
        self.bolt.auto_anchor = False
        self.bolt.emit([1, 2, 3], need_task_ids=False)
        send_message_mock.assert_called_with(self.bolt, {'command': 'emit',
                                                         'anchors': [],
                                                         'tuple': [1, 2, 3],
                                                         'need_task_ids': False})

        # Test overriding auto-anchor
        self.bolt.auto_anchor = True
        self.bolt.emit([1, 2, 3], anchors=[42], need_task_ids=False)
        send_message_mock.assert_called_with(self.bolt, {'command': 'emit',
                                                         'anchors': [42],
                                                         'tuple': [1, 2, 3],
                                                         'need_task_ids': False})

    @patch('sys.exit', new=lambda r: r)
    @patch.object(Bolt, 'read_handshake', new=lambda x: ({}, {}))
    @patch.object(Bolt, 'raise_exception', new=lambda *a: None)
    @patch.object(Bolt, 'fail', autospec=True)
    @patch.object(Bolt, '_run', autospec=True)
    def test_auto_fail_on(self, _run_mock, fail_mock):
        self.bolt._current_tups = [self.tup]
        # Make sure _run raises an exception
        def raiser(): # lambdas can't raise
            raise Exception('borkt')
        _run_mock.side_effect = raiser

        # test auto-fail on (the default)
        self.bolt.run()
        fail_mock.assert_called_with(self.bolt, self.tup)

    @patch('sys.exit', new=lambda r: r)
    @patch.object(Bolt, 'read_handshake', new=lambda x: ({}, {}))
    @patch.object(Bolt, 'raise_exception', new=lambda *a: None)
    @patch.object(Bolt, 'fail', autospec=True)
    @patch.object(Bolt, '_run', autospec=True)
    def test_auto_fail_off(self, _run_mock, fail_mock):
        self.bolt._current_tups = [self.tup]
        # Make sure _run raises an exception
        def raiser(): # lambdas can't raise
            raise Exception('borkt')
        _run_mock.side_effect = raiser

        # test auto-fail off
        self.bolt.auto_fail = False
        self.bolt.run()
        # Assert that this wasn't called, and print out what it was called with
        # otherwise.
        self.assertListEqual(fail_mock.call_args_list, [])

    @patch.object(Bolt, 'read_tuple', autospec=True)
    @patch.object(Bolt, 'send_message', autospec=True)
    def test_heartbeat_response(self, send_message_mock, read_tuple_mock):
        # Make sure we send sync for heartbeats
        read_tuple_mock.return_value = Tuple(id='foo', task=-1,
                                             stream='__heartbeat', values=[],
                                             component='__system')
        self.bolt._run()
        send_message_mock.assert_called_with(self.bolt, {'command': 'sync'})

    @patch.object(Bolt, 'read_tuple', autospec=True)
    @patch.object(Bolt, 'process_tick', autospec=True)
    def test_process_tick(self, process_tick_mock, read_tuple_mock):
        # Make sure we send sync for heartbeats
        read_tuple_mock.return_value = Tuple(id='foo', task=-1,
                                             component='__system',
                                             stream='__tick', values=[50])
        self.bolt._run()
        process_tick_mock.assert_called_with(self.bolt, 50)

class BatchingBoltTests(unittest.TestCase):

    def setUp(self):
        # mock seconds between batches to speed the tests up
        self._orig_secs = BatchingBolt.secs_between_batches

        BatchingBolt.secs_between_batches = 0.05

        self.tup_dicts = [{'id': 14,
                           'comp': 'some_spout',
                           'stream': 'default',
                           'task': 'some_bolt',
                           'tuple': [1, 2, 3]},
                          {'id': 15,
                           'comp': 'some_spout',
                           'stream': 'default',
                           'task': 'some_bolt',
                           'tuple': [4, 5, 6]},
                          {'id': 16,
                           'comp': 'some_spout',
                           'stream': 'default',
                           'task': 'some_bolt',
                           'tuple': [7, 8, 9]}]
        tups_json = '\nend\n'.join([json.dumps(tup_dict) for tup_dict in
                                    self.tup_dicts] + [''])
        self.tups = [Tuple(tup_dict['id'], tup_dict['comp'], tup_dict['stream'],
                           tup_dict['task'], tup_dict['tuple']) for tup_dict in
                     self.tup_dicts]
        self.bolt = BatchingBolt(input_stream=StringIO(tups_json),
                                 output_stream=BytesIO())
        self.bolt.initialize({}, {})

    def tearDown(self):
        # undo the mocking
        BatchingBolt.secs_between_batches = self._orig_secs

    @patch.object(BatchingBolt, 'process_batch', autospec=True)
    def test_batching(self, process_batch_mock):
        # Add a bunch of tuples
        for __ in range(3):
            self.bolt._run()

        # Wait a bit, and see if process_batch was called
        time.sleep(0.5)
        process_batch_mock.assert_called_with(self.bolt, None, self.tups[:3])

    @patch.object(BatchingBolt, 'process_batch', autospec=True)
    def test_group_key(self, process_batch_mock):
        # Change the group key to even/odd grouping
        self.bolt.group_key = lambda t: sum(t.values) % 2

        # Add a bunch of tuples
        for __ in range(3):
            self.bolt._run()

        # Wait a bit, and see if process_batch was called correctly
        time.sleep(0.5)
        process_batch_mock.assert_has_calls([mock.call(self.bolt, 0,
                                                       [self.tups[0],
                                                        self.tups[2]]),
                                             mock.call(self.bolt, 1,
                                                       [self.tups[1]])],
                                            any_order=True)

    def test_exception_handling(self):
        # Make sure the exception gets from the worker thread to the main
        with self.assertRaises(NotImplementedError):
            self.bolt._run()
            time.sleep(0.5)

    @patch.object(BatchingBolt, 'ack', autospec=True)
    @patch.object(BatchingBolt, 'process_batch', new=lambda *args: None)
    def test_auto_ack_on(self, ack_mock):
        # Test auto-ack on (the default)
        for __ in range(3):
            self.bolt._run()
        time.sleep(0.5)
        ack_mock.assert_has_calls([mock.call(self.bolt, self.tups[0]),
                                   mock.call(self.bolt, self.tups[1]),
                                   mock.call(self.bolt, self.tups[2])],
                                  any_order=True)

    @patch.object(BatchingBolt, 'ack', autospec=True)
    @patch.object(BatchingBolt, 'process_batch', new=lambda *args: None)
    def test_auto_ack_off(self, ack_mock):
        # Test auto-ack off
        self.bolt.auto_ack = False
        for __ in range(3):
            self.bolt._run()
        time.sleep(0.5)
        # Assert that this wasn't called, and print out what it was called with
        # otherwise.
        self.assertListEqual(ack_mock.call_args_list, [])

    @patch.object(BatchingBolt, '_handle_worker_exception', autospec=True)
    @patch.object(BatchingBolt, 'fail', autospec=True)
    def test_auto_fail_on(self, fail_mock, worker_exception_mock):
        # Need to re-register signal handler with mocked version, because
        # mock gets created after handler was originally registered.
        self.setUp()
        # Test auto-fail on (the default)
        for __ in range(3):
            self.bolt._run()
        time.sleep(0.5)

        # All waiting tuples should have failed at this point
        fail_mock.assert_has_calls([mock.call(self.bolt, self.tups[0]),
                                    mock.call(self.bolt, self.tups[1]),
                                    mock.call(self.bolt, self.tups[2])],
                                   any_order=True)
        self.assertEqual(worker_exception_mock.call_count, 1)

    @patch.object(BatchingBolt, '_handle_worker_exception', autospec=True)
    @patch.object(BatchingBolt, 'fail', autospec=True)
    def test_auto_fail_off(self, fail_mock, worker_exception_mock):
        # Need to re-register signal handler with mocked version, because
        # mock gets created after handler was originally registered.
        self.setUp()
        self.bolt.auto_fail = False
        for __ in range(3):
            self.bolt._run()
        time.sleep(0.5)
        # Assert that this wasn't called, and print out what it was called with
        # otherwise.
        self.assertListEqual(fail_mock.call_args_list, [])
        self.assertEqual(worker_exception_mock.call_count, 1)

    @patch.object(BatchingBolt, '_handle_worker_exception', autospec=True)
    @patch.object(BatchingBolt, 'process_batch', autospec=True)
    @patch.object(BatchingBolt, 'fail', autospec=True)
    def test_auto_fail_partial(self, fail_mock, process_batch_mock,
                               worker_exception_mock):
        # Need to re-register signal handler with mocked version, because
        # mock gets created after handler was originally registered.
        self.setUp()
        # Change the group key just be the sum of values, which makes 3 separate
        # batches
        self.bolt.group_key = lambda t: sum(t.values)
        # Make sure we fail on the second batch
        work = {'status': True} # to avoid scoping problems
        def work_once(*args):
            if work['status']:
                work['status'] = False
            else:
                raise Exception('borkt')
        process_batch_mock.side_effect = work_once
        # Run the batches
        for __ in range(3):
            self.bolt._run()
        time.sleep(0.5)
        # Only some tuples should have failed at this point. The key is that
        # all un-acked tuples should be failed, even for batches we haven't
        # started processing yet.
        self.assertEqual(fail_mock.call_count, 2)
        self.assertEqual(worker_exception_mock.call_count, 1)

    @patch.object(BatchingBolt, 'read_tuple', autospec=True)
    @patch.object(BatchingBolt, 'send_message', autospec=True)
    def test_heartbeat_response(self, send_message_mock, read_tuple_mock):
        # Make sure we send sync for heartbeats
        read_tuple_mock.return_value = Tuple(id='foo', task=-1,
                                             stream='__heartbeat', values=[],
                                             component='__system')
        self.bolt._run()
        send_message_mock.assert_called_with(self.bolt, {'command': 'sync'})

    @patch.object(BatchingBolt, 'read_tuple', autospec=True)
    @patch.object(BatchingBolt, 'process_tick', autospec=True)
    def test_process_tick(self, process_tick_mock, read_tuple_mock):
        # Make sure we send sync for heartbeats
        read_tuple_mock.return_value = Tuple(id='foo', task=-1,
                                             component='__system',
                                             stream='__tick', values=[50])
        self.bolt._run()
        process_tick_mock.assert_called_with(self.bolt, 50)

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


text:
package ee.cone.c4actor.dep

import ee.cone.c4actor.dep.ContextTypes.{ContextId, MockRoleOpt, RoleId, UserId}
import ee.cone.c4actor.dep.request.ByClassNameRequestProtocol.N_ByClassNameRequest
import ee.cone.c4actor.dep.request.ContextIdRequestProtocol.{N_ContextIdRequest, N_MockRoleRequest, N_RoleIdRequest, N_UserIdRequest}
import ee.cone.c4actor.dep_impl.DepHandlersApp

object ContextTypes {
  type ContextId = String
  type UserId = String
  type RoleId = String
  type MockRoleOpt = Option[(RoleId, Boolean)] // Id and if editable
}

trait CommonRequestUtilityFactory {
  def askByClassName[A](Class: Class[A], from: Int, to: Int): Dep[List[A]]

  def askContextId: Dep[ContextId]

  def askUserId: Dep[UserId]

  def askRoleId: Dep[RoleId]

  def askMockRole: Dep[MockRoleOpt]
}

case class CommonRequestUtilityFactoryImpl(
  depFactory: DepFactory,
  byClassNameAsk: DepAsk[N_ByClassNameRequest, List[_]],
  contextAsk: DepAsk[N_ContextIdRequest, ContextId],
  userAsk: DepAsk[N_UserIdRequest, ContextId],
  roleAsk: DepAsk[N_RoleIdRequest, ContextId],
  mockRoleAsk: DepAsk[N_MockRoleRequest, MockRoleOpt]
) extends CommonRequestUtilityFactory {
  def askByClassName[A](aCl: Class[A], from: Int = -1, to: Int = -1): Dep[List[A]] =
    byClassNameAsk.ask(N_ByClassNameRequest(aCl.getName, from, to)).map(_.asInstanceOf[List[A]])

  def askContextId: Dep[ContextId] =
    contextAsk.ask(N_ContextIdRequest())

  def askUserId: Dep[UserId] =
    userAsk.ask(N_UserIdRequest())

  def askRoleId: Dep[RoleId] =
    roleAsk.ask(N_RoleIdRequest())

  def askMockRole: Dep[MockRoleOpt] =
    mockRoleAsk.ask(N_MockRoleRequest())

}

trait CommonRequestUtilityApi {
  def commonRequestUtilityFactory: CommonRequestUtilityFactory
}

trait CommonRequestUtilityMix extends DepHandlersApp with DepFactoryApp {
  def depAskFactory: DepAskFactory

  override def depHandlers: List[DepHandler] = super.depHandlers

  private lazy val contextAsk: DepAsk[N_ContextIdRequest, ContextId] = depAskFactory.forClasses(classOf[N_ContextIdRequest], classOf[ContextId])

  private lazy val userAsk: DepAsk[N_UserIdRequest, UserId] = depAskFactory.forClasses(classOf[N_UserIdRequest], classOf[UserId])

  private lazy val roleAsk: DepAsk[N_RoleIdRequest, RoleId] = depAskFactory.forClasses(classOf[N_RoleIdRequest], classOf[RoleId])

  private lazy val byClassNameAsk: DepAsk[N_ByClassNameRequest, List[_]] = depAskFactory.forClasses(classOf[N_ByClassNameRequest], classOf[List[_]])

  private lazy val mockRoleAsk: DepAsk[N_MockRoleRequest, MockRoleOpt] = depAskFactory.forClasses(classOf[N_MockRoleRequest], classOf[MockRoleOpt])

  lazy val commonRequestUtilityFactory: CommonRequestUtilityFactory =
    CommonRequestUtilityFactoryImpl(depFactory, byClassNameAsk,
      contextAsk, userAsk, roleAsk, mockRoleAsk
    )
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.Migration.BusinessModel;
using Microsoft.TeamFoundation.Migration.Toolkit;

namespace Microsoft.TeamFoundation.Migration.Tfs2008WitAdapter
{
    public class TfsWITDiffProvider : IWITDiffProvider
    {
        private static string[] s_ignoredFieldNames = new string[]
        {
            "WorkItemID",
            "Revision",
            "ChangeDate",
            "System.CreatedDate",
            "System.History",
            "System.IterationID",
            "System.AreaID",
            "Microsoft.VSTS.Common.StateChangeDate",
            "Microsoft.VSTS.Common.ActivatedDate",
            "TfsMigrationTool.ReflectedWorkItemId"
        };

        private WorkItemStore m_workItemStore;
        private string m_projectName;
        private string m_filterString;
        private bool m_provideForContentComparison;
        private HashSet<string> m_ignoredFieldNames;
        private ILinkProvider m_linkProvider;

        /// <summary>
        /// Obtain references to services needed by this class
        /// </summary>
        public void InitializeServices(IServiceContainer witDiffServiceContainer)
        {
            m_linkProvider = witDiffServiceContainer.GetService(typeof(ILinkProvider)) as ILinkProvider;
        }

        /// <summary>
        /// Perform the adapter-specific initialization
        /// </summary>
        public virtual void InitializeClient(MigrationSource migrationSource)
        {
            TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(migrationSource.ServerUrl);
            tfs.Authenticate();

            m_workItemStore = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));

            m_projectName = migrationSource.SourceIdentifier;
        }

        #region IWITDiffProvider implementation

        /// <summary>
        /// The implementation can perform any one-time initialization here.
        /// Some adapter implementations may not need to perform any such initialization.
        /// It takes as optional arguments a filterString and a version that would be applied during subsequent queries.
        /// </summary>
        /// <param name="filterString">A string that specifies some filtering condition; if null or empty no additional filtering is applied</param>
        /// <param name="version">The version of the item; if null or empty, the tip version is accessed</param>
        /// <param name="provideForContentComparison">If true, any IDiffItem returned by any method should include the contents of the work item for comparison purposed.
        /// If false, detailed content data can be left out.
        /// </param>
        public void InitializeForDiff(string filterString, bool provideForContentComparison)
        {
            m_filterString = filterString;
            m_provideForContentComparison = provideForContentComparison;
        }

        /// <summary>
        /// Enumerate the diff items found based on the query passed in as well as the filterString and version passed
        /// to InitializeForDiff.  The return type is IEnumerable<> so that adapter implementations do not need download and keep
        /// all of the IWITDiffItems in memory at once.
        /// </summary>
        /// <param name="queryCondition">A string that specifies a query used to select a subset of the work items defined by
        /// the set that the filter string identified.</param>
        /// <returns>An enumeration of IWITDiffItems each representing a work item to be compared by the WIT Diff operation</returns>
        public IEnumerable<IWITDiffItem> GetWITDiffItems(string queryCondition)
        {
            string columnList = "[System.Id], [System.Rev]";

            StringBuilder conditionBuilder = new StringBuilder(m_filterString);

            if (!string.IsNullOrEmpty(queryCondition))
            {
                if (conditionBuilder.Length > 0)
                {
                    conditionBuilder.Append(" AND ");
                }
                conditionBuilder.Append(queryCondition);
            }

            string orderBy = "[System.Id]";
            string wiql = TfsWITQueryBuilder.BuildWiqlQuery(columnList, conditionBuilder.ToString(), orderBy);

            // Run query with date precision off
            Dictionary<string, object> context = new Dictionary<string, object>();
            context.Add("project", m_projectName);
            Query wiq = new Query(m_workItemStore, wiql, context, false);

            // Retrieve all results
            ICancelableAsyncResult car = wiq.BeginQuery();
            WorkItemCollection workItems = wiq.EndQuery(car);

            foreach(WorkItem workItem in workItems)
            {
                yield return (IWITDiffItem)new TfsWITDiffItem(this, workItem);
            }
        }

        /// <summary>
        /// Return a IWITDiffItem representing a single work item as identified by the adapter specific workItemId string
        /// </summary>
        /// <param name="workItemId"></param>
        /// <returns></returns>
        public IWITDiffItem GetWITDiffItem(string workItemId)
        {
            string queryCondition = String.Format(CultureInfo.InvariantCulture, "[System.Id] = {0}", workItemId);
            foreach (IWITDiffItem witDiffItem in GetWITDiffItems(queryCondition))
            {
                return witDiffItem;
            }
            return null;
        }

        /// <summary>
        /// IgnoreFieldInComparison is called to allow an adapter to specify that a named field should not be compared
        /// in the diff operation
        /// </summary>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public bool IgnoreFieldInComparison(string fieldName)
        {
            return IgnoredFieldNames.Contains(fieldName);
        }

        /// <summary>
        /// Give the IWITDiffProvider a chance to cleanup any reources allocated during InitializeForDiff()
        /// </summary>
        public void Cleanup()
        {
            m_filterString = null;
        }

        #endregion

        #region IServiceProvider implementation
        /// <summary>
        /// Gets the service object of the specified type.
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        public Object GetService(Type serviceType)
        {
            return this as IServiceProvider;
        }
        #endregion

        #region IDisposable members
        public void Dispose()
        {
        }
        #endregion

        #region internal properties
        internal ILinkProvider LinkProvider
        {
            get { return m_linkProvider; }
        }
        #endregion

        #region private properties
        private HashSet<string> IgnoredFieldNames
        {
            get
            {
                if (m_ignoredFieldNames == null)
                {
                    m_ignoredFieldNames = new HashSet<string>(TFStringComparer.WorkItemFieldReferenceName);
                    foreach (string fieldName in s_ignoredFieldNames)
                    {
                        m_ignoredFieldNames.Add(fieldName);
                    }
                }
                return m_ignoredFieldNames;
            }
        }
        #endregion
    }

}


text:
/**
\file  ctai_vector.h
\brief Utilities for working with CTA_Vector objects.
*/

#ifndef NL_VORTECH_CTAI_VECTOR_H
#define NL_VORTECH_CTAI_VECTOR_H

#ifdef __cplusplus
extern "C" {
#endif
/** \brief Count the number of handles with the given name in the vector (internal use only!)
 *
 * \param hvec   I  vector in which to search
 * \param name   I  name of handle(s) to find
 *
 * \return number of handles counted or -1 in case of an error.
 */
int CTAI_Vector_CountHandles(CTA_Vector hvec, const char* name);

/** \brief Find the handle with the given name (internal use only!)
 *
 *
 * \param hvec     I  vector in which to search
 * \param name     I  name of handle to find
 *
 * \return handle or CTA_NULL if not found or in case of an error
 */
CTA_Handle CTAI_Vector_FindHandle(CTA_Vector hvec, const char* name);

/** \brief Get vector value at index i as C string (internal use only!)
 *
 * \note Free pointer after use.
 *
 * \param hvec I  vector
 * \param i    I  index of value
 *
 * \return string representation of value at index i of vector
 */
const char *CTAI_Vector_GetStringVal(CTA_Vector hvec, int  i);

/** \brief Set vector value at index i giving a C string to be converted to given data type (internal use only!)
 *
 * \param hvec      IO handle of vector
 * \param i         I  index of value to set
 * \param val       I  string representation of value
 * \param datatype  I  data type of value
 *
 * \return CTA_OK if succesful or CTA_ILLEGAL_DATATYPE if invalid data type
 */
int CTAI_Vector_SetStringVal(CTA_Vector hvec, int  i, const char *val, CTA_Datatype datatype);

/** \brief Create a COSTA vector.
*
*  \param cur_node  I  Current XML node
*  \return             Handle to create or CTA_NULL in case of an error.
*/
CTA_Vector CTAI_XML_CreateVector(xmlNode *cur_node);

/** \brief Generate XML from one COSTA vector
*
*  \param hvec   I  handle of a COSTA vector
*  \param writer I  the XML text writer
*/
//void CTAI_XML_WriteVector(CTA_Vector hvec, xmlTextWriter *writer);
  void CTAI_XML_WriteVector(CTA_Vector hvec, const char *id, const char *caption, CTA_Metainfo minfo, int level, xmlTextWriter *writer);

/** \brief Create a COSTA vector from XML.
*
*  \param cur_node  I  Current XML node
*  \param minfo     I/O  Meta info object
*  \return             Handle to create or CTA_NULL in case of an error.
*/
CTA_Vector CTAI_XML_CreateVector_New(xmlNode *cur_node, CTA_Metainfo minfo);

#ifdef __cplusplus
}
#endif
#endif


text:
<?php

 require 'src/ClassroomPatchCourse.php';

 class ClassroomPatchCourseTest extends \PHPUnit\Framework\TestCase
 {
    public function testlistAllCourses()
    {
        $classroomResponse = patchCourse('531365683519');
        $this->assertNotNull($classroomResponse, "Not get any value from service");
    }
 }


text:
class QListWidget;

enum DataType {
    DT_INT8,
    DT_UINT8,
    DT_INT16,
    DT_UINT16,
    DT_INT32,
    DT_UINT32,
    DT_FLOAT,
    DT_DOUBLE,
};

class VertexDataInterpreter : public QObject
{
    Q_OBJECT
public:
    VertexDataInterpreter(QObject *parent=0);

    QByteArray data() const;

    int type() const;
    int stride() const;
    int components() const;
    int startingOffset() const;

    void setListWidget(QListWidget *listWidget);

public slots:
    void interpretData();

    void setData(const QByteArray &data);
    void setTypeFromString(const QString &str);
    void setStride(int stride);
    void setComponents(int num);
    void setType(int type);
    void setStartingOffset(int offset);

private:
    QListWidget *m_listWidget;
    QByteArray m_data;
    int m_type;
    int m_stride;
    int m_components;
    int m_startingOffset;
};

#endif


text:
#pragma once

#ifndef OPENCV_CUDEV_UTIL_TUPLE_HPP
#define OPENCV_CUDEV_UTIL_TUPLE_HPP

#include "../common.hpp"
#include "detail/tuple.hpp"

namespace cv { namespace cudev {

//! @addtogroup cudev
//! @{

using tuple_detail::tuple;
using tuple_detail::tuple_size;
using tuple_detail::get;
using tuple_detail::tuple_element;
using tuple_detail::make_tuple;
using tuple_detail::tie;

template <typename T> struct TupleTraits
{
    enum { is_tuple = 0 };
    enum { size = 1 };
};
template <typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9>
struct TupleTraits< tuple<P0, P1, P2, P3, P4, P5, P6, P7, P8, P9> >
{
    enum { is_tuple = 1 };
    enum { size = tuple_size< tuple<P0, P1, P2, P3, P4, P5, P6, P7, P8, P9> >::value };
};

template <class Tuple, template <typename T> class CvtOp> struct ConvertTuple
{
    typedef typename tuple_detail::ConvertTuple<Tuple, tuple_size<Tuple>::value, CvtOp>::type type;
};

//! @}

}}

#endif


text:
<?php

namespace AltThree\Feeder\Feeds;

/**
 * This is the atom feed class.
 *
 * @author James Brooks <james@alt-three.com>
 */
class AtomFeed extends AbstractFeed
{
    /**
     * The xml namespace.
     *
     * @var string
     */
    protected $xmlns = 'http://www.w3.org/2005/Atom';
}


text:
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // `load`, `deviceready`, `offline`, and `online`.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        document.getElementById('scan').addEventListener('click', this.scan, false);
        document.getElementById('encode').addEventListener('click', this.encode, false);
    },

    // deviceready Event Handler
    //
    // The scope of `this` is the event. In order to call the `receivedEvent`
    // function, we must explicity call `app.receivedEvent(...);`
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },

    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    },

    scan: function() {
        console.log('scanning');

        var scanner = cordova.require("cordova/plugin/BarcodeScanner");

        scanner.scan( function (result) {

            alert("We got a barcode\n" +
            "Result: " + result.text + "\n" +
            "Format: " + result.format + "\n" +
            "Cancelled: " + result.cancelled);

           console.log("Scanner result: \n" +
                "text: " + result.text + "\n" +
                "format: " + result.format + "\n" +
                "cancelled: " + result.cancelled + "\n");
            document.getElementById("info").innerHTML = result.text;
            console.log(result);
            /*
            if (args.format == "QR_CODE") {
                window.plugins.childBrowser.showWebPage(args.text, { showLocationBar: false });
            }
            */

        }, function (error) {
            console.log("Scanning failed: ", error);
        } );
    },

    encode: function() {
        var scanner = cordova.require("cordova/plugin/BarcodeScanner");

        scanner.encode(scanner.Encode.TEXT_TYPE, "http://www.nhl.com", function(success) {
            alert("encode success: " + success);
          }, function(fail) {
            alert("encoding failed: " + fail);
          }
        );

    }

};


text:
package krasa.importedMavenProjectRenamer;

import java.util.List;

import org.jetbrains.idea.maven.wizards.MavenProjectBuilder;

import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.*;

public class MyMavenProjectBuilder extends MavenProjectBuilder {

	private String parentName;
	private VirtualFile root;

	@Override
	public boolean setRootDirectory(Project projectToUpdate, String root) throws ConfigurationException {
		try {
			this.root = LocalFileSystem.getInstance().findFileByPath(root);
		} catch (Exception e) {
		}
		return super.setRootDirectory(projectToUpdate, root);
	}

	@Override
	public void setFiles(List<VirtualFile> files) {
		try {
			this.parentName = files.get(0).getParent().getName();
		} catch (Exception e) {
		}
		super.setFiles(files);
	}

	@Override
	public String getSuggestedProjectName() {
		if (parentName != null) {
			return parentName;
		} else if (root != null) {
			String name = root.getName();
			if (!name.contains("_") && root.getParent().getName().contains("_")) {
				name = root.getParent().getName();
			}
			return name;
		}
		return super.getSuggestedProjectName();
	}
}


text:
package org.kuali.kfs.module.purap.util;

import java.util.Comparator;

import org.kuali.kfs.sys.businessobject.AccountingLine;

public class PurapAccountingLineComparator implements Comparator<AccountingLine> {
    /**
     * Compares two accounting lines based on their account number and object code, in ascending order.
     * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
     */
    public int compare(AccountingLine sal1, AccountingLine sal2) {
        int compare = 0;
        if (sal1 != null && sal2 != null) {
            if (sal1.getAccountNumber() != null && sal2.getAccountNumber() != null) {
                compare = sal1.getAccountNumber().compareTo(sal2.getAccountNumber());
                if (compare == 0) {
                    if (sal1.getFinancialObjectCode() != null && sal2.getFinancialObjectCode() != null)
                        compare =  sal1.getFinancialObjectCode().compareTo(sal2.getFinancialObjectCode());
                }
            }
        }
        return compare;
    }
}


text:
'use strict';

var settings = require('./gulp-settings');

var userConfig = settings.getUserConfig();

var proxyDomain = userConfig.proxyDomain || 'http://localhost/temo';

module.exports = {

  // Task: connection
  connect: {
    path: ['src/app', 'src/modules'],
    port: 4000,
    options: {
      rewriteRules: [
        '^/temo/(.*)$ ' + proxyDomain + '/$1 [P]'
      ]
    }
  },

  // Task: build-index & watch-index
  index: {
    sources: ['src/app/index.html'],
    dest: '',
    options: {
      replace: {
        vendors: {
          src: settings.getContextPath('assets/js/vendors.min.js'),
          tpl: '<script src="%s"></script>'
        },
        scripts: {
          src: settings.getContextPath('assets/js/application.min.js'),
          tpl: '<script src="%s"></script>'
        },
        styles: {
          src: settings.getContextPath('assets/css/application.min.css'),
          tpl: '<link rel="stylesheet" href="%s">'
        },
        templates: {
          src: settings.getContextPath('assets/js/templates.min.js'),
          tpl: '<script src="%s"></script>'
        },
        vendorStyles: {
          src: settings.getContextPath('assets/css/vendors.min.css'),
          tpl: '<link rel="stylesheet" href="%s">'
        }
      },
      inject: {
        sources: [
          'src/modules/**/*.js'
        ]
      },
      htmlMin: {
        collapseWhitespace: true,
        maxLineLength: 200
      }
    }
  },

  styles: {
    sources: [
      'src/styles/variables.less',
      'src/styles/mixins.less',
      'src/styles/core.less',
      'src/styles/common/**/*.less',
      'src/modules/**/*.less'
    ],
    dest: 'assets/css',
    name: 'application.css',
    minify: 'application.min.css',
    options: {
      less: {
        paths: ['src']
      },
      miniCSS: {
        keepSpecialComments: 0,
        keepBreaks: true
      }
    }
  },

  scripts: {
    sources: [
      'src/modules/AppModule.js',
      'src/modules/**/*Value.js',
      'src/modules/**/*Const.js',
      'src/modules/**/*Object.js',
      'src/modules/**/*Provider.js',
      'src/modules/**/*Service.js',
      'src/modules/**/*Util.js',
      'src/modules/**/*Filter.js',
      'src/modules/**/*Widget.js',
      'src/modules/**/*Backend.js',
      'src/modules/**/*Controller.js',
      'src/modules/**/*Config.js',
      'src/modules/**/*Run.js'
    ],
    dest: 'assets/js',
    name: 'application.js',
    minify: 'application.min.js',
    options: {
      uglify: {
        preserveComments: 'all'
      },
      eslint: {
        rules: {
          eqeqeq: 2,
          quotes: [1, 'single'],
          'no-unused-vars': 1,
          'no-undef': 1,
          semi: [1, "always"]
        },
        globals: {
          angular: 1,
          jQuery: 0,
          $: 0
        },
        env: {
          browser: 1
        }
      }
    }
  },

  // Task **build-assets**
  assets: {
    sources: [
      'src/app/assets/**/*.*'
    ],
    dest: 'assets'
  },

  templates: {
    sources: [
      'src/modules/**/*.html'
    ],
    name: 'templates.js',
    minify: 'templates.min.js',
    dest: 'assets/js',
    options: {
      templates: {
        module: 'tsm',
        templateHeader: [
          '/*',
          ' * temperature-sensor-monitor (templates)',
          ' * NOTE: do not edit directly, this file will be created automatically!',
          ' */',
          '',
          '(function (angular) {',
          '  \'use strict\';',
          '',
          '  angular.module(\'<%= module %>\'<%= standalone %>).run([\'$templateCache\', function($templateCache) {',
          ''
        ].join('\n'),
        templateFooter: [
          '',
          '  }]);',
          '',
          '} (window.angular))',
          ''
        ].join('\n'),
        templateBody: '    $templateCache.put("<%= url %>","<%= contents %>");'
      },
      uglify: {
        preserveComments: 'all'
      }
    }
  },

  vendorScripts: {
    // always (only) include the minimized version!!
    sources: [
      'bower_components/jquery/dist/jquery.min.js',
      'bower_components/sprintf/src/sprintf.min.js',
      'bower_components/angular/angular.min.js',
      'bower_components/angular-animate/angular-animate.min.js',
      'bower_components/angular-ui-router/release/angular-ui-router.min.js',
      'bower_components/sprintf/src/angular-sprintf.min.js'
    ],
    dest: 'assets/js',
    name: 'vendors.min.js'
  },

  vendorStyles: {
    sources: [
      'bower_components/normalize-css/normalize.css',
      'bower_components/components-font-awesome/css/font-awesome.css',
//      'bower_components/bootstrap/dist/css/bootstrap.css',
      'bower_components/angular/angular-csp.css'
    ],
    dest: 'assets/css',
    name: 'vendors.css',
    minify: 'vendors.min.css',
    options: {
      miniCSS: {
        keepSpecialComments: 0,
        keepBreaks: true
      }
    }
  },
  vendorFonts: {
    sources: [
      'bower_components/bootstrap/fonts/**/*.*',
      'bower_components/components-font-awesome/fonts/**/*.*'
    ],
    dest: 'assets/fonts'
  }
};


text:
using System;
using PureMVC.Interfaces;
using PureMVC.Patterns;
using PureMVC.CSharp.Demos.Silverlight.WebService.Login.Silverlight.Model;
using PureMVC.CSharp.Demos.Silverlight.WebService.Login.Silverlight.Utils;
using PureMVC.CSharp.Demos.Silverlight.WebService.Login.Silverlight.View;

namespace PureMVC.CSharp.Demos.Silverlight.WebService.Login.Silverlight.Controller
{
    public class ApplicationStartupCommand : SimpleCommand
    {
        /// <summary>
        /// Fulfill the use-case initiated by the given <c>INotification</c>
        /// </summary>
        /// <param name="notification">The <c>INotification</c> to handle</param>
        /// <remarks>
        /// In the Command Pattern, an application use-case typically begins with some user action, which results in an <c>INotification</c> being broadcast, which is handled by business logic in the <c>execute</c> method of an <c>ICommand</c>
        /// </remarks>
        public override void Execute(INotification notification)
        {
            // Register proxies
            Facade.RegisterProxy(new ApplicationProxy());
            Facade.RegisterProxy(new LoginProxy());

            // Register application mediator
            Facade.RegisterMediator(new ApplicationMediator(notification.Body));

            // Initialize view
            SendNotification(Notifications.VIEW_STATE_CHANGE, ApplicationProxy.LOGIN_STATE);
        }
    }
}


text:
<?php

namespace Test\Synapse\Mapper;

use Synapse\Mapper as MapperNamepace;

class DatetimeColumnMapper extends MapperNamepace\AbstractMapper
{
    use MapperNamepace\InserterTrait;
    use MapperNamepace\UpdaterTrait;

    /**
     * {@inheritdoc}
     */
    protected $createdDatetimeColumn = 'created';

    /**
     * {@inheritdoc}
     */
    protected $updatedDatetimeColumn = 'updated';

    /**
     * {@inheritdoc}
     */
    protected $tableName = 'table_with_datetime_columns';
}


text:
package com.feeyo.redis.net.backend;

public interface TodoTask {

	public void execute(BackendConnection conn) throws Exception;
}


text:
// Copyright (C) 2015 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.google.gerrit.metrics.proc;

import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.metrics.MetricMaker;
import com.google.inject.Inject;

/** Guice module to configure metrics on server startup. */
public abstract class MetricModule extends LifecycleModule {
  /** Configure metrics during server startup. */
  protected abstract void configure(MetricMaker metrics);

  @Override
  protected void configure() {
    listener().toInstance(new LifecycleListener() {
      @Inject
      MetricMaker metrics;

      @Override
      public void start() {
        configure(metrics);
      }

      @Override
      public void stop() {
      }
    });
  }
}


text:
//
// StringExtensions.cs
//
// Author:
//       Ehouarn Perret <ehouarn.perret@outlook.com>
//
// Copyright (c) Ehouarn Perret
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using EhouarnPerret.CSharp.Utilities.Core.Collections.Generic;

namespace EhouarnPerret.CSharp.Utilities.Core
{
    public static class StringExtensions
    {
        public static void AppendToFile(this IEnumerable<string> source, string path)
        {
            File.AppendAllLines(path, source);
        }

        public static void WriteToFile(this IEnumerable<string> source, string path)
        {
            File.WriteAllLines(path, source);
        }

        public static void WriteToFile(this string value, string path)
        {
            File.WriteAllText(path, value);
        }

        public static void AppendToFile(this string value, string path)
        {
            File.AppendAllText(path, value);
        }

        public static string ReadTextFromFile(this string path)
        {
            return File.ReadAllText(path);
        }

        public static string ReadTextFromFile(this string path, Encoding encoding)
        {
            return File.ReadAllText(path, encoding);
        }

        public static IEnumerable<string> ReadLinesFromFile(this string path, Encoding encoding)
        {
            return File.ReadAllLines(path, encoding);
        }

        public static byte[] ReadBytesFromFile(this string path)
        {
            return File.ReadAllBytes(path);
        }

        public static ILookup<char, int> IndexesOf(this string value, params char[] characters)
        {
            var dictionary = characters.ToDictionary<char, char, IList<int>>(c => c, c => new List<int>());

            for (var i = 0; i < value.Length; i++)
            {
                var c = value[i];

                if (dictionary.ContainsKey(c))
                {
                    dictionary[c].Add(i);
                }
            }

            var lookup = dictionary.ToLookup();

            return lookup;
        }

        public static Regex ToRegex(this string value, RegexOptions regexOptions = RegexOptions.None)
        {
            var regex = new Regex(value, regexOptions);

            return regex;
        }

        public static byte[] ToBytes(this string value, Encoding encoding)
        {
            var bytes = encoding.GetBytes(value);

            return bytes;
        }

        public static SecureString ToSecureString(this string value)
        {
            var secureString = new SecureString();

            foreach (var c in value)
            {
                secureString.AppendChar(c);
            }

            return secureString;
        }

        public static sbyte ToSByte(this string value)
        {
            return sbyte.Parse(value);
        }
        public static sbyte? TryToSByte(this string value)
        {
            return sbyte.TryParse(value, out var result) ? result : default(sbyte?);
        }

        public static short ToInt16(this string value)
        {
            return short.Parse(value);
        }

        public static short? TryToInt16(this string value)
        {
            return short.TryParse(value, out var result) ? result : default(short?);
        }

        public static int ToInt32(this string value)
        {
            return int.Parse(value);
        }

        public static int? TryToInt32(this string value)
        {
            return int.TryParse(value, out var result) ? result : default(int?);
        }

        public static long ToInt64(this string value)
        {
            return long.Parse(value);
        }

        public static long? TryToInt64(this string value)
        {
            return long.TryParse(value, out var result) ? result : default(long?);
        }

        public static BigInteger ToBigInteger(this string value)
        {
            return BigInteger.Parse(value);
        }

        public static BigInteger? TryToBigInteger(this string value)
        {
            return BigInteger.TryParse(value, out var result) ? result :  default(BigInteger?);
        }

        public static byte ToByte(this string value)
        {
            return byte.Parse(value);
        }

        public static short ToUInt16(this string value)
        {
            return short.Parse(value);
        }

        public static uint ToUInt32(this string value)
        {
            return uint.Parse(value);
        }

        public static ulong ToUInt64 (this string value)
        {
            return ulong.Parse(value);
        }

        public static byte? TryToByte(this string value)
        {
            return byte.TryParse(value, out var result) ? result : default(byte?);
        }

        public static ushort? TryToUInt16(this string value)
        {
            return ushort.TryParse(value, out var result) ? result : default(ushort?);
        }

        public static uint? TryToUInt32(this string value)
        {
            return uint.TryParse(value, out var result) ? result : default(uint?);
        }

        public static ulong? TryToUInt64 (this string value)
        {
            return ulong.TryParse(value, out var result) ? result : default(ulong?);
        }

        public static float ToSingle(this string value)
        {
            return float.Parse(value);
        }

        public static float? TryToSingle(this string value)
        {
            return float.TryParse(value, out var result) ? result : default(float?);
        }

        public static double ToDouble(this string value)
        {
            return double.Parse(value);
        }

        public static double? TryToDouble(this string value)
        {
            return double.TryParse(value, out var result) ? result : default(double?);
        }

        public static decimal ToDecimal(this string value)
        {
            return decimal.Parse(value);
        }

        public static decimal? TryToDecimal(this string value)
        {
            return decimal.TryParse(value, out var result) ? result : default(decimal?);
        }

        private const int LatinAlphabetCharacterCount = 26;

        /// <summary>
        /// Determines if the specified value is a palindrom anagram.
        /// </summary>
        /// <returns><c>true</c> if  the specified value is a palindrom anagram; otherwise, <c>false</c>.</returns>
        /// <param name="value">Value.</param>
        public static bool IsPalindromAnagram(this string value)
        {
            var charactersCount = value.GroupBy(character => character, (character, characters)
                => new
                {
                    Character = character,
                    Count = characters.Count(),
                }
            );

            return charactersCount.Count(character => character.Count % 2 == 1) <= 1;
        }

        /// <summary>
        /// Determines if the specified value is a pangram.
        /// </summary>
        /// <returns><c>true</c> if the specified value is a pangram; otherwise, <c>false</c>.</returns>
        /// <param name="value">Value.</param>
        public static bool IsPangram(this string value)
        {
            return value.ToLower()
                .Where(char.IsLetter)
                .GroupBy(character => character)
                .Count() == LatinAlphabetCharacterCount;
        }

        /// <summary>
        /// Determines if  the specified value is a palindrome.
        /// </summary>
        /// <returns><c>true</c> if the specified value is a palindrome; otherwise, <c>false</c>.</returns>
        /// <param name="value">Value.</param>
        /// <param name="insensitiveCase">If set to <c>true</c> insensitive case.</param>
        public static bool IsPalindrome(this string value, bool insensitiveCase = true)
        {
            // Not sure the compiler is optimizing that sort of things
            value = insensitiveCase ? value.ToLower() : value;

            var letters = value.Where(char.IsLetter);
            var reversedLetters = value.Reverse().Where(char.IsLetter);

            return letters.SequenceEqual(reversedLetters);
        }

        /// <summary>
        /// Reverse the specified value.
        /// </summary>
        /// <param name="value">Value.</param>
        public static string Reverse(this string value)
        {
            var characters = value.ToCharArray();
            Array.Reverse(characters);
            return new string(characters);
        }

        // TODO: refactor it...
        public static IEnumerable<string> ToSubstrings(this string value)
        {
            for (var substringLength = 1; substringLength < value.Length; substringLength++)
            {
                for (var start = 0; start <= value.Length - substringLength; start++)
                {
                    yield return value.Substring(start, substringLength);
                }
            }
        }

        public static bool IsAnagramOf(this string value, string other)
        {
            return value.OrderBy(character => character).SequenceEqual(other.OrderBy(character => character));
        }

//        public static BigIntegerFraction ToBigIntegerFraction (this String value)
//        {
//            return BigIntegerFraction.Parse(value);
//        }

        public static string[] SplitLines(this string value, bool removeEmptyEntries = true)
        {
            var stringSplitOptions = removeEmptyEntries ?
                StringSplitOptions.RemoveEmptyEntries :
                StringSplitOptions.None;

            return value.Split(new [] { Environment.NewLine }, stringSplitOptions);
        }

        public static string[] SplitSpaces(this string value, bool removeEmptyEntries = true)
        {
            var stringSplitOptions = removeEmptyEntries ?
                StringSplitOptions.RemoveEmptyEntries :
                StringSplitOptions.None;

            return value.Split(new [] { ' ' } , stringSplitOptions);
        }

        public static string Join<T>(this string separator, IEnumerable<T> values)
        {
            return string.Join(separator, values);
        }

        public static bool IsNullOrEmpty(this string value)
        {
            return string.IsNullOrEmpty(value);
        }

        public static bool IsNullOrWhiteSpace(this string value)
        {
            return string.IsNullOrWhiteSpace(value);
        }

        public static string SplitCapitalsWithSpace(this string source, bool preserveAcronyms = true)
        {
            return source.SplitCapitalsWith(' ', preserveAcronyms);
        }

        public static string SplitCapitalsWith(this string source, char character, bool preserveAcronyms = true)
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                return source;
            }

            var result = new StringBuilder(source.Length * 2);
            result.Append(source[0]);

            for (var i = 1; i < source.Length; i++)
            {
                if (char.IsUpper(source[i]))
                {
                    if (source[i - 1] != character &&
                        !char.IsUpper(source[i - 1]) ||
                        preserveAcronyms &&
                        char.IsUpper(source[i - 1]) &&
                        i < source.Length - 1 &&
                        !char.IsUpper(source[i + 1]))
                    {
                        result.Append(character);
                    }
                }

                result.Append(source[i]);
            }

            return result.ToString();
        }

        public static MemoryStream ToMemoryStream(this string source)
        {
            return source.ToMemoryStream(Encoding.Default);
        }

        public static MemoryStream ToMemoryStream(this string source, Encoding encoding)
        {
            var sourceBytes = encoding.GetBytes(source);
            return new MemoryStream(sourceBytes);
        }
    }
}


text:
package nl.cloudfoundry.musicdb.georges2017.config.data;

import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.net.UnknownHostException;

@Configuration
@Profile("mongodb-local")
public class MongoLocalConfig {

    @Bean
    public MongoDbFactory mongoDbFactory() {
        try {
            return new SimpleMongoDbFactory(new MongoClient(), "music");
        } catch (UnknownHostException e) {
            throw new RuntimeException("Error creating MongoDbFactory: " + e);
        }
    }

}


text:
package staging

import (
	"net/http"
	"github.com/gin-gonic/gin"
	"github.com/renanberto/apocV2/utils"
	"strings"
	"time"
	"fmt"
)

type ContainerInformation struct {
	ID	string
	Name	string
	Status	string
	State	string
	Created	time.Time
}

func HTMLStagingHandler(c *gin.Context) {

	listedStagingContainers := listAllStagingContainers()
	if listedStagingContainers == nil{
		fmt.Println("Error.")
	}

	c.HTML(http.StatusOK, "staging.html", gin.H{
		"title": "Agile Promoter Operations Center",
		"stagingContainers": &listedStagingContainers,
	})
}

func listAllStagingContainers() []ContainerInformation {
	  var newDockerConnection utils.DockerConnection
		var stagingContainersInformation []ContainerInformation
		var ci ContainerInformation

		newDockerConnection.New("involves-hetfield")

		err, stagingContainers := utils.ListAllContainers(newDockerConnection)
		if err != nil {panic(err)}

		for _, element := range stagingContainers {
			joinContainerName := strings.Join(element.Names,"")
			ContainerNameWithReplace := strings.Replace(joinContainerName,"/","",1)
			t := time.Unix(element.Created,0)
			if strings.Contains(ContainerNameWithReplace,"staging_qa_") {
				ci.ID = element.ID
				ci.Name = ContainerNameWithReplace
				ci.Status = element.Status
				ci.Created = t
				ci.State = element.State
				stagingContainersInformation = append(stagingContainersInformation,ci)
			}
		}

	return stagingContainersInformation
}

func InputStagingRemoveHandler(c *gin.Context) {
	var newDockerConnection utils.DockerConnection

	containerID := c.PostForm("id")
	newDockerConnection.New("involves-hetfield")
	err := utils.RemoveContainerId(containerID,newDockerConnection)

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"error": "Error",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"success": "success",
		})
	}

}

func InputStagingCreateHandler(c *gin.Context) {
	var reviewApp utils.ReviewApp

	javaPR := c.PostForm("javaPR")
	htmlPR := c.PostForm("htmlPR")
	slackUser := "@" + c.PostForm("slackUser")

	reviewApp.NewReviewApp(javaPR,htmlPR,slackUser)
	reviewApp.ReviewAppCreate()

	c.String(http.StatusOK,"")
}


text:
#pragma once

#include "qt_model_extension.hpp"
#include "core_object\i_object_handle_storage.hpp"
#include "core_object\i_managed_object.hpp"

#include <cassert>
#include <memory>
#include <functional>

#include <QHash>
#include <QPersistentModelIndex>
#include <QVariant>

class QAbstractItemModel;

namespace wgt
{
class QtFrameworkCommon;

/** A user extension to a view.
An extension provides additional functionality to a model, by adding additional roles.
Any roles defined in this extension are exposed as additional properties in QML.*/
class CustomModelExtension : public QtModelExtension
{
	Q_OBJECT
	Q_PROPERTY(QVariant extension READ getExtension)

public:
	typedef std::function<QModelIndex(int, int, void*, const QAbstractItemModel* model)> ModelIndexCreationFunction;

	CustomModelExtension();
	virtual ~CustomModelExtension();

	void initialise(QtFrameworkCommon& frameworkCommon, QObject* view, ManagedObjectPtr&& object);

	virtual QVariant data(const QModelIndex& index, ItemRole::Id roleId) const override;

	virtual bool setData(const QModelIndex& index, const QVariant& value, ItemRole::Id roleId) override;

	virtual QVariant headerData(int section, Qt::Orientation orientation, ItemRole::Id roleId) const override;

	virtual bool setHeaderData(int section, Qt::Orientation orientation, const QVariant& value,
	                           ItemRole::Id roleId) override;

	void setCreateIndexFunction(const ModelIndexCreationFunction& function);

public slots:
	virtual void onDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight,
	                           const QVector<int>& roles) override;
	virtual void onHeaderDataChanged(Qt::Orientation orientation, int first, int last) override;
	virtual void onLayoutAboutToBeChanged(const QList<QPersistentModelIndex>& parents,
	                                      QAbstractItemModel::LayoutChangeHint hint) override;
	virtual void onLayoutChanged(const QList<QPersistentModelIndex>& parents,
	                             QAbstractItemModel::LayoutChangeHint hint) override;
	virtual void onRowsAboutToBeInserted(const QModelIndex& parent, int first, int last) override;
	virtual void onRowsInserted(const QModelIndex& parent, int first, int last) override;
	virtual void onRowsAboutToBeRemoved(const QModelIndex& parent, int first, int last) override;
	virtual void onRowsRemoved(const QModelIndex& parent, int first, int last) override;
	virtual void onRowsAboutToBeMoved(const QModelIndex& sourceParent, int sourceFirst, int sourceLast,
	                                  const QModelIndex& destinationParent, int destinationRow) override;
	virtual void onRowsMoved(const QModelIndex& sourceParent, int sourceFirst, int sourceLast,
	                         const QModelIndex& destinationParent, int destinationRow) override;
	virtual void onColumnsAboutToBeInserted(const QModelIndex& parent, int first, int last) override;
	virtual void onColumnsInserted(const QModelIndex& parent, int first, int last) override;
	virtual void onColumnsAboutToBeRemoved(const QModelIndex& parent, int first, int last) override;
	virtual void onColumnsRemoved(const QModelIndex& parent, int first, int last) override;
	virtual void onColumnsAboutToBeMoved(const QModelIndex& sourceParent, int sourceFirst, int sourceLast,
	                                     const QModelIndex& destinationParent, int destinationColumn) override;
	virtual void onColumnsMoved(const QModelIndex& sourceParent, int sourceFirst, int sourceLast,
	                            const QModelIndex& destinationParent, int destinationColumn) override;

private:
	QVariant getExtension() const;

	struct Implementation;
	friend Implementation;
	std::unique_ptr<Implementation> impl_;
};
} // end namespace wgt


text:
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )

package domainapp.fixture;

public final class DomainAppFixtureModule {

}


text:
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\EventCategory;

/**
 * EventCategoryTrashSearch represents the model behind the search form about `common\models\EventCategory`.
 */
class EventCategoryTrashSearch extends EventCategory
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['Id', 'parentId', 'createdBy', 'updatedBy', 'status'], 'integer'],
            [['name', 'sectionImage', 'ip', 'createdOn', 'updatedOn'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = EventCategory::find()->where('status=0');

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
          $query->andFilterWhere([
              EventCategory::tableName().'.status' => '0',
            ]);
        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'Id' => $this->Id,
            'parentId' => $this->parentId,
            'createdOn' => $this->createdOn,
            'updatedOn' => $this->updatedOn,
            'createdBy' => $this->createdBy,
            'updatedBy' => $this->updatedBy,
            'status' => $this->status,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'sectionImage', $this->sectionImage])
            ->andFilterWhere(['like', 'ip', $this->ip]);

        return $dataProvider;
    }
}


text:
package helpers;

public class PopTimer {

    private long startTime;
    private long dueTime;
    private long pauseTime;

    public PopTimer(long second) {
        startTime = System.currentTimeMillis();
        dueTime   = startTime + (second * 1000);
        pauseTime = 0;
    }

    public void pauseTimer() {
        pauseTime = System.currentTimeMillis();
    }

    public void resumeTimer() {
        if (pauseTime == 0)
            return;

        /* add the waiting time to the due time. */
        dueTime += (System.currentTimeMillis() - pauseTime);
        pauseTime = 0;
    }

    public boolean hasPassed() {
        return System.currentTimeMillis() >= dueTime;
    }

}


text:
{% load staticfiles i18n %}<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="{{ event }}">
    <meta name="author" content="">

    <title>{% block title %}{{ event }}{% endblock title %}</title>

    <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">

    <link href="{% static 'css/landing-page.css' %}" rel="stylesheet">

    <link href="{% static 'font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

    <link href="{% static 'css/project.css' %}" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Inicio: {{ event }}

                        Acerca de...

                        {{ event.activities_label }}

                        Expositores

                        Contacto

                        Otros eventos

      {% if messages %}
          {% for message in messages %}

{{ message }}

          {% endfor %}
      {% endif %}
      {% block content %}

{{ object.name }}

{{ object.start|date:"DATE_FORMAT" }}

{{ object.title }}

            {% if request.user.is_authenticated %}

            {% else %}

            {% endif %}

                             {{ event.activities_label }}

                             Expositores

Noticias

                {% for n in event.news.all %}

{{ n.title }} {{ n.media }}

                {% endfor %}

                        {{ current_info.text|safe }}

            {{ current_footer.text|safe }}

      {% endblock %}

            {% if request.user.is_authenticated %}

                                 {% trans "My Profile" %}

                             {% trans "Salir" %}

            {% else %}

                                 {% trans "Registrarse" %}

                                 {% trans "Ingresar" %}

            {% endif %}
            {% if event %}

                             {{ event.activities_label }}

                             Expositores

            {% endif %}

			    Inicio

⋅

            {% if event %}

                            Acerca de...

⋅

                            {{ event.activities_label }}

⋅

                            Expositores

⋅

                            Contacto

            {% endif %}

Copyright © {{event.organizer }} 2015. All Rights Reserved

    {% if GOOGLE_ANALYTICS_KEY %}

    {% endif %}


text:
from __future__ import absolute_import, unicode_literals

import sys
import warnings

from kombu import Connection
from kombu.exceptions import ResourceError, ChannelError
from kombu.transport import virtual
from kombu.utils import uuid
from kombu.compression import compress

from kombu.tests.case import Case, MagicMock, Mock, mock, patch

PY3 = sys.version_info[0] == 3
PRINT_FQDN = 'builtins.print' if PY3 else '__builtin__.print'

def client(**kwargs):
    return Connection(transport='kombu.transport.virtual:Transport', **kwargs)

def memory_client():
    return Connection(transport='memory')

class test_BrokerState(Case):

    def test_constructor(self):
        s = virtual.BrokerState()
        self.assertTrue(hasattr(s, 'exchanges'))

        t = virtual.BrokerState(exchanges=16)
        self.assertEqual(t.exchanges, 16)

class test_QoS(Case):

    def setup(self):
        self.q = virtual.QoS(client().channel(), prefetch_count=10)

    def teardown(self):
        self.q._on_collect.cancel()

    def test_constructor(self):
        self.assertTrue(self.q.channel)
        self.assertTrue(self.q.prefetch_count)
        self.assertFalse(self.q._delivered.restored)
        self.assertTrue(self.q._on_collect)

    def test_restore_visible__interface(self):
        qos = virtual.QoS(client().channel())
        qos.restore_visible()

    @mock.stdouts
    def test_can_consume(self, stdout, stderr):
        _restored = []

        class RestoreChannel(virtual.Channel):
            do_restore = True

            def _restore(self, message):
                _restored.append(message)

        self.assertTrue(self.q.can_consume())
        for i in range(self.q.prefetch_count - 1):
            self.q.append(i, uuid())
            self.assertTrue(self.q.can_consume())
        self.q.append(i + 1, uuid())
        self.assertFalse(self.q.can_consume())

        tag1 = next(iter(self.q._delivered))
        self.q.ack(tag1)
        self.assertTrue(self.q.can_consume())

        tag2 = uuid()
        self.q.append(i + 2, tag2)
        self.assertFalse(self.q.can_consume())
        self.q.reject(tag2)
        self.assertTrue(self.q.can_consume())

        self.q.channel = RestoreChannel(self.q.channel.connection)
        tag3 = uuid()
        self.q.append(i + 3, tag3)
        self.q.reject(tag3, requeue=True)
        self.q._flush()
        self.q.restore_unacked_once()
        self.assertListEqual(_restored, [11, 9, 8, 7, 6, 5, 4, 3, 2, 1])
        self.assertTrue(self.q._delivered.restored)
        self.assertFalse(self.q._delivered)

        self.q.restore_unacked_once()
        self.q._delivered.restored = False
        self.q.restore_unacked_once()

        self.assertTrue(stderr.getvalue())
        self.assertFalse(stdout.getvalue())

        self.q.restore_at_shutdown = False
        self.q.restore_unacked_once()

    def test_get(self):
        self.q._delivered['foo'] = 1
        self.assertEqual(self.q.get('foo'), 1)

class test_Message(Case):

    def test_create(self):
        c = client().channel()
        data = c.prepare_message('the quick brown fox...')
        tag = data['properties']['delivery_tag'] = uuid()
        message = c.message_to_python(data)
        self.assertIsInstance(message, virtual.Message)
        self.assertIs(message, c.message_to_python(message))
        if message.errors:
            message._reraise_error()

        self.assertEqual(message.body,
                         'the quick brown fox...'.encode('utf-8'))
        self.assertTrue(message.delivery_tag, tag)

    def test_create_no_body(self):
        virtual.Message(Mock(), {
            'body': None,
            'properties': {'delivery_tag': 1}})

    def test_serializable(self):
        c = client().channel()
        body, content_type = compress('the quick brown fox...', 'gzip')
        data = c.prepare_message(body, headers={'compression': content_type})
        tag = data['properties']['delivery_tag'] = uuid()
        message = c.message_to_python(data)
        dict_ = message.serializable()
        self.assertEqual(dict_['body'],
                         'the quick brown fox...'.encode('utf-8'))
        self.assertEqual(dict_['properties']['delivery_tag'], tag)
        self.assertNotIn('compression', dict_['headers'])

class test_AbstractChannel(Case):

    def test_get(self):
        with self.assertRaises(NotImplementedError):
            virtual.AbstractChannel()._get('queue')

    def test_put(self):
        with self.assertRaises(NotImplementedError):
            virtual.AbstractChannel()._put('queue', 'm')

    def test_size(self):
        self.assertEqual(virtual.AbstractChannel()._size('queue'), 0)

    def test_purge(self):
        with self.assertRaises(NotImplementedError):
            virtual.AbstractChannel()._purge('queue')

    def test_delete(self):
        with self.assertRaises(NotImplementedError):
            virtual.AbstractChannel()._delete('queue')

    def test_new_queue(self):
        self.assertIsNone(virtual.AbstractChannel()._new_queue('queue'))

    def test_has_queue(self):
        self.assertTrue(virtual.AbstractChannel()._has_queue('queue'))

    def test_poll(self):
        cycle = Mock(name='cycle')
        self.assertTrue(virtual.AbstractChannel()._poll(cycle))
        cycle.get.assert_called()

class test_Channel(Case):

    def setup(self):
        self.channel = client().channel()

    def teardown(self):
        if self.channel._qos is not None:
            self.channel._qos._on_collect.cancel()

    def test_exceeds_channel_max(self):
        c = client()
        t = c.transport
        avail = t._avail_channel_ids = Mock(name='_avail_channel_ids')
        avail.pop.side_effect = IndexError()
        with self.assertRaises(ResourceError):
            virtual.Channel(t)

    def test_exchange_bind_interface(self):
        with self.assertRaises(NotImplementedError):
            self.channel.exchange_bind('dest', 'src', 'key')

    def test_exchange_unbind_interface(self):
        with self.assertRaises(NotImplementedError):
            self.channel.exchange_unbind('dest', 'src', 'key')

    def test_queue_unbind_interface(self):
        self.channel.queue_unbind('dest', 'ex', 'key')

    def test_management(self):
        m = self.channel.connection.client.get_manager()
        self.assertTrue(m)
        m.get_bindings()
        m.close()

    def test_exchange_declare(self):
        c = self.channel

        with self.assertRaises(ChannelError):
            c.exchange_declare('test_exchange_declare', 'direct',
                               durable=True, auto_delete=True, passive=True)
        c.exchange_declare('test_exchange_declare', 'direct',
                           durable=True, auto_delete=True)
        c.exchange_declare('test_exchange_declare', 'direct',
                           durable=True, auto_delete=True, passive=True)
        self.assertIn('test_exchange_declare', c.state.exchanges)
        # can declare again with same values
        c.exchange_declare('test_exchange_declare', 'direct',
                           durable=True, auto_delete=True)
        self.assertIn('test_exchange_declare', c.state.exchanges)

        # using different values raises NotEquivalentError
        with self.assertRaises(virtual.NotEquivalentError):
            c.exchange_declare('test_exchange_declare', 'direct',
                               durable=False, auto_delete=True)

    def test_exchange_delete(self, ex='test_exchange_delete'):

        class PurgeChannel(virtual.Channel):
            purged = []

            def _purge(self, queue):
                self.purged.append(queue)

        c = PurgeChannel(self.channel.connection)

        c.exchange_declare(ex, 'direct', durable=True, auto_delete=True)
        self.assertIn(ex, c.state.exchanges)
        self.assertFalse(c.state.has_binding(ex, ex, ex))  # no bindings yet
        c.exchange_delete(ex)
        self.assertNotIn(ex, c.state.exchanges)

        c.exchange_declare(ex, 'direct', durable=True, auto_delete=True)
        c.queue_declare(ex)
        c.queue_bind(ex, ex, ex)
        self.assertTrue(c.state.has_binding(ex, ex, ex))
        c.exchange_delete(ex)
        self.assertFalse(c.state.has_binding(ex, ex, ex))
        self.assertIn(ex, c.purged)

    def test_queue_delete__if_empty(self, n='test_queue_delete__if_empty'):
        class PurgeChannel(virtual.Channel):
            purged = []
            size = 30

            def _purge(self, queue):
                self.purged.append(queue)

            def _size(self, queue):
                return self.size

        c = PurgeChannel(self.channel.connection)
        c.exchange_declare(n)
        c.queue_declare(n)
        c.queue_bind(n, n, n)
        # tests code path that returns if queue already bound.
        c.queue_bind(n, n, n)

        c.queue_delete(n, if_empty=True)
        self.assertTrue(c.state.has_binding(n, n, n))

        c.size = 0
        c.queue_delete(n, if_empty=True)
        self.assertFalse(c.state.has_binding(n, n, n))
        self.assertIn(n, c.purged)

    def test_queue_purge(self, n='test_queue_purge'):

        class PurgeChannel(virtual.Channel):
            purged = []

            def _purge(self, queue):
                self.purged.append(queue)

        c = PurgeChannel(self.channel.connection)
        c.exchange_declare(n)
        c.queue_declare(n)
        c.queue_bind(n, n, n)
        c.queue_purge(n)
        self.assertIn(n, c.purged)

    def test_basic_publish__anon_exchange(self):
        c = memory_client().channel()
        msg = MagicMock(name='msg')
        c.encode_body = Mock(name='c.encode_body')
        c.encode_body.return_value = (1, 2)
        c._put = Mock(name='c._put')
        c.basic_publish(msg, None, 'rkey', kw=1)
        c._put.assert_called_with('rkey', msg, kw=1)

    def test_basic_publish_unique_delivery_tags(self, n='test_uniq_tag'):
        c1 = memory_client().channel()
        c2 = memory_client().channel()

        for c in (c1, c2):
            c.exchange_declare(n)
            c.queue_declare(n)
            c.queue_bind(n, n, n)
        m1 = c1.prepare_message('George Costanza')
        m2 = c2.prepare_message('Elaine Marie Benes')
        c1.basic_publish(m1, n, n)
        c2.basic_publish(m2, n, n)

        r1 = c1.message_to_python(c1.basic_get(n))
        r2 = c2.message_to_python(c2.basic_get(n))

        self.assertNotEqual(r1.delivery_tag, r2.delivery_tag)
        with self.assertRaises(ValueError):
            int(r1.delivery_tag)
        with self.assertRaises(ValueError):
            int(r2.delivery_tag)

    def test_basic_publish__get__consume__restore(self,
                                                  n='test_basic_publish'):
        c = memory_client().channel()

        c.exchange_declare(n)
        c.queue_declare(n)
        c.queue_bind(n, n, n)
        c.queue_declare(n + '2')
        c.queue_bind(n + '2', n, n)

        m = c.prepare_message('nthex quick brown fox...')
        c.basic_publish(m, n, n)

        r1 = c.message_to_python(c.basic_get(n))
        self.assertTrue(r1)
        self.assertEqual(r1.body,
                         'nthex quick brown fox...'.encode('utf-8'))
        self.assertIsNone(c.basic_get(n))

        consumer_tag = uuid()

        c.basic_consume(n + '2', False,
                        consumer_tag=consumer_tag, callback=lambda *a: None)
        self.assertIn(n + '2', c._active_queues)
        r2, _ = c.drain_events()
        r2 = c.message_to_python(r2)
        self.assertEqual(r2.body,
                         'nthex quick brown fox...'.encode('utf-8'))
        self.assertEqual(r2.delivery_info['exchange'], n)
        self.assertEqual(r2.delivery_info['routing_key'], n)
        with self.assertRaises(virtual.Empty):
            c.drain_events()
        c.basic_cancel(consumer_tag)

        c._restore(r2)
        r3 = c.message_to_python(c.basic_get(n))
        self.assertTrue(r3)
        self.assertEqual(r3.body, 'nthex quick brown fox...'.encode('utf-8'))
        self.assertIsNone(c.basic_get(n))

    def test_basic_ack(self):

        class MockQoS(virtual.QoS):
            was_acked = False

            def ack(self, delivery_tag):
                self.was_acked = True

        self.channel._qos = MockQoS(self.channel)
        self.channel.basic_ack('foo')
        self.assertTrue(self.channel._qos.was_acked)

    def test_basic_recover__requeue(self):

        class MockQoS(virtual.QoS):
            was_restored = False

            def restore_unacked(self):
                self.was_restored = True

        self.channel._qos = MockQoS(self.channel)
        self.channel.basic_recover(requeue=True)
        self.assertTrue(self.channel._qos.was_restored)

    def test_restore_unacked_raises_BaseException(self):
        q = self.channel.qos
        q._flush = Mock()
        q._delivered = {1: 1}

        q.channel._restore = Mock()
        q.channel._restore.side_effect = SystemExit

        errors = q.restore_unacked()
        self.assertIsInstance(errors[0][0], SystemExit)
        self.assertEqual(errors[0][1], 1)
        self.assertFalse(q._delivered)

    @patch('kombu.transport.virtual.emergency_dump_state')
    @patch(PRINT_FQDN)
    def test_restore_unacked_once_when_unrestored(self, print_,
                                                  emergency_dump_state):
        q = self.channel.qos
        q._flush = Mock()

        class State(dict):
            restored = False

        q._delivered = State({1: 1})
        ru = q.restore_unacked = Mock()
        exc = None
        try:
            raise KeyError()
        except KeyError as exc_:
            exc = exc_
        ru.return_value = [(exc, 1)]

        self.channel.do_restore = True
        q.restore_unacked_once()
        print_.assert_called()
        emergency_dump_state.assert_called()

    def test_basic_recover(self):
        with self.assertRaises(NotImplementedError):
            self.channel.basic_recover(requeue=False)

    def test_basic_reject(self):

        class MockQoS(virtual.QoS):
            was_rejected = False

            def reject(self, delivery_tag, requeue=False):
                self.was_rejected = True

        self.channel._qos = MockQoS(self.channel)
        self.channel.basic_reject('foo')
        self.assertTrue(self.channel._qos.was_rejected)

    def test_basic_qos(self):
        self.channel.basic_qos(prefetch_count=128)
        self.assertEqual(self.channel._qos.prefetch_count, 128)

    def test_lookup__undeliverable(self, n='test_lookup__undeliverable'):
        warnings.resetwarnings()
        with warnings.catch_warnings(record=True) as log:
            self.assertListEqual(
                self.channel._lookup(n, n, 'ae.undeliver'),
                ['ae.undeliver'],
            )
            self.assertTrue(log)
            self.assertIn('could not be delivered', log[0].message.args[0])

    def test_context(self):
        x = self.channel.__enter__()
        self.assertIs(x, self.channel)
        x.__exit__()
        self.assertTrue(x.closed)

    def test_cycle_property(self):
        self.assertTrue(self.channel.cycle)

    def test_flow(self):
        with self.assertRaises(NotImplementedError):
            self.channel.flow(False)

    def test_close_when_no_connection(self):
        self.channel.connection = None
        self.channel.close()
        self.assertTrue(self.channel.closed)

    def test_drain_events_has_get_many(self):
        c = self.channel
        c._get_many = Mock()
        c._poll = Mock()
        c._consumers = [1]
        c._qos = Mock()
        c._qos.can_consume.return_value = True

        c.drain_events(timeout=10.0)
        c._get_many.assert_called_with(c._active_queues, timeout=10.0)

    def test_get_exchanges(self):
        self.channel.exchange_declare(exchange='foo')
        self.assertTrue(self.channel.get_exchanges())

    def test_basic_cancel_not_in_active_queues(self):
        c = self.channel
        c._consumers.add('x')
        c._tag_to_queue['x'] = 'foo'
        c._active_queues = Mock()
        c._active_queues.remove.side_effect = ValueError()

        c.basic_cancel('x')
        c._active_queues.remove.assert_called_with('foo')

    def test_basic_cancel_unknown_ctag(self):
        self.assertIsNone(self.channel.basic_cancel('unknown-tag'))

    def test_list_bindings(self):
        c = self.channel
        c.exchange_declare(exchange='foo')
        c.queue_declare(queue='q')
        c.queue_bind(queue='q', exchange='foo', routing_key='rk')

        self.assertIn(('q', 'foo', 'rk'), list(c.list_bindings()))

    def test_after_reply_message_received(self):
        c = self.channel
        c.queue_delete = Mock()
        c.after_reply_message_received('foo')
        c.queue_delete.assert_called_with('foo')

    def test_queue_delete_unknown_queue(self):
        self.assertIsNone(self.channel.queue_delete('xiwjqjwel'))

    def test_queue_declare_passive(self):
        has_queue = self.channel._has_queue = Mock()
        has_queue.return_value = False
        with self.assertRaises(ChannelError):
            self.channel.queue_declare(queue='21wisdjwqe', passive=True)

    def test_get_message_priority(self):

        def _message(priority):
            return self.channel.prepare_message(
                'the message with priority', priority=priority,
            )

        self.assertEqual(
            self.channel._get_message_priority(_message(5)), 5,
        )
        self.assertEqual(
            self.channel._get_message_priority(
                _message(self.channel.min_priority - 10),
            ),
            self.channel.min_priority,
        )
        self.assertEqual(
            self.channel._get_message_priority(
                _message(self.channel.max_priority + 10),
            ),
            self.channel.max_priority,
        )
        self.assertEqual(
            self.channel._get_message_priority(_message('foobar')),
            self.channel.default_priority,
        )
        self.assertEqual(
            self.channel._get_message_priority(_message(2), reverse=True),
            self.channel.max_priority - 2,
        )

class test_Transport(Case):

    def setup(self):
        self.transport = client().transport

    def test_custom_polling_interval(self):
        x = client(transport_options=dict(polling_interval=32.3))
        self.assertEqual(x.transport.polling_interval, 32.3)

    def test_close_connection(self):
        c1 = self.transport.create_channel(self.transport)
        c2 = self.transport.create_channel(self.transport)
        self.assertEqual(len(self.transport.channels), 2)
        self.transport.close_connection(self.transport)
        self.assertFalse(self.transport.channels)
        del(c1)  # so pyflakes doesn't complain
        del(c2)

    def test_drain_channel(self):
        channel = self.transport.create_channel(self.transport)
        with self.assertRaises(virtual.Empty):
            self.transport._drain_channel(channel)

    def test__deliver__no_queue(self):
        with self.assertRaises(KeyError):
            self.transport._deliver(Mock(name='msg'), queue=None)

    def test__reject_inbound_message(self):
        channel = Mock(name='channel')
        self.transport.channels = [None, channel]
        self.transport._reject_inbound_message({'foo': 'bar'})
        channel.Message.assert_called_with(channel, {'foo': 'bar'})
        channel.qos.append.assert_called_with(
            channel.Message(), channel.Message().delivery_tag,
        )
        channel.basic_reject.assert_called_with(
            channel.Message().delivery_tag, requeue=True,
        )

    def test_on_message_ready(self):
        channel = Mock(name='channel')
        msg = Mock(name='msg')
        callback = Mock(name='callback')
        self.transport._callbacks = {'q1': callback}
        self.transport.on_message_ready(channel, msg, queue='q1')
        callback.assert_called_with(msg)

    def test_on_message_ready__no_queue(self):
        with self.assertRaises(KeyError):
            self.transport.on_message_ready(
                Mock(name='channel'), Mock(name='msg'), queue=None)

    def test_on_message_ready__no_callback(self):
        self.transport._callbacks = {}
        with self.assertRaises(KeyError):
            self.transport.on_message_ready(
                Mock(name='channel'), Mock(name='msg'), queue='q1')


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="DB_MANAGER_ID" type="id">299</item>
    <item name="userNameEditText" type="id" />
    <item name="passwordEditText" type="id" />
    <item name="fragmentContainer" type="id" />
    <item name="loginForm" type="id" />
    <item name="loginButton" type="id" />
    <item name="loginStayLoggedBox" type="id" />
    <item name="toolbar" type="id" />
    <item name="drawer_layout" type="id" />
    <item name="nav_view" type="id" />
</resources>


text:
<?php

use yii\helpers\Html;
use yii\widgets\DetailView;

use app\models\general\GeneralLabel;

/* @var $this yii\web\View */
/* @var $model app\models\PengurusanPenilaianKategoriJurulatihKetua */

$this->title = $model->pengurusan_penilaian_kategori_jurulatih_id;
$this->params['breadcrumbs'][] = ['label' => GeneralLabel::pengurusan_penilaian_kategori_jurulatihs, 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

    <?= $this->render('_form', [
        'model' => $model,
        'readonly' => $readonly,
    ]) ?>

    <?php /*echo DetailView::widget([
        'model' => $model,
        'attributes' => [
            'pengurusan_penilaian_kategori_jurulatih_id',
            'pengurusan_pemantauan_dan_penilaian_jurulatih_id',
            'penilaian_kategori',
            'penilaian_sub_kategori',
            'markah_penilaian',
        ],
    ]);*/ ?>


text:
@interface TTPeriscommentCell ()

@property (nonatomic, strong) TTPeriscommentMark *mark;
@property (nonatomic, strong) TTPeriscommentLabel *commentLabel;
@property (nonatomic, strong) TTPeriscommentConfig *config;
@property (nonatomic, strong) UILabel *nameLabel;

@end

@implementation TTPeriscommentCell

- (instancetype)initWithFrame:(CGRect)frame name:(NSString *)name comment:(NSString *)comment profileImage:(UIImage *)profileImage {
    TTPeriscommentConfig *config = [[TTPeriscommentConfig alloc] init];
    return [self initWithFrame:frame name:name comment:comment profileImage:profileImage config:config];
}

- (instancetype)initWithFrame:(CGRect)frame name:(NSString *)name comment:(NSString *)comment profileImage:(UIImage *)profileImage config:(TTPeriscommentConfig *)config {
    if (self = [super initWithFrame:frame]) {

        self.backgroundColor = [UIColor whiteColor];
        self.layer.cornerRadius = 5;
        self.clipsToBounds = YES;

        self.config = config;
        self.nameLabel.text = name;
        self.commentLabel.text = comment;
        [self.nameLabel sizeToFit];
        [self.commentLabel sizeToFit];

        [self addSubview:self.nameLabel];
        [self addSubview:self.commentLabel];

        [self resetFrame:profileImage];

        [self addSubview:self.mark];

    }
    return self;
}

- (void)resetFrame:(UIImage *)image {

    TTPeriscommentConfig *config = self.config;
    CGFloat commentWidth = MAX(self.nameLabel.frame.size.width, self.commentLabel.frame.size.width);
    CGFloat inferedWidth = config.layout.markWidth + config.layout.offset + commentWidth + config.layout.padding * 2;
    CGFloat width = MIN(inferedWidth, config.layout.maximumWidth);
    CGFloat height = config.layout.padding * 2 + config.layout.commentSpace + self.nameLabel.frame.size.height + self.commentLabel.frame.size.height;

    // cell frame
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, width, height);

    // mark frame
    CGSize markSize = CGSizeMake(config.layout.markWidth, height);
    CGRect markRect = CGRectMake(self.frame.origin.x, self.frame.origin.y, markSize.width, markSize.height);
    self.mark = [[TTPeriscommentMark alloc] initWithFrame:markRect image:image];

    // comment frame
    CGRect commentOriginframe = self.commentLabel.frame;
    commentOriginframe.origin.y += self.nameLabel.frame.size.height;
    self.commentLabel.frame = commentOriginframe;

}

#pragma mark - getter
- (UILabel *)nameLabel {
    if (!_nameLabel) {
        TTPeriscommentConfig *config = self.config;
        CGPoint namePoint = CGPointMake(config.layout.markWidth + config.layout.offset, config.layout.padding);
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(namePoint.x, namePoint.y, 0, 0)];
        nameLabel.font = config.nameFont.font;
        nameLabel.textColor = config.nameFont.color;
        _nameLabel = nameLabel;
    }
    return _nameLabel;
}

- (TTPeriscommentLabel *)commentLabel {
    if (!_commentLabel) {
        TTPeriscommentConfig *config = self.config;
        CGFloat commentMaxWidth = [config.layout prepareCommentMaxWidth];
        CGPoint commentPoint = CGPointMake(config.layout.markWidth + config.layout.offset, config.layout.padding + config.layout.commentSpace);
        TTPeriscommentLabel *commentLabel = [[TTPeriscommentLabel alloc] initWithFrame:CGRectMake(commentPoint.x, commentPoint.y, 0, 0) font:config.commentFont allowLineBreak:config.layout.allowLineBreak maxWidth:commentMaxWidth];
        _commentLabel = commentLabel;
    }
    return _commentLabel;
}

@end

@implementation TTPeriscommentLabel

- (instancetype)initWithFrame:(CGRect)frame font:(TTPeriscommentFont *)commentfont allowLineBreak:(BOOL)allow maxWidth:(CGFloat)maxWidth {
    if (self = [super initWithFrame:frame]) {
        _allowLineBreak = allow;
        _maxCommentWidth = maxWidth;
        self.textColor = commentfont.color;
        self.font = commentfont.font;
    }
    return self;
}

- (void)sizeToFit {
    if (self.allowLineBreak) {
        self.lineBreakMode = NSLineBreakByWordWrapping;
        self.numberOfLines = 0;
    }
    [super sizeToFit];
    [self resetSize];
    [super sizeToFit];
}

- (void)resetSize {
    CGFloat width = MIN(self.maxCommentWidth, self.frame.size.width);
    CGRect originFrame = self.frame;
    originFrame.size.width = width;
    self.frame = originFrame;
}

@end


text:
namespace WebServiceTestStudio.UserInterface
{
    public partial class OutputDockContent
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            //
            // textBox1
            //
            this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.textBox1.Location = new System.Drawing.Point(0, 0);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(896, 253);
            this.textBox1.TabIndex = 0;
            //
            // Output
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(896, 253);
            this.Controls.Add(this.textBox1);
            this.Name = "Output";
            this.Text = "Output";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textBox1;
    }
}


text: alert("From your site.");