text:
import datetime

from nose.tools import eq_

from fjord.base.tests import TestCase
from fjord.feedback.models import (
    Product,
    Response,
    ResponseEmail,
    ResponseContext,
    ResponsePI,
    ResponseMappingType,
    purge_data
)
from fjord.feedback.tests import (
    ResponseFactory,
    ResponseEmailFactory,
    ResponseContextFactory,
    ResponsePIFactory
)
from fjord.feedback.utils import compute_grams
from fjord.search.tests import ElasticTestCase
from fjord.feedback.config import TRUNCATE_LENGTH
from fjord.journal.models import Record

class TestResponseModel(TestCase):
    def test_description_truncate_on_save(self):
        # Extra 10 characters get lopped off on save.
        resp = ResponseFactory(description=('a' * (TRUNCATE_LENGTH + 10)))
        eq_(resp.description, 'a' * TRUNCATE_LENGTH)

    def test_description_strip_on_save(self):
        # Nix leading and trailing whitespace.
        resp = ResponseFactory(description=u'   \n\tou812\t\n   ')
        eq_(resp.description, u'ou812')

    def test_url_domain(self):
        # Test a "normal domain"
        resp = ResponseFactory(url=u'http://foo.example.com.br/blah')
        eq_(resp.url_domain, u'example.com.br')
        assert isinstance(resp.url_domain, unicode)

        # Test a unicode domain
        resp = ResponseFactory(
            url=u'http://\u30c9\u30e9\u30af\u30a810.jp/dq10_skillpoint.html')
        eq_(resp.url_domain, u'\u30c9\u30e9\u30af\u30a810.jp')
        assert isinstance(resp.url_domain, unicode)

    def test_rating_to_happy(self):
        """Test that we do populate happy from rating"""
        data = {
            1: False,
            2: False,
            3: False,
            4: True,
            5: True
        }
        for rat, expected in data.items():
            # Create the response, but DON'T save it to the db.
            resp = ResponseFactory.build(happy=None, rating=rat)
            resp.save()
            eq_(resp.happy, expected)

    def test_happy_to_rating(self):
        """Test we don't populate rating from happy"""
        resp = ResponseFactory.build(happy=True, rating=None)
        resp.save()
        eq_(resp.rating, None)

        resp = ResponseFactory.build(happy=False, rating=None)
        resp.save()
        eq_(resp.rating, None)

class TestAutoTranslation(TestCase):
    def setUp(self):
        # Wipe out translation system for all products.

        # FIXME - might be better to save the state and restore it in tearDown
        # rather than stomp in both cases. But stomping works for now.
        Product.objects.update(translation_system=u'')
        super(TestAutoTranslation, self).setUp()

    def tearDown(self):
        # Wipe out translation system for all products.
        Product.objects.update(translation_system=u'')
        super(TestAutoTranslation, self).tearDown()

    def test_auto_translation(self):
        prod = Product.objects.get(db_name='firefox')
        prod.translation_system = u'dennis'
        prod.save()

        resp = ResponseFactory(
            locale=u'es',
            product=u'firefox',
            description=u'hola'
        )

        # Fetch it from the db again
        resp = Response.objects.get(id=resp.id)
        eq_(resp.translated_description, u'\xabHOLA\xbb')

class TestGenerateTranslationJobs(TestCase):
    def setUp(self):
        # Wipe out translation system for all products.

        # FIXME - might be better to save the state and restore it in tearDown
        # rather than stomp in both cases. But stomping works for now.
        Product.objects.update(translation_system=u'')
        super(TestGenerateTranslationJobs, self).setUp()

    def tearDown(self):
        # Wipe out translation system for all products.
        Product.objects.update(translation_system=u'')
        super(TestGenerateTranslationJobs, self).tearDown()

    def test_english_no_translation(self):
        """English descriptions should get copied over"""
        resp = ResponseFactory(
            locale=u'en-US',
            description=u'hello',
            translated_description=u''
        )

        # No new jobs should be generated
        eq_(len(resp.generate_translation_jobs()), 0)

        # Re-fetch from the db and make sure the description was copied over
        resp = Response.objects.get(id=resp.id)
        eq_(resp.description, resp.translated_description)

    def test_english_gb_no_translation(self):
        """en-GB descriptions should get copied over"""
        resp = ResponseFactory(
            locale=u'en-GB',
            description=u'hello',
            translated_description=u''
        )

        # No new jobs should be generated
        eq_(len(resp.generate_translation_jobs()), 0)

        # Re-fetch from the db and make sure the description was copied over
        resp = Response.objects.get(id=resp.id)
        eq_(resp.description, resp.translated_description)

    def test_english_with_dennis(self):
        """English descriptions should get copied over"""
        resp = ResponseFactory(
            locale=u'en-US',
            product=u'firefox',
            description=u'hello',
            translated_description=u''
        )

        # Set the product up for translation *after* creating the response
        # so that it doesn't get auto-translated because Response is set up
        # for auto-translation.
        prod = Product.objects.get(db_name='firefox')
        prod.translation_system = u'dennis'
        prod.save()

        # No new jobs should be generated
        eq_(len(resp.generate_translation_jobs()), 0)

        # Re-fetch from the db and make sure the description was copied over
        resp = Response.objects.get(id=resp.id)
        eq_(resp.description, resp.translated_description)

    def test_spanish_no_translation(self):
        """Spanish should not get translated"""
        resp = ResponseFactory(
            locale=u'es',
            product=u'firefox',
            description=u'hola',
            translated_description=u''
        )

        # No jobs should be translated
        eq_(len(resp.generate_translation_jobs()), 0)

        # Nothing should be translated
        eq_(resp.translated_description, u'')

    def test_spanish_with_dennis(self):
        """Spanish should get translated"""
        resp = ResponseFactory(
            locale=u'es',
            product=u'firefox',
            description=u'hola',
            translated_description=u''
        )

        # Set the product up for translation *after* creating the response
        # so that it doesn't get auto-translated because Response is set up
        # for auto-translation.
        prod = Product.objects.get(db_name='firefox')
        prod.translation_system = u'dennis'
        prod.save()

        # One job should be generated
        jobs = resp.generate_translation_jobs()
        eq_(len(jobs), 1)
        job = jobs[0]
        eq_(job[1:], (u'dennis', u'es', u'description',
                      u'en', 'translated_description'))

        eq_(resp.translated_description, u'')

    def test_spanish_with_dennis_and_existing_translations(self):
        """Response should pick up existing translation"""
        existing_resp = ResponseFactory(
            locale=u'es',
            product=u'firefox',
            description=u'hola',
            translated_description=u'DUDE!'
        )

        resp = ResponseFactory(
            locale=u'es',
            product=u'firefox',
            description=u'hola',
            translated_description=u''
        )

        # Set the product up for translation *after* creating the response
        # so that it doesn't get auto-translated because Response is set up
        # for auto-translation.
        prod = Product.objects.get(db_name='firefox')
        prod.translation_system = u'dennis'
        prod.save()

        # No jobs should be translated
        eq_(len(resp.generate_translation_jobs()), 0)
        eq_(resp.translated_description, existing_resp.translated_description)

class TestComputeGrams(TestCase):
    def test_empty(self):
        eq_(compute_grams(u''), [])

    def test_parsing(self):
        # stop words are removed
        eq_(compute_grams(u'i me him her'), [])

        # capital letters don't matter
        eq_(compute_grams(u'I ME HIM HER'), [])

        # punctuation nixed
        eq_(compute_grams(u'i, me, him, her'), [])

    def test_bigrams(self):
        # Note: Tokens look weird after being analyzed probably due to
        # the stemmer. We could write a bunch of code to "undo" some
        # of the excessive stemming, but it's probably an exercise in
        # futility. Ergo the tests look a little odd. e.g. "youtub"

        # One word a bigram does not make
        eq_(compute_grams(u'youtube'), [])

        # Two words is the minimum number to create a bigram
        eq_(sorted(compute_grams(u'youtube crash')),
            ['crash youtube'])

        # Three words creates two bigrams
        eq_(sorted(compute_grams(u'youtube crash flash')),
            ['crash flash', 'crash youtube'])

        # Four words creates three bigrams
        eq_(sorted(compute_grams(u'youtube crash flash bridge')),
            ['bridge flash', 'crash flash', 'crash youtube'])

        # Nix duplicate bigrams
        eq_(sorted(compute_grams(u'youtube crash youtube flash')),
            ['crash youtube', 'flash youtube'])

class TestParseData(ElasticTestCase):
    def test_purge(self):
        now = datetime.datetime.now()
        cutoff = now - datetime.timedelta(days=5)

        # Create 10 objs of each type--one for each day for the last
        # 10 days.
        for i in range(10):
            ResponseEmailFactory(
                opinion__created=(now - datetime.timedelta(days=i))
            )
            ResponseContextFactory(
                opinion__created=(now - datetime.timedelta(days=i))
            )
            ResponsePIFactory(
                opinion__created=(now - datetime.timedelta(days=i))
            )

        # Note that this creates 30 Response objects.

        # Since creating the objects and indexing them happens very
        # quickly in tests, we hit a race condition and the has_email
        # column ends up being false. So instead we just drop the
        # index and rebuild it.
        self.setup_indexes()

        # Make sure everything is in the db
        eq_(Response.objects.count(), 30)
        eq_(ResponseEmail.objects.count(), 10)
        eq_(ResponseContext.objects.count(), 10)
        eq_(ResponsePI.objects.count(), 10)

        # Make sure everything is in the index
        resp_s = ResponseMappingType.search()
        eq_(resp_s.count(), 30)
        eq_(resp_s.filter(has_email=True).count(), 10)

        # Now purge everything older than 5 days and make sure things
        # got removed that should have gotten removed. Also check if
        # there is a journal entry for the purge operation.
        cutoff = now - datetime.timedelta(days=5)
        purge_data(cutoff=cutoff)

        self.refresh()

        eq_(Response.objects.count(), 30)
        eq_(ResponseEmail.objects.count(), 5)
        eq_(ResponseEmail.objects.filter(
            opinion__created__gte=cutoff).count(),
            5)
        eq_(ResponseContext.objects.count(), 5)
        eq_(ResponseContext.objects.filter(
            opinion__created__gte=cutoff).count(),
            5)
        eq_(ResponsePI.objects.count(), 5)
        eq_(ResponsePI.objects.filter(
            opinion__created__gte=cutoff).count(),
            5)
        eq_(1,
            Record.objects.filter(action='purge_data').count())
        expected_msg = ('feedback_responseemail: 5, '
                        'feedback_responsecontext: 5, '
                        'feedback_responsepi: 5')
        eq_(expected_msg,
           Record.objects.get(action='purge_data').msg)

        # Everything should still be in the index, but the number of
        # things with has_email=True should go down
        resp_s = ResponseMappingType.search()
        eq_(resp_s.count(), 30)
        eq_(resp_s.filter(has_email=True).count(), 5)


text:
package com.github.mrgoro.interactivedata.api.data.operations.granularity;

import com.github.mrgoro.interactivedata.api.data.bean.DataObject;
import com.github.mrgoro.interactivedata.api.data.operations.Operation;
import com.github.mrgoro.interactivedata.api.data.operations.OperationData;

import java.util.function.Function;

/**
 * Specification of a Granularity.
 *

 * A granularity is capable of returning a different granularity levels of a single object. Granularity is used
 * when grouping multiple objects. Based on the level of granularity the amount of grouping is specified.
 * {@link Function Functions} are used when to aggregate fields that are not grouped.
 *

 * Functions are parameterized with request data and options. Options are set once. Request data originates from
 * a specific request and is therefore set per request. The Framework automatically populates the data for options
 * and requests. Functions only have to specify the form of the data with custom {@link OperationData} classes.
 *
 * @param <D> Type of the Request Data Object
 * @param <O> Type of the Options Object
 * @author Philipp Schürman
 */
public abstract class Granularity<D extends OperationData, O extends OperationData> extends Operation<D, O> {

