text:
using System.Collections;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Transactions.Configuration;
using System.Transactions.Distributed;

namespace System.Transactions
{
    public delegate Transaction HostCurrentTransactionCallback();

    public delegate void TransactionStartedEventHandler(object sender, TransactionEventArgs e);

    public static class TransactionManager
    {
        // Revovery Information Version
        private const int RecoveryInformationVersion1 = 1;
        private const int CurrentRecoveryVersion = RecoveryInformationVersion1;

        // Hashtable of promoted transactions, keyed by identifier guid.  This is used by
        // FindPromotedTransaction to support transaction equivalence when a transaction is
        // serialized and then deserialized back in this app-domain.
        // Double-checked locking pattern requires volatile for read/write synchronization
        private static volatile Hashtable s_promotedTransactionTable;

        // Sorted Table of transaction timeouts
        // Double-checked locking pattern requires volatile for read/write synchronization
        private static volatile TransactionTable s_transactionTable;

        private static TransactionStartedEventHandler s_distributedTransactionStartedDelegate;
        public static event TransactionStartedEventHandler DistributedTransactionStarted
        {
            add
            {
                lock (ClassSyncObject)
                {
                    s_distributedTransactionStartedDelegate = (TransactionStartedEventHandler)System.Delegate.Combine(s_distributedTransactionStartedDelegate, value);
                    if (value != null)
                    {
                        ProcessExistingTransactions(value);
                    }
                }
            }

            remove
            {
                lock (ClassSyncObject)
                {
                    s_distributedTransactionStartedDelegate = (TransactionStartedEventHandler)System.Delegate.Remove(s_distributedTransactionStartedDelegate, value);
                }
            }
        }

        internal static void ProcessExistingTransactions(TransactionStartedEventHandler eventHandler)
        {
            lock (PromotedTransactionTable)
            {
                // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
                IDictionaryEnumerator e = PromotedTransactionTable.GetEnumerator();
                while (e.MoveNext())
                {
                    WeakReference weakRef = (WeakReference)e.Value;
                    Transaction tx = (Transaction)weakRef.Target;
                    if (tx != null)
                    {
                        TransactionEventArgs args = new TransactionEventArgs();
                        args._transaction = tx.InternalClone();
                        eventHandler(args._transaction, args);
                    }
                }
            }
        }

        internal static void FireDistributedTransactionStarted(Transaction transaction)
        {
            TransactionStartedEventHandler localStartedEventHandler = null;
            lock (ClassSyncObject)
            {
                localStartedEventHandler = s_distributedTransactionStartedDelegate;
            }

            if (null != localStartedEventHandler)
            {
                TransactionEventArgs args = new TransactionEventArgs();
                args._transaction = transaction.InternalClone();
                localStartedEventHandler(args._transaction, args);
            }
        }

        // Data storage for current delegate
        internal static HostCurrentTransactionCallback s_currentDelegate = null;
        internal static bool s_currentDelegateSet = false;

        // CurrentDelegate
        //
        // Store a delegate to be used to query for an external current transaction.
        public static HostCurrentTransactionCallback HostCurrentCallback
        {
            // get_HostCurrentCallback is used from get_CurrentTransaction, which doesn't have any permission requirements.
            // We don't expose what is returned from this property in that case.  But we don't want just anybody being able
            // to retrieve the value.
            get
            {
                // Note do not add trace notifications to this method.  It is called
                // at the startup of SQLCLR and tracing has too much working set overhead.
                return s_currentDelegate;
            }
            set
            {
                // Note do not add trace notifications to this method.  It is called
                // at the startup of SQLCLR and tracing has too much working set overhead.
                if (value == null)
                {
                    throw new ArgumentNullException(nameof(value));
                }

                lock (ClassSyncObject)
                {
                    if (s_currentDelegateSet)
                    {
                        throw new InvalidOperationException(SR.CurrentDelegateSet);
                    }
                    s_currentDelegateSet = true;
                }

                s_currentDelegate = value;
            }
        }

        public static Enlistment Reenlist(
            Guid resourceManagerIdentifier,
            byte[] recoveryInformation,
            IEnlistmentNotification enlistmentNotification)
        {
            if (resourceManagerIdentifier == Guid.Empty)
            {
                throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
            }

            if (null == recoveryInformation)
            {
                throw new ArgumentNullException(nameof(recoveryInformation));
            }

            if (null == enlistmentNotification)
            {
                throw new ArgumentNullException(nameof(enlistmentNotification));
            }

            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
            if (etwLog.IsEnabled())
            {
                etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.Reenlist");
                etwLog.TransactionManagerReenlist(resourceManagerIdentifier);
            }

            // Put the recovery information into a stream.
            MemoryStream stream = new MemoryStream(recoveryInformation);
            int recoveryInformationVersion = 0;
            string nodeName = null;
            byte[] resourceManagerRecoveryInformation = null;

            try
            {
                BinaryReader reader = new BinaryReader(stream);
                recoveryInformationVersion = reader.ReadInt32();

                if (recoveryInformationVersion == TransactionManager.RecoveryInformationVersion1)
                {
                    nodeName = reader.ReadString();

                    resourceManagerRecoveryInformation = reader.ReadBytes(recoveryInformation.Length - checked((int)stream.Position));
                }
                else
                {
                    if (etwLog.IsEnabled())
                    {
                        etwLog.TransactionExceptionTrace(TraceSourceType.TraceSourceBase, TransactionExceptionType.UnrecognizedRecoveryInformation, nameof(recoveryInformation), string.Empty);
                    }

                    throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation));
                }
            }
            catch (EndOfStreamException e)
            {
                if (etwLog.IsEnabled())
                {
                    etwLog.TransactionExceptionTrace(TraceSourceType.TraceSourceBase, TransactionExceptionType.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e.ToString());
                }
                throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e);
            }
            catch (FormatException e)
            {
                if (etwLog.IsEnabled())
                {
                    etwLog.TransactionExceptionTrace(TraceSourceType.TraceSourceBase, TransactionExceptionType.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e.ToString());
                }
                throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e);
            }
            finally
            {
                stream.Dispose();
            }

            DistributedTransactionManager transactionManager = CheckTransactionManager(nodeName);

            // Now ask the Transaction Manager to reenlist.
            object syncRoot = new object();
            Enlistment returnValue = new Enlistment(enlistmentNotification, syncRoot);
            EnlistmentState.EnlistmentStatePromoted.EnterState(returnValue.InternalEnlistment);

            returnValue.InternalEnlistment.PromotedEnlistment =
                transactionManager.ReenlistTransaction(
                    resourceManagerIdentifier,
                    resourceManagerRecoveryInformation,
                    (RecoveringInternalEnlistment)returnValue.InternalEnlistment
                    );

            if (etwLog.IsEnabled())
            {
                etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.Reenlist");
            }

            return returnValue;
        }

        private static DistributedTransactionManager CheckTransactionManager(string nodeName)
        {
            DistributedTransactionManager tm = DistributedTransactionManager;
            if (!((tm.NodeName == null && (nodeName == null || nodeName.Length == 0)) ||
                  (tm.NodeName != null && tm.NodeName.Equals(nodeName))))
            {
                throw new ArgumentException(SR.InvalidRecoveryInformation, "recoveryInformation");
            }
            return tm;
        }

        public static void RecoveryComplete(Guid resourceManagerIdentifier)
        {
            if (resourceManagerIdentifier == Guid.Empty)
            {
                throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
            }

            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
            if (etwLog.IsEnabled())
            {
                etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.RecoveryComplete");
                etwLog.TransactionManagerRecoveryComplete(resourceManagerIdentifier);
            }

            DistributedTransactionManager.ResourceManagerRecoveryComplete(resourceManagerIdentifier);

            if (etwLog.IsEnabled())
            {
                etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.RecoveryComplete");
            }
        }

        // Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) )
        private static object s_classSyncObject;

        // Helper object for static synchronization
        private static object ClassSyncObject
        {
            get
            {
                if (s_classSyncObject == null)
                {
                    object o = new object();
                    Interlocked.CompareExchange(ref s_classSyncObject, o, null);
                }
                return s_classSyncObject;
            }
        }

        internal static IsolationLevel DefaultIsolationLevel
        {
            get
            {
                TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
                if (etwLog.IsEnabled())
                {
                    etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultIsolationLevel");
                    etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultIsolationLevel");
                }

                return IsolationLevel.Serializable;
            }
        }

        private static DefaultSettingsSection s_defaultSettings;
        private static DefaultSettingsSection DefaultSettings
        {
            get
            {
                if (s_defaultSettings == null)
                {
                    s_defaultSettings = DefaultSettingsSection.GetSection();
                }

                return s_defaultSettings;
            }
        }

        private static MachineSettingsSection s_machineSettings;
        private static MachineSettingsSection MachineSettings
        {
            get
            {
                if (s_machineSettings == null)
                {
                    s_machineSettings = MachineSettingsSection.GetSection();
                }

                return s_machineSettings;
            }
        }

        private static bool s_defaultTimeoutValidated;
        private static TimeSpan s_defaultTimeout;
        public static TimeSpan DefaultTimeout
        {
            get
            {
                TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
                if (etwLog.IsEnabled())
                {
                    etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultTimeout");
                }

                if (!s_defaultTimeoutValidated)
                {
                    s_defaultTimeout = ValidateTimeout(DefaultSettings.Timeout);
                    // If the timeout value got adjusted, it must have been greater than MaximumTimeout.
                    if (s_defaultTimeout != DefaultSettings.Timeout)
                    {
                        if (etwLog.IsEnabled())
                        {
                            etwLog.ConfiguredDefaultTimeoutAdjusted();
                        }
                    }
                    s_defaultTimeoutValidated = true;
                }

                if (etwLog.IsEnabled())
                {
                    etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultTimeout");
                }
                return s_defaultTimeout;
            }
        }

        // Double-checked locking pattern requires volatile for read/write synchronization
        private static volatile bool s_cachedMaxTimeout;
        private static TimeSpan s_maximumTimeout;
        public static TimeSpan MaximumTimeout
        {
            get
            {
                TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
                if (etwLog.IsEnabled())
                {
                    etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultMaximumTimeout");
                }

                if (!s_cachedMaxTimeout)
                {
                    lock (ClassSyncObject)
                    {
                        if (!s_cachedMaxTimeout)
                        {
                            TimeSpan temp = MachineSettings.MaxTimeout;
                            s_maximumTimeout = temp;
                            s_cachedMaxTimeout = true;
                        }
                    }
                }

                if (etwLog.IsEnabled())
                {
                    etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultMaximumTimeout");
                }

                return s_maximumTimeout;
            }
        }

        // This routine writes the "header" for the recovery information, based on the
        // type of the calling object and its provided parameter collection.  This information
        // we be read back by the static Reenlist method to create the necessary transaction
        // manager object with the right parameters in order to do a ReenlistTransaction call.
        internal static byte[] GetRecoveryInformation(string startupInfo, byte[] resourceManagerRecoveryInformation)
        {
            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
            if (etwLog.IsEnabled())
            {
                etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.GetRecoveryInformation");
            }

            MemoryStream stream = new MemoryStream();
            byte[] returnValue = null;

            try
            {
                // Manually write the recovery information
                BinaryWriter writer = new BinaryWriter(stream);

                writer.Write(TransactionManager.CurrentRecoveryVersion);
                if (startupInfo != null)
                {
                    writer.Write(startupInfo);
                }
                else
                {
                    writer.Write("");
                }
                writer.Write(resourceManagerRecoveryInformation);
                writer.Flush();
                returnValue = stream.ToArray();
            }
            finally
            {
                stream.Dispose();
            }

            if (etwLog.IsEnabled())
            {
                etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.GetRecoveryInformation");
            }

            return returnValue;
        }

        internal static byte[] ConvertToByteArray(object thingToConvert)
        {
            MemoryStream streamToWrite = new MemoryStream();
            byte[] returnValue = null;

            try
            {
                // First seralize the type to the stream.
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(streamToWrite, thingToConvert);

                returnValue = new byte[streamToWrite.Length];

                streamToWrite.Position = 0;
                streamToWrite.Read(returnValue, 0, Convert.ToInt32(streamToWrite.Length, CultureInfo.InvariantCulture));
            }
            finally
            {
                streamToWrite.Dispose();
            }

            return returnValue;
        }

        /// <summary>
        /// This static function throws an ArgumentOutOfRange if the specified IsolationLevel is not within
        /// the range of valid values.
        /// </summary>
        /// <param name="transactionIsolationLevel">
        /// The IsolationLevel value to validate.
        /// </param>
        internal static void ValidateIsolationLevel(IsolationLevel transactionIsolationLevel)
        {
            switch (transactionIsolationLevel)
            {
                case IsolationLevel.Serializable:
                case IsolationLevel.RepeatableRead:
                case IsolationLevel.ReadCommitted:
                case IsolationLevel.ReadUncommitted:
                case IsolationLevel.Unspecified:
                case IsolationLevel.Chaos:
                case IsolationLevel.Snapshot:
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(transactionIsolationLevel));
            }
        }

        /// <summary>
        /// This static function throws an ArgumentOutOfRange if the specified TimeSpan does not meet
        /// requirements of a valid transaction timeout.  Timeout values must be positive.
        /// </summary>
        /// <param name="transactionTimeout">
        /// The TimeSpan value to validate.
        /// </param>
        internal static TimeSpan ValidateTimeout(TimeSpan transactionTimeout)
        {
            if (transactionTimeout < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException(nameof(transactionTimeout));
            }

            if (MaximumTimeout != TimeSpan.Zero)
            {
                if (transactionTimeout > MaximumTimeout || transactionTimeout == TimeSpan.Zero)
                {
                    return MaximumTimeout;
                }
            }

            return transactionTimeout;
        }

        internal static Transaction FindPromotedTransaction(Guid transactionIdentifier)
        {
            Hashtable promotedTransactionTable = PromotedTransactionTable;
            WeakReference weakRef = (WeakReference)promotedTransactionTable[transactionIdentifier];
            if (null != weakRef)
            {
                Transaction tx = weakRef.Target as Transaction;
                if (null != tx)
                {
                    return tx.InternalClone();
                }
                else  // an old, moldy weak reference.  Let's get rid of it.
                {
                    lock (promotedTransactionTable)
                    {
                        promotedTransactionTable.Remove(transactionIdentifier);
                    }
                }
            }

            return null;
        }

        internal static Transaction FindOrCreatePromotedTransaction(Guid transactionIdentifier, DistributedTransaction dtx)
        {
            Transaction tx = null;
            Hashtable promotedTransactionTable = PromotedTransactionTable;
            lock (promotedTransactionTable)
            {
                WeakReference weakRef = (WeakReference)promotedTransactionTable[transactionIdentifier];
                if (null != weakRef)
                {
                    tx = weakRef.Target as Transaction;
                    if (null != tx)
                    {
                        // If we found a transaction then dispose it
                        dtx.Dispose();
                        return tx.InternalClone();
                    }
                    else
                    {
                        // an old, moldy weak reference.  Let's get rid of it.
                        lock (promotedTransactionTable)
                        {
                            promotedTransactionTable.Remove(transactionIdentifier);
                        }
                    }
                }

                tx = new Transaction(dtx);

                // Since we are adding this reference to the table create an object that will clean that entry up.
                tx._internalTransaction._finalizedObject = new FinalizedObject(tx._internalTransaction, dtx.Identifier);

                weakRef = new WeakReference(tx, false);
                promotedTransactionTable[dtx.Identifier] = weakRef;
            }
            dtx.SavedLtmPromotedTransaction = tx;

            FireDistributedTransactionStarted(tx);

            return tx;
        }

        // Table for promoted transactions
        internal static Hashtable PromotedTransactionTable
        {
            get
            {
                if (s_promotedTransactionTable == null)
                {
                    lock (ClassSyncObject)
                    {
                        if (s_promotedTransactionTable == null)
                        {
                            Hashtable temp = new Hashtable(100);
                            s_promotedTransactionTable = temp;
                        }
                    }
                }

                return s_promotedTransactionTable;
            }
        }

        // Table for transaction timeouts
        internal static TransactionTable TransactionTable
        {
            get
            {
                if (s_transactionTable == null)
                {
                    lock (ClassSyncObject)
                    {
                        if (s_transactionTable == null)
                        {
                            TransactionTable temp = new TransactionTable();
                            s_transactionTable = temp;
                        }
                    }
                }

                return s_transactionTable;
            }
        }

        // Fault in a DistributedTransactionManager if one has not already been created.
        // Double-checked locking pattern requires volatile for read/write synchronization
        internal static volatile DistributedTransactionManager distributedTransactionManager;
        internal static DistributedTransactionManager DistributedTransactionManager
        {
            get
            {
                // If the distributed transaction manager is not configured, throw an exception
                if (distributedTransactionManager == null)
                {
                    lock (ClassSyncObject)
                    {
                        if (distributedTransactionManager == null)
                        {
                            distributedTransactionManager = new DistributedTransactionManager();
                        }
                    }
                }

                return distributedTransactionManager;
            }
        }
    }
}


