text:
from django import http, template
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.shortcuts import render_to_response
from django.utils.translation import gettext_lazy
import base64, datetime, md5
import cPickle as pickle

ERROR_MESSAGE = gettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")
LOGIN_FORM_KEY = 'this_is_the_login_form'

def _display_login_form(request, error_message=''):
    request.session.set_test_cookie()
    if request.POST and request.POST.has_key('post_data'):
        # User has failed login BUT has previously saved post data.
        post_data = request.POST['post_data']
    elif request.POST:
        # User's session must have expired; save their post data.
        post_data = _encode_post_data(request.POST)
    else:
        post_data = _encode_post_data({})
    return render_to_response('admin/login.html', {
        'title': _('Log in'),
        'app_path': request.path,
        'post_data': post_data,
        'error_message': error_message
    }, context_instance=template.RequestContext(request))

def _encode_post_data(post_data):
    pickled = pickle.dumps(post_data)
    pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest()
    return base64.encodestring(pickled + pickled_md5)

def _decode_post_data(encoded_data):
    encoded_data = base64.decodestring(encoded_data)
    pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
    if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
        from django.core.exceptions import SuspiciousOperation
        raise SuspiciousOperation, "User may have tampered with session cookie."
    return pickle.loads(pickled)

def staff_member_required(view_func):
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, displaying the login page if necessary.
    """
    def _checklogin(request, *args, **kwargs):
        if request.user.is_authenticated() and request.user.is_staff:
            # The user is valid. Continue to the admin page.
            if request.POST.has_key('post_data'):
                # User must have re-authenticated through a different window
                # or tab.
                request.POST = _decode_post_data(request.POST['post_data'])
            return view_func(request, *args, **kwargs)

        assert hasattr(request, 'session'), "The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."

        # If this isn't already the login page, display it.
        if not request.POST.has_key(LOGIN_FORM_KEY):
            if request.POST:
                message = _("Please log in again, because your session has expired. Don't worry: Your submission has been saved.")
            else:
                message = ""
            return _display_login_form(request, message)

        # Check that the user accepts cookies.
        if not request.session.test_cookie_worked():
            message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.")
            return _display_login_form(request, message)

        # Check the password.
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        user = authenticate(username=username, password=password)
        if user is None:
            message = ERROR_MESSAGE
            if '@' in username:
                # Mistakenly entered e-mail address instead of username? Look it up.
                try:
                    user = User.objects.get(email=username)
                except User.DoesNotExist:
                    message = _("Usernames cannot contain the '@' character.")
                else:
                    message = _("Your e-mail address is not your username. Try '%s' instead.") % user.username
            return _display_login_form(request, message)

        # The user data is correct; log in the user in and continue.
        else:
            if user.is_active and user.is_staff:
                login(request, user)
                # TODO: set last_login with an event.
                user.last_login = datetime.datetime.now()
                user.save()
                if request.POST.has_key('post_data'):
                    post_data = _decode_post_data(request.POST['post_data'])
                    if post_data and not post_data.has_key(LOGIN_FORM_KEY):
                        # overwrite request.POST with the saved post_data, and continue
                        request.POST = post_data
                        request.user = user
                        return view_func(request, *args, **kwargs)
                    else:
                        request.session.delete_test_cookie()
                        return http.HttpResponseRedirect(request.path)
            else:
                return _display_login_form(request, ERROR_MESSAGE)

    return _checklogin


text:
from tornado import auth, web, httpclient
from bs4 import BeautifulSoup

import hashlib
import logging

from main.helper import *
from main.db import *

class ShowPhoto(myRequestHandler, Entity):
    """
    """
    entity_id = None
    photo_property = None
    isbn = None

    @web.asynchronous
    def get(self):

        entity_id = self.get_argument('entity', default=None, strip=True)
        ester_file_id = self.get_argument('ester_file', default=None, strip=True)

        if not entity_id and not ester_file_id:
            return self.missing()

        if entity_id:
            item = self.get_entities(entity_id=entity_id, full_definition=True, limit=1)
            if not item:
                return self.missing()
            self.photo_file = [x.get('db_value', '') for x in item.get('properties', {}).get('photo', {}).get('values', [])][0]
            if self.photo_file:
                return self.redirect('/api2/file-%s' % self.photo_file)
            self.entity_id = entity_id
            self.photo_property = [x.get('keyname') for x in item.get('properties', {}).values() if x.get('dataproperty') == 'photo'][0]
            self.isbn = [x.get('value', '').split(' ')[0] for x in item.get('properties', {}).get('isn', {}).get('values', [])][0]
            if not self.isbn:
                return self.redirect('https://secure.gravatar.com/avatar/%s?d=identicon&s=150' % (hashlib.md5('%s' % self.entity_id).hexdigest()))

        if ester_file_id:
            tmp_file = self.db_get('SELECT file FROM tmp_file WHERE id = %s LIMIT 1;', ester_file_id)
            if not tmp_file:
                return self.missing()
            if not tmp_file.get('file'):
                return self.missing()
            item = json.loads(tmp_file.get('file'))
            self.isbn = item.get('isn', '').split(' ')[0] if type(item.get('isn', '')) is not list else [x.split(' ')[0] for x in item.get('isn', [''])][0]
            if not self.isbn:
                return self.redirect('/static/images/blank.png')

        url = 'https://www.raamatukoi.ee/cgi-bin/index?valik=isbn&paring=%s' % self.isbn
        httpclient.AsyncHTTPClient().fetch(url, callback=self._got_raamatukoi_item, request_timeout=60)

    @web.asynchronous
    def _got_raamatukoi_item(self, response):
        if not response.body:
            self.finish()
            return

        soup = BeautifulSoup(response.body.decode('utf-8', 'ignore'))
        url = None

        table = soup.find('table', {'width' : '450'})
        if table:
            img = table.find('img')
            if img:
                url = img.get('src')
                httpclient.AsyncHTTPClient().fetch(url, callback=self._got_photo, request_timeout=60)

        if not url:
            if self.entity_id:
                return self.redirect('https://secure.gravatar.com/avatar/%s?d=identicon&s=150' % (hashlib.md5('%s' % self.entity_id).hexdigest()))
            else:
                return self.redirect('/static/images/blank.png')

    @web.asynchronous
    def _got_photo(self, response):
        if not response.body:
            self.finish()
            return

        if self.photo_property:
            self.set_property(entity_id=self.entity_id, property_definition_keyname=self.photo_property, value={'filename': response.effective_url.split('/')[-1], 'body': response.body})

        self.add_header('Content-Type', response.headers.get('Content-Type'))
        self.write(response.body)
        self.finish()

handlers = [
    ('/photo-by-isbn', ShowPhoto),
]

redpajama_set_name: RedPajamaGithub


text:
/* */
"format global";
"deps ../modernizr";
// Blob constructor
// http://dev.w3.org/2006/webapi/FileAPI/#constructorBlob

Modernizr.addTest('blobconstructor', function () {
    try {
        return !!new Blob();
    } catch (e) {
        return false;
    }
});


text:
namespace System.ServiceModel
{
    using System;
    using System.Text;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Configuration;
    using System.Globalization;
    using System.Net;
    using System.Net.Security;
    using System.Runtime.Serialization;
    using System.Security.Principal;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Configuration;
    using System.ServiceModel.Security;

    using System.Xml;

    public class WS2007HttpBinding : WSHttpBinding
    {
        static readonly ReliableMessagingVersion WS2007ReliableMessagingVersion = ReliableMessagingVersion.WSReliableMessaging11;
        static readonly TransactionProtocol WS2007TransactionProtocol = TransactionProtocol.WSAtomicTransaction11;
        static readonly MessageSecurityVersion WS2007MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;

        public WS2007HttpBinding(string configName)
            : this()
        {
            ApplyConfiguration(configName);
        }

        public WS2007HttpBinding()
            : base()
        {
            this.ReliableSessionBindingElement.ReliableMessagingVersion = WS2007ReliableMessagingVersion;
            this.TransactionFlowBindingElement.TransactionProtocol = WS2007TransactionProtocol;
            this.HttpsTransport.MessageSecurityVersion = WS2007MessageSecurityVersion;
        }

        public WS2007HttpBinding(SecurityMode securityMode)
            : this(securityMode, false)
        {
        }

        public WS2007HttpBinding(SecurityMode securityMode, bool reliableSessionEnabled)
            : base(securityMode, reliableSessionEnabled)
        {
            this.ReliableSessionBindingElement.ReliableMessagingVersion = WS2007ReliableMessagingVersion;
            this.TransactionFlowBindingElement.TransactionProtocol = WS2007TransactionProtocol;
            this.HttpsTransport.MessageSecurityVersion = WS2007MessageSecurityVersion;
        }

        internal WS2007HttpBinding(WSHttpSecurity security, bool reliableSessionEnabled)
            : base(security, reliableSessionEnabled)
        {
            this.ReliableSessionBindingElement.ReliableMessagingVersion = WS2007ReliableMessagingVersion;
            this.TransactionFlowBindingElement.TransactionProtocol = WS2007TransactionProtocol;
            this.HttpsTransport.MessageSecurityVersion = WS2007MessageSecurityVersion;
        }

        void ApplyConfiguration(string configurationName)
        {
            WS2007HttpBindingCollectionElement section = WS2007HttpBindingCollectionElement.GetBindingCollectionElement();
            WS2007HttpBindingElement element = section.Bindings[configurationName];
            if (element == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(
                    SR.GetString(SR.ConfigInvalidBindingConfigurationName,
                                 configurationName,
                                 ConfigurationStrings.WS2007HttpBindingCollectionElementName)));
            }
            else
            {
                element.ApplyConfiguration(this);
            }
        }

        protected override SecurityBindingElement CreateMessageSecurity()
        {
            return this.Security.CreateMessageSecurity(this.ReliableSession.Enabled, WS2007MessageSecurityVersion);
        }

        // This is effectively just a copy of WSHttpBinding.TryCreate(), only it news up the 2007 version
        internal new static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
        {
            bool isReliableSession = (rsbe != null);
            binding = null;

            // reverse GetTransport
            HttpTransportSecurity transportSecurity = WSHttpSecurity.GetDefaultHttpTransportSecurity();
            UnifiedSecurityMode mode;
            if (!WSHttpBinding.GetSecurityModeFromTransport(transport, transportSecurity, out mode))
            {
                return false;
            }

            HttpsTransportBindingElement httpsBinding = transport as HttpsTransportBindingElement;
            if (httpsBinding != null && httpsBinding.MessageSecurityVersion != null)
            {
                if (httpsBinding.MessageSecurityVersion.SecurityPolicyVersion != WS2007MessageSecurityVersion.SecurityPolicyVersion)
                {
                    return false;
                }
            }

            WSHttpSecurity security;
            if (WS2007HttpBinding.TryCreateSecurity(sbe, mode, transportSecurity, isReliableSession, out security))
            {
                WS2007HttpBinding ws2007HttpBinding = new WS2007HttpBinding(security, isReliableSession);

                bool allowCookies;
                if (!WSHttpBinding.TryGetAllowCookiesFromTransport(transport, out allowCookies))
                {
                    return false;
                }

                ws2007HttpBinding.AllowCookies = allowCookies;
                binding = ws2007HttpBinding;
            }

            if (rsbe != null && rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11)
            {
                return false;
            }

            if (tfbe != null && tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11)
            {
                return false;
            }

            return binding != null;
        }

        // This is effectively just a copy of WSHttpBinding.TryCreateSecurity(), only it passes the 2007 security version
        static bool TryCreateSecurity(SecurityBindingElement sbe, UnifiedSecurityMode mode, HttpTransportSecurity transportSecurity, bool isReliableSession, out WSHttpSecurity security)
        {
            if (!WSHttpSecurity.TryCreate(sbe, mode, transportSecurity, isReliableSession, out security))
                return false;
            // the last check: make sure that security binding element match the incoming security
            return SecurityElement.AreBindingsMatching(security.CreateMessageSecurity(isReliableSession, WS2007MessageSecurityVersion), sbe);
        }

    }
}


text:
rm -rf autom4te.cache
rm -f aclocal.m4

#created by libtoolize
rm -rf m4
rm -f ltmain.sh

#created by autoconf
rm -f configure

#created by automake
rm -f install-sh missing depcomp Makefile.in config.guess config.sub

#created by ./configure
rm -rf .deps
rm -f Makefile config.log config.status libtool

if [ "$1" = "clean" ]; then
    exit
fi

IPATHS="-I ."

libtoolize --force
aclocal $IPATHS
# autoheader
automake --force-missing --add-missing
autoconf $IPATHS

rm -rf autom4te.cache

echo "Now run ./configure and then make."
exit 0


text:
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Runtime.Serialization;

namespace Indexer
{
    /// <summary>
    /// Represents an index file residing on disk
    /// </summary>
    [Serializable]
    [JsonObject(MemberSerialization.OptIn)]
    internal sealed class IndexEntries : IEquatable<IndexEntries>, ISerializable
    {
        public IndexEntries()
        {
            Entries = new IndexEntry[0];
        }

        public IndexEntries(SerializationInfo info, StreamingContext context)
        {
            Entries = (IndexEntry[])info.GetValue("Entries", typeof(IndexEntry[]));
        }

        /// <summary>
        /// The array of entries in this index file
        /// </summary>
        [JsonProperty(PropertyName = "Entries", Required = Required.Always)]
        public IndexEntry[] Entries { get; set; }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Entries", Entries);
        }

        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }

            return Equals(obj as IndexEntries);
        }

        public override int GetHashCode()
        {
            int runningHashCode = 0;
            foreach (var e in Entries)
            {
                runningHashCode = runningHashCode ^ e.GetHashCode();
            }

            return runningHashCode;
        }

        public bool Equals(IndexEntries other)
        {
            if (other == null || GetType() != other.GetType())
            {
                return false;
            }

            if (this == other)
            {
                return true;
            }

            return Enumerable.SequenceEqual(Entries, other.Entries);
        }

        public override string ToString()
        {
            return string.Format("Index Entries with {0}", Entries);
        }
    }
}


text:
#ifndef RTCPeerConnectionHandlerClient_h
#define RTCPeerConnectionHandlerClient_h

#include "wtf/PassRefPtr.h"

namespace WebKit {
class WebRTCICECandidate;
}

namespace WebCore {

class MediaStreamDescriptor;
class RTCDataChannelHandler;

class RTCPeerConnectionHandlerClient {
public:
    enum SignalingState {
        SignalingStateStable = 1,
        SignalingStateHaveLocalOffer = 2,
        SignalingStateHaveRemoteOffer = 3,
        SignalingStateHaveLocalPrAnswer = 4,
        SignalingStateHaveRemotePrAnswer = 5,
        SignalingStateClosed = 6,
    };

    enum IceConnectionState {
        IceConnectionStateNew = 1,
        IceConnectionStateChecking = 2,
        IceConnectionStateConnected = 3,
        IceConnectionStateCompleted = 4,
        IceConnectionStateFailed = 5,
        IceConnectionStateDisconnected = 6,
        IceConnectionStateClosed = 7
    };

    enum IceGatheringState {
        IceGatheringStateNew = 1,
        IceGatheringStateGathering = 2,
        IceGatheringStateComplete = 3
    };

    virtual ~RTCPeerConnectionHandlerClient() { }

    virtual void negotiationNeeded() = 0;
    virtual void didGenerateIceCandidate(WebKit::WebRTCICECandidate) = 0;
    virtual void didChangeSignalingState(SignalingState) = 0;
    virtual void didChangeIceGatheringState(IceGatheringState) = 0;
    virtual void didChangeIceConnectionState(IceConnectionState) = 0;
    virtual void didAddRemoteStream(PassRefPtr<MediaStreamDescriptor>) = 0;
    virtual void didRemoveRemoteStream(MediaStreamDescriptor*) = 0;
    virtual void didAddRemoteDataChannel(PassOwnPtr<RTCDataChannelHandler>) = 0;
};

} // namespace WebCore

#endif // RTCPeerConnectionHandlerClient_h


text:
#ifndef BlueSTSDK_BlueSTSDKFeatureProximityGesture_h
#define BlueSTSDK_BlueSTSDKFeatureProximityGesture_h

#import "BlueSTSDKFeature.h"

/**
 * Export the data from the gesture recognition algorithm using the proximity sensor
 *
 * @author STMicroelectronics - Central Labs.
 */
@interface BlueSTSDKFeatureProximityGesture : BlueSTSDKFeature

/**
 *  different type of position recognized by the node
 */
typedef NS_ENUM(NSInteger, BlueSTSDKFeatureProximityGestureType){
    /**
     *  we don't have enough data for select a gesture
     */
    BlueSTSDKFeatureProximityGestureUnknown =0x00,
    /**
     *  the tap gesture
     */
    BlueSTSDKFeatureProximityGestureTap =0x01,
    /**
     *  the left gesture
     */
    BlueSTSDKFeatureProximityGestureLeft =0x02,
    /**
     *  the right gesture
     */
    BlueSTSDKFeatureProximityGestureRight =0x03,
    /**
     *  the error status
     */
    BlueSTSDKFeatureProximityGestureError =0xFF,

};

/**
 *  extract the gesture value
 *
 *  @param sample sample read from the node
 *
 *  @return activity value
 */
+(BlueSTSDKFeatureProximityGestureType)getGestureType:(BlueSTSDKFeatureSample*)sample;

@end

#endif


text:
DEFINE_string(mesh, "mesh.ply", "input mesh");
DEFINE_string(poses, "poses.csv", "input pose file");
DEFINE_int32(voxel_dim, 3, "number of voxels along each grid dimension");
DEFINE_double(voxel_size, 0.1, "size of each individual voxel");
DEFINE_bool(meshlab, false, "mesh files should to be writen for meshlab");
DEFINE_double(fx, 535.7239, "camera horizontal focal length");
DEFINE_double(fy, 536.2900, "camera vertical focal length");
DEFINE_double(cx, 320.2685, "camera horizontal center point");
DEFINE_double(cy, 240.2924, "camera vertical center point");
DEFINE_double(img_scale, 1, "downscale ration of reference cameras");
DEFINE_int32(samples, 4, "square-root of number of samples per pixel");
DEFINE_bool(euler, false, "interpret pose file rotation as euler angles");
DEFINE_bool(verbose, false, "verbose output of optimization progress");
DEFINE_int32(max_iters, 1, "max number of iterations");
DEFINE_double(min_light_change, 1E-5, "minimum change rate for light params");
DEFINE_double(min_albedo_change, 1E-5, "minimum change rate for albedo params");
DEFINE_string(out_light, "out_light.txt", "file to write light parameters");
DEFINE_string(out_image_prefix, "out_image_", "file prefix for final renders");
DEFINE_bool(use_act, false, "use activation cost regulizer");
DEFINE_double(inner_act, 1.0, "inner log scale for activation cost");
DEFINE_double(outer_act, 1.0, "outer log scale for activation cost");
DEFINE_bool(use_ref, false, "use reflectance cost regulizer");
DEFINE_double(chrom_thresh, 0.0, "chromaticiy likeness threshold for ref cost");
DEFINE_double(ref_weight, 1.0, "scaling to apply to reflectance cost");

using namespace torch;

int iteration = 0;
std::shared_ptr<Scene> scene;
std::shared_ptr<VoxelLight> light;
std::shared_ptr<MatteMaterial> material;
std::shared_ptr<Mesh> mesh;

std::vector<std::shared_ptr<Camera>> cameras;
std::vector<std::shared_ptr<Keyframe>> keyframes;

lynx::Problem* lightProblem;
VoxelCostFunction* lightCostFunction;
float* lightValues;

lynx::Problem* albedoProblem;
AlbedoCostFunction* albedoCostFunction;
float* albedoValues;

void ReadPoses(std::vector<Sophus::SE3f>& poses)
{
  poses.clear();
  std::string line;
  std::ifstream fin(FLAGS_poses);

  while(std::getline(fin, line))
  {
    Sophus::SE3f pose;

    if (FLAGS_euler)
    {
      float data[6];
      std::stringstream ss(line);
      std::string token;

      for (int j = 0; j < 6; ++j)
      {
        TORCH_ASSERT(std::getline(ss, token, ','), "invalid pose file");
        data[j] = std::stof(token);
      }

      Eigen::Quaternionf quaternion =
          Eigen::AngleAxisf(data[0], Eigen::Vector3f::UnitX()) *
          Eigen::AngleAxisf(data[1], Eigen::Vector3f::UnitY()) *
          Eigen::AngleAxisf(data[2], Eigen::Vector3f::UnitZ());

      pose.setQuaternion(quaternion);
      pose.translation() = Eigen::Vector3f(data[3], data[4], data[5]);
    }
    else
    {
      float data[7];
      std::stringstream ss(line);
      std::string token;

      for (int j = 0; j < 7; ++j)
      {
        TORCH_ASSERT(std::getline(ss, token, ','), "invalid pose file");
        data[j] = std::stof(token);
      }

      pose.setQuaternion(Eigen::Quaternionf(data[3], data[0], data[1], data[2]));
      pose.translation() = Eigen::Vector3f(data[4], data[5], data[6]);
    }

    poses.push_back(pose);
  }

  fin.close();
}

void WriteLightParameters()
{
  std::ofstream fout(FLAGS_out_light);
  const uint3 dims = light->GetDimensions();

  std::vector<float3> host(light->GetVoxelCount());
  optix::Buffer buffer = light->GetRadianceBuffer();
  float3* device = reinterpret_cast<float3*>(buffer->map());
  std::copy(device, device + host.size(), host.data());
  buffer->unmap();

  fout << "voxel" << std::endl;
  fout << dims.x << " " << dims.y << " " << dims.z << std::endl;

  for (const float3& radiance : host)
  {
    fout << radiance.x << " " << radiance.y << " " << radiance.z << std::endl;
  }

  fout.close();
}

void BuildScene(int argc, char** argv)
{
  LOG(INFO) << "Building scene...";

  scene = std::make_shared<Scene>();

  mesh = scene->CreateMesh(FLAGS_mesh);
  std::shared_ptr<Material> temp = scene->CreateMaterial(FLAGS_mesh);
  material = std::static_pointer_cast<MatteMaterial>(temp);

  std::shared_ptr<Primitive> primitive;
  primitive = scene->CreatePrimitive();
  primitive->SetGeometry(mesh);
  primitive->SetMaterial(material);
  scene->Add(primitive);

  light = scene->CreateVoxelLight();
  light->SetDimensions(FLAGS_voxel_dim);
  light->SetVoxelSize(FLAGS_voxel_size);
  light->SetRadiance(1E-8, 1E-8, 1E-8);
  scene->Add(light);

  LOG(INFO) << "Building keyframes...";

  std::vector<Sophus::SE3f> poses;
  ReadPoses(poses);
  cameras.resize(poses.size());
  keyframes.resize(cameras.size());

  for (size_t i = 0; i < cameras.size(); ++i)
  {
    std::shared_ptr<Image> image;
    image = std::make_shared<Image>();
    image->Load(argv[i + 1]);
    image->Scale(1 / FLAGS_img_scale);

    cameras[i] = scene->CreateCamera();
    cameras[i]->SetImageSize(image->GetWidth(), image->GetHeight());
    cameras[i]->SetFocalLength(FLAGS_fx / FLAGS_img_scale, FLAGS_fy / FLAGS_img_scale);
    cameras[i]->SetCenterPoint(FLAGS_cx / FLAGS_img_scale, FLAGS_cy / FLAGS_img_scale);
    cameras[i]->SetSampleCount(FLAGS_samples);
    cameras[i]->SetTransform(poses[i]);

    // // corner04
    // cameras[i]->SetOrientation(-0.1876, 0.020051, -0.00564309, 0.982025);
    // cameras[i]->SetPosition(-0.0138542, -0.325955, 0.276384);

    // // sink01
    // cameras[i]->SetOrientation(-0.0481747, 0.00691056, -0.0414812, 0.997953);
    // cameras[i]->SetPosition(0.0237228, 0.0249558, -0.0143689);

    // // kitchen01
    // // // image_rgb_00060
    // // cameras[i]->SetOrientation(-0.0262128, 0.0620964, 0.0213342, 0.997498);
    // // cameras[i]->SetPosition(0.0173549, 0.0174267, -0.011409);
    // // image_rgb_02016
    // cameras[i]->SetOrientation(-0.0858785, -0.179851, -0.087353, 0.976037);
    // cameras[i]->SetPosition(0.607607, -0.0107669, 0.232484);

    // corner02
    // // image_rgb_01010
    // cameras[i]->SetOrientation(-0.00600349, 0.00614246, -0.0346581, 0.999362);
    // cameras[i]->SetPosition(0.0896841, 0.372875, -0.532748);
    // // image_rgb_00876
    // cameras[i]->SetOrientation(-0.00870524, -0.0240282, -0.0542144, 0.998202);
    // cameras[i]->SetPosition(0.127279, 0.321349, -0.281022);
    // image_rgb_00862
    cameras[i]->SetOrientation(-0.0256108, 0.034136, -0.0424451, 0.998187);
    cameras[i]->SetPosition(0.198602, 0.315767, -0.219588);

    Image tempImage;
    cameras[i]->CaptureNormals(tempImage);
    tempImage.Save("normal_" + std::to_string(i) + ".png");

    cameras[i]->CaptureAlbedo(tempImage);
    tempImage.Save("albedo_" + std::to_string(i) + ".png");

    keyframes[i] = std::make_shared<Keyframe>(cameras[i], image);
  }
}

void CreateLightProblem()
{
  LOG(INFO) << "Creating light problem...";

  const size_t paramCount = 3 * light->GetVoxelCount();
  optix::Buffer buffer = light->GetRadianceBuffer();
  CUdeviceptr pointer = buffer->getDevicePointer(0);
  lightValues = reinterpret_cast<float*>(pointer);

  lightProblem = new lynx::Problem();
  lightProblem->AddParameterBlock(lightValues, paramCount);
  lightProblem->SetLowerBound(lightValues, 0.0f);

  lightCostFunction = new torch::VoxelCostFunction(light);

  for (std::shared_ptr<Keyframe> keyframe : keyframes)
  {
    lightCostFunction->AddKeyframe(keyframe);
  }

  lightProblem->AddResidualBlock(lightCostFunction, nullptr, lightValues);

  if (FLAGS_use_act)
  {
    VoxelActivationCostFunction* actCostFunction;
    actCostFunction = new VoxelActivationCostFunction(light);
    actCostFunction->SetBias(1.0);
    actCostFunction->SetInnerScale(FLAGS_inner_act);
    actCostFunction->SetOuterScale(FLAGS_outer_act);
    lightProblem->AddResidualBlock(actCostFunction, nullptr, lightValues);
  }
}

void CreateAlbedoProblem()
{
  LOG(INFO) << "Creating albedo problem...";

  const size_t paramCount = 3 * material->GetAlbedoCount();
  optix::Buffer buffer = material->GetAlbedoBuffer();
  CUdeviceptr pointer = buffer->getDevicePointer(0);
  albedoValues = reinterpret_cast<float*>(pointer);

  albedoProblem = new lynx::Problem();
  albedoProblem->AddParameterBlock(albedoValues, paramCount);
  albedoProblem->SetLowerBound(albedoValues, 0.0f);
  albedoProblem->SetUpperBound(albedoValues, 1.0f);

  albedoCostFunction = new torch::AlbedoCostFunction(material, mesh);

  for (std::shared_ptr<Keyframe> keyframe : keyframes)
  {
    albedoCostFunction->AddKeyframe(keyframe);
  }

  albedoProblem->AddResidualBlock(albedoCostFunction, nullptr, albedoValues);

  if (FLAGS_use_ref)
  {
    ReflectanceCostFunction* refCostFunction;
    refCostFunction = new ReflectanceCostFunction(material, mesh);
    refCostFunction->SetChromaticityThreshold(FLAGS_chrom_thresh);
    refCostFunction->SetWeight(FLAGS_ref_weight);
    albedoProblem->AddResidualBlock(refCostFunction, nullptr, albedoValues);
  }
}

void SolveLightProblem()
{
  LOG(INFO) << "Solving light problem...";

  lynx::Solver::Options options;
  options.maxIterations = 50000;
  options.minCostChangeRate = FLAGS_min_light_change;
  options.verbose = FLAGS_verbose;

  lynx::Solver solver(lightProblem);
  solver.Configure(options);

  lynx::Solver::Summary summary;
  solver.Solve(&summary);

  LOG(INFO) << std::endl << summary.BriefReport();

  const size_t count = lightProblem->GetParameterBlockSize(0);
  std::vector<Spectrum> radiance(count / 3);

  const size_t bytes = sizeof(float) * count;
  const cudaMemcpyKind type = cudaMemcpyDeviceToHost;
  LYNX_CHECK_CUDA(cudaMemcpy(radiance.data(), lightValues, bytes, type));
  light->SetRadiance(radiance);

  lightCostFunction->ClearJacobian();

  LOG(INFO) << "Rendering new light estimate...";

  Image image;

  for (size_t i = 0; i < cameras.size(); ++i)
  {
    cameras[i]->CaptureLighting(image);

    image.Save("light_estimate_" + std::to_string(i) + "_" +
        std::to_string(iteration) + ".png");
  }
}

void SolveAlbedoProblem()
{
  LOG(INFO) << "Solving albedo problem...";

  albedoCostFunction->ClearJacobian();

  lynx::Solver::Options options;
  options.maxIterations = 50000;
  options.minCostChangeRate = FLAGS_min_albedo_change;
  options.verbose = FLAGS_verbose;

  lynx::Solver solver(albedoProblem);
  solver.Configure(options);

  lynx::Solver::Summary summary;
  solver.Solve(&summary);

  LOG(INFO) << summary.BriefReport();

  const size_t count = albedoProblem->GetParameterBlockSize(0);
  std::vector<Spectrum> albedos(count / 3);

  const size_t bytes = sizeof(float) * count;
  const cudaMemcpyKind type = cudaMemcpyDeviceToHost;
  LYNX_CHECK_CUDA(cudaMemcpy(albedos.data(), albedoValues, bytes, type));
  material->SetAlbedos(albedos);

  LOG(INFO) << "Rendering new albedo estimate...";

  Image image;

  for (size_t i = 0; i < cameras.size(); ++i)
  {
    cameras[i]->CaptureAlbedo(image);

    image.Save("albedo_estimate_" + std::to_string(i) + "_" +
        std::to_string(iteration) + ".png");
  }
}

void SolveProblem(int argc, char** argv)
{
  BuildScene(argc, argv);
  // CreateAlbedoProblem();
  CreateLightProblem();

  for (iteration = 0; iteration < FLAGS_max_iters; ++iteration)
  {
    LOG(INFO) << "Starting iteration " << iteration << "...";
    // SolveAlbedoProblem();
    SolveLightProblem();
  }

  LOG(INFO) << "Saving lighting parameters...";
  WriteLightParameters();

  LOG(INFO) << "Rendering final results...";
  Image image;

  for (size_t i = 0; i < cameras.size(); ++i)
  {
    cameras[i]->Capture(image);
    image.Save(FLAGS_out_image_prefix + std::to_string(i) + ".png");
  }
}

int main(int argc, char** argv)
{
  google::InitGoogleLogging(argv[0]);
  gflags::ParseCommandLineFlags(&argc, &argv, true);

  const clock_t start = clock();
  SolveProblem(argc, argv);
  const clock_t stop = clock();
  const double time = double(stop - start) / CLOCKS_PER_SEC;

  LOG(INFO) << "Elapsed time: " << time;
  return 0;
}


text:
from .client_stats import ClientStatsEndpoint
from .environment_runs import EnvironmentRunsEndpoint
from .environments import EnvironmentsEndpoint
from .generators import GeneratorsEndpoint
from .generator_rows import GeneratorRowsEndpoint
from .integrations import IntegrationsEndpoint
from .run_tests import RunTestsEndpoint
from .runs import RunsEndpoint
from .schedules import SchedulesEndpoint
from .site_environments import SiteEnvironmentsEndpoint
from .sites import SitesEndpoint
from .tests import TestsEndpoint
from .users import UsersEndpoint


text:
package japicmp.cli;

import japicmp.config.Options;
import japicmp.exception.JApiCmpException;
import japicmp.util.Optional;
import japicmp.util.StringArrayEnumeration;

import static japicmp.model.AccessModifier.toModifier;
import static japicmp.util.FileHelper.createFileList;

public class CliParser {
	public static final String IGNORE_MISSING_CLASSES = "--ignore-missing-classes";
	public static final String IGNORE_MISSING_CLASSES_BY_REGEX = "--ignore-missing-classes-by-regex";
	public static final String OLD_CLASSPATH = "--old-classpath";
	public static final String NEW_CLASSPATH = "--new-classpath";

	public Options parse(String[] args) throws IllegalArgumentException {
		Options options = Options.newDefault();
		boolean includeExclusively = false;
		boolean excludeExclusively = false;
		StringArrayEnumeration sae = new StringArrayEnumeration(args);
		while (sae.hasMoreElements()) {
			String arg = sae.nextElement();
			if ("--include-exclusively".equals(arg)) {
				includeExclusively = true;
			} else if ("--exclude-exclusively".equals(arg)) {
				excludeExclusively = true;
			} else if ("-h".equals(arg) || "--help".equals(arg)) {
				options.setHelpRequested(true);
			}
		}
		if (options.isHelpRequested()) {
			return options;
		}
		sae = new StringArrayEnumeration(args);
		while (sae.hasMoreElements()) {
			String arg = sae.nextElement();
			if ("--include-exclusively".equals(arg) || "--exclude-exclusively".equals(arg)){
                // Do nothing
			} else if ("-n".equals(arg) || "--new".equals(arg)) {
				String newArchive = getOptionWithArgument("-n, --new", sae);
				options.getNewArchives().addAll(createFileList(checkNonNull(newArchive, "Required option -n is missing.")));
			} else if ("-o".equals(arg) || "--old".equals(arg)) {
				String oldArchive = getOptionWithArgument("-o, --old", sae);
				options.getOldArchives().addAll(createFileList(checkNonNull(oldArchive, "Required option -o is missing.")));
			} else if ("-m".equals(arg) || "--only-modified".equals(arg)) {
				options.setOutputOnlyModifications(true);
			} else if ("-b".equals(arg) || "--only-incompatible".equals(arg)) {
				options.setOutputOnlyBinaryIncompatibleModifications(true);
			} else if ("-a".equals(arg)) {
				String accessModifier = getOptionWithArgument("-a", sae);
				options.setAccessModifier(toModifier(accessModifier));
			} else if ("-i".equals(arg) || "--include".equals(arg)) {
				String includes = getOptionWithArgument("-i, --include", sae);
				options.addIncludeFromArgument(Optional.fromNullable(includes), includeExclusively);
			} else if ("-e".equals(arg) || "--exclude".equals(arg)) {
				String excludes = getOptionWithArgument("-e, --exclude", sae);
				options.addExcludeFromArgument(Optional.fromNullable(excludes), excludeExclusively);
			} else if ("-x".equals(arg) || "--xml-file".equals(arg)) {
				String pathToXmlOutputFile = getOptionWithArgument("-x, --xml-file", sae);
				options.setXmlOutputFile(Optional.fromNullable(pathToXmlOutputFile));
			} else if ("--html-file".equals(arg)) {
				String pathToHtmlOutputFile = getOptionWithArgument("--html-file", sae);
				options.setHtmlOutputFile(Optional.fromNullable(pathToHtmlOutputFile));
			} else if ("-s".equals(arg) || "--semantic-versioning".equals(arg)) {
				options.setSemanticVersioning(true);
			} else if ("--include-synthetic".equals(arg)) {
				options.setIncludeSynthetic(true);
			} else if (IGNORE_MISSING_CLASSES.equals(arg)) {
				options.setIgnoreMissingClasses(true);
			} else if (IGNORE_MISSING_CLASSES_BY_REGEX.equals(arg)) {
				while (sae.hasMoreElements()) {
					String nextElement = sae.inspectNextElement();
					if (!nextElement.startsWith("-")) {
						nextElement = sae.nextElement();
						options.addIgnoreMissingClassRegularExpression(nextElement);
					}
				}
			} else if ("--html-stylesheet".equals(arg)) {
				String htmlStylesheet = getOptionWithArgument("--html-stylesheet", sae);
				options.setHtmlStylesheet(Optional.fromNullable(htmlStylesheet));
			} else if (OLD_CLASSPATH.equals(arg)) {
				String oldClassPath = getOptionWithArgument(OLD_CLASSPATH, sae);
				options.setOldClassPath(Optional.fromNullable(oldClassPath));
			} else if (NEW_CLASSPATH.equals(arg)) {
				String newClassPath = getOptionWithArgument(NEW_CLASSPATH, sae);
				options.setNewClassPath(Optional.fromNullable(newClassPath));
			} else if ("--no-annotations".equals(arg)) {
				options.setNoAnnotations(true);
			} else if ("--report-only-filename".equals(arg)) {
				options.setReportOnlyFilename(true);
			} else if ("--error-on-binary-incompatibility".equals(arg)) {
				options.setErrorOnBinaryIncompatibility(true);
			} else if ("--error-on-source-incompatibility".equals(arg)) {
				options.setErrorOnSourceIncompatibility(true);
			} else if ("--no-error-on-exclusion-incompatibility".equals(arg)) {
				options.setErrorOnExclusionIncompatibility(false);
			} else if ("--error-on-modifications".equals(arg)) {
				options.setErrorOnModifications(true);
			} else if ("--error-on-semantic-incompatibility".equals(arg)) {
				options.setErrorOnSemanticIncompatibility(true);
			} else if ("--ignore-missing-old-version".equals(arg)) {
				options.setIgnoreMissingOldVersion(true);
			} else if ("--ignore-missing-new-version".equals(arg)) {
				options.setIgnoreMissingNewVersion(true);
			} else {
				throw new JApiCmpException(JApiCmpException.Reason.CliError, "Unknown argument: " + arg);
			}
		}
		options.verify();
		return options;
	}

	public static void printHelp() {
		System.out.println("SYNOPSIS\n" +
			"        java -jar japicmp.jar [-a <accessModifier>] [(-b | --only-incompatible)]\n" +
			"                [(-e <excludes> | --exclude <excludes>)] [--exclude-exclusively]\n" +
			"                [(-h | --help)] [--html-file <pathToHtmlOutputFile>]\n" +
			"                [--html-stylesheet <pathToHtmlStylesheet>]\n" +
			"                [(-i <includes> | --include <includes>)] [--ignore-missing-classes]\n" +
			"                [--ignore-missing-classes-by-regex <ignoreMissingClassesByRegEx>...]\n" +
			"                [--include-exclusively] [--include-synthetic] [(-m | --only-modified)]\n" +
			"                [(-n <pathToNewVersionJar> | --new <pathToNewVersionJar>)]\n" +
			"                [--new-classpath <newClassPath>] [--no-annotations]\n" +
			"                [(-o <pathToOldVersionJar> | --old <pathToOldVersionJar>)]\n" +
			"                [--old-classpath <oldClassPath>] [--report-only-filename]\n" +
			"                [(-s | --semantic-versioning)]\n" +
			"                [(-x <pathToXmlOutputFile> | --xml-file <pathToXmlOutputFile>)]\n" +
			"                [--error-on-binary-incompatibility]\n" +
			"                [--error-on-source-incompatibility]\n" +
			"                [--error-on-modifications]\n" +
			"                [--no-error-on-exclusion-incompatibility]\n" +
			"                [--error-on-semantic-incompatibility]\n" +
			"                [--ignore-missing-old-version] [--ignore-missing-new-version]\n" +
			"\n" +
			"OPTIONS\n" +
			"        -a <accessModifier>\n" +
			"            Sets the access modifier level (public, package, protected,\n" +
			"            private), which should be used.\n" +
			"\n" +
			"        -b, --only-incompatible\n" +
			"            Outputs only classes/methods that are binary incompatible. If not\n" +
			"            given, all classes and methods are printed.\n" +
			"\n" +
			"        -e <excludes>, --exclude <excludes>\n" +
			"            Semicolon separated list of elements to exclude in the form\n" +
			"            package.Class#classMember, * can be used as wildcard. Annotations\n" +
			"            are given as FQN starting with @. Examples:\n" +
			"            mypackage;my.Class;other.Class#method(int,long);foo.Class#field;@my.Annotation.\n" +
			"\n" +
			"        --exclude-exclusively\n" +
			"            Exclude only packages specified in the \"exclude\" option, include\n" +
			"            their sub-packages\n" +
			"\n" +
			"        -h, --help\n" +
			"            Display help information\n" +
			"\n" +
			"        --html-file <pathToHtmlOutputFile>\n" +
			"            Provides the path to the html output file.\n" +
			"\n" +
			"        --html-stylesheet <pathToHtmlStylesheet>\n" +
			"            Provides the path to your own stylesheet.\n" +
			"\n" +
			"        -i <includes>, --include <includes>\n" +
			"            Semicolon separated list of elements to include in the form\n" +
			"            package.Class#classMember, * can be used as wildcard. Annotations\n" +
			"            are given as FQN starting with @. Examples:\n" +
			"            mypackage;my.Class;other.Class#method(int,long);foo.Class#field;@my.Annotation.\n" +
			"\n" +
			"        --ignore-missing-classes\n" +
			"            Ignores all superclasses/interfaces missing on the classpath.\n" +
			"\n" +
			"        --ignore-missing-classes-by-regex <ignoreMissingClassesByRegEx>\n" +
			"            Ignores only those superclasses/interface missing on the classpath\n" +
			"            that are selected by a regular expression.\n" +
			"\n" +
			"        --include-exclusively\n" +
			"            Include only packages specified in the \"include\" option, exclude\n" +
			"            their sub-packages\n" +
			"\n" +
			"        --include-synthetic\n" +
			"            Include synthetic classes and class members that are hidden per\n" +
			"            default.\n" +
			"\n" +
			"        -m, --only-modified\n" +
			"            Outputs only modified classes/methods.\n" +
			"\n" +
			"        -n <pathToNewVersionJar>, --new <pathToNewVersionJar>\n" +
			"            Provides the path to the new version(s) of the jar(s). Use ; to\n" +
			"            separate jar files.\n" +
			"\n" +
			"        --new-classpath <newClassPath>\n" +
			"            The classpath for the new version.\n" +
			"\n" +
			"        --no-annotations\n" +
			"            Do not evaluate annotations.\n" +
			"\n" +
			"        -o <pathToOldVersionJar>, --old <pathToOldVersionJar>\n" +
			"            Provides the path to the old version(s) of the jar(s). Use ; to\n" +
			"            separate jar files.\n" +
			"\n" +
			"        --old-classpath <oldClassPath>\n" +
			"            The classpath for the old version.\n" +
			"\n" +
			"        --report-only-filename\n" +
			"            Reports just filenames (not full paths) in report description.\n" +
			"\n" +
			"        -s, --semantic-versioning\n" +
			"            Tells you which part of the version to increment.\n" +
			"\n" +
			"        -x <pathToXmlOutputFile>, --xml-file <pathToXmlOutputFile>\n" +
			"            Provides the path to the xml output file.\n" +
			"\n" +
			"        --error-on-binary-incompatibility\n" +
			"            Exit with an error if a binary incompatibility is detected.\n" +
			"\n" +
			"        --error-on-source-incompatibility\n" +
			"            Exit with an error if a source incompatibility is detected.\n" +
			"\n" +
			"        --error-on-modifications\n" +
			"            Exit with an error if any change between versions is detected.\n" +
			"\n" +
			"        --no-error-on-exclusion-incompatibility\n" +
			"            Ignore incompatible changes caused by an excluded class\n" +
			"            (e.g. excluded interface removed from not excluded class) when\n" +
			"            deciding whether to exit with an error.\n" +
			"\n" +
			"        --error-on-semantic-incompatibility\n" +
			"            Exit with an error if the binary compatibility changes are\n" +
			"            inconsistent with Semantic Versioning. This expects versions of\n" +
			"            the form Major.Minor.Patch (e.g. 1.2.3 or 1.2.3-SNAPSHOT).\n" +
			"            See http://semver.org/spec/v2.0.0.html for more information about\n" +
			"            Semantic Versioning.\n" +
			"\n" +
			"        --ignore-missing-old-version\n" +
			"            When --error-on-semantic-incompatibility is passed, ignore\n" +
			"            non-resolvable artifacts for the old version.\n" +
			"\n" +
			"        --ignore-missing-new-version\n" +
			"            When --error-on-semantic-incompatibility is passed, ignore\n" +
			"            non-resolvable artifacts for the new version.\n");
	}

	private String getOptionWithArgument(String option, StringArrayEnumeration sae) {
		if (sae.hasMoreElements()) {
			String value = sae.nextElement();
			if (value.startsWith("-")) {
				throw new JApiCmpException(JApiCmpException.Reason.CliError, String.format("Missing argument for option '%s'.", option));
			}
			return value;
		} else {
			throw new JApiCmpException(JApiCmpException.Reason.CliError, String.format("Missing argument for option '%s'.", option));
		}
	}

	private <T> T checkNonNull(T in, String errorMessage) {
		if (in == null) {
			throw new JApiCmpException(JApiCmpException.Reason.CliError, errorMessage);
		} else {
			return in;
		}
	}
}


text:
package net.sf.extjwnl.data;

import net.sf.extjwnl.JWNL;
import net.sf.extjwnl.JWNLException;
import net.sf.extjwnl.dictionary.Dictionary;

/**
 * A Synset for adjectives.
 *
 * @author Aliaksandr Autayeu
 */
public class AdjectiveSynset extends Synset {

    private static final long serialVersionUID = 4L;

    /**
     * for use only with WordNet 1.6 and earlier
     */
    private boolean isAdjectiveCluster = false;

    public AdjectiveSynset(Dictionary dictionary, POS pos) throws JWNLException {
        super(dictionary, pos);
        if (POS.ADJECTIVE != pos) {
            throw new IllegalArgumentException(JWNL.resolveMessage("DICTIONARY_EXCEPTION_057"));
        }
    }

    public AdjectiveSynset(Dictionary dictionary, POS pos, long offset) throws JWNLException {
        super(dictionary, pos, offset);
        if (POS.ADJECTIVE != pos) {
            throw new IllegalArgumentException(JWNL.resolveMessage("DICTIONARY_EXCEPTION_057"));
        }
    }

    public boolean isAdjectiveCluster() {
        return isAdjectiveCluster;
    }

    public void setIsAdjectiveCluster(boolean isAdjectiveCluster) {
        this.isAdjectiveCluster = isAdjectiveCluster;
    }
}


text:
The storage component for the Sensing Architecture developed in the ProaSense project (http://www.proasense.eu). The storage layer builds upon the ideas of SensApp and extends it with additional capabilities from the ProaSense project addressing specific requirements for the sensing enterprise.

## Requirements
* MongoDB 3.0 or higher

## Setup

###Modules
The storage component consists of four modules:

* **storage-base**, which contains common, shared base classes for the Storage Writer, Storage Reader and Storage Registry services.
* **storage-writer**, which contains the classes for the Storage Writer service.
* **storage-reader**, which contains the classes for the Storage Reader service.
* **storage-registry**, which contains the classes for the Storage Registry service.

### Configuration files
Each module has its own set of configuration files under the `resources` folder:

* The **`server.properties`** file contains the configuration properties for the Storage Writer and Storage Reader services.
* The **`client.properties`** file contains the configuration for the test and benchmark code.

### Compile
```
mvn clean install
mvn package
```

## Storage Writer service

### Compile

### Run the Storage Writer service
```
cd storage-writer
mvn exec:java -Dexec.mainClass=net.modelbased.proasense.storage.writer.StorageWriterMongoService
```

### Test and benchmark

#### Run the local storage writer benchmark
```
mvn exec:java -Dexec.classpathScope=test -Dexec.mainClass=net.modelbased.proasense.storage.writer.StorageWriterMongoServiceLocalBenchmark
```

### Run the Kafka storage writer benchmark
```
mvn exec:java -Dexec.classpathScope=test -Dexec.mainClass=net.modelbased.proasense.storage.writer.StorageWriterMongoServiceKafkaBenchmark
```

## Storage Reader service

### Deploy the Storage Reader service
```
cd storage-reader
mvn jetty:run
```

## Storage Registry service

### Deploy the Storage Registry service
```
cd storage-reader
mvn jetty:run
```

## Test and benchmark

### Property files

#### client.properties
The `client.properties` file contains the configuration for the test and benchmark code.

### Run the local storage writer benchmark
```
mvn exec:java -Dexec.classpathScope=test -Dexec.mainClass=net.modelbased.proasense.storage.writer.StorageWriterServiceMongoLocalBenchmark
```

### Run the local storage reader benchmark
```
cd storage-reader
mvn exec:java -Dexec.classpathScope=test -Dexec.mainClass=net.modelbased.proasense.storage.reader.StorageReaderMongoServiceLocalBenchmark
```

### Run the Kafka storage writer benchmark
```
mvn exec:java -Dexec.classpathScope=test -Dexec.mainClass=net.modelbased.proasense.storage.writer.StorageWriterServiceMongoKafkaBenchmark
```

### Run the local storage reader test
```
mvn clean install
```

## Documentation
* [Installation Guide](https://github.com/SINTEF-9012/proasense-storage/wiki/Installation-Guide)
* [User Guide](https://github.com/SINTEF-9012/proasense-storage/wiki/User-Guide)


text:
<?php

session_start();

require("config.php");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title><?php echo $config_sitename; ?></title>

<link href="stylesheet.css" rel="stylesheet">

<?php echo $config_sitename; ?>

<a href="<?php echo $config_basedir; ?>index.php">Home
•
<a href="<?php echo $config_basedir; ?>about.php">About
•
<a href="<?php echo $config_basedir; ?>faq.php">FAQ
•
<a href="<?php echo $config_basedir; ?>pel.php">PEL

<?php

# If the user is logged in
if(isset($_SESSION['USERNAME']) == TRUE) {
# show a link to logout.php
echo "[Logout]";
}
# If they're not logged in show a link to login.php
else{
echo "[Login]";
}

# Show the menu bar
require("bar.php");
?>


text:
<?php

namespace App\Http\Controllers;

use App\Client;
use App\ClientsToTickets;
use App\Models\Events\EventModel;
use App\Ticket;
use App\TraningToTrainer;
use App\VisitedClients;
use Illuminate\Http\Request;

use App\Http\Requests;

class EventsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function addEvents(Request $request)
    {

        $events = new EventModel(Client::find($request->id_client));
        $response = $events->saveToEvent($request->id_event);
        $response['calendar'] = $events->getAllTrainingOfClient();
        return json_encode($response);
    }

    public function deleteEvents(Request $request)
    {

        $events = new EventModel(Client::find($request->id_client));
        $response = $events->delEvent($request->id_event);
        $response['calendar'] = $events->getAllTrainingOfClient();
        return json_encode($response);
    }

}


text:
<?php

namespace Tiloweb\MaTPEBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class MaTPEExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $configuration = new Configuration();

        $config = $this->processConfiguration($configuration, $configs);

        foreach ($config as $name => $node) {
            $container->setParameter('ma_tpe.'.$name, $node);
        }

        return $config;
    }
}


text:
package org.archive.archivespark.specific.warc.implicits

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, PrintWriter}

import org.apache.hadoop.fs.Path
import org.apache.spark.rdd.RDD
import org.archive.archivespark.model.dataloads.ByteLoad
import org.archive.archivespark.sparkling.io.{GzipBytes, HdfsIO, IOUtil}
import org.archive.archivespark.sparkling.util.{Common, RddUtil, StringUtil}
import org.archive.archivespark.sparkling.warc.{
  WarcHeaders,
  WarcRecord,
  WarcRecordMeta
}
import org.archive.archivespark.specific.warc.functions.{
  HttpPayload,
  WarcPayloadFields
}
import org.archive.archivespark.specific.warc.{WarcFileMeta, WarcLikeRecord}

import scala.reflect.ClassTag

object WarcRDD {
  val WarcIpField = "WARC-IP-Address"
  val WarcRecordIdField = "WARC-Record-ID"
}

class WarcRDD[WARC <: WarcLikeRecord: ClassTag](rdd: RDD[WARC]) {
  import WarcRDD._
  import org.archive.archivespark.sparkling.Sparkling._

  def saveAsWarc(path: String,
                 meta: org.archive.archivespark.sparkling.warc.WarcFileMeta =
                   WarcFileMeta(),
                 generateCdx: Boolean = true): Long = {
    HdfsIO.ensureOutDir(path)

    val gz = path.toLowerCase.trim.endsWith(GzipExt)
    val filePrefix =
      StringUtil.stripSuffixes(new Path(path).getName, GzipExt, WarcExt, ArcExt)

    val emptyLines = {
      val bytes = new ByteArrayOutputStream()
      val print = new PrintWriter(bytes)
      print.println()
      print.println()
      print.flush()
      bytes.toByteArray
    }

    rdd.mapPartitionsWithIndex {
      case (idx, records) =>
        val warcPrefix = filePrefix + "-" + StringUtil.padNum(idx, 5)
        val warcFile = warcPrefix + WarcExt + (if (gz) GzipExt else "")
        val warcPath = new Path(path, warcFile).toString
        val warcCdxPath = new Path(
          path,
          warcPrefix + WarcExt + CdxExt + (if (gz) GzipExt else "")
        ).toString

        var warcPosition = 0L
        val warcOut = Common.lazyValWithCleanup({
          val out = HdfsIO.out(warcPath, compress = false)
          val headerBytes = WarcHeaders.warcFile(meta, warcFile)
          val compressedHeader = if (gz) GzipBytes(headerBytes) else headerBytes
          out.write(compressedHeader)
          warcPosition += compressedHeader.length
          out
        })(_.close)

        val cdxOut = Common.lazyValWithCleanup(
          IOUtil.print(HdfsIO.out(warcCdxPath))
        )(_.close)

        val processed = records.map { record =>
          val payloadPointer = record.dataLoad(ByteLoad).get
          val enriched = payloadPointer.init(record, excludeFromOutput = false)

          val warcHeadersOpt = payloadPointer
            .sibling[Seq[(String, String)]](WarcPayloadFields.RecordHeader)
            .get(enriched)
          val recordMeta = WarcRecordMeta(
            enriched.get.originalUrl,
            enriched.get.time.toInstant,
            warcHeadersOpt.flatMap(_.find(_._1 == WarcRecordIdField).map(_._2)),
            warcHeadersOpt.flatMap(_.find(_._1 == WarcIpField).map(_._2))
          )

          val httpStatusOpt = payloadPointer
            .sibling[String](HttpPayload.StatusLineField)
            .get(enriched)
          val httpHeadersOpt = payloadPointer
            .sibling[Seq[(String, String)]](HttpPayload.HeaderField)
            .get(enriched)
          val httpHeader =
            if (httpStatusOpt.isDefined && httpHeadersOpt.isDefined)
              WarcHeaders.http(httpStatusOpt.get, httpHeadersOpt.get)
            else Array.empty[Byte]

          payloadPointer.get(enriched) match {
            case Some(payload) =>
              val content = httpHeader ++ payload
              val recordHeader =
                WarcHeaders.warcResponseRecord(recordMeta, content, payload)

              val recordBytes =
                if (gz) GzipBytes(recordHeader ++ content ++ emptyLines)
                else recordHeader ++ content ++ emptyLines

              if (generateCdx) {
                val warc = WarcRecord.get(new ByteArrayInputStream(recordBytes))
                if (warc.isDefined) {
                  val cdx = warc.get.toCdx(recordBytes.length)
                  if (cdx.isDefined) {
                    warcOut.get.write(recordBytes)
                    val locationInfo = Array(warcPosition.toString, warcFile)
                    cdxOut.get.println(cdx.get.toCdxString(locationInfo))
                    warcPosition += recordBytes.length
                    1L
                  } else 0L
                } else 0L
              } else {
                warcOut.get.write(recordBytes)
                warcPosition += recordBytes.length
                1L
              }
            case None => 0L
          }
        }.sum

        warcOut.clear(true)
        cdxOut.clear(true)

        Iterator(processed)
    }
  }.reduce(_ + _)

  def toCdxStrings: RDD[String] = toCdxStrings()
  def toCdxStrings(includeAdditionalFields: Boolean = true): RDD[String] =
    rdd.map(_.toCdxString(includeAdditionalFields))

  def saveAsCdx(path: String): Unit = RddUtil.saveAsTextFile(toCdxStrings, path)
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>in.ashwanthkumar</groupId>
        <artifactId>notify</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <name>notify-pagerduty</name>
    <artifactId>notify-pagerduty</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <description>Notify events in your application as Triggers in Pager Duty</description>

    <dependencies>
        <dependency>
            <groupId>in.ashwanthkumar</groupId>
            <artifactId>notify-core</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>com.squareup.pagerduty</groupId>
            <artifactId>pagerduty-incidents</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>
</project>


text:
function getToken(username) {
  const { amqp } = this;

  return amqp
    .publishAndWait('users.login', {
      username,
      audience: '*.localhost',
      password: 'megalongsuperpasswordfortest',
    });
}

function makeHeader(token) {
  return { authorization: `JWT ${token}` };
}

module.exports = {
  getToken,
  makeHeader,
};


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Activites_model extends CI_Model {

	public function __construct()	{
		parent::__construct();
		$this->db->db_select('db_activ');

	}

	public function getLastActivites() {
		$date6m = date('Y-m-d', strtotime("last year"));

		$this->db->where('DateDebut >', $date6m);
		$this->db->order_by('DateDebut', 'desc');
		$query = $this->db->get('activites', 30);

		return $query->result();
	}

	public function addActivite(){

		$data = array(
            'Nom'        	=> $this->input->post('nom'),
            'Description'   => $this->input->post('description'),
            'Type'      	=> $this->input->post('typeActivite'),
            'DateDebut'     => $this->input->post('dateDebut'),
            'DateFin'    	=> $this->input->post('dateFin'),
        );

		$this->db->insert('activites',$data);
	}

	public function getSingleActivite($id){
		$this->db->where('Id', $id);
		$query = $this->db->get('activites');

		return $query->row();
	}

	public function updateActivite($id){
		$data = array(
            'Nom'        	=> $this->input->post('nom'),
            'Description'   => $this->input->post('description'),
            'Type'      	=> $this->input->post('typeActivite'),
            'DateDebut'     => $this->input->post('dateDebut'),
            'DateFin'    	=> $this->input->post('dateFin'),
        );

        $this->db->where('Id', $id);
        $this->db->update('activites', $data);

	}

	public function deleteActivite($id){
		$this->db->where('Id', $id);
        $this->db->delete('activites');
	}
}

/* End of file Activites_model.php */
/* Location: ./application/models/Activites_model.php */
?>


text:
import numpy

from .core import Configurable
from .boundaries import (
    BaseBoundary, YFunctionBoundary, XConstBoundary, to_boundary)

class BaseInequality(Configurable):

    def __init__(self, baseconfig, data, less=False, domain=None):
        super(BaseInequality, self).__init__(baseconfig)
        bclass = self._boundaryclass
        if isinstance(data, bclass):
            assert domain is None
            self.boundary = data
            """
            An instance of :class:`.BaseBoundary` instance.
            """
        else:
            self.boundary = bclass(self.config, data, domain=domain)
        self.less = less

    def get_errorbar_kwds(self):
        kwds = {}
        for line in self.boundary.cax.lines:
            kwds['boundary_color'] = line.get_color()
            break
        return kwds

    def plot_positive_direction(self):
        """
        Plot direction that makes LHS of the inequality positive.
        """

class YFunctionInequality(BaseInequality):

    _boundaryclass = YFunctionBoundary

    def plot_positive_direction(self):
        self.cax.yerrorbar(self.boundary._masked_y, self.less,
                           xlim=self.boundary._domain,
                           **self.get_errorbar_kwds())

class XConstInequality(BaseInequality):

    _boundaryclass = XConstBoundary

    def plot_positive_direction(self):
        func = lambda ys: self.x * numpy.ones_like(ys)
        self.cax.xerrorbar(func, self.less, **self.get_errorbar_kwds())

_IEQ_CLASSES = [YFunctionInequality, XConstInequality]
_IEQ_CLASS_MAP = dict((cls._boundaryclass, cls) for cls in _IEQ_CLASSES)

def to_inequality(config, obj):
    if isinstance(obj, BaseInequality):
        # FIXME: should I care other cases?
        obj.config._set_base(config)
        return obj
    obj = tuple(obj)
    if isinstance(obj[0], BaseBoundary):
        data = to_boundary(config, obj[0])
        return _IEQ_CLASS_MAP[data.__class__](config, data, *obj[1:])
    elif callable(obj[0]):
        return YFunctionInequality(config, *obj)
    else:
        return XConstInequality(config, *obj)


text:
<?php

namespace Application\Migrations;

use CampaignChain\CoreBundle\Entity\Activity;
use CampaignChain\CoreBundle\Entity\Operation;
use CampaignChain\CoreBundle\EntityService\OperationService;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20160916085817 extends AbstractMigration implements ContainerAwareInterface
{
    private $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE campaignchain_activity ADD mustValidate TINYINT(1) NOT NULL');
    }

    public function postUp(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        /** @var ManagerRegistry $managerRegistry */
        $managerRegistry = $this->container->get('doctrine');
        $em = $managerRegistry->getManager();

        $activities = $em->getRepository('CampaignChainCoreBundle:Activity')->findAll();

        if(count($activities)) {
            try {
                $em->getConnection()->beginTransaction();

                /** @var Activity $activity */
                foreach ($activities as $activity) {
                    $operations = $em->getRepository('CampaignChainCoreBundle:Operation')
                        ->findByActivity($activity);

                    if (count($operations)) {
                        /** @var OperationService $operationService */
                        $operationService = $this->container->get('campaignchain.core.operation');

                        /** @var Operation $operation */
                        foreach ($operations as $operation) {
                            try {
                                $content = $operationService->getContent($operation);

                                $handlerService = $this->container->get(
                                    $activity->getModule()->getServices()['handler']
                                );

                                $activity->setMustValidate(
                                    $handlerService->mustValidate($content)
                                );

                                $em->persist($activity);
                                $em->flush();
                            } catch (\Exception $e) {
                                // Do nothing.
                            }
                        }
                    }
                }

                $em->getConnection()->commit();

                return $activity;
            } catch (\Exception $e) {
                $em->getConnection()->rollback();
                throw $e;
            }
        }
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE campaignchain_activity DROP mustValidate');
    }
}


text:
<!DOCTYPE html>
<body>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/feature-policy/resources/featurepolicy.js"></script>
<script>
  "use strict";

  const same_origin_src =
    "/feature-policy/resources/feature-policy-geolocation.html";
  const cross_origin_src =
    "https://{{domains[www]}}:{{ports[https][0]}}" + same_origin_src;

  async_test(t => {
    test_feature_availability(
      "geolocation",
      t,
      same_origin_src,
      expect_feature_available_default,
      "geolocation"
    );
  }, 'Feature policy "geolocation" can be enabled in same-origin iframe using allow="geolocation" attribute');

  async_test(t => {
    test_feature_availability(
      "geolocation",
      t,
      cross_origin_src,
      expect_feature_available_default,
      "geolocation"
    );
  }, 'Feature policy "geolocation" can be enabled in cross-origin iframe using allow="geolocation" attribute');
</script>
</body>


text:
//******************************************************************************************************
//  WelcomePage.xaml.cs - Gbtc
//
//  Copyright © 2010, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
//  not use this file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://www.opensource.org/licenses/eclipse-1.0.php
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  09/07/2010 - Stephen C. Wills
//       Generated original version of source code.
//  09/19/2010 - J. Ritchie Carroll
//       Added code to cache 64-bit installation state when passed as a command line argument
//
//******************************************************************************************************

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace ConfigurationSetupUtility.Screens
{
    /// <summary>
    /// Interaction logic for WelcomePage.xaml
    /// </summary>
    public partial class WelcomeScreen : UserControl, IScreen
    {
        #region [ Members ]

        // Fields

        private readonly IScreen m_nextPage;
        private Dictionary<string, object> m_state;

        #endregion

        #region [ Constructors ]

        /// <summary>
        /// Creates a new instance of the <see cref="WelcomeScreen"/> class.
        /// </summary>
        public WelcomeScreen()
        {
            InitializeComponent();
            m_nextPage = new ExistingConfigurationScreen();
        }

        #endregion

        #region [ Properties ]

        /// <summary>
        /// Gets the screen to be displayed when the user clicks the "Next" button.
        /// </summary>
        public IScreen NextScreen => m_nextPage;

        /// <summary>
        /// Gets a boolean indicating whether the user can advance to
        /// the next screen from the current screen.
        /// </summary>
        public bool CanGoForward => true;

        /// <summary>
        /// Gets a boolean indicating whether the user can return to
        /// the previous screen from the current screen.
        /// </summary>
        public bool CanGoBack => false;

        /// <summary>
        /// Gets a boolean indicating whether the user can cancel the
        /// setup process from the current screen.
        /// </summary>
        public bool CanCancel => true;

        /// <summary>
        /// Gets a boolean indicating whether the user input is valid on the current page.
        /// </summary>
        public bool UserInputIsValid => true;

        /// <summary>
        /// Collection shared among screens that represents the state of the setup.
        /// </summary>
        public Dictionary<string, object> State
        {
            get
            {
                return m_state;
            }
            set
            {
                m_state = value;
                InitializeWelcomeMessage();
            }
        }

        /// <summary>
        /// Allows the screen to update the navigation buttons after a change is made
        /// that would affect the user's ability to navigate to other screens.
        /// </summary>
        public Action UpdateNavigation { get; set; }

        #endregion

        #region [ Methods ]

        // Initializes the welcome message based on the existence of the -install flag.
        private void InitializeWelcomeMessage()
        {
            string[] args = Environment.GetCommandLineArgs();
            bool installFlag = args.Contains("-install", StringComparer.CurrentCultureIgnoreCase);

            if (m_state != null)
                m_state["64bit"] = args.Contains("-64bit", StringComparer.CurrentCultureIgnoreCase);

            if (installFlag)
                m_welcomeMessageTextBlock.Text = "You now need to set up the openPDC configuration.\r\n";
            else
                m_welcomeMessageTextBlock.Text = "";

            m_welcomeMessageTextBlock.Text += "\r\nThis wizard will walk you through the needed steps so you can easily set up your system configuration.";

            // The historian setup screen takes time to load because of DLL scanning, so we cache it at startup
            if (m_state != null)
                m_state["historianSetupScreen"] = new HistorianSetupScreen();

            m_installConnectionTester.IsEnabled = File.Exists("Installers\\PMUConnectionTesterSetup.msi");
            m_installStreamSplitter.IsEnabled = File.Exists("Installers\\StreamSplitterSetup.msi");
        }

        private void m_installConnectionTester_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            using (Process installProcess = new Process())
            {
                installProcess.StartInfo.FileName = "msiexec.exe";
                installProcess.StartInfo.Arguments = "-i Installers\\PMUConnectionTesterSetup.msi";
                installProcess.Start();
                installProcess.WaitForExit();
            }
        }

        private void m_installStreamSplitter_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            using (Process installProcess = new Process())
            {
                installProcess.StartInfo.FileName = "msiexec.exe";
                installProcess.StartInfo.Arguments = "-i Installers\\StreamSplitterSetup.msi";
                installProcess.Start();
                installProcess.WaitForExit();
            }
        }

        #endregion
    }
}


text:
#import "BonjourWebAppDelegate.h"
#import "BonjourBrowser.h"

#define kWebServiceType @"_http._tcp"
#define kInitialDomain  @"local"

@implementation BonjourWebAppDelegate

@synthesize window;
@synthesize browser;
@synthesize navigationController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  {
	// Create the Bonjour Browser for Web services
	BonjourBrowser *aBrowser = [[BonjourBrowser alloc] initForType:kWebServiceType
														  inDomain:kInitialDomain
												  customDomains:nil // we won't save any additional domains added by the user
									   showDisclosureIndicators:NO
											   showCancelButton:NO];
	self.browser = aBrowser;
	[aBrowser release];

	self.browser.delegate = self;

    // We want to let the user know that the services list is dynamic and always updating, even when there are no
    // services currently found.
    self.browser.searchingForServicesString = NSLocalizedString(@"Searching for web services", @"Searching for web services string");

	self.window.rootViewController = self.browser;
    [self.window makeKeyAndVisible];
    return YES;

}

- (void)dealloc {
	[browser release];
	[window release];
	[super dealloc];
}

- (NSString *)copyStringFromTXTDict:(NSDictionary *)dict which:(NSString*)which {
	// Helper for getting information from the TXT data
	NSData* data = [dict objectForKey:which];
	NSString *resultString = nil;
	if (data) {
		resultString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	}
	return resultString;
}

- (void) bonjourBrowser:(BonjourBrowser*)browser didResolveInstance:(NSNetService*)service {
	// Construct the URL including the port number
	// Also use the path, username and password fields that can be in the TXT record
	NSDictionary* dict = [[NSNetService dictionaryFromTXTRecordData:[service TXTRecordData]] retain];
	NSString *host = [service hostName];

	NSString* user = [self copyStringFromTXTDict:dict which:@"u"];
	NSString* pass = [self copyStringFromTXTDict:dict which:@"p"];

	NSString* portStr = @"";

	// Note that [NSNetService port:] returns an NSInteger in host byte order
	NSInteger port = [service port];
	if (port != 0 && port != 80)
			portStr = [[NSString alloc] initWithFormat:@":%d",port];

	NSString* path = [self copyStringFromTXTDict:dict which:@"path"];
	if (!path || [path length]==0) {
			[path release];
			path = [[NSString alloc] initWithString:@"/"];
	} else if (![[path substringToIndex:1] isEqual:@"/"]) {
			NSString *tempPath = [[NSString alloc] initWithFormat:@"/%@",path];
			[path release];
			path = tempPath;
	}

	NSString* string = [[NSString alloc] initWithFormat:@"http://%@%@%@%@%@%@%@",
												user?user:@"",
												pass?@":":@"",
												pass?pass:@"",
												(user||pass)?@"@":@"",
												host,
												portStr,
												path];

	NSURL *url = [[NSURL alloc] initWithString:string];
	[[UIApplication sharedApplication] openURL:url];

	[url release];
	[string release];
	[portStr release];
	[pass release];
	[user release];
	[dict release];
	[path release];
}

@end


text:
"""
Base classes for tests
http://www.sontek.net/blog/2011/12/01/writing_tests_for_pyramid_and_sqlalchemy.html
"""
import imp
import unittest

from pyramid import testing
from sqlalchemy import Column, Integer, engine_from_config
from sqlalchemy.orm import sessionmaker

from pyramid_sacrud.security import (PYRAMID_SACRUD_DELETE,
                                     PYRAMID_SACRUD_UPDATE)
from sqlalchemy_mptt import mptt_sessionmaker
from sqlalchemy_mptt.mixins import BaseNestedSets
from webtest import TestApp

imp.load_source('ps_tree_example', 'example/ps_tree_example.py')
from ps_tree_example import Base, DBSession, Fixtures, PageTree, main  # noqa

settings = {
    'sqlalchemy.url': 'sqlite:///test.sqlite',
    'ps_tree.models': (PageTree, )
}

PREFIX = 'admin'

class Foo(Base, BaseNestedSets):

    __tablename__ = 'foo'

    id = Column(Integer, primary_key=True)

class BaseTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.engine = engine_from_config(settings, prefix='sqlalchemy.')
        cls.DBSession = mptt_sessionmaker(sessionmaker())

    def setUp(self):
        # bind an individual Session to the connection
        self.dbsession = self.DBSession(bind=self.engine)
        self.create_db()

    def tearDown(self):
        # rollback - everything that happened with the
        # Session above (including calls to commit())
        # is rolled back.
        testing.tearDown()
        self.drop_db()
        self.dbsession.close()

    def drop_db(self):
        Base.metadata.drop_all(bind=self.engine)
        self.dbsession.commit()

    def create_db(self):
        Base.metadata.create_all(bind=self.engine)
        self.dbsession.commit()

    def initialize_db(self):
        fixture = Fixtures(self.dbsession)
        fixture.add(PageTree, 'fixtures/pages.json')
        fixture.add(PageTree, 'fixtures/country.json')
        self.dbsession.commit()

    def node(self, id):
        return self.dbsession.query(PageTree).filter_by(id=id).one()

class UnitTestBase(BaseTestCase):

    def _init_request(self, tablename):
        self.request.matchdict['tablename'] = tablename
        self.request.registry.settings['ps_tree.models'] = (Foo, PageTree)
        self.request.dbsession = self.dbsession

    def _init_config(self):
        self.config.add_route(PYRAMID_SACRUD_DELETE,
                              PREFIX + '{table}/delete/*pk')
        self.config.add_route(PYRAMID_SACRUD_UPDATE,
                              PREFIX + '{table}/update/*pk')

    def setUp(self):
        self.request = testing.DummyRequest()
        self.config = testing.setUp(request=self.request)
        super(UnitTestBase, self).setUp()

class IntegrationTestBase(BaseTestCase):

    def setUp(self):
        self.app = TestApp(main({}, **settings))
        self.config = testing.setUp()
        super(IntegrationTestBase, self).setUp()


text:
<?php namespace Innodite\Generator\Generators\API;

use Config;
use Innodite\Generator\CommandData;
use Innodite\Generator\Generators\GeneratorProvider;

class APIControllerGenerator implements GeneratorProvider
{
	/** @var  CommandData */
	private $commandData;

	private $path;

	private $namespace;

	function __construct($commandData)
	{
		$this->commandData = $commandData;
		$this->path = Config::get('generator.path_api_controller', app_path('Http/Controllers/API/'));
		$this->namespace = Config::get('generator.namespace_api_controller', 'App\Http\Controllers\API');
	}

	public function generate()
	{
		$templateData = $this->commandData->templatesHelper->getTemplate("Controller", "API");

		$templateData = $this->fillTemplate($templateData);

		$fileName = $this->commandData->modelName . "APIController.php";

		if(!file_exists($this->path))
			mkdir($this->path, 0755, true);

		$path = $this->path . $fileName;

		$this->commandData->fileHelper->writeFile($path, $templateData);
		$this->commandData->commandObj->comment("\nController created: ");
		$this->commandData->commandObj->info($fileName);
	}

	private function fillTemplate($templateData)
	{
		$templateData = str_replace('$NAMESPACE$', $this->namespace, $templateData);
		$templateData = str_replace('$MODEL_NAMESPACE$', $this->commandData->modelNamespace, $templateData);

		$templateData = str_replace('$MODEL_NAME$', $this->commandData->modelName, $templateData);
		$templateData = str_replace('$MODEL_NAME_PLURAL$', $this->commandData->modelNamePlural, $templateData);

		$templateData = str_replace('$MODEL_NAME_CAMEL$', $this->commandData->modelNameCamel, $templateData);
		$templateData = str_replace('$MODEL_NAME_PLURAL_CAMEL$', $this->commandData->modelNamePluralCamel, $templateData);

		return $templateData;
	}
}


text:
package com.intellij.vcs.log.graph.parser;

import com.intellij.vcs.log.graph.GraphCommit;
import javax.annotation.Nonnull;

import java.util.ArrayList;
import java.util.List;

import static com.intellij.vcs.log.graph.parser.CommitParser.toLines;

/**
 * @author erokhins
 */
public class SimpleCommitListParser {

  @Nonnull
  public static List<GraphCommit<String>> parseStringCommitList(@Nonnull String input) {
    List<GraphCommit<String>> vcsCommitParentses = new ArrayList<GraphCommit<String>>();
    for(String line : toLines(input)) {
      vcsCommitParentses.add(CommitParser.parseCommitParentsAsString(line));
    }
    return vcsCommitParentses;
  }

  @Nonnull
  public static List<GraphCommit<Integer>> parseIntegerCommitList(@Nonnull String input) {
    List<GraphCommit<Integer>> vcsCommitParentses = new ArrayList<GraphCommit<Integer>>();
    for(String line : toLines(input)) {
      vcsCommitParentses.add(CommitParser.parseCommitParentsAsInteger(line));
    }
    return vcsCommitParentses;
  }

}


text:
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "arbotix_sensors"
PROJECT_SPACE_DIR = "/home/fabi/catkin_ws/install"
PROJECT_VERSION = "0.10.0"


text:
import os

import pytest

import video_detect_logo_gcs

RESOURCES = os.path.join(os.path.dirname(__file__), "resources")

# Flaky Deadline
@pytest.mark.flaky(max_runs=3, min_passes=1)
def test_detect_logo_gcs(capsys):
    input_uri = "gs://cloud-samples-data/video/googlework_tiny.mp4"

    video_detect_logo_gcs.detect_logo_gcs(input_uri=input_uri)

    out, _ = capsys.readouterr()

    assert "Description" in out
    assert "Confidence" in out
    assert "Start Time Offset" in out
    assert "End Time Offset" in out


text:
namespace phd
{

struct doctor_cloud
{

typedef doctor_cloudRequest Request;
typedef doctor_cloudResponse Response;
Request request;
Response response;

typedef Request RequestType;
typedef Response ResponseType;

}; // struct doctor_cloud
} // namespace phd

namespace ros
{
namespace service_traits
{

template<>
struct MD5Sum< ::phd::doctor_cloud > {
  static const char* value()
  {
    return "cae4fb365d52ae353fa3450fdf68bef2";
  }

  static const char* value(const ::phd::doctor_cloud&) { return value(); }
};

template<>
struct DataType< ::phd::doctor_cloud > {
  static const char* value()
  {
    return "phd/doctor_cloud";
  }

  static const char* value(const ::phd::doctor_cloud&) { return value(); }
};

// service_traits::MD5Sum< ::phd::doctor_cloudRequest> should match
// service_traits::MD5Sum< ::phd::doctor_cloud >
template<>
struct MD5Sum< ::phd::doctor_cloudRequest>
{
  static const char* value()
  {
    return MD5Sum< ::phd::doctor_cloud >::value();
  }
  static const char* value(const ::phd::doctor_cloudRequest&)
  {
    return value();
  }
};

// service_traits::DataType< ::phd::doctor_cloudRequest> should match
// service_traits::DataType< ::phd::doctor_cloud >
template<>
struct DataType< ::phd::doctor_cloudRequest>
{
  static const char* value()
  {
    return DataType< ::phd::doctor_cloud >::value();
  }
  static const char* value(const ::phd::doctor_cloudRequest&)
  {
    return value();
  }
};

// service_traits::MD5Sum< ::phd::doctor_cloudResponse> should match
// service_traits::MD5Sum< ::phd::doctor_cloud >
template<>
struct MD5Sum< ::phd::doctor_cloudResponse>
{
  static const char* value()
  {
    return MD5Sum< ::phd::doctor_cloud >::value();
  }
  static const char* value(const ::phd::doctor_cloudResponse&)
  {
    return value();
  }
};

// service_traits::DataType< ::phd::doctor_cloudResponse> should match
// service_traits::DataType< ::phd::doctor_cloud >
template<>
struct DataType< ::phd::doctor_cloudResponse>
{
  static const char* value()
  {
    return DataType< ::phd::doctor_cloud >::value();
  }
  static const char* value(const ::phd::doctor_cloudResponse&)
  {
    return value();
  }
};

} // namespace service_traits
} // namespace ros

#endif // PHD_MESSAGE_DOCTOR_CLOUD_H


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
use OwenIt\Auditing\AuditingTrait;

class CssClass extends Model
{
    use Sluggable,AuditingTrait;
    public static function rules(){
      return ['title' => 'required'];
    }

    public function author(){
      return $this->belongsTo('App\User', 'user_id', 'id');
    }

    public function sluggable()
    {
      return ['slug' => ['source' => 'title']];
    }
}


text:
static NUS_result nus_vulkan_instance_build_instance
(NUS_vulkan_instance *, NUS_string_group, NUS_string_group);
static NUS_result nus_vulkan_instance_extension_support(NUS_string_group);
static NUS_result nus_vulkan_instance_layer_support(NUS_string_group);

#if defined(NUS_DEBUG)
VkDebugReportCallbackEXT NUS_vulkan_debug_report_callback;
#endif

NUS_result nus_vulkan_instance_build
(NUS_vulkan_instance *p_vulkan_instance,
 NUS_string_group extensions, NUS_string_group layers)
{
  if(nus_vulkan_instance_build_instance(p_vulkan_instance,
					extensions, layers) != NUS_SUCCESS){
    NUS_LOG_ERROR("failed to build vulkan instance instance\n");
    return NUS_FAILURE;
  }

  nus_load_instance_vulkan_library(p_vulkan_instance->vk_instance,
				   &p_vulkan_instance->functions);
  nus_bind_instance_vulkan_library(p_vulkan_instance->functions);

#if defined(NUS_DEBUG)

  // create debug callback

  VkDebugReportCallbackCreateInfoEXT callback_create_info = {
    .sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT,
    .pNext = NULL,
    .flags = VK_DEBUG_REPORT_ERROR_BIT_EXT |
    VK_DEBUG_REPORT_WARNING_BIT_EXT |
    VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
    .pfnCallback = &nus_vulkan_validation_callback,
    .pUserData = NULL
  };
  if(vkCreateDebugReportCallbackEXT(p_vulkan_instance->vk_instance,
				    &callback_create_info, NULL,
				    &NUS_vulkan_debug_report_callback) !=
     VK_SUCCESS){
    NUS_LOG_ERROR("failed to create vulkan instance debug report\n");
    return NUS_FAILURE;
  }

#endif
  return NUS_SUCCESS;
}
void nus_vulkan_instance_free(NUS_vulkan_instance *p_vulkan_instance)
{
#if defined(NUS_DEBUG)
  if(VK_NULL_HANDLE != NUS_vulkan_debug_report_callback){
    vkDestroyDebugReportCallbackEXT(p_vulkan_instance->vk_instance,
				    NUS_vulkan_debug_report_callback,
				    VK_NULL_HANDLE);
    NUS_vulkan_debug_report_callback = VK_NULL_HANDLE;
  }
#endif
  if(VK_NULL_HANDLE != p_vulkan_instance->vk_instance){
    vkDestroyInstance(p_vulkan_instance->vk_instance, NULL);
  }
}
static NUS_result nus_vulkan_instance_build_instance
(NUS_vulkan_instance *p_vulkan_instance,
 NUS_string_group extensions, NUS_string_group layers)
{
#if defined(NUS_DEBUG)
  NUS_string_group tmp_extensions,
    tmp_layers;
  nus_string_group_build(&tmp_extensions);
  nus_string_group_build(&tmp_layers);
  nus_string_group_copy(&tmp_extensions, extensions);
  nus_string_group_copy(&tmp_layers, layers);
  nus_string_group_append(&tmp_extensions, "VK_EXT_debug_report");
  nus_string_group_append(&tmp_layers, "VK_LAYER_LUNARG_standard_validation");
  extensions = tmp_extensions;
  layers = tmp_layers;
#endif
  if(nus_vulkan_instance_extension_support(extensions) != NUS_SUCCESS){
    NUS_LOG_ERROR("vulkan instance extension not supported\n");
    return NUS_FAILURE;
  }
  if(nus_vulkan_instance_layer_support(layers) != NUS_SUCCESS){
    NUS_LOG_ERROR("vulkan instance layer not supported\n");
    return NUS_FAILURE;
  }
  VkApplicationInfo application_create_info = {
    .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
    .pNext = NULL,
    .pApplicationName = "application",
    .applicationVersion = VK_MAKE_VERSION(1, 0, 0),
    .pEngineName = "NUS_engine",
    .engineVersion = VK_MAKE_VERSION(1, 0, 0),
    .apiVersion = VK_API_VERSION_1_0
  };

  VkInstanceCreateInfo instance_create_info = {
    .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
    .pNext = NULL,
    .flags = 0,
    .pApplicationInfo = &application_create_info,
    .enabledLayerCount = layers.count,
    .ppEnabledLayerNames = (char const * const *)layers.strings,
    .enabledExtensionCount = extensions.count,
    .ppEnabledExtensionNames = (char const * const *)extensions.strings
  };
  p_vulkan_instance->vk_instance = VK_NULL_HANDLE;
  if(vkCreateInstance(&instance_create_info, NULL,
		      &p_vulkan_instance->vk_instance) != VK_SUCCESS){
    NUS_LOG_ERROR("unable to create vulkan instance\n");
    return NUS_FAILURE;
  }

#if defined(NUS_DEBUG)
  //free string groups we created earlier

  nus_string_group_free(&extensions);
  nus_string_group_free(&layers);

#endif
  return NUS_SUCCESS;
}
static NUS_result nus_vulkan_instance_extension_support
(NUS_string_group string_group)
{
  unsigned int supported_extension_count,
    supported_wanted_extension_count,
    i;
  if(vkEnumerateInstanceExtensionProperties(NULL, &supported_extension_count,
					    NULL) != VK_SUCCESS ||
     supported_extension_count == 0){
    NUS_LOG_ERROR("instance extension enumeration: count=%d\n",
	   supported_extension_count);
    return NUS_FAILURE;
  }
  VkExtensionProperties supported_extensions[supported_extension_count];
  if(vkEnumerateInstanceExtensionProperties(NULL, &supported_extension_count,
					    supported_extensions) != VK_SUCCESS){
    NUS_LOG_ERROR("instance extension enumeration: extensions\n");
    return NUS_FAILURE;
  }

  // "count" tracks how many of the supported extensions are in the string group
  // we want this to be equal to the length of the string group
  for(i = 0, supported_wanted_extension_count = 0;
      i < supported_extension_count; ++i){

    if(nus_string_group_string_index(string_group,
				     supported_extensions[i].extensionName) !=
       UINT_MAX){
      ++supported_wanted_extension_count;
    }
  }
  if(supported_wanted_extension_count < string_group.count){
    return NUS_FAILURE;
  }
  return NUS_SUCCESS;
}
static NUS_result nus_vulkan_instance_layer_support
(NUS_string_group string_group)
{//TODO fix memleak originating from vkEnumereate...
  unsigned int supported_layer_count,
    supported_wanted_layer_count,
    i;

  if(vkEnumerateInstanceLayerProperties(&supported_layer_count,
					NULL) != VK_SUCCESS ||
     supported_layer_count == 0){
    NUS_LOG_ERROR("instance layer enumeration: count=%d\n",
	   supported_layer_count);
    return NUS_FAILURE;
  }

  VkLayerProperties supported_layers[supported_layer_count];
  if(vkEnumerateInstanceLayerProperties(&supported_layer_count,
					supported_layers) != VK_SUCCESS){
    NUS_LOG_ERROR("instance layer enumeration: layers\n");
    return NUS_FAILURE;
  }

  // "count" tracks how many of the supported layers are in the string group
  // we want this to be equal to the length of the string group
  for(i = 0, supported_wanted_layer_count = 0; i < supported_layer_count; ++i){
    if(nus_string_group_string_index(string_group,
				     supported_layers[i].layerName) !=
       UINT_MAX){
      ++supported_wanted_layer_count;
    }
  }
  if(supported_wanted_layer_count < string_group.count){
    return NUS_FAILURE;
  }

  return NUS_SUCCESS;
}
#if defined(NUS_DEBUG)
VKAPI_ATTR VkBool32 VKAPI_CALL nus_vulkan_validation_callback
(VkDebugReportFlagsEXT flags,
 VkDebugReportObjectTypeEXT objectType,
 uint64_t object,
 size_t location,
 int32_t messageCode,
 const char* pLayerPrefix,
 const char* pMessage,
 void* pUserData)
{
  printf("\n");
  NUS_LOG_WARNING("VALIDATION::%s\n\n", pMessage);
  return VK_FALSE;
}
#endif