    /**
     * Transform an object to the specified granularity level.
     *

     * Grouping is based on this object. Equal objects are grouped.
     *
     * @param dataObject Object to transform
     * @return Object at granularity level
     */
    protected abstract Object group(DataObject dataObject);

    /**
     * Get a {@link Function} for grouping from the Granularity.
     *
     * @return Granularity group function
     */
    public Function<DataObject, Object> toGroupFunction() {
        if(shouldOperate()) {
            return this::group;
        } else {
            return this::getProperty;
        }
    }

    public Granularity(String fieldName, Class fieldClass, D requestData, O options) {
        super(fieldName, fieldClass, requestData, options);
    }

}

redpajama_set_name: RedPajamaGithub


text:
  Castetpugon est
       un village
       situé dans le département des Pyrénées-Atlantiques en Aquitaine. Elle totalisait 174 habitants en 2008.

Si vous pensez demenager à Castetpugon, vous pourrez facilement trouver une maison à vendre.

La commune offre quelques  aménagements, elle dispose, entre autres, de une boucle de randonnée.

À proximité de Castetpugon sont positionnées géographiquement les villes de
Taron-Sadirac-Viellenave à 5 km, 190 habitants,
Mascaraàs-Haron localisée à 2 km, 123 habitants,
Baliracq-Maumusson à 2 km, 120 habitants,
Saint-Jean-Poudge localisée à 5 km, 77 habitants,
Conchez-de-Béarn située à 5 km, 103 habitants,
Portet située à 4 km, 169 habitants,
 entre autres. De plus, Castetpugon est située à seulement 16 km de Aire-sur-l'Adour.

Le parc d'habitations, à Castetpugon, était réparti en 2011 en cinq appartements et 99 maisons soit
 un marché plutôt équilibré.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace Xyglo.Brazil
{
    /// <summary>
    /// The type of the Resource
    /// </summary>
    public enum ResourceType
    {
        Image,
        Video,
        Audio,
        Midi
    }

    /// <summary>
    /// Mode identifier for a Resource - how it is applied to a Component
    /// </summary>
    public enum ResourceMode
    {
        None   = 0x000000,  // Default
        Wrap   = 0x000001,  // video or image
        Centre = 0x000002,  // video or image
        Fill   = 0x000004,  // video or image
        Scroll = 0x000008,  // video or image
        Loop   = 0x00000F   // video
    }

    /// <summary>
    /// A Resource is a file type that will be included as an Asset in the app package.
    ///
    /// We can assign a resource to a State or to a Component and they may be re-used.
    ///
    /// </summary>
    [DataContract(Namespace = "http://www.xyglo.com")]
    public class Resource
    {
        public Resource(ResourceType type, string name, string filePath, string description = "")
        {
            m_type = type;
            m_name = name;
            m_filePath = filePath;
            m_description = description;
        }

        public string getName() { return m_name; }
        public string getFilePath() { return m_filePath; }
        public ResourceType getType() { return m_type; }
        public string getDescription() { return m_description; }

        /// <summary>
        /// Name for this resource which should be unique in a Resource collection
        /// </summary>
        [DataMember]
        protected string m_name;

        /// <summary>
        /// Path to this resource
        /// </summary>
        [DataMember]
        protected string m_filePath;

        /// <summary>
        /// Type of this resource
        /// </summary>
        [DataMember]
        protected ResourceType m_type;

        /// <summary>
        /// Description
        /// </summary>
        [DataMember]
        protected string m_description;
    }

    /// <summary>
    /// The instance of a Resource in a Component
    /// </summary>
    [DataContract(Namespace = "http://www.xyglo.com")]
    public class ResourceInstance
    {
        public ResourceInstance(Resource resource, ResourceMode mode = ResourceMode.None, string description = "")
        {
            m_resourceName = resource.getName();
            m_mode = mode;
            m_resource = resource;
        }

        /*
        private void OnCreated()
        {
            m_resource = new Resource(ResourceType.Image, "none");
        }

        [OnDeserializing]
        private void OnDeserializing(StreamingContext c)
        {
            OnCreated();
        }
        */

        /// <summary>
        /// Get the resource reference
        /// </summary>
        /// <returns></returns>
        public Resource getResource() { return m_resource; }

        /// <summary>
        /// Set the resource reference
        /// </summary>
        /// <param name="resource"></param>
        public void setResource(Resource resource) { m_resource = resource; }

        /// <summary>
        /// Get resource mode
        /// </summary>
        /// <returns></returns>
        public ResourceMode getMode() { return m_mode; }

        /// <summary>
        /// Get the resource name
        /// </summary>
        /// <returns></returns>
        public string getResourceName() { return m_resourceName; }

        /// <summary>
        /// Resource pointer - don't serialise
        /// </summary>
        [NonSerialized]
        protected Resource m_resource;

        /// <summary>
        /// Unique name of resource
        /// </summary>
        [DataMember]
        protected string m_resourceName;

        /// <summary>
        /// Resource mode
        /// </summary>
        [DataMember]
        protected ResourceMode m_mode;
    }

}


text:
let path = require('path');

class SetPublicPath {
    register(defaultPath) {
        Config.publicPath = path.normalize(defaultPath.replace(/\/$/, ''));

        return this;
    }
}

module.exports = SetPublicPath;


text:
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2020 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the author nor the names of other contributors may
//      be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////

#pragma once

#include <thread>
#include <mutex>
#include <memory>
#include <musikcore/runtime/IMessageTarget.h>
#include <musikcore/sdk/HttpClient.h>

namespace musik { namespace cube {
    class UpdateCheck: private musik::core::runtime::IMessageTarget {
        public:
            /* args = updateRequired, version, url */
            using Callback = std::function<void(bool, std::string, std::string)>;
            using HttpClient = musik::core::sdk::HttpClient<std::stringstream>;

            static void ShowUpgradeAvailableOverlay(
                const std::string& version, const std::string& url, bool silent = true);

            static void ShowNoUpgradeFoundOverlay();

            DELETE_COPY_AND_ASSIGNMENT_DEFAULTS(UpdateCheck)

            UpdateCheck();
            ~UpdateCheck();

            bool Run(Callback callback);
            void Cancel();

        private:
            void Reset();

            /* IMessageHandler */
            void ProcessMessage(musik::core::runtime::IMessage &message) override;

            std::recursive_mutex mutex;
            Callback callback;
            std::shared_ptr<HttpClient> httpClient;
            std::string result, latestVersion, updateUrl;
    };

} }


text:
"""Common classes for hostinfo unit tests.

Contents:

  RequestHandlerTest
"""

import tests.appenginesdk
from google.apputils import app
from google.apputils import basetest
import mox
import stubout

class GenericContainer(object):
  """Generic data container for testing purposes.

  This class can have attributes set on it (and retrieved to full effect),
  and can have any function called on it (they will do nothing).
  """

  class GenericFunction(object):
    """Emulates a function and does nothing."""

    def __call__(self, *args):
      pass

  def __init__(self, **kwargs):
    """Take all kwargs and set them as retrievable attributes."""
    for key in kwargs:
      setattr(self, key, kwargs[key])

class TestBase(mox.MoxTestBase):
  """Base class."""

class RequestHandlerTest(TestBase):
  """Test class for RequestHandler derived classes."""

  def setUp(self):
    mox.MoxTestBase.setUp(self)
    self.stubs = stubout.StubOutForTesting()
    self.GenericRequestTestSetup()

  def tearDown(self):
    self.mox.UnsetStubs()
    self.stubs.UnsetAll()

  def GetTestClassInstance(self):
    """Return the test class instance."""
    raise NotImplementedError('Must implement GetTestClassInstance')

  def GetTestClassModule(self):
    """Return the module the test class is located in."""
    raise NotImplementedError('Must implement GetTestClassModule')

  def GetTestClassInstanceVariableName(self):
    """Return the name of the test class instance variable.

    Returns:
      str like 'classundertest'
    """
    return 'c'

  def GenericRequestTestSetup(self):
    """Setup a standard mocked webapp.Request test framework."""
    self._test = self.GetTestClassInstance()
    setattr(self, self.GetTestClassInstanceVariableName(), self._test)
    self.request = self.mox.CreateMockAnything()
    self.request.headers = self.mox.CreateMockAnything()
    self.request.headers.get = self.mox.CreateMockAnything()
    self.response = self.mox.CreateMockAnything()
    self.response.headers = self.mox.CreateMockAnything()
    self.send_blob = self.mox.CreateMockAnything()
    self._test.request = self.request
    self._test.response = self.response
    self._test.response.out = self.response
    self._test.send_blob = self.send_blob
    self._set_mock = {}

  def MockSelf(self, name):
    """Mock a method in the tested class's instance."""
    if not name in self._set_mock:
      self.mox.StubOutWithMock(self._test, name)
      self._set_mock[name] = 1

  def MockError(self, status_code):
    """Mock an error().

    Args:
      status_code: int, like 400
    """
    self.MockSelf('error')
    self._test.error(status_code).AndReturn(None)

  def MockSetStatus(self, status_code, message=None):
    """Mock a response.set_status().

    Args:
      status_code: int, like 400
      message: str, optional, like "Bad request"
    """
    if message is None:
      self._test.response.set_status(status_code).AndReturn(None)
    else:
      self._test.response.set_status(status_code, message).AndReturn(None)

  def MockRedirect(self, url):
    """Mock a .redirect().

    Args:
      url: str, like '/foo'
    """
    self.MockSelf('redirect')
    self._test.redirect(url).AndReturn(None)

  def MockModelStaticBase(self, model_name, method_name, *args):
    """Mock a model static method, return a mock setup.

    Args:
      model_name: str, name of model
      method_name: str, name of static method on model to call
      *args: optional, list of arguments to supply to mock setup
    Returns:
      a mock setup ready for completion with AndReturn, AndRaise, etc.
    """
    test_class_models = self.GetTestClassModule().models
    model_class = getattr(test_class_models, model_name)
    if not '%s:%s' % (model_name, method_name) in self._set_mock:
      mock_model = self.mox.CreateMock(getattr(model_class, method_name))
      self.stubs.Set(model_class, method_name, mock_model)
      self._set_mock['%s:%s' % (model_name, method_name)] = mock_model
    model = self.mox.CreateMockAnything()
    return getattr(model_class, method_name)(*args)

  def MockModelStatic(self, model_name, method_name, *args):
    """Mock a model static method, return a mocked model.

    Args:
      same as MockModelStaticBase
    Returns:
      a new mocked instance of the model
    """
    model = self.mox.CreateMockAnything()
    self.MockModelStaticBase(model_name, method_name, *args).AndReturn(model)
    return model

  def MockModelStaticNone(self, model_name, method_name, *args):
    """Mock a model static method, return None.

    Used to return "no entity" type responses from static methods.
    e.g.
      MockModelStaticNone('ModelName', 'get', 12345)

    Args:
      same as MockModelStaticBase
    Returns:
      None
    """
    model = None
    self.MockModelStaticBase(model_name, method_name, *args).AndReturn(model)
    return model

  def MockModel(self, model_name, *args, **kwargs):
    """Mock creating an instance of a model, and return the mock instance.

    Args:
      name: str, name of model, like 'Package'
      args: list, optional arguments supplied to model instantiation
      kwargs: dict, optional arguments supplied to model instantiation
    Returns:
      a new mocked instance of the model
    """
    test_class_models = self.GetTestClassModule().models

    if not 'models_%s' % model_name in self._set_mock:
      self.mox.StubOutWithMock(
          getattr(self.GetTestClassModule(), 'models'),
          model_name)
      # we need to put back any stubs which MockModelStaticBase placed
      for mock in self._set_mock:
        if mock.startswith('%s:' % model_name):
          self.stubs.Set(
              getattr(test_class_models, model_name),
              mock.split(':')[1],
              self._set_mock[mock])
      self._set_mock['models_%s' % model_name] = 1

    model = self.mox.CreateMockAnything()
    getattr(
        self.GetTestClassModule().models,
        model_name)(*args, **kwargs).AndReturn(model)
    return model