text:
const express = require('express');
const router = express.Router();

/* GET users listing. */
router.get('/', ( request, response ) => {
  response.send('respond with a resource');
});

module.exports = router;

redpajama_set_name: RedPajamaGithub


text:
Tools
=====
Many tools have been written for working with **PyMongo**. If you know
of or have created a tool for working with MongoDB from Python please
list it here.

.. note:: We try to keep this list current. As such, projects that
   have not been updated recently or appear to be unmaintained will
   occasionally be removed from the list or moved to the back (to keep
   the list from becoming too intimidating). If a project gets removed
   that is still being developed or is in active use please let us
   know or add it back.

ORM-like Layers
---------------
Some people have found that they prefer to work with a layer that
has more features than PyMongo provides. Often, things like models and
validation are desired. To that end, several different ORM-like layers
have been written by various authors.

It is our recommendation that new users begin by working directly with
PyMongo, as described in the rest of this documentation. Many people
have found that the features of PyMongo are enough for their
needs. Even if you eventually come to the decision to use one of these
layers, the time spent working directly with the driver will have
increased your understanding of how MongoDB actually works.

MongoKit
  The `MongoKit <http://github.com/namlook/mongokit>`_ framework
  is an ORM-like layer on top of PyMongo. There is also a MongoKit
  `google group <http://groups.google.com/group/mongokit>`_.

Ming
  `Ming <http://merciless.sourceforge.net/>`_ (the Merciless) is a
  library that allows you to enforce schemas on a MongoDB database in
  your Python application. It was developed by `SourceForge
  <http://sourceforge.net/>`_ in the course of their migration to
  MongoDB. See the `introductory blog post
  <http://blog.pythonisito.com/2009/12/ming-01-released-python-library-for.html>`_
  for more details.

MongoAlchemy
  `MongoAlchemy <http://mongoalchemy.org>`_ is another ORM-like layer on top of
  PyMongo. Its API is inspired by `SQLAlchemy <http://sqlalchemy.org>`_. The
  code is available `on github <http://github.com/jeffjenkins/MongoAlchemy>`_;
  for more information, see `the tutorial <http://mongoalchemy.org/tutorial.html>`_.

MongoEngine
  `MongoEngine <http://hmarr.com/mongoengine/>`_ is another ORM-like
  layer on top of PyMongo. It allows you to define schemas for
  documents and query collections using syntax inspired by the Django
  ORM. The code is available on `github
  <http://github.com/hmarr/mongoengine>`_; for more information, see
  the `tutorial <http://hmarr.com/mongoengine/tutorial.html>`_.

django-mongodb-engine
  `Django MongoDB Engine
  <http://github.com/django-mongodb-engine/mongodb-engine/>`_ is a MongoDB
  database backend for Django.

Minimongo
  `minimongo <http://pypi.python.org/pypi/minimongo>`_ is a lightweight,
  pythonic interface to MongoDB.  It retains pymongo's query and update API,
  and provides a number of additional features, including a simple
  document-oriented interface, connection pooling, index management, and
  collection & database naming helpers. The `source is on github
  <http://github.com/slacy/minimongo>`_.

Smaller or less well-maintained projects (in order from most to least
recently committed to at the time of the last update to this list):

  - `pymongo-bongo <http://pypi.python.org/pypi/pymongo-bongo/>`_ (11/2009)
  - `mongodb-object <http://github.com/marcboeker/mongodb-object>`_ (10/2009)
  - `MongoMagic <http://bitbucket.org/bottiger/mongomagic/wiki/Home>`_ (7/2009)
  - `django-mongodb <http://bitbucket.org/kpot/django-mongodb/>`_ (7/2009)

Framework Tools
---------------
This section lists tools and adapters that have been designed to work with various Python frameworks and libraries.

mango
  `mango <http://github.com/vpulim/mango>`_ provides MongoDB
  backends for Django sessions and authentication (bypassing
  :mod:`django.db` entirely).

mongodb_beaker
  `mongodb_beaker <http://pypi.python.org/pypi/mongodb_beaker>`_ is a
  project to enable using MongoDB as a backend for `beaker's
  <http://beaker.groovie.org/>`_ caching / session system.
  `The source is on github
  <http://github.com/bwmcadams/mongodb_beaker>`_.

MongoLog
  `MongoLog <http://github.com/andreisavu/mongodb-log/>`_
  is a Python logging handler that stores logs in MongoDB using a
  capped collection.

c5t
  `c5t <http://bitbucket.org/percious/c5t/>`_ is a
  content-management system using TurboGears and MongoDB.

rod.recipe.mongodb
  `rod.recipe.mongodb
  <http://pypi.python.org/pypi/rod.recipe.mongodb/>`_ is a ZC Buildout
  recipe for downloading and installing MongoDB.

repoze-what-plugins-mongodb
  `repoze-what-plugins-mongodb
  <http://code.google.com/p/repoze-what-plugins-mongodb/>`_ is a
  project working to support a plugin for using MongoDB as a backend
  for :mod:`repoze.what`.