def main(unused_argv):
  basetest.main()


text:
namespace xwalk {
namespace sysapps {

typedef std::map<const std::string, DeviceCapabilitiesObject&> DeviceMap;
typedef std::pair<const std::string, DeviceCapabilitiesObject&> DeviceMapPair;

static DeviceMap device_map_;

DeviceCapabilitiesInstance::DeviceCapabilitiesInstance() {
}

DeviceCapabilitiesInstance::~DeviceCapabilitiesInstance() {
  for (DeviceMap::iterator it = device_map_.begin();
       it != device_map_.end(); it++) {
    (it->second).RemoveEventListener(this);
  }
}

void DeviceCapabilitiesInstance::DeviceMapInitialize() {
  device_map_.insert(DeviceMapPair(
      "AVCodec", DeviceCapabilitiesAVCodecs::GetDeviceInstance()));
  device_map_.insert(DeviceMapPair(
      "CPU", DeviceCapabilitiesCpu::GetDeviceInstance()));
  device_map_.insert(DeviceMapPair(
      "Display", DeviceCapabilitiesDisplay::GetDeviceInstance()));
  device_map_.insert(DeviceMapPair(
      "Memory", DeviceCapabilitiesMemory::GetDeviceInstance()));
  device_map_.insert(DeviceMapPair(
      "Storage", DeviceCapabilitiesStorage::GetDeviceInstance()));
}

void DeviceCapabilitiesInstance::PostMessage(const char* msg) {
  PostMessageToJS(scoped_ptr<base::Value>(new base::StringValue(msg)));
}

void DeviceCapabilitiesInstance::HandleMessage(scoped_ptr<base::Value> msg) {
  std::string message;
  msg->GetAsString(&message);
  Json::Value input;
  Json::Reader reader;
  if (!reader.parse(message, input)) {
    LOG(ERROR) << "Failed to parse message: " << message;
    return;
  }
  std::string cmd = input["cmd"].asString();

  if (cmd == "getAVCodecs") {
    HandleGetDeviceInfo("AVCodec", input);
  } else if (cmd == "getCPUInfo") {
    HandleGetDeviceInfo("CPU", input);
  } else if (cmd == "getMemoryInfo") {
    HandleGetDeviceInfo("Memory", input);
  } else if (cmd == "getStorageInfo") {
    HandleGetDeviceInfo("Storage", input);
  } else if (cmd == "getDisplayInfo") {
    HandleGetDeviceInfo("Display", input);
  } else if (cmd == "addEventListener") {
    HandleAddEventListener(input);
  }
}

void DeviceCapabilitiesInstance::HandleGetDeviceInfo(std::string deviceName,
                                                     const Json::Value& msg) {
  std::string reply_id = msg["_promise_id"].asString();
  Json::Value* output = new Json::Value();
  (*output)["_promise_id"] = Json::Value(reply_id);

  DeviceMap::iterator it = device_map_.find(deviceName);
  if (it == device_map_.end()) {
    LOG(ERROR) << "Invalid device name:" << deviceName;
    return;
  }

  (*output)["data"] = *((it->second).Get());
  Json::StyledWriter writer;
  std::string result = writer.write(*output);
  PostMessage(result.c_str());
}

void
DeviceCapabilitiesInstance::HandleAddEventListener(const Json::Value& msg) {
  std::string event_name = msg["eventName"].asString();
  DeviceMap::iterator it;
  if (event_name == "storageattach" || event_name == "storagedetach") {
    it = device_map_.find("Storage");
    if (it != device_map_.end()) {
      (it->second).AddEventListener(event_name, this);
    }
  } else if (event_name == "displayconnect" ||
             event_name == "displaydisconnect") {
    it = device_map_.find("Display");
    if (it != device_map_.end()) {
      (it->second).AddEventListener(event_name, this);
    }
  }
}

}  // namespace sysapps
}  // namespace xwalk


text:
from scannerpy.common import ScannerException
from typing import List, Callable, Any, Generator
from scannerpy.types import get_type_info_cpp
import hwang
import storehouse

class NullElement:
    """Represents a 'null' output in a stream generated through Scanner.

    These can show up e.g. when you use a spacing/repeat operator. NullElement is used instead
    of the more generic Python 'None', as a Python kernel can have 'None' as a valid output which
    isn't the same as a 'null' stream element.
    """

    pass

class StorageBackend:
    """I/O backend for streams fed in/out of Scanner."""

    def source(self, sc, streams):
        """Returns the Scanner source corresponding to this storage backend.

        Parameters
        ----------
        sc: Client
          Scanner client

        streams: List[StoredStream]
          List of StoredStream objects of the same storage type

        Returns
        ----------
        source: Source
          Scanner source
        """

        raise ScannerException(
            "StorageBackend class `{}` cannot serve as a Scanner input.".format(type(self).__name__))

    def sink(self, sc, op, streams):
        """Returns the Scanner sink corresponding to this storage backend.

        Parameters
        ----------
        sc: Client
          Scanner client

        op: Op
          Input op from computation graph

        streams: List[StoredStream]
          List of StoredStream objects of the same storage type

        Returns
        ----------
        sink: Sink
          Scanner sink
        """

        raise ScannerException(
            "StorageBackend class `{}` cannot serve as a Scanner output.".format(type(self).__name__))

    def delete(self, sc, streams):
        """Deletes the streams from storage if they exist.

        Parameters
        ----------
        sc: Client
          Scanner client

        streams: List[StoredStream]
          List of StoredStream objects of the same storage type
        """

        raise ScannerException(
            "StorageBackend class `{}` cannot delete elements.".format(type(self).__name__))

class StoredStream:
    """Handle to a stream stored in a particular storage backend.

    In general, a StoredStream is not guaranteed to exist, but you can always check this using
    :func:`exists`.
    """

    def load_bytes(self, rows: List[int] = None) -> Generator[bytes, None, None]:
        """A generator that incrementally loads raw bytes from the stored stream.

        This function is not intended to be called directly by the user. See :func:`load`.

        Parameters
        ----------
        rows: List[int]
          List of indices in the stream to load. Default is all elements.
        """

        raise ScannerException(
            "Stream `{}` cannot load elements into Python.".format(type(self).__name__))

    def committed(self) -> bool:
        """Check if a stream is completely materialized in storage.

        A stream may exist, but not be committed if a Scanner job was run that was supposed to
        output the stream, but the job failed for any reason.
        """
        raise NotImplementedError

    def exists(self) -> bool:
        """Check if any part of a stream exists in storage."""
        raise NotImplementedError

    def storage(self) -> StorageBackend:
        """Get the storage backend corresponding to this stream."""
        raise NotImplementedError

    def len(self) -> int:
        """Get the number of elements in this stream."""
        raise NotImplementedError

    def name(self) -> str:
        """Gets a human interpretable name for this stored stream."""
        raise NotImplementedError

    def type(self) -> type:
        """Get the Scanner type of elements in this stream if it exists, and return None otherwise."""
        raise NotImplementedError

    def estimate_size(self) -> int:
        """Estimates the size in bytes of elements in the stream. Not guaranteed to be accurate,
        just used for heuristics."""
        raise NotImplementedError

    def load(self, ty: type = None, fn: Callable[[bytes], Any] = None, rows: List[int] = None) -> Generator[Any, None, None]:
        """Load elements from the stored stream into Python.

        Parameters
        ----------
        ty: type
          Scanner type of elements in the stream. If the storage backend recorded the type, that
          will be used by default.

        fn: Callable[[bytes], Any]
          Deserialization function that maps elements as bytes to their actual type.

        rows: List[int]
          List of indices in the stream to load. Default is all elements.

        Returns
        ----------
        generator: Generator[Any, None, None]
          A generator that outputs one stream element at a time.
        """

        if not self.committed():
            raise ScannerException("Tried to load from uncommitted stream")

        # Use a deserialize function if provided.
        # If not, use a type if provided.
        # If not, attempt to determine the type from the column's table descriptor.
        # If that doesn't work, then assume no deserialization function, and return bytes.
        if fn is None:
            if ty is None:
                ty = self.type()
            if ty is not None:
                fn = ty.deserialize

        for obj in self.load_bytes(rows=rows):
            if fn is not None and type(obj) == bytes:
                yield fn(obj)
            else:
                yield obj

    def delete(self, sc):
        """Deletes the stream from its storage if it exists.

        Parameters
        ----------
        sc: Client
          Scanner client
        """

        self.storage().delete(sc, [self])

class NamedStorage(StorageBackend):
    """Named storage for byte streams. Useful default output format for non-video-data.

    Stores byte streams in a custom packed binary file format. Supports both local filesystems
    (Linux/Posix) and cloud file systems (S3, GCS).
    """

    def __init__(self, storage_config=None):
        if storage_config is None:
            storage_config = storehouse.StorageConfig.make_posix_config()
        self._storage_config = storage_config
        self._storehouse_backend = None

    def _storehouse(self):
        if self._storehouse_backend is None:
            self._storehouse_backend = storehouse.StorageBackend.make_from_config(self._storage_config)
        return self._storehouse_backend

    def source(self, sc, streams):
        return sc.sources.Column(
            table_name=[s._name for s in streams],
            column_name=['column' for s in streams])

    def sink(self, sc, op, streams):
        return sc.sinks.Column(
            columns={'column': op},
            table_name=[s._name for s in streams],
            column_name=['column' for s in streams])

    def delete(self, sc, streams):
        if len(streams) > 0:
            sc.delete_tables([e._name for e in streams])

class NamedVideoStorage(NamedStorage):
    """Named storage for video streams. Special baked-in storage class for keeping videos compressed."""

    def source(self, sc, streams):
        return sc.sources.FrameColumn(
            table_name=[s._name for s in streams],
            column_name=['frame' for s in streams])

    def sink(self, sc, op, streams):
        return sc.sinks.FrameColumn(
            columns={'frame': op},
            table_name=[s._name for s in streams],
            column_name=['frame' for s in streams])

    def ingest(self, sc, streams, batch=500):
        to_ingest = [(s._name, s._path) for s in streams
                     if (s._path is not None and
                         s._inplace == False)]
        to_ingest_inplace = [(s._name, s._path) for s in streams
                             if (s._path is not None and
                                 s._inplace == True)]
        if len(to_ingest) > 0:
            for i in range(0, len(to_ingest), batch):
                sc.ingest_videos(to_ingest[i:i+batch], inplace=False, force=True)
        if len(to_ingest_inplace) > 0:
            for i in range(0, len(to_ingest_inplace), batch):
                sc.ingest_videos(to_ingest_inplace[i:i+batch], inplace=True, force=True)

class NamedStream(StoredStream):
    """Stream of elements stored on disk with a given name."""

    def __init__(self, sc, name: str, storage=None):
        """
        Parameters
        ----------
        sc: Client
          Scanner client.

        name: str
          Name of the stream.

        storage: NamedStorage
          Optional NamedStorage object.
        """

        if storage is None:
            self._storage = NamedStorage()
        else:
            self._storage = storage

        self._sc = sc
        self._name = name

    def type(self):
        seq = self._sc.sequence(self._name)
        seq._load_meta()
        type_name = seq._descriptor.type_name
        if type_name != "":
            return get_type_info_cpp(type_name)
        else:
            return None

    def name(self):
        return self._name

    def storage(self):
        return self._storage

    def committed(self):
        return self._sc.sequence(self._name)._table.committed()

    def exists(self):
        return self._sc.sequence(self._name)._table.exists()

    def len(self):
        return self._sc.sequence(self._name)._table.num_rows()

    def load_bytes(self, rows=None):
        seq = self._sc.sequence(self._name)
        yield from seq.load(fn=lambda x: x, workers=16, rows=rows)