Alternative Drivers
-------------------
These are alternatives to PyMongo.

PyMonga
  `PyMonga <http://github.com/fiorix/mongo-async-python-driver>`_ is
  an asynchronous Python driver for MongoDB, although it is not
  currently recommended for production use.


text:
package com.google.cloud.apigateway.v1.samples;

// [START apigateway_v1_generated_apigatewayserviceclient_listapis_sync]
import com.google.cloud.apigateway.v1.Api;
import com.google.cloud.apigateway.v1.ApiGatewayServiceClient;
import com.google.cloud.apigateway.v1.ListApisRequest;
import com.google.cloud.apigateway.v1.LocationName;

public class SyncListApis {

  public static void main(String[] args) throws Exception {
    syncListApis();
  }

  public static void syncListApis() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (ApiGatewayServiceClient apiGatewayServiceClient = ApiGatewayServiceClient.create()) {
      ListApisRequest request =
          ListApisRequest.newBuilder()
              .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
              .setPageSize(883849137)
              .setPageToken("pageToken873572522")
              .setFilter("filter-1274492040")
              .setOrderBy("orderBy-1207110587")
              .build();
      for (Api element : apiGatewayServiceClient.listApis(request).iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}
// [END apigateway_v1_generated_apigatewayserviceclient_listapis_sync]


text:
"""Integration tests for ubla command."""

from __future__ import absolute_import
import re

from gslib.cs_api_map import ApiSelector
import gslib.tests.testcase as testcase
from gslib.tests.util import ObjectToURI as suri
from gslib.tests.util import unittest
from gslib.utils.retry_util import Retry

class TestUbla(testcase.GsUtilIntegrationTestCase):
  """Integration tests for ubla command."""

  _set_ubla_cmd = ['ubla', 'set']
  _get_ubla_cmd = ['ubla', 'get']

  def _AssertEnabled(self, bucket_uri, value):
    stdout = self.RunGsUtil(self._get_ubla_cmd + [suri(bucket_uri)],
                            return_stdout=True)
    uniform_bucket_level_access_re = re.compile(
        r'^\s*Enabled:\s+(?P<enabled_val>.+)$', re.MULTILINE)
    uniform_bucket_level_access_match = re.search(
        uniform_bucket_level_access_re, stdout)
    uniform_bucket_level_access_val = uniform_bucket_level_access_match.group(
        'enabled_val')
    self.assertEqual(str(value), uniform_bucket_level_access_val)

  def test_off_on_default_buckets(self):
    if self.test_api == ApiSelector.XML:
      return unittest.skip(
          'XML API has no concept of Uniform bucket-level access')
    bucket_uri = self.CreateBucket()
    self._AssertEnabled(bucket_uri, False)

  def test_turning_off_on_enabled_buckets(self):
    if self.test_api == ApiSelector.XML:
      return unittest.skip(
          'XML API has no concept of Uniform bucket-level access')
    # TODO(mynameisrafe): Replace bucket_policy_only with uniform_bucket_level_access  when the property is live.
    bucket_uri = self.CreateBucket(bucket_policy_only=True,
                                   prefer_json_api=True)
    self._AssertEnabled(bucket_uri, True)

    self.RunGsUtil(self._set_ubla_cmd + ['off', suri(bucket_uri)])
    self._AssertEnabled(bucket_uri, False)

  def test_turning_on(self):
    if self.test_api == ApiSelector.XML:
      return unittest.skip(
          'XML API has no concept of Uniform bucket-level access')

    bucket_uri = self.CreateBucket()
    self.RunGsUtil(self._set_ubla_cmd + ['on', suri(bucket_uri)])

    self._AssertEnabled(bucket_uri, True)

  def test_turning_on_and_off(self):
    if self.test_api == ApiSelector.XML:
      return unittest.skip(
          'XML API has no concept of Uniform bucket-level access')

    bucket_uri = self.CreateBucket()

    self.RunGsUtil(self._set_ubla_cmd + ['on', suri(bucket_uri)])
    self._AssertEnabled(bucket_uri, True)

    self.RunGsUtil(self._set_ubla_cmd + ['off', suri(bucket_uri)])
    self._AssertEnabled(bucket_uri, False)

  def testTooFewArgumentsFails(self):
    """Ensures ubla commands fail with too few arguments."""
    # No arguments for set, but valid subcommand.
    stderr = self.RunGsUtil(self._set_ubla_cmd,
                            return_stderr=True,
                            expected_status=1)
    self.assertIn('command requires at least', stderr)

    # No arguments for get, but valid subcommand.
    stderr = self.RunGsUtil(self._get_ubla_cmd,
                            return_stderr=True,
                            expected_status=1)
    self.assertIn('command requires at least', stderr)

    # Neither arguments nor subcommand.
    stderr = self.RunGsUtil(['ubla'], return_stderr=True, expected_status=1)
    self.assertIn('command requires at least', stderr)


text:
/**
 * Returns a list of user names.
 * In the case of existing duplicate first names - returns the full name
 * Otherwise returns the first name
 * @param members {string[]}
 * @param allWorkspaceUsers {object[]}
 * @return {object[]}
 */
export const getDisplayNamesForUsers = (members, allWorkspaceUsers) => {
  const duplicateFirstNames = {};
  const userNamesMap = {};

  allWorkspaceUsers.forEach((u) => {
    const firstName = u.profile.firstName;
    if (!duplicateFirstNames[firstName]) {
      duplicateFirstNames[firstName] = 1;
    } else {
      duplicateFirstNames[firstName] += 1;
    }

    userNamesMap[u._id] = {
      firstName: u.profile.firstName || (u.emails.length && u.emails[0].address) || '',
      fullName: `${u.profile.firstName} ${u.profile.lastName}`,
    };
  });

  return members.map((id) => {
    const user = userNamesMap[id];
    if (user) {
      if (duplicateFirstNames[user.firstName] > 1) {
        return user.fullName;
      }
      return user.firstName;
    }

    return '';
  });
};


text:
<?xml version="1.0"?>
<package>
  <name>ensenso_seg</name>
  <version>0.0.0</version>
  <description>The ensenso_seg package</description>

  <maintainer email="olalekan.ogunmolu@utdallas.edu">lex</maintainer>

  <license>MIT</license>

  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>roscpp</build_depend>
  <build_depend>rospy</build_depend>
  <build_depend>sensor_msgs</build_depend>
  <build_depend>tf</build_depend>
  <build_depend>tf_conversions</build_depend>
  <build_depend>ensenso</build_depend>

  <run_depend>roscpp</run_depend>
  <run_depend>rospy</run_depend>
  <run_depend>sensor_msgs</run_depend>
  <run_depend>tf</run_depend>
  <run_depend>tf_conversions</run_depend>
  <run_depend>ensenso</run_depend>

  <!-- The export tag contains other, unspecified, tags -->
  <export>
    <!-- Other tools can request additional information be placed here -->

  </export>
</package>


text:
require 'test_helper'

class UserTest < ActiveSupport::TestCase

  def setup
    @user = users(:matt)
    @other_user = users(:jess)
  end

  test "should be valid" do
    assert @user.valid?
  end

  test "email should be present" do
    @user.email = "     "
    assert_not @user.valid?
  end

  test "email addresses should be unique" do
    duplicate_user = @user.dup
    duplicate_user.email = @user.email.upcase
    @user.save
    assert_not duplicate_user.valid?
  end

  test "email addresses should be saved as lower-case" do
    mixed_case_email = "MatT@ExAMPle.CoM"
    @user.email = mixed_case_email
    @user.save
    assert_equal mixed_case_email.downcase, @user.reload.email
  end

  test "email should not be too long" do
    @user.email = "a" * 244 + "@example.com"
    assert_not @user.valid?
  end

  test "email validation should accept valid email addresses" do
    valid_addresses = %w[foobar@example.com USER@foo.COM A_US-ER@foo.bar.org first.last@foo.jp alice+bob@baz.cn]
    valid_addresses.each do |valid_address|
      @user.email = valid_address
      assert @user.valid?, "#{valid_address.inspect} should be valid"
    end
  end

  test "email validation should reject invalid addresses" do
    invalid_addresses = %w[user@example,com user_at_foo.org user.name@example. foo@bar_baz.com foo@bar+baz.com]
    invalid_addresses.each do |invalid_address|
      @user.email = invalid_address
      assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
    end
  end

  test "password should be present" do
    @user.password = @user.password_confirmation = " " * 6
    assert_not @user.valid?
  end

  test "password should have numbers and letters" do
    @user.password = @user.password_confirmation = "a" * 6
    assert_not @user.valid?
  end

  test "authenticated? should return false for a user with nil digest" do
    assert_not @user.authenticated?('')
  end

  test "associated profile should be destroyed" do
    assert_difference 'Profile.count', -1 do
      @user.destroy
    end
  end

  test "associated likes should be destroyed" do
    @user.save
    assert_difference 'Likeable.count', -2 do
      @user.destroy
    end
  end

  test "associated match users plus matches should be destroyed" do
    Match.create!(user_one_id: @user.id, user_two_id: @other_user.id)
    assert @user.match_users.any?
    assert_difference 'Match.count', -1 do
      @user.destroy
    end
  end

end


text:
'''Trains a simple convnet on the MNIST dataset.
Gets to 99.25% test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
16 seconds per epoch on a GRID K520 GPU.
'''

from __future__ import print_function
import numpy as np
np.random.seed(1337)  # for reproducibility

from tensorflow.contrib.keras.api.keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D, BatchNormalization
from keras.utils import np_utils
from keras import backend as K
from keras.callbacks import TensorBoard, ModelCheckpoint
tensorboard = TensorBoard(log_dir='/home/norman/MNIST_train', histogram_freq=1,
                          write_graph=True, write_images=False, embeddings_freq=1)
import time
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--extras', help='(absolute) path to keras-extras')
parser.add_argument('--gpus', help='number of GPUs')
parser.print_help()
args = parser.parse_args()

import sys
sys.path.append(args.extras)

from multi_gpu import make_parallel

#ngpus = int(args.gpus)
ngpus = int(2)
print("Using %i GPUs" %ngpus)

batch_size = 128
nb_classes = 10
nb_epoch = 12

# input image dimensions
img_rows, img_cols = 28, 28
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)

# the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()

if K.image_dim_ordering() == 'th':
    X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
    X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)
    X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)

model = Sequential()

model.add(Convolution2D(nb_filters, (kernel_size[0], kernel_size[1]),
                        padding='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(Convolution2D(256, (kernel_size[0], kernel_size[1])))
model.add(Activation('relu'))
model.add(BatchNormalization())
model.add(Convolution2D(128, (kernel_size[0], kernel_size[1])))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('softmax'))

if ngpus > 1:
    model = make_parallel(model,ngpus)

model.compile(loss='categorical_crossentropy',
              optimizer='adadelta',
              metrics=['accuracy'])

start_time = time.time()
model.fit(X_train, Y_train, batch_size=batch_size*ngpus, epochs=nb_epoch,
          verbose=1, validation_data=(X_test, Y_test))#, callbacks=[tensorboard])
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])
duration = time.time() - start_time
print('Total Duration (%.3f sec)' % duration)


text:
using System;
using System.Collections.Generic;
using TagLib.IFD.Entries;
using TagLib.IFD.Tags;

namespace TagLib.IFD
{
	/// <summary>
	///    This class resembles the structure of a TIFF file. It can either be a
	///    top-level IFD, or a nested IFD (in the case of Exif).
	/// </summary>
	public class IFDStructure
	{

#region Private Fields

		private static readonly string DATETIME_FORMAT = "yyyy:MM:dd HH:mm:ss";

		/// <summary>
		///    Contains the IFD directories in this tag.
		/// </summary>
		internal readonly List<IFDDirectory> directories = new List<IFDDirectory> ();

#endregion

#region Public Properties

		/// <summary>
		///    Gets the IFD directories contained in the current instance.
		/// </summary>
		/// <value>
		///    An array of <see cref="IFDDirectory"/> instances.
		/// </value>
		public IFDDirectory [] Directories {
			get { return directories.ToArray (); }
		}

#endregion

#region Public Methods

		/// <summary>
		///    Checks, if a value for the given tag is contained in the IFD.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> value with the directory index that
		///    contains the tag.
		/// </param>
		/// <param name="tag">
		///    A <see cref="System.UInt16"/> value with the tag.
		/// </param>
		/// <returns>
		///    A <see cref="System.Boolean"/>, which is true, if the tag is already
		///    contained in the IFD, otherwise false.
		/// </returns>
		public bool ContainsTag (int directory, ushort tag)
		{
			if (directory >= directories.Count)
				return false;
			return directories [directory].ContainsKey (tag);
		}

		/// <summary>
		///    Removes a given tag from the IFD.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> value with the directory index that
		///    contains the tag to remove.
		/// </param>
		/// <param name="tag">
		///    A <see cref="System.UInt16"/> value with the tag to remove.
		/// </param>
		public void RemoveTag (int directory, ushort tag)
		{
			if (ContainsTag (directory, tag)) {
				directories [directory].Remove (tag);
			}
		}

		/// <summary>
		///    Removes a given tag from the IFD.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> value with the directory index that
		///    contains the tag to remove.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="IFDEntryTag"/> value with the tag to remove.
		/// </param>
		public void RemoveTag (int directory, IFDEntryTag entry_tag)
		{
			RemoveTag (directory, (ushort) entry_tag);
		}

		/// <summary>
		///    Adds an <see cref="IFDEntry"/> to the IFD, if it is not already
		///    contained in, it fails otherwise.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> value with the directory index that
		///    should contain the tag that will be added.
		/// </param>
		/// <param name="entry">
		///    A <see cref="IFDEntry"/> to add to the IFD.
		/// </param>
		public void AddEntry (int directory, IFDEntry entry)
		{
			while (directory >= directories.Count)
				directories.Add (new IFDDirectory ());

			directories [directory].Add (entry.Tag, entry);
		}

		/// <summary>
		///    Adds an <see cref="IFDEntry"/> to the IFD. If it is already contained
		///    in the IFD, it is overwritten.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> value with the directory index that
		///    contains the tag that will be set.
		/// </param>
		/// <param name="entry">
		///    A <see cref="IFDEntry"/> to add to the IFD.
		/// </param>
		public void SetEntry (int directory, IFDEntry entry)
		{
			if (ContainsTag (directory, entry.Tag))
				RemoveTag (directory, entry.Tag);

			AddEntry (directory, entry);
		}

		/// <summary>
		///   Returns the <see cref="IFDEntry"/> belonging to the given tag.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the directory that contains
		///    the wanted tag.
		/// </param>
		/// <param name="tag">
		///    A <see cref="System.UInt16"/> with the tag to get.
		/// </param>
		/// <returns>
		///    A <see cref="IFDEntry"/> belonging to the given tag, or
		///    null, if no such tag is contained in the IFD.
		/// </returns>
		public IFDEntry GetEntry (int directory, ushort tag)
		{
			if (!ContainsTag (directory, tag))
				return null;

			return directories [directory] [tag];
		}

		/// <summary>
		///   Returns the <see cref="IFDEntry"/> belonging to the given tag.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the directory that contains
		///    the wanted tag.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="IFDEntryTag"/> with the tag to get.
		/// </param>
		/// <returns>
		///    A <see cref="IFDEntry"/> belonging to the given tag, or
		///    null, if no such tag is contained in the IFD.
		/// </returns>
		public IFDEntry GetEntry (int directory, IFDEntryTag entry_tag)
		{
			return GetEntry (directory, (ushort) entry_tag);
		}

		/// <summary>
		///    Returns the <see cref="System.String"/> stored in the
		///    entry defined by <paramref name="entry_tag"/>.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the number of the directory
		///    to search for the entry.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="System.UInt16"/> with the tag of the entry
		/// </param>
		/// <returns>
		///    A <see cref="System.String"/> with the value stored in the entry
		///    or <see langword="null" /> if no such entry is contained or it
		///    does not contain a <see cref="System.String"/> value.
		/// </returns>
		public string GetStringValue (int directory, ushort entry_tag)
		{
			var entry = GetEntry (directory, entry_tag);

			if (entry != null && entry is StringIFDEntry)
				return (entry as StringIFDEntry).Value;

			return null;
		}

		/// <summary>
		///    Returns a <see cref="System.Nullable"/> containing the
		///    <see cref="System.Byte"/> stored in the entry defined
		///    by <paramref name="entry_tag"/>.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the number of the directory
		///    to search for the entry.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="System.UInt16"/> with the tag of the entry
		/// </param>
		/// <returns>
		///    A <see cref="System.Nullable"/> containing the
		///    <see cref="System.Byte"/> stored in the entry, or
		///    <see langword="null" /> if no such entry is contained or it
		///    does not contain a <see cref="System.Byte"/> value.
		/// </returns>
		public byte? GetByteValue (int directory, ushort entry_tag)
		{
			var entry = GetEntry (directory, entry_tag);

			if (entry != null && entry is ByteIFDEntry)
				return (entry as ByteIFDEntry).Value;

			return null;
		}

		/// <summary>
		///    Returns a <see cref="System.Nullable"/> containing the
		///    <see cref="System.UInt32"/> stored in the entry defined
		///    by <paramref name="entry_tag"/>.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the number of the directory
		///    to search for the entry.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="System.UInt16"/> with the tag of the entry
		/// </param>
		/// <returns>
		///    A <see cref="System.Nullable"/> containing the
		///    <see cref="System.UInt32"/> stored in the entry, or
		///    <see langword="null" /> if no such entry is contained or it
		///    does not contain a <see cref="System.UInt32"/> value.
		/// </returns>
		public uint? GetLongValue (int directory, ushort entry_tag)
		{
			var entry = GetEntry (directory, entry_tag);

			if (entry is LongIFDEntry)
				return (entry as LongIFDEntry).Value;

			if (entry is ShortIFDEntry)
				return (entry as ShortIFDEntry).Value;

			return null;
		}

		/// <summary>
		///    Returns a <see cref="System.Nullable"/> containing the
		///    <see cref="System.Double"/> stored in the entry defined
		///    by <paramref name="entry_tag"/>. The entry can be of type
		///    <see cref="Entries.RationalIFDEntry"/> or
		///    <see cref="Entries.SRationalIFDEntry"/>
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the number of the directory
		///    to search for the entry.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="System.UInt16"/> with the tag of the entry
		/// </param>
		/// <returns>
		///    A <see cref="System.Nullable"/> containing the
		///    <see cref="System.Double"/> stored in the entry, or
		///    <see langword="null" /> if no such entry is contained.
		/// </returns>
		public double? GetRationalValue (int directory, ushort entry_tag)
		{
			var entry = GetEntry (directory, entry_tag);

			if (entry is RationalIFDEntry)
				return (entry as RationalIFDEntry).Value;

			if (entry is SRationalIFDEntry)
				return (entry as SRationalIFDEntry).Value;

			return null;
		}

		/// <summary>
		///    Returns a <see cref="System.Nullable"/> containing the
		///    <see cref="System.DateTime"/> stored in the entry defined
		///    by <paramref name="entry_tag"/>. The entry must be of type
		///    <see cref="Entries.StringIFDEntry"/> and contain an datestring
		///    according to the Exif specification.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the number of the directory
		///    to search for the entry.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="System.UInt16"/> with the tag of the entry
		/// </param>
		/// <returns>
		///    A <see cref="System.Nullable"/> containing the
		///    <see cref="System.DateTime"/> stored in the entry, or
		///    <see langword="null" /> if no such entry is contained or it
		///    does not contain a valid value.
		/// </returns>
		public DateTime? GetDateTimeValue (int directory, ushort entry_tag)
		{
			string date_string = GetStringValue (directory, entry_tag);

			try {
				DateTime date_time = DateTime.ParseExact (date_string,
						DATETIME_FORMAT, System.Globalization.CultureInfo.InvariantCulture);

				return date_time;
			} catch {}

			return null;
		}

		/// <summary>
		///    Adds a <see cref="Entries.StringIFDEntry"/> to the directory with tag
		///    given by <paramref name="entry_tag"/> and value given by <paramref name="value"/>
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the number of the directory
		///    to add the entry to.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="System.UInt16"/> with the tag of the entry
		/// </param>
		/// <param name="value">
		///    A <see cref="System.String"/> with the value to add. If it is <see langword="null" />
		///    an possibly already contained entry is removed for given tag.
		/// </param>
		public void SetStringValue (int directory, ushort entry_tag, string value)
		{
			if (value == null) {
				RemoveTag (directory, entry_tag);
				return;
			}

			SetEntry (directory, new StringIFDEntry (entry_tag, value));
		}

		/// <summary>
		///    Adds a <see cref="Entries.ByteIFDEntry"/> to the directory with tag
		///    given by <paramref name="entry_tag"/> and value given by <paramref name="value"/>
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the number of the directory
		///    to add the entry to.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="System.UInt16"/> with the tag of the entry
		/// </param>
		/// <param name="value">
		///    A <see cref="System.Byte"/> with the value to add.
		/// </param>
		public void SetByteValue (int directory, ushort entry_tag, byte value)
		{
			SetEntry (directory, new ByteIFDEntry (entry_tag, value));
		}

		/// <summary>
		///    Adds a <see cref="Entries.LongIFDEntry"/> to the directory with tag
		///    given by <paramref name="entry_tag"/> and value given by <paramref name="value"/>
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the number of the directory
		///    to add the entry to.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="System.UInt16"/> with the tag of the entry
		/// </param>
		/// <param name="value">
		///    A <see cref="System.UInt32"/> with the value to add.
		/// </param>
		public void SetLongValue (int directory, ushort entry_tag, uint value)
		{
			SetEntry (directory, new LongIFDEntry (entry_tag, value));
		}