class NamedVideoStream(NamedStream):
    """Stream of video frame stored (compressed) in named storage."""

    def __init__(self, sc, name, path=None, inplace=False, storage=None):
        """
        Parameters
        ----------
        sc: Client
          Scanner client

        name: str
          Name of the stream in Scanner storage.

        path: str
          Path to corresponding video file. If this parameter is given, the named video stream will be
          created from the video at the given path.

        storage: NamedFrameStorage
          Optional NamedFrameStorage object.
        """

        if storage is None:
            self._storage = NamedVideoStorage()
        else:
            self._storage = storage

        self._sc = sc
        self._name = name
        self._path = path
        self._inplace = inplace
        self._ingested = False

    def _ingest(self):
        if not self._ingested and self._path is not None:
            self._ingested = True
            self.storage().ingest(self._sc, [self])

    def committed(self):
        self._ingest()
        return self._sc.sequence(self._name)._table.committed()

    def exists(self):
        self._ingest()
        return self._sc.sequence(self._name)._table.exists()

    def len(self):
        self._ingest()
        return self._sc.sequence(self._name)._table.num_rows()

    def load_bytes(self, rows=None):
        self._ingest()
        seq = self._sc.sequence(self._name)
        yield from seq.load(fn=lambda x: x, workers=16, rows=rows)

    def estimate_size(self):
        self._ingest()
        col = self._sc.sequence(self._name)
        col._load_meta()
        vmeta = col._video_descriptor
        return vmeta.width * vmeta.height * vmeta.channels

    def save_mp4(self, output_name, fps=None, scale=None):
        self._ingest()
        return self._sc.sequence(self._name).save_mp4(output_name, fps=fps, scale=scale)

    def as_hwang(self):
        try:
            video_file = storehouse.RandomReadFile(self._storage._storehouse(), self._path.encode('ascii'))
        except UserWarning:
            raise Exception('Path to video `{}` does not exist.'.format(self._path))
        return hwang.Decoder(video_file)


text:
<?php

namespace MC\TestBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MCTestBundle extends Bundle
{
    public function getNamespace()
    {
        return parent::getNamespace(); // TODO: Change the autogenerated stub
    }
}


text:
'use strict';

angular.module('hacktrackApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'btford.socket-io',
  'ui.bootstrap'
  ])
.config(function ($routeProvider, $locationProvider, $httpProvider) {
  $routeProvider
  .otherwise({
    redirectTo: '/'
  });

  $locationProvider.html5Mode(true);
  $httpProvider.interceptors.push('authInterceptor');
})

.factory('authInterceptor', function ($rootScope, $q, $cookieStore, $location,$window) {
  return {
      // Add authorization token to headers
      request: function (config) {
        config.headers = config.headers || {};
        if ($cookieStore.get('token')) {
          config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
        }
        return config;
      },

      // Intercept 401s and redirect you to login
      responseError: function(response) {
        if(response.status === 401) {
          $window.location.href ='/auth/google';
          // remove any stale tokens
          $cookieStore.remove('token');
          return $q.reject(response);
        }
        else {
          return $q.reject(response);
        }
      }
    };
  })

.run(function ($rootScope, $location, Auth,$window,$route, $q) {
    // Redirect to login if route requires auth and you're not logged in
    $rootScope.$on('$routeChangeError', function (event, current, previous, reason) {
      var redirectTo = "/";
      if(current)
        {
          redirectTo = current.$$route.originalPath;
        }

      if(reason && !reason.authenticated){
        $window.location.href = '/auth/google?success_url=' + redirectTo;
     }
   })
  });


text:
Pimcore Crontab Manager Plugin

With this Plugin you can view/edit/delete Cronjobs from Pimcore Admin Panel

Alpha Version!


text:
<?php
/** @var \rock\template\Template $this */
?>

<a href="<?=$this->url?>" title="<?=$this->pageFirstName?>"><?=$this->pageFirstName?>


text:
/**
 *  This file hides differences that are based on compiler, CPU, and OS.  In
 *  particular, we define:
 *
 *    1) atomic operations (cas, swap, etc, atomic 64-bit load/store)
 *    2) access to the tick counter
 *    3) clean definitions of custom compiler constructs (__builtin_expect,
 *       alignment attributes, etc)
 *    4) scheduler syscalls (sleep, yield)
 *    5) a high-resolution timer
 */

#ifndef PLATFORM_HPP__
#define PLATFORM_HPP__

#include <stm/config.h>
#include <stdint.h>
#include <limits.h>

/**
 *  We set up a bunch of macros that we use to insulate the rest of the code
 *  from potentially platform-dependent behavior.
 *
 *  NB:  This is partially keyed off of __LP64__ which isn't universally defined
 *       for -m64 code, but it works on the platforms that we support.
 *
 *  NB2: We don't really support non-gcc compatible compilers, so there isn't
 *       any compiler logic in these ifdefs. If we begin to support the Windows
 *       platform these will need to be more complicated
 */

/**
 *  We begin by hard-coding some macros that may become platform-dependent in
 *  the future.
 */
#define CACHELINE_BYTES 64
#define NORETURN        __attribute__((noreturn))
#define NOINLINE        __attribute__((noinline))
#define ALWAYS_INLINE   __attribute__((always_inline))
#define USED            __attribute__((used))
#define REGPARM(N)      __attribute__((regparm(N)))

/**
 *  Pick up the BITS define from the __LP64__ token.
 */
#if defined(__LP64__)
#define STM_BITS_64
#else
#define STM_BITS_32
#endif

/**
 *  GCC's fastcall attribute causes a warning on x86_64, so we don't use it
 *  there (it's not necessary in any case because of the native calling
 *  convention.
 */
#if defined(__LP64__) && defined(STM_CPU_X86)
#define GCC_FASTCALL
#else
#define GCC_FASTCALL    __attribute__((fastcall))
#endif

/**
 *  We rely on the configured parameters here (no cross platform building yet)
 */
#if !defined(STM_CC_GCC) || !defined(STM_CPU_SPARC)
#define TM_INLINE       ALWAYS_INLINE
#else
#define TM_INLINE
#endif

#if defined(STM_CPU_X86) && !defined(STM_CC_SUN)
#define TM_FASTCALL     REGPARM(3)
#else
#define TM_FASTCALL
#endif

#define TM_ALIGN(N)     __attribute__((aligned(N)))

/**
 *  The first task for this file is to declare atomic operations (cas, swap,
 *  etc) and custom assembly codes, such as compiler fences, memory barriers,
 *  and no-op instructions.  This code depends on the compiler and processor.
 */

/**
 *  icc is nominally an x86/x86-64 compiler that supports sync builtins,
 *  however the stm prototype doesn't support operations on pointer types,
 *  which we perform all the time. This header performs the fixes by #defining
 *  the __sync builtin symbols as partial templates.
 */
#if defined(STM_CPU_X86) && defined(__ICC)
#   include "icc-sync.hpp"
#endif

/**
 *  Here is the declaration of atomic operations when we're on an x86 (32bit or
 *  64bit) and using the GNU compiler collection.  This assumes that the
 *  compiler is recent enough that it supports the builtin __sync operations
 */
#if defined(STM_CPU_X86) && !defined(STM_CC_SUN)

#define CFENCE              __asm__ volatile ("":::"memory")
#define WBR                 __sync_synchronize()

#define cas32(p, o, n)      __sync_val_compare_and_swap(p, o, n)
#define cas64(p, o, n)      __sync_val_compare_and_swap(p, o, n)
#define casptr(p, o, n)     __sync_val_compare_and_swap(p, o, n)
#define bcas32(p, o, n)     __sync_bool_compare_and_swap(p, o, n)
#define bcas64(p, o, n)     __sync_bool_compare_and_swap(p, o, n)
#define bcasptr(p, o, n)    __sync_bool_compare_and_swap(p, o, n)

#define tas(p)              __sync_lock_test_and_set(p, 1)

#define nop()               __asm__ volatile("nop")

// NB: GCC implements test_and_set via swap
#define atomicswap8(p, v)   __sync_lock_test_and_set(p, v)
#define atomicswap32(p, v)  __sync_lock_test_and_set(p, v)
#define atomicswap64(p, v)  __sync_lock_test_and_set(p, v)
#define atomicswapptr(p, v) __sync_lock_test_and_set(p, v)

#define fai32(p)            __sync_fetch_and_add(p, 1)
#define fai64(p)            __sync_fetch_and_add(p, 1)
#define faiptr(p)           __sync_fetch_and_add(p, 1)
#define faa32(p, a)         __sync_fetch_and_add(p, a)
#define faa64(p, a)         __sync_fetch_and_add(p, a)
#define faaptr(p, a)        __sync_fetch_and_add(p, a)

#endif

/**
 *  Here is the declaration of atomic operations when we're on a sparc (32bit)
 *  and using the GNU compiler collection.  For some reason, gcc 4.3.1 __sync_*
 *  operations can sometimes cause odd compiler crashes, so we provide our own
 *  assembly and use it instead.
 *
 *  NB: gcc doesn't provide a builtin equivalent to the SPARC swap instruction,
 *      and thus we have to implement atomicswap ourselves.
 */
#if defined(STM_CPU_SPARC) && defined (STM_CC_GCC)
#define CFENCE          __asm__ volatile ("":::"memory")
#define WBR             __sync_synchronize()

/**
 * 32-bit CAS via SPARC CAS instruction
 */
inline uint32_t internal_cas32(volatile uint32_t* ptr, uint32_t old,
                               uint32_t _new)
{
    __asm__ volatile("cas [%2], %3, %0"                     // instruction
                     : "=&r"(_new)                          // output
                     : "0"(_new), "r"(ptr), "r"(old)        // inputs
                     : "memory");                           // side effects
    return _new;
}

/**
 *  64-bit CAS via SPARC CASX instruction.
 *
 *  NB: This code only works correctly with -m64 specified, as otherwise GCC
 *      refuses to use a 64-bit register to pass a value.
 */
inline uint64_t internal_cas64(volatile uint64_t* ptr, uint64_t old,
                               uint64_t _new)
{
    __asm__ volatile("casx [%2], %3, %0"                    // instruction
                     : "=&r"(_new)                          // output
                     : "0"(_new), "r"(ptr), "r"(old)        // inputs
                     : "memory");                           // side effects
    return _new;
}

#define cas32(p, o, n)      internal_cas32((uint32_t*)(p), (uint32_t)(o), (uint32_t)(n))
#ifdef STM_BITS_64
#define cas64(p, o, n)      internal_cas64((uint64_t*)(p), (uint64_t)(o), (uint64_t)(n))
#define casptr(p, o, n)     cas64(p, o, n)
#else
#define cas64(p, o, n)      __sync_val_compare_and_swap(p, o, n)
#define casptr(p, o, n)     cas32(p, o, n)
#endif

#define bcas32(p, o, n)  ({ o == cas32(p, (o), (n)); })
#define bcas64(p, o, n)  ({ o == cas64(p, (o), (n)); })
#define bcasptr(p, o, n) ({ ((void*)o) == (void*)casptr(p, (o), (n)); })

#define tas(p)            __sync_lock_test_and_set(p, 1)

#define nop()             __asm__ volatile("nop")

// NB: SPARC swap instruction only is 32/64-bit... there is no atomicswap8
#ifdef STM_BITS_32
#define atomicswapptr(p, v)                                 \
    ({                                                      \
        __typeof((v)) v1 = v;                               \
        __typeof((p)) p1 = p;                               \
        __asm__ volatile("swap [%2], %0;"                   \
                     :"=r"(v1) :"0"(v1), "r"(p1):"memory"); \
        v1;                                                 \
    })
#else
#define atomicswapptr(p, v)                     \
    ({                                          \
        __typeof((v)) tmp;                      \
        while (1) {                             \
            tmp = *(p);                         \
            if (bcasptr((p), tmp, (v))) break;  \
        }                                       \
        tmp;                                    \
    })
#endif

#define faa32(p,a)                                              \
    ({ __typeof(*p) _f, _e;                                     \
       do { _e = _f; }                                          \
       while ((_f = (__typeof(*p))cas32(p, _e, (_e+a))) != _e); \
       _f;                                                      \
    })
#define fai32(p)            faa32(p,1)
#define faiptr(p)           __sync_fetch_and_add(p, 1)
#define faa64(p, a)         __sync_fetch_and_add(p, a)
#define faaptr(p, a)        __sync_fetch_and_add(p, a)
#endif