		/// <summary>
		///    Adds a <see cref="Entries.RationalIFDEntry"/> to the directory with tag
		///    given by <paramref name="entry_tag"/> and value given by <paramref name="value"/>
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the number of the directory
		///    to add the entry to.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="System.UInt16"/> with the tag of the entry
		/// </param>
		/// <param name="value">
		///    A <see cref="System.Double"/> with the value to add. It must be possible to
		///    represent the value by a <see cref="Entries.Rational"/>.
		/// </param>
		public void SetRationalValue (int directory, ushort entry_tag, double value)
		{
			if (value < 0.0d || value > (double)UInt32.MaxValue)
				throw new ArgumentException ("value");

			uint scale = (value >= 1.0d) ? 1 : UInt32.MaxValue;

			Rational rational = new Rational ((uint) (scale * value), scale);

			SetEntry (directory, new RationalIFDEntry (entry_tag, rational));
		}

		/// <summary>
		///    Adds a <see cref="Entries.StringIFDEntry"/> to the directory with tag
		///    given by <paramref name="entry_tag"/> and value given by <paramref name="value"/>.
		///    The value is stored as a date string according to the Exif specification.
		/// </summary>
		/// <param name="directory">
		///    A <see cref="System.Int32"/> with the number of the directory
		///    to add the entry to.
		/// </param>
		/// <param name="entry_tag">
		///    A <see cref="System.UInt16"/> with the tag of the entry
		/// </param>
		/// <param name="value">
		///    A <see cref="DateTime"/> with the value to add.
		/// </param>
		public void SetDateTimeValue (int directory, ushort entry_tag, DateTime value)
		{
			string date_string = value.ToString (DATETIME_FORMAT);

			SetStringValue (directory, entry_tag, date_string);
		}

#endregion

	}

}


text:
/** @file Clock.cpp
	@brief */

#if defined(__unix__) || defined(__native_client__) || defined(EMSCRIPTEN) || defined(ANDROID) || defined(__APPLE__) || defined (__CYGWIN__)
#include <time.h>
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#endif

#ifdef WIN32
#include "../Math/InclWindows.h"
#endif

#ifdef EMSCRIPTEN
#include <emscripten.h>
#endif

#ifdef __APPLE__
#include <mach/mach_time.h>
#endif

#include "Clock.h"
#include "../Math/myassert.h"
#include "../Math/assume.h"
#include <time.h>

MATH_BEGIN_NAMESPACE

#ifdef WIN32
u64 Clock::ddwTimerFrequency;
#endif

#ifdef __APPLE__
tick_t Clock::ticksPerSecond = 0;
#endif

tick_t Clock::appStartTime = 0;

Clock impl;

void Clock::InitClockData()
{
	if (appStartTime == 0)
		appStartTime = Tick();

#ifdef WIN32
	if (!QueryPerformanceFrequency(reinterpret_cast<LARGE_INTEGER*>(&ddwTimerFrequency)))
	{
		LOGE("The system doesn't support high-resolution timers!");
		ddwTimerFrequency = (u64)-1;
	}

	if (appStartTime == 0)
	{
#if WINVER >= 0x0600 /* Vista or newer */ && !defined(MATH_ENABLE_WINXP_SUPPORT)
		appStartTime = (tick_t)GetTickCount64();
#else
// We are explicitly building with XP support, so GetTickCount() instead of GetTickCount64 is desired.
#if _MSC_VER >= 1700 // VS2012
#pragma warning(push)
#pragma warning(disable:28159) // warning C28159: Consider using 'GetTickCount64' instead of 'GetTickCount'. Reason: GetTickCount overflows roughly every 49 days.  Code that does not take that into account can loop indefinitely.  GetTickCount64 operates on 64 bit values and does not have that problem
#endif
		appStartTime = (tick_t)GetTickCount();
#if _MSC_VER >= 1700 // VS2012
#pragma warning(pop)
#endif

#endif
	}
#endif

#ifdef __APPLE__
	mach_timebase_info_data_t timeBaseInfo;
	mach_timebase_info(&timeBaseInfo);
	ticksPerSecond = 1000000000ULL * (uint64_t)timeBaseInfo.denom / (uint64_t)timeBaseInfo.numer;
	assert(ticksPerSecond > (uint64_t)timeBaseInfo.denom/timeBaseInfo.numer); // Guard against overflow if OSX numer/denom change or similar.
#endif
}

Clock::Clock()
{
	InitClockData();
}

void Clock::Sleep(int milliseconds)
{
#ifdef WIN8RT
#pragma warning(Clock::Sleep has not been implemented!)
#elif defined(WIN32)
	::Sleep(milliseconds);
#elif !defined(__native_client__) && !defined(EMSCRIPTEN) //Working in WIN32
	// http://linux.die.net/man/2/nanosleep
	//timespec ts;
	//ts.tv_sec = milliseconds / 1000;
	//ts.tv_nsec = (milliseconds - ts.tv_sec * 1000) * 1000 * 1000;
	//int ret = nanosleep(&ts, NULL);
	//if (ret == -1)
		//LOGI("nanosleep returned -1! Reason: %s(%d).", strerror(errno), (int)errno);
#else
#warning Clock::Sleep has not been implemented!
#endif
}

int Clock::Year()
{
#ifdef WIN32
	SYSTEMTIME s;
	GetSystemTime(&s);
	return s.wYear;
#else
	///\todo.
	return 0;
#endif
}

int Clock::Month()
{
#ifdef WIN32
	SYSTEMTIME s;
	GetSystemTime(&s);
	return s.wMonth;
#else
	///\todo.
	return 0;
#endif
}

int Clock::Day()
{
#ifdef WIN32
	SYSTEMTIME s;
	GetSystemTime(&s);
	return s.wDay;
#else
	///\todo.
	return 0;
#endif
}

int Clock::Hour()
{
#ifdef WIN32
	SYSTEMTIME s;
	GetSystemTime(&s);
	return s.wHour;
#else
	///\todo.
	return 0;
#endif
}

int Clock::Min()
{
#ifdef WIN32
	SYSTEMTIME s;
	GetSystemTime(&s);
	return s.wMinute;
#else
	///\todo.
	return 0;
#endif
}

int Clock::Sec()
{
#ifdef WIN32
	SYSTEMTIME s;
	GetSystemTime(&s);
	return s.wSecond;
#else
	///\todo.
	return 0;
#endif
}

unsigned long Clock::SystemTime()
{
#ifdef WIN32
#if WINVER >= 0x0600 /* Vista or newer */ && !defined(MATH_ENABLE_WINXP_SUPPORT)
	return (unsigned long)GetTickCount64();
#else
// We are explicitly building with XP support, so GetTickCount() instead of GetTickCount64 is desired.
#if _MSC_VER >= 1700 // VS2012
#pragma warning(push)
#pragma warning(disable:28159) // warning C28159: Consider using 'GetTickCount64' instead of 'GetTickCount'. Reason: GetTickCount overflows roughly every 49 days.  Code that does not take that into account can loop indefinitely.  GetTickCount64 operates on 64 bit values and does not have that problem
#endif
	return (unsigned long)GetTickCount();
#if _MSC_VER >= 1700 // VS2012
#pragma warning(pop)
#endif

#endif
#else
	return TickU32();
#endif
}
/*
tick_t Clock::ApplicationStartupTick()
{
	return appStartTime;
}
*/
unsigned long Clock::Time()
{
	return (unsigned long)(Tick() - appStartTime);
}

tick_t Clock::Tick()
{
#if defined(ANDROID)
	struct timespec res;
	clock_gettime(CLOCK_REALTIME, &res);
	return 1000000000ULL*res.tv_sec + (tick_t)res.tv_nsec;
#elif defined(EMSCRIPTEN)

#ifdef MATH_TICK_IS_FLOAT
	return (tick_t)emscripten_get_now();
#else
	// emscripten_get_now() returns a wallclock time as a float in milliseconds (1e-3).
	// scale it to microseconds (1e-6) and return as a tick.
	return (tick_t)(((double)emscripten_get_now()) * 1e3);
#endif

#elif defined(WIN32)
	LARGE_INTEGER ddwTimer;
	BOOL success = QueryPerformanceCounter(&ddwTimer);
	assume(success != 0);
	MARK_UNUSED(success);
	return ddwTimer.QuadPart;
#elif defined(__APPLE__)
	return mach_absolute_time();
#elif defined(_POSIX_MONOTONIC_CLOCK)
	timespec t;
	clock_gettime(CLOCK_MONOTONIC, &t);
	return (tick_t)t.tv_sec * 1000 * 1000 * 1000 + (tick_t)t.tv_nsec;
#elif defined(_POSIX_C_SOURCE)
	timeval t;
	gettimeofday(&t, NULL);
	return (tick_t)t.tv_sec * 1000 * 1000 + (tick_t)t.tv_usec;
#else
	return (tick_t)clock();
#endif
}

unsigned long Clock::TickU32()
{
#ifdef WIN32
	LARGE_INTEGER ddwTimer;
	BOOL success = QueryPerformanceCounter(&ddwTimer);
	assume(success != 0);
	MARK_UNUSED(success);
	return ddwTimer.LowPart;
#else
	return (unsigned long)Tick();
#endif
}

tick_t Clock::TicksPerSec()
{
#if defined(ANDROID)
	return 1000000000ULL; // 1e9 == nanoseconds.
#elif defined(EMSCRIPTEN)

#ifdef MATH_TICK_IS_FLOAT
	return (tick_t)1000.0;
#else
	return 1000000ULL; // 1e6 == microseconds.
#endif

#elif defined(WIN32)
	return ddwTimerFrequency;
#elif defined(__APPLE__)
	return ticksPerSecond;
#elif defined(_POSIX_MONOTONIC_CLOCK)
	return 1000 * 1000 * 1000;
#elif defined(_POSIX_C_SOURCE) || defined(__APPLE__)
	return 1000 * 1000;
#else
	return CLOCKS_PER_SEC;
#endif
}

unsigned long long Clock::Rdtsc()
{
#if defined(_MSC_VER) && !defined(WIN8PHONE)
	return __rdtsc();
#elif defined(__x86_64__)
	unsigned hi, lo;
	__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
	return ((unsigned long long)lo) | (((unsigned long long)hi) << 32);
#elif defined(__i386__) || defined(__X86__) || defined(_X86_)
	unsigned long long int x;
	__asm__ volatile ("rdtsc" : "=A" (x));
	return x;
#else
	return Clock::Tick();
#endif
}

MATH_END_NAMESPACE


text:
import * as backgrounds from '../libs/backgrounds';

backgrounds
	.get('bhollander-bodie')
	.then(({ variants, hasDefault }) => {
		console.log(variants, hasDefault);
	})
	.catch(err => {
		throw err;
	});