/**
 *  Here is the declaration of atomic operations when we're using Sun Studio
 *  12.1.  These work for x86 and SPARC, at 32-bit or 64-bit
 */
#if (defined(STM_CPU_X86) || defined(STM_CPU_SPARC)) && defined(STM_CC_SUN)
#include <atomic.h>
#define CFENCE              __asm__ volatile("":::"memory")
#define WBR                 membar_enter()

#define cas32(p, o, n)      atomic_cas_32(p, (o), (n))
#define cas64(p, o, n)      atomic_cas_64(p, (o), (n))
#define casptr(p, o, n)     atomic_cas_ptr(p, (void*)(o), (void*)(n))
#define bcas32(p, o, n)     ({ o == cas32(p, (o), (n)); })
#define bcas64(p, o, n)     ({ o == cas64(p, (o), (n)); })
#define bcasptr(p, o, n)    ({ ((void*)o) == casptr(p, (o), (n)); })

#define tas(p)              atomic_set_long_excl((volatile unsigned long*)p, 0)

#define nop()               __asm__ volatile("nop")

#define atomicswap8(p, v)   atomic_swap_8(p, v)
#define atomicswap32(p, v)  atomic_swap_32(p, v)
#define atomicswap64(p, v)  atomic_swap_64(p, v)
#define atomicswapptr(p, v) atomic_swap_ptr(p, (void*)(v))

#define fai32(p)            (atomic_inc_32_nv(p)-1)
#define fai64(p)            __sync_fetch_and_add(p, 1)
#define faiptr(p)           (atomic_inc_ulong_nv((volatile unsigned long*)p)-1)
#define faa32(p, a)         atomic_add_32(p, a)
#define faa64(p, a)         atomic_add_64(p, a)
#define faaptr(p, a)        atomic_add_long((volatile unsigned long*)p, a)

//  NB: must shut off 'builtin_expect' support
#define __builtin_expect(a, b) a
#endif

/**
 *  Now we must deal with the ability to load/store 64-bit values safely.  In
 *  32-bit mode, this is potentially a problem, so we handle 64-bit atomic
 *  load/store via the mvx() function.  mvx() depends on the bit level and the
 *  CPU
 */

#if defined(STM_BITS_64)
/**
 *  64-bit code is easy... 64-bit accesses are atomic
 */
inline void mvx(const volatile uint64_t* src, volatile uint64_t* dest)
{
    *dest = *src;
}
#endif

#if defined(STM_BITS_32) && defined(STM_CPU_X86)
/**
 *  32-bit on x86... cast to double
 */
inline void mvx(const volatile uint64_t* src, volatile uint64_t* dest)
{
    const volatile double* srcd = (const volatile double*)src;
    volatile double* destd = (volatile double*)dest;
    *destd = *srcd;
}
#endif

#if defined(STM_BITS_32) && defined(STM_CPU_SPARC)
/**
 *  32-bit on SPARC... use ldx/stx
 */
inline void mvx(const volatile uint64_t* from, volatile uint64_t* to)
{
    __asm__ volatile("ldx  [%0], %%o4;"
                     "stx  %%o4, [%1];"
                     :: "r"(from), "r"(to)
                     : "o4", "memory");
}
#endif

/**
 *  The next task for this file is to establish access to a high-resolution CPU
 *  timer.  The code depends on the CPU and bit level.  It is identical for
 *  32/64-bit x86.  For sparc, the code depends on if we are 32-bit or 64-bit.
 */
#if defined(STM_CPU_X86)
/**
 *  On x86, we use the rdtsc instruction
 */
inline uint64_t tick()
{
    uint32_t tmp[2];
    __asm__ ("rdtsc" : "=a" (tmp[1]), "=d" (tmp[0]) : "c" (0x10) );
    return (((uint64_t)tmp[0]) << 32) | tmp[1];
}
#endif

#if defined(STM_CPU_SPARC) && defined(STM_BITS_64)
/**
 *  64-bit SPARC: read the tick register into a regular (64-bit) register
 *
 *  This code is based on http://blogs.sun.com/d/entry/reading_the_tick_counter and
 *  http://sourceware.org/binutils/docs-2.20/as/Sparc_002dRegs.html
 */
inline uint64_t tick()
{
    uint64_t val;
    __asm__ volatile("rd %%tick, %[val]" : [val] "=r" (val) : :);
    return val;
}
#endif

#if defined(STM_CPU_SPARC) && defined(STM_BITS_32)
/**
 *  32-bit SPARC: read the tick register into two 32-bit registers, then
 *  manually combine the result
 *
 *  This code is based on
 *    http://blogs.sun.com/d/entry/reading_the_tick_counter
 *  and
 *    http://sourceware.org/binutils/docs-2.20/as/Sparc_002dRegs.html
 */
inline uint64_t tick()
{
    uint32_t lo = 0, hi = 0;
    __asm__ volatile("rd   %%tick, %%o2;"
                     "srlx %%o2,   32, %[high];"
                     "sra  %%o2,   0,  %[low];"
                     : [high] "=r"(hi),
                       [low]  "=r"(lo)
                     :
                     : "%o2" );
    uint64_t ans = hi;
    ans = ans << 32;
    ans |= lo;
    return ans;
}
#endif

/**
 *  Next, we provide a platform-independent function for sleeping for a number
 *  of milliseconds.  This code depends on the OS.
 *
 *  NB: since we do not have Win32 support, this is now very easy... we just
 *      use the usleep instruction.
 */
#include <unistd.h>
inline void sleep_ms(uint32_t ms) { usleep(ms*1000); }

/**
 *  Now we present a clock that operates in nanoseconds, instead of in ticks,
 *  and a function for yielding the CPU.  This code also depends on the OS
 */
#if defined(STM_OS_LINUX)
#include <stdio.h>
#include <cstring>
#include <assert.h>
#include <pthread.h>
#include <time.h>

/**
 *  Yield the CPU
 */
inline void yield_cpu() { pthread_yield(); }

/**
 *  The Linux clock_gettime is reasonably fast, has good resolution, and is not
 *  affected by TurboBoost.  Using MONOTONIC_RAW also means that the timer is
 *  not subject to NTP adjustments, which is preferably since an adjustment in
 *  mid-experiment could produce some funky results.
 */
inline uint64_t getElapsedTime()
{
    struct timespec t;
    clock_gettime(CLOCK_REALTIME, &t);

    uint64_t tt = (((long long)t.tv_sec) * 1000000000L) + ((long long)t.tv_nsec);
    return tt;
}

#endif // STM_OS_LINUX

#if defined(STM_OS_SOLARIS)
#include <sys/time.h>

/**
 *  Yield the CPU
 */
inline void yield_cpu() { yield(); }

/**
 *  We'll just use gethrtime() as our nanosecond timer
 */
inline uint64_t getElapsedTime()
{
    return gethrtime();
}

#endif // STM_OS_SOLARIS

#endif // PLATFORM_HPP__


text:
namespace blink {

class ResolvedVariableChecker : public CSSInterpolationType::ConversionChecker {
 public:
  ResolvedVariableChecker(CSSPropertyID property,
                          const CSSValue* variable_reference,
                          const CSSValue* resolved_value)
      : property_(property),
        variable_reference_(variable_reference),
        resolved_value_(resolved_value) {}

 private:
  bool IsValid(const InterpolationEnvironment& environment,
               const InterpolationValue&) const final {
    const auto& css_environment = To<CSSInterpolationEnvironment>(environment);
    // TODO(alancutter): Just check the variables referenced instead of doing a
    // full CSSValue resolve.
    const CSSValue* resolved_value = css_environment.Resolve(
        PropertyHandle(CSSProperty::Get(property_)), variable_reference_);
    return base::ValuesEquivalent(resolved_value_.Get(), resolved_value);
  }

  CSSPropertyID property_;
  Persistent<const CSSValue> variable_reference_;
  Persistent<const CSSValue> resolved_value_;
};

class InheritedCustomPropertyChecker
    : public CSSInterpolationType::CSSConversionChecker {
 public:
  InheritedCustomPropertyChecker(const AtomicString& name,
                                 bool is_inherited_property,
                                 const CSSValue* inherited_value,
                                 const CSSValue* initial_value)
      : name_(name),
        is_inherited_property_(is_inherited_property),
        inherited_value_(inherited_value),
        initial_value_(initial_value) {}

 private:
  bool IsValid(const StyleResolverState& state,
               const InterpolationValue&) const final {
    const CSSValue* inherited_value =
        state.ParentStyle()->GetVariableValue(name_, is_inherited_property_);
    if (!inherited_value) {
      inherited_value = initial_value_.Get();
    }
    return base::ValuesEquivalent(inherited_value_.Get(), inherited_value);
  }

  AtomicString name_;
  const bool is_inherited_property_;
  Persistent<const CSSValue> inherited_value_;
  Persistent<const CSSValue> initial_value_;
};

class ResolvedRegisteredCustomPropertyChecker
    : public InterpolationType::ConversionChecker {
 public:
  ResolvedRegisteredCustomPropertyChecker(
      const PropertyHandle& property,
      const CSSValue& value,
      scoped_refptr<CSSVariableData> resolved_tokens)
      : property_(property),
        value_(value),
        resolved_tokens_(std::move(resolved_tokens)) {}

 private:
  bool IsValid(const InterpolationEnvironment& environment,
               const InterpolationValue&) const final {
    const auto& css_environment = To<CSSInterpolationEnvironment>(environment);
    const CSSValue* resolved = css_environment.Resolve(property_, value_);
    scoped_refptr<CSSVariableData> resolved_tokens;
    if (const auto* decl = DynamicTo<CSSCustomPropertyDeclaration>(resolved))
      resolved_tokens = decl->Value();

    return base::ValuesEquivalent(resolved_tokens, resolved_tokens_);
  }

  PropertyHandle property_;
  Persistent<const CSSValue> value_;
  scoped_refptr<CSSVariableData> resolved_tokens_;
};

template <typename RevertValueType>
class RevertChecker : public CSSInterpolationType::ConversionChecker {
 public:
  static_assert(
      std::is_same<RevertValueType, cssvalue::CSSRevertValue>::value ||
          std::is_same<RevertValueType, cssvalue::CSSRevertLayerValue>::value,
      "RevertCheck only accepts CSSRevertValue and CSSRevertLayerValue");

  RevertChecker(const PropertyHandle& property_handle,
                const CSSValue* resolved_value)
      : property_handle_(property_handle), resolved_value_(resolved_value) {
  }

 private:
  bool IsValid(const InterpolationEnvironment& environment,
               const InterpolationValue&) const final {
    const auto& css_environment = To<CSSInterpolationEnvironment>(environment);
    const CSSValue* current_resolved_value =
        css_environment.Resolve(property_handle_, RevertValueType::Create());
    return base::ValuesEquivalent(resolved_value_.Get(),
                                  current_resolved_value);
  }

  PropertyHandle property_handle_;
  Persistent<const CSSValue> resolved_value_;
};

CSSInterpolationType::CSSInterpolationType(
    PropertyHandle property,
    const PropertyRegistration* registration)
    : InterpolationType(property), registration_(registration) {
  DCHECK(!GetProperty().IsCSSCustomProperty() || registration);
  DCHECK(!CssProperty().IsShorthand());
}

InterpolationValue CSSInterpolationType::MaybeConvertSingle(
    const PropertySpecificKeyframe& keyframe,
    const InterpolationEnvironment& environment,
    const InterpolationValue& underlying,
    ConversionCheckers& conversion_checkers) const {
  InterpolationValue result = MaybeConvertSingleInternal(
      keyframe, environment, underlying, conversion_checkers);
  if (result && keyframe.Composite() !=
                    EffectModel::CompositeOperation::kCompositeReplace) {
    return PreInterpolationCompositeIfNeeded(std::move(result), underlying,
                                             keyframe.Composite(),
                                             conversion_checkers);
  }
  return result;
}

InterpolationValue CSSInterpolationType::MaybeConvertSingleInternal(
    const PropertySpecificKeyframe& keyframe,
    const InterpolationEnvironment& environment,
    const InterpolationValue& underlying,
    ConversionCheckers& conversion_checkers) const {
  const CSSValue* value = To<CSSPropertySpecificKeyframe>(keyframe).Value();
  const auto& css_environment = To<CSSInterpolationEnvironment>(environment);
  const StyleResolverState& state = css_environment.GetState();

  if (!value)
    return MaybeConvertNeutral(underlying, conversion_checkers);

  if (GetProperty().IsCSSCustomProperty()) {
    return MaybeConvertCustomPropertyDeclaration(
        To<CSSCustomPropertyDeclaration>(*value), environment,
        conversion_checkers);
  }

  if (value->IsVariableReferenceValue() ||
      value->IsPendingSubstitutionValue()) {
    const CSSValue* resolved_value =
        css_environment.Resolve(GetProperty(), value);

    DCHECK(resolved_value);
    conversion_checkers.push_back(std::make_unique<ResolvedVariableChecker>(
        CssProperty().PropertyID(), value, resolved_value));
    value = resolved_value;
  }

  if (value->IsRevertValue()) {
    value = css_environment.Resolve(GetProperty(), value);
    DCHECK(value);
    conversion_checkers.push_back(
        std::make_unique<RevertChecker<cssvalue::CSSRevertValue>>(GetProperty(),
                                                                  value));
  }

  if (value->IsRevertLayerValue()) {
    value = css_environment.Resolve(GetProperty(), value);
    DCHECK(value);
    conversion_checkers.push_back(
        std::make_unique<RevertChecker<cssvalue::CSSRevertLayerValue>>(
            GetProperty(), value));
  }

  bool is_inherited = CssProperty().IsInherited();
  if (value->IsInitialValue() || (value->IsUnsetValue() && !is_inherited)) {
    return MaybeConvertInitial(state, conversion_checkers);
  }

  if (value->IsInheritedValue() || (value->IsUnsetValue() && is_inherited)) {
    return MaybeConvertInherit(state, conversion_checkers);
  }

  return MaybeConvertValue(*value, &state, conversion_checkers);
}

InterpolationValue CSSInterpolationType::MaybeConvertCustomPropertyDeclaration(
    const CSSCustomPropertyDeclaration& declaration,
    const InterpolationEnvironment& environment,
    ConversionCheckers& conversion_checkers) const {
  const auto& css_environment = To<CSSInterpolationEnvironment>(environment);
  const StyleResolverState& state = css_environment.GetState();

  AtomicString name = GetProperty().CustomPropertyName();

  const CSSValue* value = &declaration;
  value = css_environment.Resolve(GetProperty(), value);
  DCHECK(value) << "CSSVarCycleInterpolationType should have handled nullptr";

  if (declaration.IsRevert()) {
    conversion_checkers.push_back(
        std::make_unique<RevertChecker<cssvalue::CSSRevertValue>>(GetProperty(),
                                                                  value));
  }
  if (declaration.IsRevertLayer()) {
    conversion_checkers.push_back(
        std::make_unique<RevertChecker<cssvalue::CSSRevertLayerValue>>(
            GetProperty(), value));
  }
  if (const auto* resolved_declaration =
          DynamicTo<CSSCustomPropertyDeclaration>(value)) {
    // If Resolve returned a different CSSCustomPropertyDeclaration, var()
    // references were substituted.
    if (resolved_declaration != &declaration) {
      conversion_checkers.push_back(
          std::make_unique<ResolvedRegisteredCustomPropertyChecker>(
              GetProperty(), declaration, resolved_declaration->Value()));
    }
  }

  // Unfortunately we transport CSS-wide keywords inside the
  // CSSCustomPropertyDeclaration. Expand those keywords into real CSSValues
  // if present.
  bool is_inherited = Registration().Inherits();
  if (const auto* resolved_declaration =
          DynamicTo<CSSCustomPropertyDeclaration>(value)) {
    if (resolved_declaration->IsInitial(is_inherited))
      value = CSSInitialValue::Create();
    else if (resolved_declaration->IsInherit(is_inherited))
      value = CSSInheritedValue::Create();
  }

  // Handle CSS-wide keywords (except 'revert', which should have been
  // handled already).
  DCHECK(!value->IsRevertValue());
  if (value->IsInitialValue() || (value->IsUnsetValue() && !is_inherited)) {
    value = Registration().Initial();
  } else if (value->IsInheritedValue() ||
             (value->IsUnsetValue() && is_inherited)) {
    value = state.ParentStyle()->GetVariableValue(name, is_inherited);
    if (!value) {
      value = Registration().Initial();
    }
    conversion_checkers.push_back(
        std::make_unique<InheritedCustomPropertyChecker>(
            name, is_inherited, value, Registration().Initial()));
  }

  if (const auto* resolved_declaration =
          DynamicTo<CSSCustomPropertyDeclaration>(value)) {
    DCHECK(resolved_declaration->Value());
    DCHECK(!resolved_declaration->Value()->NeedsVariableResolution());
    value = resolved_declaration->Value()->ParseForSyntax(
        registration_->Syntax(),
        state.GetDocument().GetExecutionContext()->GetSecureContextMode());
    if (!value)
      return nullptr;
  }

  DCHECK(value);
  return MaybeConvertValue(*value, &state, conversion_checkers);
}

InterpolationValue CSSInterpolationType::MaybeConvertUnderlyingValue(
    const InterpolationEnvironment& environment) const {
  const ComputedStyle& style =
      To<CSSInterpolationEnvironment>(environment).Style();
  if (!GetProperty().IsCSSCustomProperty()) {
    return MaybeConvertStandardPropertyUnderlyingValue(style);
  }

  const PropertyHandle property = GetProperty();
  const AtomicString& name = property.CustomPropertyName();
  const CSSValue* underlying_value =
      style.GetVariableValue(name, Registration().Inherits());
  if (!underlying_value)
    return nullptr;
  // TODO(alancutter): Remove the need for passing in conversion checkers.
  ConversionCheckers dummy_conversion_checkers;
  return MaybeConvertValue(*underlying_value, nullptr,
                           dummy_conversion_checkers);
}

void CSSInterpolationType::Apply(
    const InterpolableValue& interpolable_value,
    const NonInterpolableValue* non_interpolable_value,
    InterpolationEnvironment& environment) const {
  StyleResolverState& state =
      To<CSSInterpolationEnvironment>(environment).GetState();

  if (GetProperty().IsCSSCustomProperty()) {
    ApplyCustomPropertyValue(interpolable_value, non_interpolable_value, state);
    return;
  }
  ApplyStandardPropertyValue(interpolable_value, non_interpolable_value, state);
}

void CSSInterpolationType::ApplyCustomPropertyValue(
    const InterpolableValue& interpolable_value,
    const NonInterpolableValue* non_interpolable_value,
    StyleResolverState& state) const {
  DCHECK(GetProperty().IsCSSCustomProperty());

  const CSSValue* css_value =
      CreateCSSValue(interpolable_value, non_interpolable_value, state);
  DCHECK(!css_value->IsCustomPropertyDeclaration());

  // TODO(alancutter): Defer tokenization of the CSSValue until it is needed.
  String string_value = css_value->CssText();
  CSSTokenizer tokenizer(string_value);
  const auto tokens = tokenizer.TokenizeToEOF();
  bool is_animation_tainted = true;
  bool needs_variable_resolution = false;
  scoped_refptr<CSSVariableData> variable_data = CSSVariableData::Create(
      {CSSParserTokenRange(tokens), StringView(string_value)},
      is_animation_tainted, needs_variable_resolution, KURL(),
      WTF::TextEncoding());
  const PropertyHandle property = GetProperty();

  // TODO(andruud): Avoid making the CSSCustomPropertyDeclaration by allowing
  // any CSSValue in CustomProperty::ApplyValue.
  const CSSValue* value = MakeGarbageCollected<CSSCustomPropertyDeclaration>(
      std::move(variable_data));
  StyleBuilder::ApplyProperty(GetProperty().GetCSSPropertyName(), state,
                              ScopedCSSValue(*value, nullptr));
}

}  // namespace blink


text:
from distutils.core import setup

setup(
    name='glpi_api',
    version='0.0.1',
    packages=['requests'],
    url='https://github.com/marcelogomess/glpi_api.git',
    license='BSD 2',
    author='marcelogomess',
    author_email='celo.gomess@gmail.com',
    description='Just a app to start with glpi api communitacion. glpi-project.org'
)


text:
nac consists of

* a client binary called `nac`
* a server binary called `nacd`