text:
package com.larscheidschmitzhermes.nexus3.github.oauth.plugin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.larscheidschmitzhermes.nexus3.github.oauth.plugin.api.GithubApiClient;
import com.larscheidschmitzhermes.nexus3.github.oauth.plugin.api.GithubOrg;
import com.larscheidschmitzhermes.nexus3.github.oauth.plugin.api.GithubTeam;
import com.larscheidschmitzhermes.nexus3.github.oauth.plugin.api.GithubUser;
import com.larscheidschmitzhermes.nexus3.github.oauth.plugin.configuration.GithubOauthConfiguration;
import com.larscheidschmitzhermes.nexus3.github.oauth.plugin.configuration.MockGithubOauthConfiguration;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.hamcrest.MatcherAssert;
import org.hamcrest.core.Is;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RunWith(MockitoJUnitRunner.class)
public class GithubApiClientTest {
    private MockGithubOauthConfiguration config = new MockGithubOauthConfiguration(Duration.ofDays(1));
    private ObjectMapper mapper = new ObjectMapper();

    private List<GithubTeam> mockTeams() {
        GithubOrg org = new GithubOrg();
        org.setLogin("TEST-ORG");

        List<GithubTeam> teams = new ArrayList<>();

        GithubTeam team = new GithubTeam();
        team.setOrganization(org);
        team.setName("admin");
        teams.add(team);

        return teams;
    }

    private GithubUser mockUser(String username) {
        GithubUser user = new GithubUser();
        user.setName(username);
        user.setLogin("demo-user");
        return user;
    }

    private Set<GithubOrg> mockOrg(String orgname) {
        Set orgs = new HashSet();
        GithubOrg org = new GithubOrg();
        org.setLogin(orgname);
        orgs.add(org);
        return orgs;
    }

    private HttpResponse createMockResponse(Object entity) throws IOException {
        HttpResponse mockOrgRespone = Mockito.mock(HttpResponse.class, Mockito.RETURNS_DEEP_STUBS);
        Mockito.when(mockOrgRespone.getStatusLine().getStatusCode()).thenReturn(200);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mapper.writeValue(baos, entity);
        byte[] data = baos.toByteArray();
        Mockito.when(mockOrgRespone.getEntity().getContent()).thenReturn(new ByteArrayInputStream(data));
        return mockOrgRespone;
    }

    private HttpClient fullyFunctionalMockClient() throws IOException {
        HttpClient mockClient = Mockito.mock(HttpClient.class);
        mockResponsesForGithubAuthRequest(mockClient);
        return mockClient;
    }

    private void mockResponsesForGithubAuthRequest(HttpClient mockClient) throws IOException {
        HttpResponse mockUserResponse = createMockResponse(mockUser("Hans Wurst"));
        Mockito.when(mockClient.execute(Mockito.any())).thenAnswer(invocationOnMock -> answerOnInvocation(invocationOnMock, mockUserResponse));
    }

    private HttpResponse answerOnInvocation(InvocationOnMock invocationOnMock, HttpResponse mockUserResponse) throws IOException {
        HttpResponse mockTeamResponse = createMockResponse(mockTeams());
        HttpResponse mockOrgsResponse = createMockResponse(mockOrg("TEST-ORG"));

        String uriString = ((HttpGet) invocationOnMock.getArguments()[0]).getURI().toString();
        if (uriString.equals(config.getGithubUserTeamsUri())) {
            return mockTeamResponse;
        } else if (uriString.equals(config.getGithubUserUri())) {
            return mockUserResponse;
        } else if (uriString.equals(config.getGithubUserOrgsUri())) {
            return mockOrgsResponse;
        }
        return null;
    }

    @Test
    public void shouldDoAuthzIfRequestStatusIs200() throws Exception {
        HttpClient mockClient = fullyFunctionalMockClient();

        GithubApiClient clientToTest = new GithubApiClient(mockClient, config);
        GithubPrincipal authorizedPrincipal = clientToTest.authz("demo-user", "DUMMY".toCharArray());

        MatcherAssert.assertThat(authorizedPrincipal.getRoles().size(), Is.is(1));
        MatcherAssert.assertThat(authorizedPrincipal.getRoles().iterator().next(), Is.is("TEST-ORG/admin"));
        MatcherAssert.assertThat(authorizedPrincipal.getUsername(), Is.is("demo-user"));

    }

    @Test(expected = GithubAuthenticationException.class)
    public void shouldNotAuthenticateIfRequestIsNot200() throws Exception {
        HttpClient mockClient = Mockito.mock(HttpClient.class);
        HttpResponse mockRespone = Mockito.mock(HttpResponse.class, Mockito.RETURNS_DEEP_STUBS);
        Mockito.when(mockRespone.getStatusLine().getStatusCode()).thenReturn(403);
        Mockito.when(mockClient.execute(Mockito.any())).thenReturn(mockRespone);

        GithubApiClient clientToTest = new GithubApiClient(mockClient, new MockGithubOauthConfiguration(Duration.ofDays(1)));

        clientToTest.authz("demo-user", "DUMMY".toCharArray());
    }

    @Test(expected = GithubAuthenticationException.class)
    public void shouldNotAuthenticateIfUsernameDoesntMatch() throws Exception {
        HttpClient mockClient = fullyFunctionalMockClient();

        GithubApiClient clientToTest = new GithubApiClient(mockClient, config);
        clientToTest.authz("not-the-demo-user", "DUMMY".toCharArray());
    }

    @Test(expected = GithubAuthenticationException.class)
    public void shouldNotAuthenticateIfUserNotInOrg() throws Exception {
        HttpClient mockClient = fullyFunctionalMockClient();
        config.setGithubOrg("OTHER-ORG");
        GithubApiClient clientToTest = new GithubApiClient(mockClient, config);
        clientToTest.authz("demo-user", "DUMMY".toCharArray());
    }

    @Test
    public void cachedPrincipalReturnsIfNotExpired() throws Exception {
        HttpClient mockClient = fullyFunctionalMockClient();

        GithubApiClient clientToTest = new GithubApiClient(mockClient, config);
        String login = "demo-user";
        char[] token = "DUMMY".toCharArray();
        clientToTest.authz(login, token);

        // We make 2 calls to Github for a single auth check
        Mockito.verify(mockClient, Mockito.times(3)).execute(Mockito.any(HttpGet.class));
        Mockito.verifyNoMoreInteractions(mockClient);

        // This invocation should hit the cache and should not use the client
        clientToTest.authz(login, token);
        Mockito.verifyNoMoreInteractions(mockClient);
    }

    @Test
    public void shouldNotCheckOrgDuringAuthentication() throws Exception {
        HttpClient mockClient = fullyFunctionalMockClient();
        config.setGithubOrg(null);

        GithubApiClient clientToTest = new GithubApiClient(mockClient, config);
        String login = "demo-user";
        char[] token = "DUMMY".toCharArray();
        clientToTest.authz(login, token);

        // We make 2 calls to Github for a single auth check
        Mockito.verify(mockClient, Mockito.times(2)).execute(Mockito.any(HttpGet.class));
        Mockito.verifyNoMoreInteractions(mockClient);

    }

    @Test
    public void principalCacheHonorsTtl() throws Exception {
        HttpClient mockClient = fullyFunctionalMockClient();

        GithubOauthConfiguration configWithShortCacheTtl = new MockGithubOauthConfiguration(Duration.ofMillis(1));
        GithubApiClient clientToTest = new GithubApiClient(mockClient, configWithShortCacheTtl);
        char[] token = "DUMMY".toCharArray();

        clientToTest.authz("demo-user", token);
        // We make 2 calls to Github for a single auth check
        Mockito.verify(mockClient, Mockito.times(3)).execute(Mockito.any(HttpGet.class));
        Mockito.verifyNoMoreInteractions(mockClient);

        // Wait a bit for the cache to become invalidated
        Thread.sleep(10);

        // Mock the responses again so a second auth attempt works
        Mockito.reset(mockClient);
        mockResponsesForGithubAuthRequest(mockClient);
        // This should also hit Github because the cache TTL has elapsed
        clientToTest.authz("demo-user", token);
        // We make 3 calls to Github for a single auth check
        Mockito.verify(mockClient, Mockito.times(3)).execute(Mockito.any(HttpGet.class));
        Mockito.verifyNoMoreInteractions(mockClient);
    }

    @Test
    public void shouldAcceptOrgAnywhereInList() throws Exception {
        HttpClient mockClient = fullyFunctionalMockClient();
        config.setGithubOrg("TEST-ORG,TEST-ORG2");
        GithubApiClient clientToTest = new GithubApiClient(mockClient, config);
        GithubPrincipal authorizedPrincipal = clientToTest.authz("demo-user", "DUMMY".toCharArray());
        MatcherAssert.assertThat(authorizedPrincipal.getRoles().iterator().next(), Is.is("TEST-ORG/admin"));

        HttpClient mockClient2 = fullyFunctionalMockClient();
        config.setGithubOrg("TEST-ORG2,TEST-ORG");
        GithubApiClient clientToTest2 = new GithubApiClient(mockClient2, config);
        GithubPrincipal authorizedPrincipal2 = clientToTest2.authz("demo-user", "DUMMY".toCharArray());
        MatcherAssert.assertThat(authorizedPrincipal2.getRoles().iterator().next(), Is.is("TEST-ORG/admin"));
    }
}


text:
angular.module('myApp')
  .directive('passwordMatch', function() {
    return {
      require: 'ngModel',
      scope: {
        otherModelValue: '=passwordMatch'
      },
      link: function(scope, element, attributes, ngModel) {
        ngModel.$validators.compareTo = function(modelValue) {
          return modelValue === scope.otherModelValue;
        };
        scope.$watch('otherModelValue', function() {
          ngModel.$validate();
        });
      }
    };
  });


text:
** DO NOT OPEN NEW ISSUES ON THIS REPOSITORY **

This repository has not been marked archived/read-only, as we do periodically
update the list of packages and/or their constraints. However, this repository
is a _metapackage_, and is only used to install the various packages listed in
its `composer.json`.

If you find an issue, you should determine which package is responsible, and
report against the correct package repository. As an example, if you see an
exception reported that mentions `Zend\Db\Exception\RuntimeException`, this
indicates an issue with the zend-db package, and should be reported against the
zendframework/zend-db repository.

In the majority of cases, we will close any new issues without comment.


text:
package com.codahale.metrics.jvm;

import com.codahale.metrics.RatioGauge;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;

/**
 * A gauge for the ratio of used to total file descriptors.
 */
public class FileDescriptorRatioGauge extends RatioGauge {
    private static boolean unixOperatingSystemMXBeanExists = false;

    private final OperatingSystemMXBean os;

    static {
        try {
            Class.forName("com.sun.management.UnixOperatingSystemMXBean");
            unixOperatingSystemMXBeanExists = true;
        } catch (ClassNotFoundException e) {
            // do nothing
        }
    }

    /**
     * Creates a new gauge using the platform OS bean.
     */
    public FileDescriptorRatioGauge() {
        this(ManagementFactory.getOperatingSystemMXBean());
    }

    /**
     * Creates a new gauge using the given OS bean.
     *
     * @param os an {@link OperatingSystemMXBean}
     */
    public FileDescriptorRatioGauge(OperatingSystemMXBean os) {
        this.os = os;
    }