Communication between the client and the server happens through
UNIX sockets using [dnode](http://github.com/substack/dnode), meaning
that the authentication used is also unix-socket based.

`nacd` runs as root (usually started by systemd or upstart) and
receives commands from user-ran `nac` instances

`nacd` keeps some data in an sqlite database

# app execution model

nac will use `child_process.spawn` to spawn apps. This function
has an options argument which is going to be filled as follows:

* cwd: path to the nacfile
* env: whatever happens to be in env, extended with the env specified
  in the configuration file
* detached: false because we want the child to die if nac dies.
* uid, gid: taken from the unix socket credentials

# database model

* Table: apps
  * id - integer primary key
  * uid - app owner uid
  * name - app name
  * nacfile - path to the nacfile
  * active - true if started, false if stopped.

_Remarks_:  start sets active to true, stop sets active to false.
If `active = true` when starting nacd, nacd will start the app.
Otherwise the app will not be started. As a result, the start and
stop commands are preserved across daemon restarts.

* Table: logs (?)
  * appId - application id
  * event - stderr | stdout | start | stop | etc
  * timestamp - date logged
  * text - logged text


text:
<?php

namespace Earls\LeaseBundle\Controller;

use Earls\LeaseBundle\Entity\Storeclasses;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Acme\DemoBundle\Form\ContactType;

// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Earls\LeaseBundle\Entity\Leases;

class LeasesByExpiryController extends Controller
{
    /**
     * @Route("/", name="_leases_byExpiry")
     * @Template()
     */
    public function indexAction()
    {
        $restaurantlist = $this->getDoctrine()
            ->getRepository('EarlsLeaseBundle:Restaurants')
            ->findAll();

        $restaurantArray = array();
        $restaurantObj = array();

        foreach($restaurantlist as $restaurant){

            $storeNickname = $restaurant->getStorenickname();

            $storeId = $restaurant->getRestaurantid();

            $restaurantStoreClass = $restaurant->getStoreclassid();

            if(empty($restaurantStoreClass)){
                $storeClass= "";
            }else{
                $storeClassid = $restaurantStoreClass->getStoreclassid();

                $storeClassObj = $this->getDoctrine()
                    ->getRepository('EarlsLeaseBundle:Storeclasses')
                    ->find($storeClassid);

                $storeClass= $storeClassObj->getStoreclass();
            }

            $storeId = $restaurant->getRestaurantid();

            $leaseObj = $this->getDoctrine()
                ->getRepository('EarlsLeaseBundle:Leases')
                ->findOneBy(array(
                    'restaurantid' => $storeId
                ));

            if(empty($leaseObj)){
                $leaseObj = new Leases();
            }

            $leaseExpiryDateObj = $leaseObj->getExpirydate();

            $leaseExpiryDate= "";

            if(isset($leaseExpiryDateObj)){
                $leaseExpiryDate = $leaseExpiryDateObj->format('M d, Y');
            }

            $leaseOptionDate = $leaseObj->getOptiontime();

            $leaseOptionDeadlineObj = $leaseObj->getRenewaloptiondate();

            $leaseOptionDeadline= "";

            if(isset($leaseOptionDeadlineObj)){
                $leaseOptionDeadline = $leaseOptionDeadlineObj->format('M d, Y');
            }

            $leaseRenewalComments = $leaseObj->getRenewalcomments();

            $restaurantObj = array(
                'storeNickName' => $storeNickname,
                'storeClass' => $storeClass,
                'leaseExpiryDate' => $leaseExpiryDate,
                'leaseOptionDate' => $leaseOptionDate,
                'leaseOptionDeadline' => $leaseOptionDeadline,
                'leaseRenewalComments' =>$leaseRenewalComments,
                'restaurantId' => $storeId
            );

            array_push($restaurantArray, $restaurantObj);
        }

        return $this->render('EarlsLeaseBundle:LeasesByExpiry:index.html.twig',
            array(
                'leasesByExpiry' => $restaurantArray
            )
        );
    }
}

?>


text:
#ifndef DISTANCECALCULATOR_HPP
#define DISTANCECALCULATOR_HPP

#include "ExceptionHandler.hpp"

#include <cmath>
#include <cfloat>
#include <xmmintrin.h>        /* SSE  */
#include <emmintrin.h>        /* SSE2 */
#include <tmmintrin.h>      /* SSE3 */
#include <cstdint>

class DistanceCalculator {
    const float bl45[21][21];
public:

    enum CorrectionType {
        not_assigned, none, JukesCantor/*DNA*/, Kimura2/*DNA*/, FastTree /*amino*/};
    enum AlphabetType {
        dna, amino, null
    };

    DistanceCalculator(std::string **A /*alignment*/, AlphabetType alphType, CorrectionType corrType,
                       int numberOfSequences, bool useSSE);

    ~DistanceCalculator();

    AlphabetType alph_type;
    CorrectionType corr_type;

    std::string dna_chars;
    std::string aa_chars;
    std::string **A;

    int numberOfSequences;
    int lengthOfSequences;

    //TODO: set this as true only if it has support for SSE3
    bool newCalculation;

    double calc(int a, int b);

    static int *getInverseAlphabet(std::string alph, int length);

    double testDifferenceCluster(int a, int b);

    unsigned int **convertedSequences;
    unsigned int **gapInTheSequences;

    __m128i x128;
    __m128i zero;
    __m128i GAPS_COUNT_MASK;

    __m128i DECOMPRESSED_GAPS;
    __m128i COUNTS_MASK;
    __m128i TRANSITIONS_MASK;
    __m128i TRANSVERSIONS_MASK;

    __m128i VALUES_0;
    __m128i VALUES_1;
    __m128i VALUES_2;
    __m128i VALUES_3;
    __m128i VALUES_4;
    __m128i VALUES_5;
    __m128i VALUES_6;
    __m128i VALUES_7;

private:
    int *inv_alph;

    int protein_dict[256];
    int protein_dict_original[256];
    int additionalGaps; //inverse of the number of gaps added at the end of the sequence in sse calculation

    inline void count128(register __m128i &seq1, register __m128i &seq2, register __m128i &gap1, register __m128i &gap2,
                         register __m128i &tmp, register __m128i &tmp2, register __m128i &tmp3,
                         register __m128i &count_transversions, register __m128i &count_transitions,
                         register __m128i &count_gaps) const;

    static inline void
    count128P(register __m128i &seq1, register __m128i &seq2, register __m128i &gap1, register __m128i &gap2,
              register __m128i &VALUES_0, register __m128i &VALUES_1, register __m128i &VALUES_2,
              register __m128i &VALUES_3, register __m128i &VALUES_4, register __m128i &VALUES_5,
              register __m128i &VALUES_6, register __m128i &VALUES_7, register __m128i &sum,
              register __m128i &gap_count, register __m128i &tmp1, register __m128i &tmp2, int a, int b);

    double newCalcDNA(int a, int b);

    double newCalcProtein(int a, int b);

    void convertAllDNA();

    void convertAllProtein();

    static void getBitsDNA(const char *seq, int *size, unsigned int *seqOut, unsigned int *gapOut);

    static void generateProteinClusterDict(int *protein_dictionary);

    void getBitsProteinClustered(const char *seq, int *size, unsigned int *seqOut, unsigned int *gapOut);

    static void generateProteinOriginalDict(int *protein_dictionary);

    unsigned int *getProteinDic(std::string alph, int length);

};

#endif


text:
using namespace swift;

void *SILSSAUpdater::allocate(unsigned size, unsigned align) const {
  return AlignedAlloc(size, align);
}

void SILSSAUpdater::deallocateSentinel(SILUndef *undef) {
  AlignedFree(undef);
}

SILSSAUpdater::SILSSAUpdater(SmallVectorImpl<SILPhiArgument *> *phis)
    : blockToAvailableValueMap(nullptr), ownershipKind(OwnershipKind::None),
      phiSentinel(nullptr, deallocateSentinel), insertedPhis(phis) {}

SILSSAUpdater::~SILSSAUpdater() = default;

void SILSSAUpdater::initialize(SILType inputType, ValueOwnershipKind kind) {
  type = inputType;
  ownershipKind = kind;

  phiSentinel = std::unique_ptr<SILUndef, void (*)(SILUndef *)>(
      SILUndef::getSentinelValue(inputType, this),
      SILSSAUpdater::deallocateSentinel);

  if (!blockToAvailableValueMap)
    blockToAvailableValueMap.reset(new AvailableValsTy());
  else
    blockToAvailableValueMap->clear();
}

bool SILSSAUpdater::hasValueForBlock(SILBasicBlock *block) const {
  return blockToAvailableValueMap->count(block);
}

/// Indicate that a rewritten value is available in the specified block with the
/// specified value.
void SILSSAUpdater::addAvailableValue(SILBasicBlock *block, SILValue value) {
  assert(value->getOwnershipKind().isCompatibleWith(ownershipKind));
  (*blockToAvailableValueMap)[block] = value;
}

/// Construct SSA form, materializing a value that is live at the end of the
/// specified block.
SILValue SILSSAUpdater::getValueAtEndOfBlock(SILBasicBlock *block) {
  return getValueAtEndOfBlockInternal(block);
}

/// Are all available values identicalTo each other.
static bool
areIdentical(llvm::DenseMap<SILBasicBlock *, SILValue> &availableValues) {
  if (auto *firstInst =
          dyn_cast<SingleValueInstruction>(availableValues.begin()->second)) {
    for (auto value : availableValues) {
      auto *svi = dyn_cast<SingleValueInstruction>(value.second);
      if (!svi)
        return false;
      if (!svi->isIdenticalTo(firstInst))
        return false;
    }
    return true;
  }

  auto *mvir =
      dyn_cast<MultipleValueInstructionResult>(availableValues.begin()->second);
  if (!mvir)
    return false;

  for (auto value : availableValues) {
    auto *result = dyn_cast<MultipleValueInstructionResult>(value.second);
    if (!result)
      return false;
    if (!result->getParent()->isIdenticalTo(mvir->getParent()) ||
        result->getIndex() != mvir->getIndex()) {
      return false;
    }
  }
  return true;
}

/// This should be called in top-down order of each def that needs its uses
/// rewrited. The order that we visit uses for a given def is irrelevant.
void SILSSAUpdater::rewriteUse(Operand &use) {
  // Replicate function_refs to their uses. SILGen can't build phi nodes for
  // them and it would not make much sense anyways.
  if (auto *fri = dyn_cast<FunctionRefInst>(use.get())) {
    assert(areIdentical(*blockToAvailableValueMap) &&
           "The function_refs need to have the same value");
    SILInstruction *user = use.getUser();
    use.set(cast<FunctionRefInst>(fri->clone(user)));
    return;
  } else if (auto *pdfri =
                 dyn_cast<PreviousDynamicFunctionRefInst>(use.get())) {
    assert(areIdentical(*blockToAvailableValueMap) &&
           "The function_refs need to have the same value");
    SILInstruction *user = use.getUser();
    use.set(cast<PreviousDynamicFunctionRefInst>(pdfri->clone(user)));
    return;
  } else if (auto *dfri = dyn_cast<DynamicFunctionRefInst>(use.get())) {
    assert(areIdentical(*blockToAvailableValueMap) &&
           "The function_refs need to have the same value");
    SILInstruction *user = use.getUser();
    use.set(cast<DynamicFunctionRefInst>(dfri->clone(user)));
    return;
  } else if (auto *ili = dyn_cast<IntegerLiteralInst>(use.get()))
    if (areIdentical(*blockToAvailableValueMap)) {
      // Some llvm intrinsics don't like phi nodes as their constant inputs (e.g
      // ctlz).
      SILInstruction *user = use.getUser();
      use.set(cast<IntegerLiteralInst>(ili->clone(user)));
      return;
    }

  // Again we need to be careful here, because ssa construction (with the
  // existing representation) can change the operand from under us.
  UseWrapper useWrapper(&use);

  SILInstruction *user = use.getUser();
  SILValue newVal = getValueInMiddleOfBlock(user->getParent());
  assert(newVal && "Need a valid value");
  static_cast<Operand *>(useWrapper)->set(newVal);
}

/// Get the edge values from the terminator to the destination basic block.
static OperandValueArrayRef getEdgeValuesForTerminator(TermInst *ti,
                                                       SILBasicBlock *toBlock) {
  if (auto *br = dyn_cast<BranchInst>(ti)) {
    assert(br->getDestBB() == toBlock &&
           "Incoming edge block and phi block mismatch");
    return br->getArgs();
  }
  if (auto *cbi = dyn_cast<CondBranchInst>(ti)) {
    bool isTrueEdge = cbi->getTrueBB() == toBlock;
    assert(((isTrueEdge && cbi->getTrueBB() == toBlock) ||
            cbi->getFalseBB() == toBlock) &&
           "Incoming edge block and phi block mismatch");
    return isTrueEdge ? cbi->getTrueArgs() : cbi->getFalseArgs();
  }

  // We need a predecessor who is capable of holding outgoing branch
  // arguments.
  llvm_unreachable("Unrecognized terminator leading to phi block");
}

/// Check that the argument has the same incoming edge values as the value
/// map.
static bool
isEquivalentPHI(SILPhiArgument *phi,
                llvm::SmallDenseMap<SILBasicBlock *, SILValue, 8> &valueMap) {
  SILBasicBlock *phiBlock = phi->getParent();
  size_t phiArgEdgeIndex = phi->getIndex();
  for (auto *predBlock : phiBlock->getPredecessorBlocks()) {
    auto desiredVal = valueMap[predBlock];
    OperandValueArrayRef edgeValues =
        getEdgeValuesForTerminator(predBlock->getTerminator(), phiBlock);
    if (edgeValues[phiArgEdgeIndex] != desiredVal)
      return false;
  }
  return true;
}

SILValue SILSSAUpdater::getValueInMiddleOfBlock(SILBasicBlock *block) {
  // If this basic block does not define a value we can just use the value
  // live at the end of the block.
  if (!hasValueForBlock(block))
    return getValueAtEndOfBlock(block);

  /// Otherwise, we have to build SSA for the value defined in this block and
  /// this block's predecessors.
  SILValue singularValue;
  SmallVector<std::pair<SILBasicBlock *, SILValue>, 4> predVals;
  bool firstPred = true;

  // SSAUpdater can modify TerminatorInst and therefore invalidate the
  // predecessor iterator. Find all the predecessors before the SSA update.
  SmallVector<SILBasicBlock *, 4> preds;
  for (auto *predBlock : block->getPredecessorBlocks()) {
    preds.push_back(predBlock);
  }

  for (auto *predBlock : preds) {
    SILValue predVal = getValueAtEndOfBlock(predBlock);
    predVals.push_back(std::make_pair(predBlock, predVal));
    if (firstPred) {
      singularValue = predVal;
      firstPred = false;
    } else if (singularValue != predVal)
      singularValue = SILValue();
  }

  // Return undef for blocks without predecessor.
  if (predVals.empty())
    return SILUndef::get(type, *block->getParent());

  if (singularValue)
    return singularValue;

  // Check if we already have an equivalent phi.
  if (!block->getArguments().empty()) {
    llvm::SmallDenseMap<SILBasicBlock *, SILValue, 8> valueMap(predVals.begin(),
                                                               predVals.end());
    for (auto *arg : block->getSILPhiArguments())
      if (isEquivalentPHI(arg, valueMap))
        return arg;
  }

  // Create a new phi node.
  SILPhiArgument *phiArg = block->createPhiArgument(type, ownershipKind);
  for (auto &pair : predVals) {
    addNewEdgeValueToBranch(pair.first->getTerminator(), block, pair.second,
                            deleter);
  }
  if (insertedPhis)
    insertedPhis->push_back(phiArg);

  return phiArg;
}

namespace llvm {

/// Traits for the SSAUpdaterImpl specialized for SIL and the SILSSAUpdater.
template <>
class SSAUpdaterTraits<SILSSAUpdater> {
public:
  using BlkT = SILBasicBlock;
  using ValT = SILValue;
  using PhiT = SILPhiArgument;

  using BlkSucc_iterator = SILBasicBlock::succ_iterator;
  static BlkSucc_iterator BlkSucc_begin(BlkT *block) {
    return block->succ_begin();
  }
  static BlkSucc_iterator BlkSucc_end(BlkT *block) { return block->succ_end(); }

  /// Iterator for PHI operands.
  class PHI_iterator {
  private:
    SILBasicBlock::pred_iterator predBlockIter;
    SILBasicBlock *phiBlock;
    size_t phiArgEdgeIndex;

  public:
    explicit PHI_iterator(SILPhiArgument *phiArg) // begin iterator
        : predBlockIter(phiArg->getParent()->pred_begin()),
          phiBlock(phiArg->getParent()), phiArgEdgeIndex(phiArg->getIndex()) {}
    PHI_iterator(SILPhiArgument *phiArg, bool) // end iterator
        : predBlockIter(phiArg->getParent()->pred_end()),
          phiBlock(phiArg->getParent()), phiArgEdgeIndex(phiArg->getIndex()) {}

    PHI_iterator &operator++() {
      ++predBlockIter;
      return *this;
    }

    bool operator==(const PHI_iterator &x) const {
      return predBlockIter == x.predBlockIter;
    }

    bool operator!=(const PHI_iterator& x) const { return !operator==(x); }

    SILValue getValueForBlock(size_t inputArgIndex, SILBasicBlock *block,
                              TermInst *ti) {
      OperandValueArrayRef args = getEdgeValuesForTerminator(ti, block);
      assert(inputArgIndex < args.size() &&
             "Not enough values on incoming edge");
      return args[inputArgIndex];
    }

    SILValue getIncomingValue() {
      return getValueForBlock(phiArgEdgeIndex, phiBlock,
                              (*predBlockIter)->getTerminator());
    }

    SILBasicBlock *getIncomingBlock() { return *predBlockIter; }
  };

  static inline PHI_iterator PHI_begin(PhiT *phi) { return PHI_iterator(phi); }
  static inline PHI_iterator PHI_end(PhiT *phi) {
    return PHI_iterator(phi, true);
  }

  /// Put the predecessors of BB into the Preds vector.
  static void
  FindPredecessorBlocks(SILBasicBlock *block,
                        SmallVectorImpl<SILBasicBlock *> *predBlocks) {
    llvm::copy(block->getPredecessorBlocks(), std::back_inserter(*predBlocks));
  }

  static SILValue GetUndefVal(SILBasicBlock *block, SILSSAUpdater *ssaUpdater) {
    return SILUndef::get(ssaUpdater->type, *block->getParent());
  }

  /// Add an Argument to the basic block.
  static SILValue CreateEmptyPHI(SILBasicBlock *block, unsigned numPreds,
                                 SILSSAUpdater *ssaUpdater) {
    // Add the argument to the block.
    SILValue phi(
        block->createPhiArgument(ssaUpdater->type, ssaUpdater->ownershipKind));

    // Mark all predecessor blocks with the sentinel undef value.
    SmallVector<SILBasicBlock *, 4> predBlockList(
        block->getPredecessorBlocks());

    for (auto *predBlock : predBlockList) {
      TermInst *ti = predBlock->getTerminator();
      addNewEdgeValueToBranch(ti, block, ssaUpdater->phiSentinel.get(),
                              ssaUpdater->deleter);
    }

    return phi;
  }

  /// Add \p value as an operand of the phi argument \p phi for the specified
  /// predecessor block \p predBlock.
  static void AddPHIOperand(SILPhiArgument *phi, SILValue value,
                            SILBasicBlock *predBlock) {
    auto *phiBlock = phi->getParent();
    size_t phiArgIndex = phi->getIndex();
    auto *ti = predBlock->getTerminator();

    changeEdgeValue(ti, phiBlock, phiArgIndex, value);
  }

  /// Check if an instruction is a PHI.
  static SILPhiArgument *InstrIsPHI(ValueBase *valueBase) {
    return dyn_cast<SILPhiArgument>(valueBase);
  }

  /// Check if the instruction that defines the specified SILValue is a PHI
  /// instruction.
  static SILPhiArgument *ValueIsPHI(SILValue value, SILSSAUpdater *) {
    return InstrIsPHI(value);
  }

  /// Like ValueIsPHI but also check if the PHI has no source
  /// operands, i.e., it was just added.
  static SILPhiArgument *ValueIsNewPHI(SILValue value,
                                       SILSSAUpdater *ssaUpdater) {
    SILPhiArgument *phiArg = ValueIsPHI(value, ssaUpdater);
    if (!phiArg) {
      return nullptr;
    }

    auto *phiBlock = phiArg->getParent();
    size_t phiArgEdgeIndex = phiArg->getIndex();

    // If all predecessor edges are 'not set' this is a new phi.
    for (auto *predBlock : phiBlock->getPredecessorBlocks()) {
      OperandValueArrayRef edgeValues =
          getEdgeValuesForTerminator(predBlock->getTerminator(), phiBlock);

      assert(phiArgEdgeIndex < edgeValues.size() && "Not enough edges!");

      SILValue edgeValue = edgeValues[phiArgEdgeIndex];
      // Check for the 'not set' sentinel.
      if (edgeValue != ssaUpdater->phiSentinel.get())
        return nullptr;
    }
    return phiArg;
  }

  static SILValue GetPHIValue(SILPhiArgument *phi) { return phi; }
};

} // namespace llvm

/// Check to see if AvailableVals has an entry for the specified BB and if so,
/// return it.  If not, construct SSA form by first calculating the required
/// placement of PHIs and then inserting new PHIs where needed.
SILValue SILSSAUpdater::getValueAtEndOfBlockInternal(SILBasicBlock *block) {
  AvailableValsTy &availableValues = *blockToAvailableValueMap;
  auto iter = availableValues.find(block);
  if (iter != availableValues.end())
    return iter->second;

  llvm::SSAUpdaterImpl<SILSSAUpdater> impl(this, &availableValues,
                                           insertedPhis);
  return impl.GetValue(block);
}

/// Construct a use wrapper. For branches we store information so that we
/// can reconstruct the use after the branch has been modified.
///
/// When a branch is modified existing pointers to the operand
/// (ValueUseIterator) become invalid as they point to freed operands.  Instead
/// we store the branch's parent and the idx so that we can reconstruct the use.
UseWrapper::UseWrapper(Operand *inputUse) {
  wrappedUse = nullptr;
  type = kRegularUse;

  SILInstruction *user = inputUse->getUser();

  // Direct branch user.
  if (auto *br = dyn_cast<BranchInst>(user)) {
    for (auto pair : llvm::enumerate(user->getAllOperands())) {
      if (inputUse == &pair.value()) {
        index = pair.index();
        type = kBranchUse;
        parent = br->getParent();
        return;
      }
    }
  }

  // Conditional branch user.
  if (auto *cbi = dyn_cast<CondBranchInst>(user)) {
    auto operands = user->getAllOperands();
    auto numTrueArgs = cbi->getTrueArgs().size();
    for (auto pair : llvm::enumerate(operands)) {
      if (inputUse == &pair.value()) {
        unsigned i = pair.index();
        // We treat the condition as part of the true args.
        if (i < numTrueArgs + 1) {
          index = i;
          type = kCondBranchUseTrue;
        } else {
          index = i - numTrueArgs - 1;
          type = kCondBranchUseFalse;
        }
        parent = cbi->getParent();
        return;
      }
    }
  }

  wrappedUse = inputUse;
}

/// Return the operand we wrap. Reconstructing branch operands.
Operand *UseWrapper::getOperand() {
  switch (type) {
  case kRegularUse:
    return wrappedUse;

  case kBranchUse: {
    auto *br = cast<BranchInst>(parent->getTerminator());
    assert(index < br->getNumArgs());
    return &br->getAllOperands()[index];
  }

  case kCondBranchUseTrue:
  case kCondBranchUseFalse: {
    auto *cbi = cast<CondBranchInst>(parent->getTerminator());
    auto indexToUse = [&]() -> unsigned {
      if (type == kCondBranchUseTrue)
        return index;
      return cbi->getTrueArgs().size() + 1 + index;
    }();
    assert(indexToUse < cbi->getAllOperands().size());
    return &cbi->getAllOperands()[indexToUse];
  }
  }

  llvm_unreachable("uninitialize use type");
}

/// At least one value feeding the specified SILArgument is a Struct. Attempt to
/// replace the Argument with a new Struct in the same block.
///
/// When we handle more types of casts, this can become a template.
///
/// ArgValues are the values feeding the specified Argument from each
/// predecessor. They must be listed in order of Arg->getParent()->getPreds().
static StructInst *
replaceBBArgWithStruct(SILPhiArgument *phiArg,
                       SmallVectorImpl<SILValue> &argValues) {

  SILBasicBlock *phiBlock = phiArg->getParent();
  auto *firstSI = dyn_cast<StructInst>(argValues[0]);
  if (!firstSI)
    return nullptr;

  // Collect the BBArg index of each struct oper.
  // e.g.
  //   struct(A, B)
  //   br (B, A)
  // : ArgIdxForOper => {1, 0}
  SmallVector<unsigned, 4> argIdxForOper;
  for (unsigned operIdx : indices(firstSI->getElements())) {
    bool foundMatchingArgIdx = false;
    for (unsigned argIdx : indices(phiBlock->getArguments())) {
      auto avIter = argValues.begin();
      bool tryNextArgIdx = false;
      for (SILBasicBlock *predBlock : phiBlock->getPredecessorBlocks()) {
        // All argument values must be StructInst.
        auto *predSI = dyn_cast<StructInst>(*avIter++);
        if (!predSI)
          return nullptr;
        OperandValueArrayRef edgeValues =
            getEdgeValuesForTerminator(predBlock->getTerminator(), phiBlock);
        if (edgeValues[argIdx] != predSI->getElements()[operIdx]) {
          tryNextArgIdx = true;
          break;
        }
      }
      if (!tryNextArgIdx) {
        assert(avIter == argValues.end() &&
               "# ArgValues does not match # BB preds");
        foundMatchingArgIdx = true;
        argIdxForOper.push_back(argIdx);
        break;
      }
    }
    if (!foundMatchingArgIdx)
      return nullptr;
  }

  SmallVector<SILValue, 4> structArgs;
  for (auto argIdx : argIdxForOper)
    structArgs.push_back(phiBlock->getArgument(argIdx));

  // TODO: We probably want to use a SILBuilderWithScope here. What should we
  // use?
  SILBuilder builder(phiBlock, phiBlock->begin());
  return builder.createStruct(cast<StructInst>(argValues[0])->getLoc(),
                              phiArg->getType(), structArgs);
}

/// Canonicalize BB arguments, replacing argument-of-casts with
/// cast-of-arguments. This only eliminates existing arguments, replacing them
/// with casts. No new arguments are created. This allows downstream pattern
/// detection like induction variable analysis to succeed.
///
/// If Arg is replaced, return the cast instruction. Otherwise return nullptr.
SILValue swift::replaceBBArgWithCast(SILPhiArgument *arg) {
  SmallVector<SILValue, 4> argValues;
  arg->getIncomingPhiValues(argValues);
  if (isa<StructInst>(argValues[0]))
    return replaceBBArgWithStruct(arg, argValues);
  return nullptr;
}