    @Override
    protected Ratio getRatio() {
        if (unixOperatingSystemMXBeanExists && os instanceof com.sun.management.UnixOperatingSystemMXBean) {
            final com.sun.management.UnixOperatingSystemMXBean unixOs = (com.sun.management.UnixOperatingSystemMXBean) os;
            return Ratio.of(unixOs.getOpenFileDescriptorCount(), unixOs.getMaxFileDescriptorCount());
        } else {
            return Ratio.of(Double.NaN, Double.NaN);
        }
    }
}


text:
//  **************************************
//  File:        KProcessView.cpp
//  Copyright:   Copyright(C) 2013-2017 Wuhan KOTEI Informatics Co., Ltd. All rights reserved.
//  Website:     http://www.nuiengine.com
//  Description: This code is part of NUI Engine (NUI Graphics Lib)
//  Comments:
//  Rev:         2
//  Created:     2017/4/11
//  Last edit:   2017/4/28
//  Author:      Chen Zhi
//  E-mail:      cz_666@qq.com
//  License: APACHE V2.0 (see license file)
//  ***************************************
#include "KProcessView.h"
#include "DataSync.h"
#include "KShapeDrawable.h"
#include "boost/lexical_cast.hpp"
#include "KFontManager.h"
//////////////////////////////////////////////////////////////////////////
// KProcessView
KProcessView::KProcessView()
{
	m_value = 0;
	m_e_dir = PROCESS_Horizontal;
	m_b_process_clip = TRUE;
	m_b_auto_center_text = FALSE;
}

KProcessView::~KProcessView()
{

}

void KProcessView::setIconDrawableRect(int l, int r, int w, int h)
{
	if (m_b_process_clip)
	{
		m_icon_drawable->SetClip( RERect::MakeXYWH(l, r, w, h ) );
	}
	else
	{
		m_icon_drawable->setRect( l, r, w, h );
	}
}

void KProcessView::init(PROCESS_DIR e)
{
	m_e_dir = e;

	RERect rect = m_icon_drawable->GetRect();
	switch (e)
	{
	case PROCESS_Horizontal://水平
		setIconDrawableRect( rect.left(), rect.top(), 0, rect.height());
		break;
	case PROCESS_Vertical:
		setIconDrawableRect(  rect.left(), rect.top(), rect.width(), 0 );
		break;
	}

	if (m_b_auto_center_text)
	{
		m_text_drawable->setRect(  (m_rect.width() -50)/2, m_rect.height()/2-10, 50, 28 );
	}
}

void KProcessView::enableProcessClip(kn_bool b)
{
	m_b_process_clip = b;
}

void KProcessView::setValue(int iPos)    //设定进度的起始位置
{
	if (m_text_drawable->isShow())
	{
		kn_string str = boost::lexical_cast<kn_string>(iPos);
		str += _T("%");
		m_text_drawable->SetText(str);
		int w = m_text_drawable->getTextWidth();

		if (m_b_auto_center_text)
		{
			RERect txt_rect = m_text_drawable->GetRect();
			m_text_drawable->SetRect( RERect::MakeXYWH( (m_rect.width() -w)/2, txt_rect.top(), w, txt_rect.height()) );
		}
	}

	if (iPos == 0)
	{
		m_icon_drawable->SetShow(FALSE);
	}
	else
	{
		m_icon_drawable->SetShow(TRUE);
		RERect rect;
		if (m_b_process_clip)
		{
			rect = m_icon_drawable->GetRect();
		}
		else
		{//非裁剪显示,icon rect不断变化,不能使用,但是用bk的,如果bk和icon不一样大也有问题
			rect = m_bk_drawable->GetRect();
		}

		switch (m_e_dir)
		{
		case PROCESS_Horizontal:
			setIconDrawableRect( rect.left(), rect.top(), iPos * rect.width()/100, rect.height() );
			break;
		case PROCESS_Vertical:
			setIconDrawableRect(  rect.left(), rect.top()+ (100-iPos) * rect.height()/100, rect.width(), iPos * rect.height()/100 );
			break;
		}
	}

	m_value = iPos;
}

int KProcessView::getValue()
{
	return m_value;
}

//////////////////////////////////////////////////////////////////////////
// KProcessView
KProcessCirleView::KProcessCirleView()
{

}

KProcessCirleView::~KProcessCirleView()
{

}

void KProcessCirleView::init(REColor color)
{
	KCircleShape* p_shape2 = new KCircleShape(m_rect.width()/2, m_rect.height()/2, m_rect.width()/2 );
	REColor clr = ARGB(255, 223,223,223) ;
	p_shape2->setFillColor( clr );
	p_shape2->initPaint();
	KShapeDrawable_PTR drawable = KShapeDrawable_PTR(new KShapeDrawable( p_shape2) );
	drawable->SetRect( RERect::MakeXYWH(0,0, m_rect.width(), m_rect.height() ) );
	setBKDrawable(drawable);

	int interval = 8; //边框
	KArcShape* p_shape = new KArcShape(RERect::MakeXYWH(0,0, m_rect.width(), m_rect.height() ) );
	p_shape->setStartAngle(-90);
	p_shape->setSweepAngle(0);
	p_shape->setFillColor(color);
	p_shape->initPaint();
	m_arc_drawable = KShapeDrawable_PTR(new KShapeDrawable( p_shape) );
	m_arc_drawable->setRect(0,0,m_rect.width(), m_rect.height() );

	addDrawable(m_arc_drawable);

	//覆盖层
	p_shape2 = new KCircleShape(m_rect.width()/2, m_rect.height()/2, m_rect.width()/2 - interval );
	clr = ARGB(255, 240,240,240) ;
	p_shape2->setFillColor( clr );
	p_shape2->initPaint();
	drawable = KShapeDrawable_PTR(new KShapeDrawable( p_shape2) );
	drawable->SetRect( RERect::MakeXYWH(0,0, m_rect.width(), m_rect.height() ) );
	addDrawable(drawable);

	//Txt提到最上层
//	KDrawable_PTR tmp = m_lst_drawable[2];
	//删除老的txt
	m_lst_drawable.erase( m_lst_drawable.begin()+2 );

	m_text_drawable = KTextDrawable_PTR (new KTextDrawable(_T(""), RE_ColorBLACK, 40, REPaint::kCenter_Align) );
	//m_text_drawable->setFontName("Microsoft YaHei");
	m_text_drawable->setFont(GetFontManagerSingleton()->GetFontFromFile(_T("./resource/bebas.ttf") ));
	m_text_drawable->SetRect(RERect::MakeXYWH(0, 15, m_rect.width(), m_rect.height() ) );
	m_text_drawable->setColor(color);
	addDrawable(m_text_drawable);

}

void KProcessCirleView::setValue(int iPos)    //设定进度的起始位置
{
	if (m_text_drawable->isShow())
	{
		kn_string str = boost::lexical_cast<kn_string>(iPos);
		str += _T("%");
		m_text_drawable->SetText(str);
//		int w = m_text_drawable->getTextWidth();
		//RERect txt_rect = m_text_drawable->GetRect();
		//m_text_drawable->SetRect( RERect::MakeXYWH( (m_rect.width() -w)/2, txt_rect.top(), w, txt_rect.height()) );

	}

	KArcShape* p_shape = (KArcShape* )(m_arc_drawable->getShape() );
	if (p_shape)
	{
		p_shape->setSweepAngle( iPos*360/100);
	}

	m_value = iPos;
}

//////////////////////////////////////////////////////////////////////////
// KLoadingView

KLoadingView::KLoadingView(): KView()
{

}

KLoadingView::~KLoadingView()
{
	endAnimation();
}

// 设置动画图片
void KLoadingView::setCycleImage(const kn_string& strResPath)
{
	KImageDrawable_PTR drawable = KImageDrawable_PTR(new KImageDrawable(strResPath));

	REPaint* paint = drawable->GetPaint();
	paint->setFilterBitmap(true);
	paint->setAntiAlias(true);

    drawable->SetFillType(KImageDrawable::FILL_ALL);

	setCycleDrawable(drawable);
}

void KLoadingView::setCycleDrawable(KDrawable_PTR drawable)
{
	writeLock lock(m_lst_drawable_mutex);

	VEC_DRAWABLE::iterator it = find(m_lst_drawable.begin(), m_lst_drawable.end(), drawable);
	if(it == m_lst_drawable.end())
	{
		m_lst_drawable.push_back(drawable);
	}

	m_drawable_cycle = drawable;
}

void KLoadingView::startAnimation(kn_int iCycleTime,kn_int frame_time)
{
 	CNUIAnimation* pNUIAnimation = new CNUIAnimation (iCycleTime, 0, 0);	//  一圈

	RERect rect = m_drawable_cycle->GetRect();

	CPropertyAngle* pAngleStart = new CPropertyAngle(shared_from_this(), 0, rect.width() / 2, rect.height() / 2);
	CPropertyAngle* pAngleEnd = new CPropertyAngle(shared_from_this(), 360, rect.width() / 2, rect.height() / 2);
	CPropertyAnimationData* pAnimationData = new CPropertyAnimationData(pAngleStart, pAngleEnd, KEasingCurve::Linear);
	pNUIAnimation->addAnimationData(pAnimationData);
	pNUIAnimation->setLoopType(CNUIAnimation::LOOP_TIME);
	pNUIAnimation->setLoopTimes(LOOP_ALWAYS);
	pNUIAnimation->setFrameTime(frame_time);
	m_ani_thread.addAnimation(pNUIAnimation);

	m_ani_thread.Start();
}

void KLoadingView::endAnimation()
{
	m_ani_thread.Stop();
}


text:
"""
This module contains code to efficiently enumerate subgraphs
(for some arbitrary definition of efficiently).

Most of the code is based on
Wernicke, Sebastian (2006). Efficient Detection of Network Motifs.
"""

import random
import networkx as nx
from multiprocessing import Pool # CPUs

def open_neighborhood(graph, node_subset):
    """
    $N(V')$: returns the set of all nodes that are in the graph's node set
    (but not in the given subset) and are adjacent to at least one node
    in the subset. Based on Wernicke (2006).

    WARNING: different results for directed vs. undirected graphs
    """
    open_nbh = set()
    node_set = set(graph.nodes())
    nodes_not_in_subset = node_set - node_subset
    for node_not_in_subset in nodes_not_in_subset:
        if any(neighbor in node_subset
               for neighbor in graph.neighbors(node_not_in_subset)):
            open_nbh.add(node_not_in_subset)
    return open_nbh

def exclusive_neighborhood(graph, node, node_subset):
    """
    given a node v that doesn't belong to the given node subset V',
    returns all nodes that are neighbors of v, but don't belong to
    the node subset V' or its open neighborhood N(V').
    Based on Wernicke (2006).

    WARNING: different results for directed vs. undirected graphs
    """
    assert node not in node_subset
    open_nbh = open_neighborhood(graph, node_subset)

    exclusive_nbh = set()
    for neighbor in graph.neighbors(node):
        if neighbor not in node_subset and neighbor not in open_nbh:
            exclusive_nbh.add(neighbor)
    return exclusive_nbh

def enumerate_all_size_k_subgraphs(graph, k):
    """
    returns all subgraphs of the given graph that have k nodes.
    The algorith is called ``ESU`` in Wernicke (2006).
    """
    assert all(isinstance(node, int) for node in graph.nodes_iter())
    if not 1 <= k <= len(graph):
        return []

    all_subgraphs = []
    for node in graph.nodes_iter():
        extension = {neighbor for neighbor in graph.neighbors(node)
                     if neighbor > node}
        subgraphs = extend_subgraph(graph, k, {node}, extension, node)
        if isinstance(subgraphs, list):
            all_subgraphs.extend(subgraphs)
        else: # isinstance(subgraphs, nx.Graph)
            all_subgraphs.append(subgraphs)
    return all_subgraphs

def extend_subgraph(graph, k, subgraph_nodes, extension_nodes, node):
    """
    This function is the recursively called part of the ``ESU`` algorithm
    in Wernicke (2006).
    """
    if len(subgraph_nodes) == k:
        return graph.subgraph(subgraph_nodes)

    all_subgraphs = []
    while extension_nodes:
        # remove random node w from extension_nodes
        random_extension_node = random.choice(list(extension_nodes))
        extension_nodes.remove(random_extension_node)
        exclusive_neighbors = {neighbor for neighbor in exclusive_neighborhood(graph,
                                                                               random_extension_node,
                                                                               subgraph_nodes)
                               if neighbor > node}
        vbar_extension = extension_nodes | exclusive_neighbors # union
        extended_subgraph_nodes = subgraph_nodes | {random_extension_node}
        subgraphs = extend_subgraph(graph, k, extended_subgraph_nodes, vbar_extension, node)

        if isinstance(subgraphs, list):
            all_subgraphs.extend(subgraphs)
        else: # isinstance(subgraphs, nx.Graph)
            all_subgraphs.append(subgraphs)
    return all_subgraphs

def __extract_subgraphs_from_node(graph, node, k):
    extension = {neighbor for neighbor in graph.neighbors(node)
                 if neighbor > node}
    return extend_subgraph(graph, k, {node}, extension, node)

def enumerate_all_size_k_subgraphs_parellel(graph, k, num_of_workers=4):
    """
    Trivial parallelization of the ESU algorithm from Wernicke (2006).
    """
    assert all(isinstance(node, int) for node in graph.nodes_iter())
    if not 1 <= k <= len(graph):
        return []

    pool = Pool(num_of_workers) # number of CPUs / workers
    results = [pool.apply_async(__extract_subgraphs_from_node,
                                args=(graph, node, k))
               for node in graph.nodes_iter()]

    pool.close()
    pool.join()
    return [result.get() for result in results]

def enumerate_all_subgraphs_upto_size_k(document_graph, k):
    """
    returns all subgraphs of a DiscourseDocumentGraph (i.e. a MultiDiGraph)
    with up to k nodes.

    WARNING: This just calls ESU / enumerate_all_size_k_subgraphs() for
    1 ... k.

    TODO: optimize the algorithm to use the results of ESU(k-1) to calculate
    ESU(k).
    """
    document_nodes = len(document_graph)
    if k > document_nodes:
        k = document_nodes

    all_subgraphs = []
    int_graph = nx.convert_node_labels_to_integers(nx.DiGraph(document_graph),
                                                   first_label=1,
                                                   label_attribute='node_id')
    for i in xrange(1, k+1):
        size_k_subgraphs = enumerate_all_size_k_subgraphs(int_graph, i)
        all_subgraphs.extend(size_k_subgraphs)
    return all_subgraphs

def enumerate_all_subgraphs_upto_size_k_parallel(document_graph, k, num_of_workers=4):
    """
    returns all subgraphs of a DiscourseDocumentGraph (i.e. a MultiDiGraph)
    with up to k nodes. This is a trivially parallelized version of
    enumerate_all_subgraphs_upto_size_k()
    """
    document_nodes = len(document_graph)
    if k > document_nodes:
        k = document_nodes

    int_graph = nx.convert_node_labels_to_integers(nx.DiGraph(document_graph),
                                                   first_label=1,
                                                   label_attribute='node_id')

    pool = Pool(processes=num_of_workers) # number of CPUs
    results = [pool.apply_async(enumerate_all_size_k_subgraphs, args=(int_graph, i))
                for i in xrange(1, k+1)]
    pool.close()
    pool.join()

    subgraphs = []
    for result in results:
        tmp_result = result.get()
        if isinstance(tmp_result, list):
            subgraphs.extend(tmp_result)
        else:
            subgraphs.append(tmp_result)
    return subgraphs


text:
package attribute

import (
	"sync"

	mixerpb "istio.io/api/mixer/api/v1"
)

// Tracker is responsible for tracking a set of live attributes over time.
//
// An instance of this type is created for every gRPC stream incoming to the
// mixer. The instance tracks a current dictionary along with a set of
// attribute contexts.
type Tracker interface {
	// StartRequest refreshes the set of attributes tracked based on an incoming proto.
	//
	// This returns a Bag that can be used to query and update the current
	// set of attributes.
	//
	// If this returns a non-nil error, it indicates there was a problem in the
	// supplied Attributes proto. When this happens, none of the tracked attribute
	// state will have been affected.
	StartRequest(attrs *mixerpb.Attributes) (MutableBag, error)

	// EndRequest performs post-request cleanup
	EndRequest()

	// Done indicates the tracker can be reclaimed.
	Done()
}

type tracker struct {
	dictionaries *dictionaries

	// all active attribute contexts
	contexts map[int32]*rootBag

	// the current live dictionary
	currentDictionary dictionary

	// the bag currently in use by an outstanding request
	currentChild *mutableBag
}

var trackers = sync.Pool{
	New: func() interface{} {
		return &tracker{
			contexts: make(map[int32]*rootBag),
		}
	},
}

func getTracker(dictionaries *dictionaries) *tracker {
	at := trackers.Get().(*tracker)
	at.dictionaries = dictionaries
	return at
}

func (at *tracker) Done() {
	for k, rb := range at.contexts {
		rb.Done()
		delete(at.contexts, k)
	}

	at.dictionaries.Release(at.currentDictionary)
	at.currentDictionary = nil
	at.currentChild = nil
	at.dictionaries = nil

	trackers.Put(at)
}

func (at *tracker) StartRequest(attrs *mixerpb.Attributes) (MutableBag, error) {
	// replace the dictionary if requested
	if len(attrs.Dictionary) > 0 {
		at.dictionaries.Release(at.currentDictionary)
		at.currentDictionary = at.dictionaries.Intern(attrs.Dictionary)
	}

	// find the context or create it if needed
	rb := at.contexts[attrs.AttributeContext]
	if rb == nil {
		rb = getRootBag()
		at.contexts[attrs.AttributeContext] = rb
	}

	if err := rb.update(at.currentDictionary, attrs); err != nil {
		return nil, err
	}

	// to maintain the integrity of the API-level attribute protocol,
	// we need to ensure that the rest of the mixer's processing pipeline
	// doesn't mutate the set of protocol-level attributes. We do this
	// by returning a child bag.
	at.currentChild = rb.child()
	return at.currentChild, nil
}

func (at *tracker) EndRequest() {
	if at.currentChild != nil {
		at.currentChild.Done()
		at.currentChild = nil
	}
}


text:
<?php

namespace OrganisationApi\Service\Validator\UpdateProperty;

use DvsaCommon\Model\AuthorisedExaminerPatchModel;
use DvsaCommonApi\Service\Validator\AbstractValidator;
use DvsaCommonApi\Service\Validator\ErrorSchema;
use DvsaCommonApi\Service\Validator\ValidatorInterface;

class AeNameValidator extends AbstractValidator implements ValidatorInterface
{
    public function validate(array $data)
    {
        if (empty($data[AuthorisedExaminerPatchModel::NAME])) {
            $errorSchema = new ErrorSchema();
            $errorSchema->add('Name - must not be empty');
            $errorSchema->throwIfAny();
        }
    }
}


text:
Sequel.migration do
  change do
    add_column :averages, :visible, Integer
    from(:averages).update(visible: true)
  end
end


text:
package redis.clients.util;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Sharded<R, S extends ShardInfo<R>> {

	public static final int DEFAULT_WEIGHT = 1;
	private TreeMap<Long, S> nodes;
	private final Hashing algo;
	private final Map<ShardInfo<R>, R> resources = new LinkedHashMap<ShardInfo<R>, R>();

	/**
	 * The default pattern used for extracting a key tag. The pattern must have a
	 * group (between parenthesis), which delimits the tag to be hashed. A null
	 * pattern avoids applying the regular expression for each lookup, improving
	 * performance a little bit is key tags aren't being used.
	 */
	private Pattern tagPattern = null;
	// the tag is anything between {}
	public static final Pattern DEFAULT_KEY_TAG_PATTERN = Pattern.compile("\\{(.+?)\\}");

	public Sharded(List<S> shards) {
		this(shards, Hashing.MURMUR_HASH); // MD5 is really not good as we works
		// with 64-bits not 128
	}

	public Sharded(List<S> shards, Hashing algo) {
		this.algo = algo;
		initialize(shards);
	}

	public Sharded(List<S> shards, Pattern tagPattern) {
		this(shards, Hashing.MURMUR_HASH, tagPattern); // MD5 is really not good
		// as we works with
		// 64-bits not 128
	}

	public Sharded(List<S> shards, Hashing algo, Pattern tagPattern) {
		this.algo = algo;
		this.tagPattern = tagPattern;
		initialize(shards);
	}

	private void initialize(List<S> shards) {
		nodes = new TreeMap<Long, S>();

		for (int i = 0; i != shards.size(); ++i) {
			final S shardInfo = shards.get(i);
			if (shardInfo.getName() == null)
				for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
					nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo);
				}
			else
				for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
					nodes.put(this.algo.hash(shardInfo.getName() + "*" + shardInfo.getWeight() + n), shardInfo);
				}
			resources.put(shardInfo, shardInfo.createResource());
		}
	}

	public R getShard(byte[] key) {
		return resources.get(getShardInfo(key));
	}

	public R getShard(String key) {
		return resources.get(getShardInfo(key));
	}

	public S getShardInfo(byte[] key) {
		SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));
		if (tail.isEmpty()) {
			return nodes.get(nodes.firstKey());
		}
		return tail.get(tail.firstKey());
	}

	public S getShardInfo(String key) {
		return getShardInfo(SafeEncoder.encode(getKeyTag(key)));
	}

	/**
	 * A key tag is a special pattern inside a key that, if preset, is the only part
	 * of the key hashed in order to select the server for this key.
	 *
	 * @param key
	 * @return The tag if it exists, or the original key
	 */
	public String getKeyTag(String key) {
		if (tagPattern != null) {
			Matcher m = tagPattern.matcher(key);
			if (m.find())
				return m.group(1);
		}
		return key;
	}

	public Collection<S> getAllShardInfo() {
		return Collections.unmodifiableCollection(nodes.values());
	}

	public Collection<R> getAllShards() {
		return Collections.unmodifiableCollection(resources.values());
	}
}