text:
#include "mitkLabelSetImageSurfaceStampFilter.h"

#include "mitkImageAccessByItk.h"
#include "mitkImageCast.h"

#include <mitkLabelSetImage.h>
#include <mitkLabelSetImage.h>
#include <mitkSurface.h>
#include <mitkSurfaceToImageFilter.h>

mitk::LabelSetImageSurfaceStampFilter::LabelSetImageSurfaceStampFilter() : m_ForceOverwrite(false)
{
  this->SetNumberOfIndexedInputs(1);
  this->SetNumberOfRequiredInputs(1);
}

mitk::LabelSetImageSurfaceStampFilter::~LabelSetImageSurfaceStampFilter()
{
}

void mitk::LabelSetImageSurfaceStampFilter::GenerateData()
{
  // GenerateOutputInformation();
  this->SetNthOutput(0, this->GetInput(0));

  mitk::Image::Pointer inputImage = this->GetInput(0);

  if (m_Surface.IsNull())
  {
    MITK_ERROR << "Input surface is nullptr.";
    return;
  }

  mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New();
  surfaceToImageFilter->MakeOutputBinaryOn();
  surfaceToImageFilter->SetInput(m_Surface);
  surfaceToImageFilter->SetImage(inputImage);
  surfaceToImageFilter->Update();
  mitk::Image::Pointer resultImage = surfaceToImageFilter->GetOutput();

  AccessByItk_1(inputImage, ItkImageProcessing, resultImage);
  inputImage->DisconnectPipeline();
}

template <typename TPixel, unsigned int VImageDimension>
void mitk::LabelSetImageSurfaceStampFilter::ItkImageProcessing(itk::Image<TPixel, VImageDimension> *itkImage,
                                                               mitk::Image::Pointer resultImage)
{
  typedef itk::Image<TPixel, VImageDimension> ImageType;
  mitk::LabelSetImage::Pointer LabelSetInputImage = dynamic_cast<LabelSetImage *>(GetInput());
  try
  {
    typename ImageType::Pointer itkResultImage = ImageType::New();
    mitk::CastToItkImage(resultImage, itkResultImage);

    typedef itk::ImageRegionConstIterator<ImageType> SourceIteratorType;
    typedef itk::ImageRegionIterator<ImageType> TargetIteratorType;

    SourceIteratorType sourceIter(itkResultImage, itkResultImage->GetLargestPossibleRegion());
    sourceIter.GoToBegin();

    TargetIteratorType targetIter(itkImage, itkImage->GetLargestPossibleRegion());
    targetIter.GoToBegin();

    int activeLabel = (LabelSetInputImage->GetActiveLabel(LabelSetInputImage->GetActiveLayer()))->GetValue();

    while (!sourceIter.IsAtEnd())
    {
      auto sourceValue = static_cast<int>(sourceIter.Get());
      auto targetValue = static_cast<int>(targetIter.Get());

      if ((sourceValue != 0) &&
          (m_ForceOverwrite ||
           !LabelSetInputImage->GetLabel(targetValue)->GetLocked())) // skip exterior and locked labels
      {
        targetIter.Set(activeLabel);
      }
      ++sourceIter;
      ++targetIter;
    }
  }
  catch (itk::ExceptionObject &e)
  {
    mitkThrow() << e.GetDescription();
  }
  this->Modified();
}

void mitk::LabelSetImageSurfaceStampFilter::GenerateOutputInformation()
{
  mitk::Image::Pointer inputImage = (mitk::Image *)this->GetInput();
  mitk::Image::Pointer output = this->GetOutput();
  itkDebugMacro(<< "GenerateOutputInformation()");
  if (inputImage.IsNull())
    return;
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Email Sent</title>

Your Email has been sent!

		<button class="forum_btn">Return to Login Page</button>

redpajama_set_name: RedPajamaGithub


text:
// tslint:disable-next-line
require('source-map-support').install();
// Don't change the order;
export { Loggers, cls } from 'island-loggers';

export { Event, BaseEvent } from 'island-types';

export import mongoose = require('mongoose');
mongoose.Promise = Promise as any;

import Islet from './islet';
export { Islet };

// adapters
export { default as AbstractAdapter, IAbstractAdapter } from './adapters/abstract-adapter';
export { default as ListenableAdapter } from './adapters/listenable-adapter';

// adapters/impl
export { default as MessageBrokerAdapter } from './adapters/impl/message-broker-adapter';
export { default as MongooseAdapter, MongooseAdapterOptions } from './adapters/impl/mongoose-adapter';
export { default as PushAdapter, PushAdapterOptions } from './adapters/impl/push-adapter';
export { default as RedisConnectionAdapter, RedisAdapterOptions } from './adapters/impl/redis-connection-adapter';
export { default as RestifyAdapter, RestifyAdapterOptions } from './adapters/impl/restify-adapter';
export { default as RPCAdapter, RPCAdapterOptions } from './adapters/impl/rpc-adapter';
export { default as SocketIOAdapter, SocketIOAdapterOptions } from './adapters/impl/socketio-adapter';
export { default as RabbitMqAdapter, RabbitMqAdapterOptions } from './adapters/impl/rabbitmq-adapter';
export { AmqpChannelPoolAdapter } from './adapters/impl/amqp-channel-pool-adapter';
export { EventAdapter, EventAdapterOptions } from './adapters/impl/event-adapter';

// controllers
export { default as AbstractController } from './controllers/abstract-controller';
export {
  validate,
  sanitize,
  admin,
  extra,
  auth,
  devonly,
  mangle,
  nosession,
  ensure,
  EnsureOptions,
  EndpointOptions,
  EndpointSchemaOptions,
  endpoint,
  endpointController,
  quota,
  groupServiceQuota,
  groupQuota,
  sessionGroup
} from './controllers/endpoint-decorator';
export {
  rpc,
  rpcController
} from './controllers/rpc-decorator';
export {
  Response,
  middleware
} from './controllers/middleware-decorator';
export { eventController, subscribeEvent, subscribePattern } from './controllers/event-decorator';

// models
/**
 * @deprecated
 */
export { default as ModelFactory } from './models/model-factory';

// services
export { default as MessageBrokerService } from './services/message-broker-service';
export { default as PushService, BroadcastTarget, BroadcastTargets } from './services/push-service';
export { RPCService, RpcHook, RpcHookType } from './services/rpc-service';

export {
  default as AbstractBrokerService,
  IConsumerInfo
} from './services/abstract-broker-service';
export { AmqpChannelPoolService, AmqpOptions } from './services/amqp-channel-pool-service';
export { EventService } from './services/event-service';

// utils
export { Environments } from './utils/environments';
export { TraceLog } from './utils/tracelog';
export { ScopeExit } from './utils/scope-exit';
export { ResourcePush } from './utils/resource-push';
export { default as MessagePack } from './utils/msgpack';
export { default as StaticDataLoader } from './utils/staticdata-loader';
export { default as StaticDataFactory } from './utils/staticdata-factory';
export {
  jasmineAsyncAdapter as spec,
  createSpyObjWithAllMethods as spyAll,
  resetSpyObjWithCallsCount as resetCallsCount
} from './utils/jasmine-async-support';
export {
  AbstractError,
  AbstractExpectedError,
  AbstractFatalError,
  AbstractLogicError,
  ErrorOptions,
  ErrorLevel,
  ISLAND,
  IslandLevel,
  toCode,
  setIslandCode
} from './utils/error';
export { Events } from './utils/event';
export { IntervalHelper } from './utils/interval-helper';
export { collector } from './utils/status-collector';
export { env, LoadEnv } from './utils/env-loader';

export { Di, ObjectWrapper, ObjectFactory } from 'island-di';
export { RouteLogger } from './utils/route-logger';


text:
using System;

namespace DddDemo.Infrastructure
{
    public class Class1
    {
    }
}


text:
require 'aws-sdk-s3'

Given /^I have a randomized file containing the eicar test signature$/ do
  @file = Fixtures.eicar_test_signature + SecureRandom.base64(129)
end

When /^I upload #{MAYBE_VAR} to the documents bucket under the key #{MAYBE_VAR}$/ do |file_contents, destination_key|
  s3 = Aws::S3::Resource.new(region: 'eu-west-1')  # actual region is unimportant
  @s3_obj = s3.bucket(dm_documents_bucket_name).object(destination_key)
  @s3_obj_response = @s3_obj.put(
    acl: "bucket-owner-full-control",
    body: file_contents,
  )
  puts "File etag: #{@s3_obj_response.etag}"
end

Then /^I receive a notification regarding that file within ([0-9]+) minutes?$/ do |minutes_string|
  etag = @s3_obj_response.etag.downcase.gsub(/[^a-z0-9]/, '')
  minutes = minutes_string.to_i

  expected_ref = "eicar-found-#{etag}-#{dm_environment}"
  puts "Notify ref: #{expected_ref}"

  messages = nil
  (0..(minutes * 6)).each {
    sleep(10)
    messages = DMNotify.get_email_raw(expected_ref)
    if messages.collection.length != 0
      break
    end
  }
  expect(messages.collection.length).to eq(1)
  @email = messages.collection[0]
  puts "Notify id: #{@email.id}"
end


text:
require 'test_helper'
require 'openssl'
require 'net/http'

class NetworkConnectionRetriesTest < Minitest::Test
  class MyNewError < StandardError
  end

  include NetworkConnectionRetries

  def setup
    @logger = stubs(:logger)
    @requester = stubs(:requester)
    @ok = stub(:code => 200, :message => 'OK', :body => 'success')
  end

  def test_unrecoverable_exception
    raised = assert_raises(ActiveUtils::ConnectionError) do
      retry_exceptions do
        raise EOFError
      end
    end
    assert_equal "The remote server dropped the connection", raised.message
  end

  def test_econnreset_raises_correctly
    raised = assert_raises(ActiveUtils::ConnectionError) do
      retry_exceptions do
        raise Errno::ECONNRESET
      end
    end
    assert_equal "The remote server reset the connection", raised.message
  end

  def test_timeout_errors_raise_correctly
    exceptions = [Timeout::Error, Errno::ETIMEDOUT]
    if RUBY_VERSION >= '2.0.0'
      exceptions += [Net::ReadTimeout, Net::OpenTimeout]
    end

    exceptions.each do |exception|
      raised = assert_raises(ActiveUtils::ConnectionError) do
        retry_exceptions do
          raise exception
        end
      end
      assert_equal "The connection to the remote server timed out", raised.message
    end
  end

  def test_socket_error_raises_correctly
    raised = assert_raises(ActiveUtils::ConnectionError) do
      retry_exceptions do
        raise SocketError
      end
    end
    assert_equal "The connection to the remote server could not be established", raised.message
  end

  def test_ssl_errors_raise_correctly
    exceptions = [OpenSSL::SSL::SSLError]
    if RUBY_VERSION >= '2.1.0'
      exceptions += [OpenSSL::SSL::SSLErrorWaitWritable, OpenSSL::SSL::SSLErrorWaitReadable]
    end

    exceptions.each do |exception|
      raised = assert_raises(ActiveUtils::ConnectionError) do
        retry_exceptions do
          raise exception
        end
      end
      assert_equal "The SSL connection to the remote server could not be established", raised.message
    end
  end

  def test_invalid_response_error
    assert_raises(ActiveUtils::InvalidResponseError) do
      retry_exceptions do
        raise Zlib::BufError
      end
    end
  end

  def test_unrecoverable_exception_logged_if_logger_provided
    @logger.expects(:info).once
    assert_raises(ActiveUtils::ConnectionError) do
      retry_exceptions :logger => @logger do
        raise EOFError
      end
    end
  end

  def test_failure_then_success_with_recoverable_exception
    @requester.expects(:post).times(2).raises(Errno::ECONNREFUSED).then.returns(@ok)

    retry_exceptions do
      @requester.post
    end
  end

  def test_failure_limit_reached
    @requester.expects(:post).times(ActiveUtils::NetworkConnectionRetries::DEFAULT_RETRIES).raises(Errno::ECONNREFUSED)

    assert_raises(ActiveUtils::ConnectionError) do
      retry_exceptions do
        @requester.post
      end
    end
  end

  def test_failure_limit_reached_logs_final_error
    @logger.expects(:info).times(3)
    @requester.expects(:post).times(ActiveUtils::NetworkConnectionRetries::DEFAULT_RETRIES).raises(Errno::ECONNREFUSED)

    assert_raises(ActiveUtils::ConnectionError) do
      retry_exceptions(:logger => @logger) do
        @requester.post
      end
    end
  end

  def test_failure_then_success_with_retry_safe_enabled
    @requester.expects(:post).times(2).raises(EOFError).then.returns(@ok)

    retry_exceptions :retry_safe => true do
      @requester.post
    end
  end

  def test_failure_then_success_logs_success
    @logger.expects(:info).with(regexp_matches(/dropped/))
    @logger.expects(:info).with(regexp_matches(/success/))
    @requester.expects(:post).times(2).raises(EOFError).then.returns(@ok)

    retry_exceptions(:logger => @logger, :retry_safe => true) do
      @requester.post
    end
  end

  def test_mixture_of_failures_with_retry_safe_enabled
    @requester.expects(:post).times(3).raises(Errno::ECONNRESET).
                                       raises(Errno::ECONNREFUSED).
                                       raises(EOFError)

    assert_raises(ActiveUtils::ConnectionError) do
      retry_exceptions :retry_safe => true do
        @requester.post
      end
    end
  end

  def test_delay_between_retries
    @requester.expects(:post).times(2).raises(EOFError).then.returns(@ok)
    Kernel.expects(sleep: 0.5)

    retry_exceptions retry_safe: true, delay: 0.5 do
      @requester.post
    end
  end

  def test_no_delay_without_specified_option
    @requester.expects(:post).times(2).raises(EOFError).then.returns(@ok)
    Kernel.expects(sleep: 0.5).never

    retry_exceptions retry_safe: true do
      @requester.post
    end
  end

  def test_failure_with_ssl_certificate
    @requester.expects(:post).raises(OpenSSL::X509::CertificateError)

    assert_raises(ActiveUtils::ClientCertificateError) do
      retry_exceptions do
        @requester.post
      end
    end
  end

  def test_failure_with_ssl_certificate_logs_error_if_logger_specified
    @logger.expects(:error).once
    @requester.expects(:post).raises(OpenSSL::X509::CertificateError)

    assert_raises(ActiveUtils::ClientCertificateError) do
      retry_exceptions :logger => @logger do
        @requester.post
      end
    end
  end

  def test_failure_with_additional_exceptions_specified
    @requester.expects(:post).raises(MyNewError)

    assert_raises(ActiveUtils::ConnectionError) do
      retry_exceptions :connection_exceptions => {MyNewError => "my message"} do
        @requester.post
      end
    end
  end

  def test_failure_without_additional_exceptions_specified
    @requester.expects(:post).raises(MyNewError)

    assert_raises(MyNewError) do
      retry_exceptions do
        @requester.post
      end
    end
  end

  def test_retries_with_custom_error_specified
    @requester.expects(:post).times(2).raises(Errno::ETIMEDOUT).then.returns(@ok)

    retry_exceptions retriable_exceptions: { Errno::ETIMEDOUT => "The connection to the remote server timed out"} do
      @requester.post
    end
  end
end


text:
[![Gem Version](https://badge.fury.io/rb/mongoid_appender.svg)](https://badge.fury.io/rb/mongoid_appender)
[![Code Climate](https://codeclimate.com/github/armchairtheorist/mongoid_appender/badges/gpa.svg)](https://codeclimate.com/github/armchairtheorist/mongoid_appender)

# MongoidAppender

MongoidAppender is a simple implementation of a standard `Logging::Appender` for Tim Pease's [Logging](http://github.com/TwP/logging) framework using [Mongoid](http://www.mongoid.org), useful for writing log messages into MongoDB. MongoidAppender has been tested with both Mongoid 3.x and 4.0.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'mongoid_appender'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install mongoid_appender

## Usage

Configure MongoidAppender as you would a normal `Logging::Appender`. For example, to configure your root logger to output all messages to `stdout` but only write `:warn` messages and above to MongoDB, you can use the following code:

```ruby
require 'logging'
require 'mongoid'

# Some code to set up Mongoid here...

Logging.logger.root.add_appenders(
    Logging.appenders.stdout,
	MongoidAppender.new('mongoid', :level => :warn)
)
```

By default, MongoidAppender will write log documents into a MongoDB collection named `logs`. Every document has the following fields:

* `level` - The event level (debug, info, warn, error, etc.)
* `logger` - The name of the logger
* `message` - The log message
* `exception` - The log exception (if any)
* `backtrace` - The log backtrace (if any)

Simple!


text:
namespace ouzel
{
    namespace graphics
    {
        class Renderer final
        {
            friend Window;
        public:
            Renderer(Driver driver,
                     Window* newWindow,
                     const Size2U& newSize,
                     uint32_t newSampleCount,
                     Texture::Filter newTextureFilter,
                     uint32_t newMaxAnisotropy,
                     bool newVerticalSync,
                     bool newDepth,
                     bool newStencil,
                     bool newDebugRenderer);

            Renderer(const Renderer&) = delete;
            Renderer& operator=(const Renderer&) = delete;

            Renderer(Renderer&&) = delete;
            Renderer& operator=(Renderer&&) = delete;

            static Driver getDriver(const std::string& driver);
            static std::set<Driver> getAvailableRenderDrivers();

            inline RenderDevice* getDevice() const { return device.get(); }

            inline const Size2U& getSize() const { return size; }

            void saveScreenshot(const std::string& filename);

            void setRenderTarget(uintptr_t renderTarget);
            void clearRenderTarget(bool clearColorBuffer,
                                   bool clearDepthBuffer,
                                   bool clearStencilBuffer,
                                   Color clearColor,
                                   float clearDepth,
                                   uint32_t clearStencil);
            void setScissorTest(bool enabled, const RectF& rectangle);
            void setViewport(const RectF& viewport);
            void setDepthStencilState(uintptr_t depthStencilState,
                                      uint32_t stencilReferenceValue);
            void setPipelineState(uintptr_t blendState,
                                  uintptr_t shader,
                                  CullMode cullMode,
                                  FillMode fillMode);
            void draw(uintptr_t indexBuffer,
                      uint32_t indexCount,
                      uint32_t indexSize,
                      uintptr_t vertexBuffer,
                      DrawMode drawMode,
                      uint32_t startIndex);
            void pushDebugMarker(const std::string& name);
            void popDebugMarker();
            void setShaderConstants(std::vector<std::vector<float>> fragmentShaderConstants,
                                    std::vector<std::vector<float>> vertexShaderConstants);
            void setTextures(const std::vector<uintptr_t>& textures);

            inline void addCommand(std::unique_ptr<Command>&& command)
            {
                commandBuffer.pushCommand(std::move(command));
            }
            void present();

            inline uintptr_t getResourceId()
            {
                return device->getResourceId();
            }

            void deleteResourceId(uintptr_t resourceId)
            {
                addCommand(std::unique_ptr<Command>(new DeleteResourceCommand(resourceId)));
                device->deleteResourceId(resourceId);
            }

            void waitForNextFrame();
            inline bool getRefillQueue() const { return refillQueue; }

            Vector2F convertScreenToNormalizedLocation(const Vector2F& position)
            {
                return Vector2F(position.v[0] / size.v[0],
                                      1.0F - (position.v[1] / size.v[1]));
            }

            Vector2F convertNormalizedToScreenLocation(const Vector2F& position)
            {
                return Vector2F(position.v[0] * size.v[0],
                                      (1.0F - position.v[1]) * size.v[1]);
            }

        private:
            void handleEvent(const RenderDevice::Event& event);
            void setSize(const Size2U& newSize);

            std::unique_ptr<RenderDevice> device;

            Size2U size;
            CommandBuffer commandBuffer;

            bool newFrame = false;
            std::mutex frameMutex;
            std::condition_variable frameCondition;
            std::atomic_bool refillQueue{true};
        };
    } // namespace graphics
} // namespace ouzel

#endif // OUZEL_GRAPHICS_RENDERER_HPP


text:
{% if data %}

			{% for key, value in routes %}
				{% if value is iterable %}
					{% for childKey, childValue in value %}

						{{childKey | upper | replace({'_': " "}) }}

							{% if childValue is iterable %}
								{% for childChildKey, childChildValue in childValue %}

{{childChildValue | upper | replace({'_': " "}) }}

								{% endfor %}
							{% endif %}

					{% endfor %}
				{% else %}
					{% if value %}

{{value | upper | replace({'_': " "})}}

					{% endif %}
				{% endif %}
			{% endfor %}

{% endif %}


text:
'use strict';

module.exports = require('./async').findLimit;


text:
<?php namespace Tsi\Lutetium\Models;

use Model;
use Carbon\Carbon;

/**
 * Model
 */
class Subscription extends Model
{
    use \October\Rain\Database\Traits\Validation;

    use \October\Rain\Database\Traits\SoftDelete;

    protected $dates = ['deleted_at', 'date_start', 'date_end'];

    /*
     * Validation
     */
    public $rules = [
    ];

    /**
     * @var string The database table used by the model.
     */
    public $table = 'tsi_lutetium_subscription';

    public $belongsTo = [
        'plan' => ['Tsi\Lutetium\Models\Plan'],
        'subscriber' => ['Tsi\Lutetium\Models\Subscriber'],
    ];

    public $belongsToMany = [
        'addons' => [
            'Tsi\Lutetium\Models\Addon',
            'table' => 'tsi_lutetium_addon_subscription',
            'pivot' => ['redeemable_redeemed', 'redeemable_max'],
        ],
    ];

    public $hasMany = [
        'invoices' => 'Tsi\Lutetium\Models\Invoice',
    ];

    public $attachMany = [
        'files' => 'System\Models\File',
    ];

    public $morphMany = [
        'traces' => ['Tsi\Lutetium\Models\Trace', 'name' => 'traceable'],
        'comments' => ['Tsi\Lutetium\Models\Comment', 'name' => 'commentable'],
    ];

    public function getPercentageToExpiryAttribute()
    {
        $daysBetween = $this->date_start->diffInDays($this->date_end, false);

        $now = Carbon::now();
        $daysPassed = $this->date_start->diffInDays($now, false);

        return $percentageToExpiry = ($daysPassed/$daysBetween)*100;
    }

    public function getDaysToExpiryAttribute()
    {
        $now = Carbon::now();
        $daysBetween = $now->diffInDays($this->date_end, false);

        return $daysBetween;
    }

    public function getNextBillingDateAttribute()
    {

        $p = $this->plan;

        // Date Start
        $ds = $this->date_start;
        // Date End
        $nb = $ds->addMonths($this->plan['bill_cycle']);

        return $nb->format('n M Y');
    }

    public function filterFields($fields, $context = null)
    {

        if($context == 'create' or $context == 'update') {
            $p = $this->plan;

            // Date Start
            $ds = Carbon::parse($fields->date_start->value);
            // Date End
            $de = $ds->addMonths($this->plan['bill_cycle']);
            // Next Bill Date is Date End + 1 Day
            $de = $de->addDays(-1);

            $fields->_placeholder_date_end->value = $ds->format('n/d/Y');
        }

    }

    /**
     * Generate a random token
     */
    public function beforeCreate()
    {
        /**
         * Generate a random token
         */

        $characters = '23456789abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $length = 5;
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }

        $this->token = $randomString;

        $billCycle = $this->plan->bill_cycle;

        $now = Carbon::create();
        $ds = $this->date_start;
        $de = $ds->addMonths($billCycle);

        $this->date_end = $de;

        $this->auto_renew = $this->plan->auto_renew;

        $this->date_subscribed = $now;
    }

    public function beforeSave()
    {
        // Everytime update or create, set the Date End date
        $p = $this->plan;

        // Date Start
        $ds = $this->date_start;
        // Date End
        $de = $ds->addMonths($this->plan['bill_cycle']);
        // Next Bill Date is Date End + 1 Day
        $de = $de->addDays(-1);

        $this->date_end = $de;

    }
}


text:
<?php

namespace JobBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class JobType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('jobTitle')
            ->add('company')
            ->add('jobDescription')
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'JobBundle\Entity\Job'
        ));
    }
}


text:
	<md-content layout="column" layout-align="start">

			<form name="settingsForm">
		      <md-input-container class="md-block">
		        Home Currency
		        <input md-maxlength="3" required ng-pattern="/^[A-Z]*$/" md-no-asterisk name="homecurrency" ng-model="settings.home_currency">

Required!

Doesn't seem right!

Doesn't seem right!

Doesn't seem right!

		      </md-input-container>
		      <md-input-container class="md-block">
		        Trip Currency
		        <input md-minlength="3" md-maxlength="3" required ng-pattern="/^(\D)+$/" md-no-asterisk name="tripcurrency" ng-model="settings.trip_currency">

Required!

Doesn't seem right!

Doesn't seem right!

Doesn't seem right!

		      </md-input-container>
		      <md-input-container class="md-block">
		        FX Rate (1 {{ settings.trip_currency }} = ? {{settings.home_currency}})
		        <input required type="number" step="any" name="fxrate" ng-model="settings.fx_rate" min="0.01" />

Required!

		      </md-input-container>
		    </form>

			<md-button class="md-raised md-primary" ng-click="saveSettings()" ng-disabled="settingsForm.$invalid">Save</md-button>
			<md-button class="md-raised md-warn" ng-click="cancelSettings()">Cancel</md-button>

	</md-content>


text:
namespace ElasticAnalytics.ScAdapter.FacetModelSerialization
{
    using System.Linq;

    using Newtonsoft.Json.Linq;

    using Sitecore.Analytics.Model.Framework;

    public class CollectionModelSerializer : IModelMemberSerializer
    {
        public bool CanProcess(IModelMember member)
        {
            return member is IModelCollectionMember;
        }

        public JToken Serialize(
            IModelMember dataSource,
            ISerializerProvider provider,
            IElementSerializer elementSerializer)
        {
            var colDataSource = dataSource as IModelCollectionMember;

            var arr = new JArray();
            var res = new JProperty(colDataSource.Name, arr);
            foreach (var element in colDataSource.Elements)
            {
                var newEl = elementSerializer.Serialize(element, provider);
                arr.Add(newEl);
            }

            return res;
        }

        public void Deserialize(
            JToken dataSource,
            IModelMember destination,
            ISerializerProvider provider,
            IElementSerializer elementSerializer)
        {
            var current = destination as IModelCollectionMember;

            var jArrayDataSource = dataSource as JArray;
            if (jArrayDataSource == null) return;

            foreach (var childJObject in jArrayDataSource.Children().OfType<JObject>())
            {
                var newEl = current.Elements.Create();
                elementSerializer.Deserialize(childJObject, newEl, provider);
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Csla;

namespace SelfLoadROSoftDelete.DataAccess.ERLevel
{
    /// <summary>
    /// DAL Interface for G07_Country_Child type
    /// </summary>
    public partial interface IG07_Country_ChildDal
    {
        /// <summary>
        /// Loads a G07_Country_Child object from the database.
        /// </summary>
        /// <param name="country_ID1">The fetch criteria.</param>
        /// <returns>A <see cref="G07_Country_ChildDto"/> object.</returns>
        G07_Country_ChildDto Fetch(int country_ID1);
    }
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * Search box.
 *
 * @param {element} element Root element of the search box.
 * @constructor
 */
function SearchBox(element) {
  /**
   * Autocomplete List.
   * @type {AutocompleteList}
   */
  this.autocompleteList = new SearchBox.AutocompleteList(element.ownerDocument);

  /**
   * Root element of the search box.
   * @type {HTMLElement}
   */
  this.element = element;

  /**
   * Text input of the search box.
   * @type {HTMLElement}
   */
  this.inputElement = element.querySelector('input');

  /**
   * Clear button of the search box.
   * @type {HTMLElement}
   */
  this.clearButton = element.querySelector('.clear');

  /**
   * Text measure.
   * @type {TextMeasure}
   * @private
   */
  this.textMeasure_ = new TextMeasure(this.inputElement);

  Object.freeze(this);

  // Register events.
  this.inputElement.addEventListener('input', this.updateStyles_.bind(this));
  this.inputElement.addEventListener('keydown', this.onKeyDown_.bind(this));
  this.inputElement.addEventListener('focus', this.onFocus_.bind(this));
  this.inputElement.addEventListener('blur', this.onBlur_.bind(this));
  this.inputElement.ownerDocument.addEventListener('dragover',
                                                   this.onDragEnter_.bind(this),
                                                   true);
  this.inputElement.ownerDocument.addEventListener('dragend',
                                                   this.onDragEnd_.bind(this),
                                                   true);
  element.querySelector('.icon').addEventListener(
      'click', this.onIconClick_.bind(this));
  element.parentNode.appendChild(this.autocompleteList);
}

/**
 * Autocomplete list for search box.
 * @param {HTMLDocument} document Document.
 * @constructor
 */
SearchBox.AutocompleteList = function(document) {
  var self = cr.ui.AutocompleteList.call(this);
  self.__proto__ = SearchBox.AutocompleteList.prototype;
  self.id = 'autocomplete-list';
  self.autoExpands = true;
  self.itemConstructor = SearchBox.AutocompleteListItem_.bind(null, document);
  self.addEventListener('mouseover', self.onMouseOver_.bind(self));
  return self;
};

SearchBox.AutocompleteList.prototype = {
  __proto__: cr.ui.AutocompleteList.prototype
};

/**
 * Do nothing when a suggestion is selected.
 * @override
 */
SearchBox.AutocompleteList.prototype.handleSelectedSuggestion = function() {};

/**
 * Change the selection by a mouse over instead of just changing the
 * color of moused over element with :hover in CSS. Here's why:
 *
 * 1) The user selects an item A with up/down keys (item A is highlighted)
 * 2) Then the user moves the cursor to another item B
 *
 * If we just change the color of moused over element (item B), both
 * the item A and B are highlighted. This is bad. We should change the
 * selection so only the item B is highlighted.
 *
 * @param {Event} event Event.
 * @private
 */
SearchBox.AutocompleteList.prototype.onMouseOver_ = function(event) {
  if (event.target.itemInfo)
    this.selectedItem = event.target.itemInfo;
};

/**
 * ListItem element for autocomple.
 *
 * @param {HTMLDocument} document Document.
 * @param {Object} item An object representing a suggestion.
 * @constructor
 * @private
 */
SearchBox.AutocompleteListItem_ = function(document, item) {
  var li = new cr.ui.ListItem();
  li.itemInfo = item;

  var icon = document.createElement('div');
  icon.className = 'detail-icon';

  var text = document.createElement('div');
  text.className = 'detail-text';

  if (item.isHeaderItem) {
    icon.setAttribute('search-icon', '');
    text.innerHTML =
        strf('SEARCH_DRIVE_HTML', util.htmlEscape(item.searchQuery));
  } else {
    var iconType = FileType.getIcon(item.entry);
    icon.setAttribute('file-type-icon', iconType);
    // highlightedBaseName is a piece of HTML with meta characters properly
    // escaped. See the comment at fileBrowserPrivate.searchDriveMetadata().
    text.innerHTML = item.highlightedBaseName;
  }
  li.appendChild(icon);
  li.appendChild(text);
  return li;
};

/**
 * Updates the size related style.
 */
SearchBox.prototype.updateSizeRelatedStyle = function() {
  // Hide the search box if there is not enough space.
  this.element.classList.toggle(
      'too-short',
      this.element.clientWidth < 100);
};

/**
 * Clears the search query.
 */
SearchBox.prototype.clear = function() {
  this.inputElement.value = '';
  this.updateStyles_();
};

/**
 * Handles a focus event of the search box.
 * @private
 */
SearchBox.prototype.onFocus_ = function() {
  this.element.classList.toggle('has-cursor', true);
  this.inputElement.tabIndex = '99';  // See: go/filesapp-tabindex.
  this.autocompleteList.attachToInput(this.inputElement);
};

/**
 * Handles a blur event of the search box.
 * @private
 */
SearchBox.prototype.onBlur_ = function() {
  this.element.classList.toggle('has-cursor', false);
  this.inputElement.tabIndex = '-1';
  this.autocompleteList.detach();
};

/**
 * Handles a keydown event of the search box.
 * @private
 */
SearchBox.prototype.onKeyDown_ = function() {
  // Handle only Esc key now.
  if (event.keyCode != 27 || this.inputElement.value)
    return;
  this.inputElement.blur();
};

/**
 * Handles a click event of the search icon.
 * @private
 */
SearchBox.prototype.onIconClick_ = function() {
  this.inputElement.focus();
};

/**
 * Handles a dragenter event and refuses a drag source of files.
 * @param {DragEvent} event The dragenter event.
 * @private
 */
SearchBox.prototype.onDragEnter_ = function(event) {
  // For normal elements, they does not accept drag drop by default, and accept
  // it by using event.preventDefault. But input elements accept drag drop
  // by default. So disalbe the input element here to prohibit drag drop.
  if (event.dataTransfer.types.indexOf('text/plain') === -1)
    this.inputElement.style.pointerEvents = 'none';
};

/**
 * Handles a dragend event.
 * @private
 */
SearchBox.prototype.onDragEnd_ = function() {
  this.inputElement.style.pointerEvents = '';
};

/**
 * Updates styles of the search box.
 * @private
 */
SearchBox.prototype.updateStyles_ = function() {
  this.element.classList.toggle('has-text',
                                 !!this.inputElement.value);
  var width = this.textMeasure_.getWidth(this.inputElement.value) +
      16 /* Extra space to allow leeway. */;
  this.inputElement.style.width = width + 'px';
};


text:
\hypertarget{unionsocket__address}{}\section{socket\+\_\+address Union Reference}
\label{unionsocket__address}\index{socket\+\_\+address@{socket\+\_\+address}}
\subsection*{Public Attributes}
\begin{DoxyCompactItemize}
\item
struct sockaddr {\bfseries sa}\hypertarget{unionsocket__address_ab6a9b0bc545e839df7e06e5b6bff0891}{}\label{unionsocket__address_ab6a9b0bc545e839df7e06e5b6bff0891}

\item
struct sockaddr\+\_\+in {\bfseries sin}\hypertarget{unionsocket__address_af540a7224ea459c48bc6ec1ca592e55d}{}\label{unionsocket__address_af540a7224ea459c48bc6ec1ca592e55d}

\item
struct sockaddr {\bfseries sin6}\hypertarget{unionsocket__address_a923a2caba3cad046553b3632f7c2c571}{}\label{unionsocket__address_a923a2caba3cad046553b3632f7c2c571}

\end{DoxyCompactItemize}

The documentation for this union was generated from the following file\+:\begin{DoxyCompactItemize}
\item
Appserver/src/external/mongoose/mongoose.\+h\end{DoxyCompactItemize}


text:
package br.com.delogic.jnerator.test.entities;

public interface IsEntityId<T> {

    T getId();

    void setId(T obj);

}


text:
'''
Created on 05-Feb-2015

@author: Asawari.Vaidya
'''
from PythonNetBanxSDK.common.DomainObject import DomainObject

class ExtendedOptions(DomainObject):
    '''
    classdocs
    '''
    def __init__(self, obj):
        '''
        Constructor
        '''

        if obj is not None:
            self.setProperties(obj)
        else:
            pass

    '''
    Property Key
    '''
    def key(self, key):
        self.__dict__['key'] = key

    '''
    Property Value
    '''
    def value(self, value):
        self.__dict__['value'] = value


text:
The portscanner module is
an asynchronous JavaScript port scanner for Node.js.

Portscanner can check a port,
or range of ports,
for 'open' or 'closed' statuses.

## Install

```bash
npm install portscanner
```

## Usage

A brief example:

```javascript
var portscanner = require('portscanner')

// Checks the status of a single port
portscanner.checkPortStatus(3000, '127.0.0.1', function(error, status) {
  // Status is 'open' if currently in use or 'closed' if available
  console.log(status)
})

// Find the first available port. Asynchronously checks, so first port
// determined as available is returned.
portscanner.findAPortNotInUse(3000, 3010, '127.0.0.1', function(error, port) {
  console.log('AVAILABLE PORT AT: ' + port)
})

// Find the first port in use or blocked. Asynchronously checks, so first port
// to respond is returned.
portscanner.findAPortInUse(3000, 3010, '127.0.0.1', function(error, port) {
  console.log('PORT IN USE AT: ' + port)
})
```

The example directory contains a more detailed example.

## Test

```sh
npm test
```

## Future

Please create issues or pull requests
for port scanning related features
you'd like to see included.

## License (MIT)

[MIT](LICENSE)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="60dip"
    android:orientation="horizontal" >

    <ProgressBar
        android:layout_width="40dip"
        android:layout_height="40dip"
        android:layout_margin="10dip" />

    <TextView
        android:id="@+id/mam_progress_dialog_text"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="left|center_vertical"
        android:textColor="@color/white" />

</LinearLayout>


text:
{-# LANGUAGE OverloadedStrings #-}

module Comic.Translate where

import Control.Exception as E
import Control.Lens
import Data.Aeson
import Data.Aeson.Lens (_Array, key)
import qualified Data.Text as T
import Data.Vector ((!))
import Network.HTTP.Base (urlEncodeVars)
import Network.Wreq (get, responseBody)
import Network.HTTP.Client (HttpException)

type SourceLanguage = T.Text

type DestinationLanguage = T.Text

type OriginalText = T.Text

class Translator a  where
    -- | Translate text from the source language to the destination language.
    translate
        :: a
        -> SourceLanguage
        -> DestinationLanguage
        -> OriginalText
        -> IO T.Text

-- | Translator which returns the text in its original form. A dummy translator implementation.
data NoopTranslator =
    NoopTranslator

instance Translator NoopTranslator where
    translate _ _ _ originalText = return originalText

-- | Translate text from the source language to the destination language using Yandex web service.
data YandexClient = YandexClient
    { apiKey :: String
    }

instance Translator YandexClient where
    translate translator = yandexTranslate apiKey
      where
        (YandexClient apiKey) = translator

yandexTranslate apiKey sourceLang destLang text =
    (do let translateParams =
                urlEncodeVars
                    [ ("key", apiKey)
                    , ( "lang"
                      , (T.unpack sourceLang) ++ "-" ++ (T.unpack destLang))
                    , ("text", T.unpack text)]
        r <-
            get $ "https://translate.yandex.net/api/v1.5/tr.json/translate?" ++
            translateParams
        let textVec = r ^. responseBody . key "text" . _Array
        return $ unpackString $ textVec ! 0) `E.catch`
    handler
  where
    unpackString (String s) = s
    handler :: HttpException -> IO T.Text
    handler _ = return ""


text:
"""
python package to handle RPN calculation.
RPN: Reverse Polish Notation
"""

from __future__ import division, print_function
import decimal
import math

decimal.getcontext().prec = 20

try:
    basestring
except NameError:
    basestring = str

class Rpn(object):
    """Class to handle RPN calculation.

    Parameters
    ----------
    istr : str
        String of rpn expression.
    delimiter : str
        Delimiter of *istr*.

    Examples
    --------
    >>> from rpn import Rpn
    >>> rpnstr = '10 1 2 + sin *'
    >>> rpnins = Rpn(rpnstr)
    >>> result = rpnins.solve()
    1.4112000805986722
    >>> # or:
    >>> result = Rpn.solve_rpn(rpnstr)
    """
    def __init__(self, istr, delimiter=None):
        self.opslist = istr.lower().split(delimiter)
        self.opslist.reverse()

        # initial stored variables, will keep user-defined ones by 'sto'.
        self.variables = {'pi': math.pi}

        # initial stored operations
        self.operators = ['+', '-', '*', '/',
                          'sin', 'cos', 'tan',
                          'sqrt',
                          'pop', 'swap',
                          'sto',
        ]
        opfun = [self.fadd, self.fsub, self.fmul, self.fdiv,
                 self.fsin, self.fcos, self.ftan, self.fsqrt,
                 self.fpop, self.fswap, self.fsto,
        ]
        self.opdict = dict(zip(self.operators, opfun))

    def fadd(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        return b + a

    def fsub(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        return b - a

    def fmul(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        return  b * a

    def fdiv(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        if a == 0:
            print("The dividend must not be zero.")
        return b / a

    def fsin(self):
        a = float(self.tmpopslist.pop())
        return math.sin(a)

    def fcos(self):
        a = float(self.tmpopslist.pop())
        return math.cos(a)

    def ftan(self):
        a = float(self.tmpopslist.pop())
        return math.tan(a)

    def fsqrt(self):
        a = float(self.tmpopslist.pop())
        if a < 0:
            print('Input of sqrt must be a positive number.')
        return math.sqrt(a)

    def fpop(self):
        self.tmpopslist.pop()
        return None

    def fswap(self):
        a = self.tmpopslist.pop()
        b = self.tmpopslist.pop()
        self.tmpopslist.append(a)
        self.tmpopslist.append(b)
        return None

    def fsto(self):
        """sto operation.
        """
        a = float(self.tmpopslist.pop())
        var = self.opslist.pop()
        if isinstance(var, basestring):
            self.variables.update({var: a})
            return a
        else:
            print("Can only sto into a variable.")
            return 'ERROR'

    def __str__(self):
        return ' '.join(reversed(self.opslist))

    @classmethod
    def solve_rpn(cls, istr):
        """Solve rpn expression.

        USAGE: solve_rpn(rpnstr)

        Parameters
        ----------
        rpnstr : str
            String of rpn expression.

        Returns
        -------
        ret : float
            Calculated result.
        """
        return cls(istr).solve()

    def solve(self):
        """Solve rpn expression, return None if not valid."""
        popflag = True
        self.tmpopslist = []
        while True:
            while self.opslist and popflag:
                op = self.opslist.pop()
                if self.is_variable(op):
                    op = self.variables.get(op)
                if self.is_operator(op):
                    popflag = False
                    break
                self.tmpopslist.append(op)

            # operations
            tmpr = self._get_temp_result(op)
            if tmpr == 'ERROR':
                return None

            if tmpr is not None:
                self.opslist.append('{r:.20f}'.format(r=tmpr))

            if len(self.tmpopslist) > 0 or len(self.opslist) > 1:
                popflag = True
            else:
                break

        return float(self.opslist[0])

    def _get_temp_result(self, op):
        try:
            tmpr = self.opdict[op]()
        except (IndexError, ValueError, KeyError, ZeroDivisionError):
            tmpr = 'ERROR'
        return tmpr

    def is_operator(self, s):
        """Test if *s* is a valid operation.
        """
        return s in self.operators

    def is_variable(self, s):
        """Test if *s* is a defined variable (attribute).
        """
        return s in self.variables

def solve_rpn(istr):
    """Solve rpn expression.

    USAGE: solve_rpn(rpnstr)

    Parameters
    ----------
    rpnstr : str
        String of rpn expression.

    Returns
    -------
    ret : float
        Calculated result.
    """
    return Rpn(istr).solve()

def test():
    istr1 = '1 2 + 3 * sin'
    rpnins1 = Rpn(istr1)
    print(rpnins1)
    print(rpnins1.solve())

    istr2 = '1 2 + 3 * cos'
    rpnins2 = Rpn(istr2)
    print(rpnins2)
    print(rpnins2.solve())

    istr3 = '10,3,1,2,/,*,-,tan'
    rpnins3 = Rpn(istr3, ',')
    print(rpnins3)
    print(rpnins3.solve())

    istr4 = '0.2 10.24 pi * 180 / * 10.24 pi * 180 / sin /'
    rpnins4 = Rpn(istr4)
    print(rpnins4)
    print(rpnins4.solve())

    istr5 = '0.2 10.24 pi * 180 / * 10.24 pi * 180'
    rpnins5 = Rpn(istr5)
    print(rpnins5)
    print(rpnins5.solve())

def main():
    test()

if __name__ == '__main__':
    main()


text: please look at the [Docker SELinux Playground on github.com/de-wiring/docker-selinux-playground](https://github.com/de-wiring/docker-selinux-playground)


text:
@interface PodsDummy_Pods_luckybeastTests : NSObject
@end
@implementation PodsDummy_Pods_luckybeastTests
@end


text:
<!DOCTYPE html>

    <title>Search Input</title>
     <meta name=viewport content="width=device-width, maximum-scale=1.0, user-scalable=no" />
     <link rel="author" title="Fabrice Clari" href="mailto:f.clari@inno-group.com">
     <link rel="author" title="Dimitri Bocquet" href="mailto:Dimitri.Bocquet@mosquito-fp7.eu">
    <link rel="help" href="https://html.spec.whatwg.org/multipage/#the-input-element">

Search Input

      <input type="search" style="display:none" placeholder="Search..." />


text:
using System;

namespace ReallySimpleProxy.RequestProxying
{
    public interface IRequestModifier
    {
        void Modify(string outgoingUri, Nancy.Request incomingRequest, System.Net.HttpWebRequest outgoingRequest);
    }
}


text:
module FlattenRecord
  extend ActiveSupport::Concern
  extend ActiveSupport::Autoload

  module Meta
    def self.autoload_nodes
      path =  "#{File.dirname(__FILE__)}/flatten_record/meta/"
      dir = Dir["#{path}*.rb"]

      dir.each do|file|
        file_name = file.gsub(path, '')[0..-4]
        klass_name = file_name.camelize.to_sym

        autoload klass_name, "flatten_record/meta/#{file_name}"
      end
    end

    autoload_nodes
  end

  autoload :Flattener, 'flatten_record/flattener'
  autoload :Definition, 'flatten_record/definition'
end


text:
import datetime
from bson import ObjectId
import yaml
import os
import logging

_logger = logging.getLogger(__name__)

FIXTURES_HOME = 'test/fixtures/'

def oid_con(seed):
    value = int(seed)
    dt = datetime.datetime.fromtimestamp(value)
    return ObjectId.from_datetime(dt)

def setup_data(paths, db):
    def object_id_constructor(loader, seed):
        seed = loader.construct_scalar(seed)
        return oid_con(seed)

    yaml.add_constructor(u'!oid', object_id_constructor)

    for path in paths:
        fixtures = yaml.load(file(os.path.join(FIXTURES_HOME, path)))
        if 'configuration' in fixtures:
            conf = fixtures.pop('configuration')
            collection = conf['collection']
            if conf.get('drop', False):
                db[collection].drop()
            for key in fixtures:
                db[collection].insert(fixtures[key])

def teardown_data(paths, db):
    for path in paths:
        fixtures = yaml.load(file(os.path.join(FIXTURES_HOME, path)))
        if 'configuration' in fixtures:
            conf = fixtures.pop('configuration')
            collection = conf['collection']
            if conf.get('drop', False):
                db[collection].drop()
            else:
                # don't drop collection but remove inserted items
                for key in fixtures:
                    db[collection].delete(fixtures[key])


text:
package net.uncontended.precipice.pattern;

@FunctionalInterface
public interface SequenceFactory<C> {
    WritableSequence<C> getSequence(int size);
}


text:
var ImportJSONForm = React.createClass({
	getInitialState: function() {
   		return {
			fileData: false
		};
	},

	cancel: function(event) {
		event.preventDefault();
		this.props.cancel(this.props.modalName)
	},

	submit: function(event) {
		event.preventDefault();
		var submitPayload = "";

		var file = this.state.fileData.files[0];

		var reader = new FileReader();
    	reader.readAsText(file);

    	reader.onload = function(event) {
    		submitPayload = reader.result;
    		this.props.submit(this.props.modalName, submitPayload)
    	}.bind(this)
	},

	onFormChange: function(event) {
		var elementName = event.target.attributes.name.value;
		if (elementName == "uploadField"){
			this.setState({fileData: event.target})
		}
	},

	render: function() {
		var buttonClassString = "affirmative";
		var fileName = this.state.fileName;
		if (fileName == false) {
			buttonClassString += " disabled";
		}
		return (
			<form id="importJSON">

Import Project JSON

					<button onClick={this.cancel}>×</button>

Choose a JSON file to import…

					<input type="file" name="uploadField" accept="application/json" onChange={this.onFormChange}/>

					<input type="button" className={buttonClassString} onClick={this.submit} value="Import"/>
					<input type="button" onClick={this.cancel} value="Cancel"/>

			</form>
		)
	}

});

var SaveAsModuleForm = React.createClass({
	getInitialState: function() {
   		return {
			name: this.props.projectName,
			description: "",
			categories: []
		};
	},

	cancel: function(event) {
		event.preventDefault();
		this.props.cancel(this.props.modalName)
	},

	submit: function(event) {
		event.preventDefault();
		var submitPayload = {
			name: this.state.name,
			description: this.state.description,
			categories: this.state.categories,
			refProject: this.props.projectID
		}
		this.props.submit(this.props.modalName, submitPayload)
	},

	onFormChange: function(event) {
		var elementName = event.target.attributes.name.value;
		if (elementName == "name"){this.setState({name: event.target.value})}
		else if (elementName == "description"){this.setState({description: event.target.value})}
		else {
			var newArray = _.cloneDeep(this.state.categories);
			if (this.state.categories.indexOf(elementName) >= 0){
				//take away category from arry
				_.pull(newArray, elementName)
			}
			else {
				//add category to array
				newArray.push(elementName)
			}
			this.setState({categories: newArray})
		}
	},

	render: function() {
		var buttonClassString = "affirmative";
		var invalidClassString = "";
		if (this.state.name == "") {
			buttonClassString += " disabled";
			invalidClassString = "invalid"
		}
		var categoryItems = [];
		for (var category in this.props.categories) {

			if (category == "uncategorised") {continue}
			categoryItems.push(

      				<input type="checkbox" name={category} value={this.state.analytics} onChange={this.onFormChange}/>
      				{category}

      		);
		}

		return (
		<form id="saveAsModule">

Publish as IO Module

				<button onClick={this.cancel}>×</button>

Name

				<input type="text" className={invalidClassString} name="name" value={this.state.name} onChange={this.onFormChange}/>

Description

				<textarea name="description" value={this.state.description} onChange={this.onFormChange}/>

Categories

Select or leave uncategorised.

				{categoryItems}

				<input type="button" className={buttonClassString} onClick={this.submit} value="Publish"/>
				<input type="button" onClick={this.cancel} value="Cancel"/>

		</form>
		)
	}
});

var LibrariesForm = React.createClass({
	getInitialState: function() {
   		return {
			modulesSrc: this.props.modulesSrc,
			projectsSrc: this.props.projectsSrc
		};
	},

	cancel: function(event) {
		event.preventDefault();
		this.props.cancel(this.props.modalName)
	},

	submit: function(event) {
		event.preventDefault();

		var submitPayload = {
			modulesSrc: this.state.modulesSrc,
			projectsSrc: this.state.projectsSrc
		}
		this.props.submit(this.props.modalName, submitPayload)
	},

	onFormChange: function(event) {
		var elementName = event.target.attributes.name.value;
		if (elementName == "moduleSrc"){
			this.setState({
				modulesSrc: event.target.value
			})
		}
		else if (elementName == "projectsSrc"){
			this.setState({
				projectsSrc: event.target.value
			})
		}
	},

	render: function() {
		var invalidClassString = "";
		var buttonClassString = "affirmative";
		var validationMessageString = "";
		if (this.state.modulesSrc == this.state.projectsSrc) {
			invalidClassString = "invalid";
			buttonClassString += " disabled";
			validationMessageString = "Locations for Projects and IO Modules must be different"
		}
		return (
		<form id="librariesForm">

Data Repositories

				<button onClick={this.cancel}>×</button>

Provide locations for Projects and IO Modules.

Projects

				<input className={invalidClassString} type="text" name="projectsSrc" value={this.state.projectsSrc} onChange={this.onFormChange}/>

e.g. https://io-visor-projects.firebaseio.com

IO Modules

				<input className={invalidClassString} type="text" name="moduleSrc" value={this.state.modulesSrc} onChange={this.onFormChange}/>

e.g. https://io-visor-modules.firebaseio.com

				{validationMessageString}
				<input type="button" className={buttonClassString}  onClick={this.submit} value="Save"/>
				<input type="button" onClick={this.cancel} value="Cancel"/>

		</form>
		)
	}
});

var IOVisorForm = React.createClass({
	getInitialState: function() {
   		return {
			iovisorLoc: this.props.iovisorLoc,
			invalidClassString: "",
			buttonClassString: "affirmative",
			validationMessageString: ""
		};
	},

	cancel: function(event) {
		event.preventDefault();
		this.props.cancel(this.props.modalName);
	},

	submit: function(event) {
		event.preventDefault();

		var submitPayload = {
			iovisorLoc: this.state.iovisorLoc
		}

		this.setState({
			buttonClassString: "affirmative disabled",
			validationMessageString: "Checking IO Visor path..."
		});

		if (this.state.iovisorLoc != ""){
			$.ajax({
				url: this.state.iovisorLoc + "/modules/"
			}).then(
				function(data) {
					this.props.submit(this.props.modalName, submitPayload)
				}.bind(this),
				function() {
					this.setState({
						invalidClassString: "invalid",
						buttonClassString: "affirmative disabled",
						validationMessageString: "IO Visor path invalid"
					});
				}.bind(this)
			);
		} else{
			this.setState({
				invalidClassString: "",
				buttonClassString: "affirmative",
				validationMessageString: ""
			});
			this.props.submit(this.props.modalName, submitPayload);
		}
	},

	onFormChange: function(event) {
		var elementName = event.target.attributes.name.value;
		if (elementName == "iovisorLoc"){
			this.setState({
				iovisorLoc: event.target.value,
				invalidClassString: "",
				buttonClassString: "affirmative",
				validationMessageString: ""
			})
		}
	},

	render: function() {
		return (
		<form id="IOVisorForm">

IO Visor Settings

				<button onClick={this.cancel}>×</button>

Provide Path for IO Visor IO Modules.

IO Modules

				<input className={this.state.invalidClassString} type="text" name="iovisorLoc" value={this.state.iovisorLoc} onChange={this.onFormChange}/>

e.g. http://localhost:5000 or leave empty for none

				{this.state.validationMessageString}
				<input type="button" className={this.state.buttonClassString}  onClick={this.submit} value="Save"/>
				<input type="button" onClick={this.cancel} value="Cancel"/>

		</form>
		)
	}
});

var ModalDialogue = React.createClass({
	cancel: function() {
		this.props.cancelModal()
	},

	submit: function(modalName, payload) {
		this.props.submitModal(modalName, payload)
	},

	render: function() {
		var modal;

		if (this.props.modalName == "importJSON"){
			modal = (

	  					<ImportJSONForm
	  						modalName = {this.props.modalName}
	  						cancel = {this.cancel}
	  						submit = {this.submit}/>

			)
		}

		if (this.props.modalName == "librariesSettings"){
			modal = (

	  					<LibrariesForm
	  						modalName = {this.props.modalName}
	  						projectsSrc = {this.props.projectsSrc}
	  						modulesSrc = {this.props.modulesSrc}
	  						cancel = {this.cancel}
	  						submit = {this.submit}/>

			)
		}

		if (this.props.modalName == "IOVisorSettings"){
			modal = (

	  					<IOVisorForm
	  						modalName = {this.props.modalName}
	  						iovisorLoc = {this.props.iovisorLoc}
	  						cancel = {this.cancel}
	  						submit = {this.submit}/>

			)
		}

		if (this.props.modalName == "saveAsModule"){
			modal = (

	  					<SaveAsModuleForm
	  						modalName = {this.props.modalName}
	  						categories = {this.props.categories}
	  						cancel = {this.cancel}
	  						submit = {this.submit}
	  						projectID = {this.props.projectID}
	  						projectName = {this.props.selectedProject.name}/>

			)
		}
		return modal
	},
});


text:
package com.spotify.styx;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpResponseException;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.model.ServiceAccountKey;
import com.spotify.styx.monitoring.Stats;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class ServiceAccountKeyManagerTest {

  @Mock(answer = Answers.RETURNS_DEEP_STUBS)
  private Iam iam;

  @Mock
  private Iam.Projects.ServiceAccounts serviceAccounts;

  @Mock
  private Iam.Projects.ServiceAccounts.Keys keys;

  @Mock
  private Iam.Projects.ServiceAccounts.Keys.Delete delete;

  @Mock
  private Iam.Projects.ServiceAccounts.Keys.Get get;

  @Mock
  private Iam.Projects.ServiceAccounts.Keys.Create create;

  @Mock
  private Stats stats;

  private ServiceAccountKeyManager sakm;

  private static final GoogleJsonResponseException INTERNAL_SERVER_ERROR =
      new GoogleJsonResponseException(
          new HttpResponseException.Builder(500, "Internal Server Error", new HttpHeaders()),
          new GoogleJsonError().set("status", "INTERNAL_SERVER_ERROR"));

  private static final GoogleJsonResponseException PERMISSION_DENIED =
      new GoogleJsonResponseException(
          new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()),
          new GoogleJsonError().set("status", "PERMISSION_DENIED"));

  private static final GoogleJsonResponseException NOT_FOUND =
      new GoogleJsonResponseException(
          new HttpResponseException.Builder(404, "Not found", new HttpHeaders()),
          new GoogleJsonError().set("status", "NOT_FOUND"));

  @Before
  public void setUp() throws Exception {
    when(iam.projects().serviceAccounts()).thenReturn(serviceAccounts);
    when(serviceAccounts.keys()).thenReturn(keys);
    when(keys.get(any())).thenReturn(get);
    when(keys.delete(any())).thenReturn(delete);
    when(keys.create(any(), any())).thenReturn(create);

    sakm = new ServiceAccountKeyManager(iam, stats);
  }

  @Test
  public void keyExistsTreatsPermissionDeniedAsNotFound() throws Exception {
    when(get.execute()).thenThrow(PERMISSION_DENIED);
    assertThat(sakm.keyExists("foo"), is(false));
    verify(iam.projects().serviceAccounts().keys()).get("foo");
  }

  @Test
  public void keyExistsReturnsFalseForNotFound() throws Exception {
    when(get.execute()).thenThrow(NOT_FOUND);
    assertThat(sakm.keyExists("foo"), is(false));
    verify(iam.projects().serviceAccounts().keys()).get("foo");
  }

  @Test(expected = GoogleJsonResponseException.class)
  public void keyExistsShouldThrowUnknownExceptions() throws Exception {
    when(get.execute()).thenThrow(INTERNAL_SERVER_ERROR);
    sakm.keyExists("foo");
    verify(iam.projects().serviceAccounts().keys()).get("foo");
  }

  @Test(expected = GoogleJsonResponseException.class)
  public void deleteKeyShouldThrowUnknownExceptions() throws Exception {
    when(delete.execute()).thenThrow(INTERNAL_SERVER_ERROR);
    sakm.deleteKey("foo");
    verify(iam.projects().serviceAccounts().keys()).delete("foo");
  }

  @Test
  public void tryDeleteKeyShouldIgnoreUnknownExceptions() throws Exception {
    when(delete.execute()).thenThrow(INTERNAL_SERVER_ERROR);
    sakm.tryDeleteKey("foo");
    verify(iam.projects().serviceAccounts().keys()).delete("foo");
  }

  @Test
  public void deleteKeyShouldIgnorePermissionDenied() throws Exception {
    when(delete.execute()).thenThrow(PERMISSION_DENIED);
    sakm.deleteKey("foo");
    verify(iam.projects().serviceAccounts().keys()).delete("foo");
  }

  @Test
  public void deleteKeyShouldIgnoreNotFound() throws Exception {
    when(delete.execute()).thenThrow(NOT_FOUND);
    sakm.deleteKey("foo");
    verify(iam.projects().serviceAccounts().keys()).delete("foo");
  }

  @Test
  public void createKeyShouldBeRecorded() throws Exception {
    ServiceAccountKey key = new ServiceAccountKey();
    when(create.execute()).thenReturn(key);
    sakm.createJsonKey("SA");
    verify(stats).recordKeyCreation();
  }

  @Test
  public void deleteKeyShouldBeRecorded() throws Exception {
    sakm.deleteKey("SA");
    verify(stats).recordKeyDeletion();
  }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('job', '0049_auto_20180927_1531'),
        ('recipe', '0030_auto_20181024_1607'),
    ]

    operations = [
        migrations.CreateModel(
            name='RecipeTypeJobLink',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('job_type', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='job_types_for_recipe_type', to='job.JobType')),
                ('recipe_type', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='recipe_types_for_job_type', to='recipe.RecipeType')),
            ],
            options={
                'db_table': 'recipe_type_job_link',
            },
        ),
        migrations.CreateModel(
            name='RecipeTypeSubLink',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('recipe_type', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='parent_recipe_type', to='recipe.RecipeType')),
                ('sub_recipe_type', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='sub_recipe_type', to='recipe.RecipeType')),
            ],
            options={
                'db_table': 'recipe_type_sub_link',
            },
        ),
        migrations.AlterUniqueTogether(
            name='recipetypesublink',
            unique_together=set([('recipe_type', 'sub_recipe_type')]),
        ),
        migrations.AlterUniqueTogether(
            name='recipetypejoblink',
            unique_together=set([('recipe_type', 'job_type')]),
        ),
    ]


text:
/* $Header: pentry.c,v 2.2 89/05/03 09:51:41 ceriel Exp $ */
/*
 * (c) copyright 1983 by the Vrije Universiteit, Amsterdam, The Netherlands.
 *
 *          This product is part of the Amsterdam Compiler Kit.
 *
 * Permission to use, sell, duplicate or disclose this software must be
 * obtained in writing. Requests for such permissions may be sent to
 *
 *      Dr. Andrew S. Tanenbaum
 *      Wiskundig Seminarium
 *      Vrije Universiteit
 *      Postbox 7161
 *      1007 MC Amsterdam
 *      The Netherlands
 *
 */

/* Author: J.W. Stevenson */

#include	<pc_file.h>

extern struct file	**_extfl;
extern			_wrs();
extern			_wrz();
extern			_wln();

procentry(name) char *name; {
	struct file *f;

	f = _extfl[1];
	_wrs(5,"call ",f);
	_wrz(name,f);
	_wln(f);
}


text:
namespace app {
namespace Uno {
namespace UX {

struct Property__string;

struct Property__string__uType : ::uClassType
{
    void(*__fp_OnAddListener)(Property__string*, ::uDelegate*);
    ::uString*(*__fp_OnGet)(Property__string*);
    void(*__fp_OnRemoveListener)(Property__string*, ::uDelegate*);
    void(*__fp_OnSet)(Property__string*, ::uString*, ::uObject*);
};

Property__string__uType* Property__string__typeof();

void Property__string___ObjInit(Property__string* __this);
void Property__string__add_ValueChanged(Property__string* __this, ::uDelegate* value);
::uString* Property__string__Get(Property__string* __this);
::uString* Property__string__GetRestState(Property__string* __this);
void Property__string__OnAddListener(Property__string* __this, ::uDelegate* listener);
::uString* Property__string__OnGet(Property__string* __this);
void Property__string__OnRemoveListener(Property__string* __this, ::uDelegate* listener);
void Property__string__OnSet(Property__string* __this, ::uString* value, ::uObject* origin);
void Property__string__remove_ValueChanged(Property__string* __this, ::uDelegate* value);
void Property__string__RetainRestState(Property__string* __this);
void Property__string__Set(Property__string* __this, ::uString* value, ::uObject* origin);
void Property__string__SetRestState(Property__string* __this, ::uString* value, ::uObject* origin);

struct Property__string : ::uObject
{
    bool _hasRestState;
    ::uStrong< ::uString*> _restState;

    void _ObjInit() { Property__string___ObjInit(this); }
    void add_ValueChanged(::uDelegate* value) { Property__string__add_ValueChanged(this, value); }
    ::uString* Get() { return Property__string__Get(this); }
    ::uString* GetRestState() { return Property__string__GetRestState(this); }
    void OnAddListener(::uDelegate* listener) { (((Property__string__uType*)this->__obj_type)->__fp_OnAddListener)(this, listener); }
    ::uString* OnGet() { return (((Property__string__uType*)this->__obj_type)->__fp_OnGet)(this); }
    void OnRemoveListener(::uDelegate* listener) { (((Property__string__uType*)this->__obj_type)->__fp_OnRemoveListener)(this, listener); }
    void OnSet(::uString* value, ::uObject* origin) { (((Property__string__uType*)this->__obj_type)->__fp_OnSet)(this, value, origin); }
    void remove_ValueChanged(::uDelegate* value) { Property__string__remove_ValueChanged(this, value); }
    void RetainRestState() { Property__string__RetainRestState(this); }
    void Set(::uString* value, ::uObject* origin) { Property__string__Set(this, value, origin); }
    void SetRestState(::uString* value, ::uObject* origin) { Property__string__SetRestState(this, value, origin); }
};

}}}

#endif


text:
'''
Defines the methods/endpoints (the views) of the userprofile service.
This defines the interaction points, but the actual logic is treated
by the :mod:`controller`.
'''

#Flask and modules
from flask import Blueprint, jsonify, request, make_response
from flask.ext.api import status
#from flask.helpers import make_response

#Exceptions and errors
from flask.ext.api.exceptions import AuthenticationFailed, ParseError
#from sqlalchemy.orm.exc import NoResultFound
from .errors import *

#Python modules
#import datetime
#import json
#import time
import simplejson

#Import controller
from userprofile_app import controller

#Extensions
from .extensions import LOG

#Userprofile blueprint
userprofile = Blueprint('userprofile', __name__, url_prefix='/v1')

######################################################
# Handshake
######################################################

@userprofile.route('/version')
def get_version():
    '''
    Returns the current version of the API.
    '''
    return jsonify(version='v1'), status.HTTP_200_OK

######################################################
# user management
######################################################

@userprofile.route('/users/<userid>')
def get_user(userid):
    error={}
    error["message"] = "Forbidden"
    error["code"] = 403
    return jsonify(error=error), status.HTTP_403_FORBIDDEN

@userprofile.route('/users', methods = ['POST'])
def new_user():
    '''
    Creates a new user with the data received from a request.

    :<json string username:
    :<json string password:
    :status 201: Successful request
    :status 400: Not JSON object or missing parameters
    :status 401: Wrong credentials
    '''
    #Check if request is json and contains all the required fields
    required_fields = ["username", "password"]

    error = {}

    if not request.json or not (set(required_fields).issubset(request.json)):
        error["message"] = "Invalid request."
        error["code"] = 400
        return jsonify(error=error), status.HTTP_400_BAD_REQUEST

    else:

        try:
            username = request.json["username"]
            password = request.json["password"]

            #############################
            # Success
            #############################

            user = controller.create_user(username, password)
            user_response= simplejson.dumps(user.as_hateoas(), indent=2)

            response = make_response(user_response, status.HTTP_201_CREATED)
            response.headers["X-Total-Count"] = 1
            response.headers["Content-Type"] = "application/json"

            return response

        except AuthenticationFailed:
            error["message"] = "Could not authenticate. Check your credentials."
            error["code"] = 401
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED

        except UsernameExistsException:
            error["message"] = "Username already in database."
            error["code"] = 409
            return jsonify(error=error), status.HTTP_409_CONFLICT

        except ParseError:
            error["message"] = "Invalid parameters."
            error["code"] = 400
            return jsonify(error=error), status.HTTP_400_BAD_REQUEST

######################################################
# Session
######################################################

@userprofile.route('/sessions', methods = ['POST'])
def new_session():
    '''
    Creates a new gaming session. Requires authentication by providing a valid username/password.

    TODO: Switch to token authentication

    :<json string username: Username of the user who is using the session
    :<json string password: Password for authenticating
    :status 201: Successful request
    :status 400: Not JSON object or missing parameters
    :status 401: Wrong credentials
    '''
    #Check if request is json and contains all the required fields
    required_fields = ["username", "password"]

    error = {}

    if not request.json or not (set(required_fields).issubset(request.json)):
        error["message"] = "Invalid request."
        error["code"] = 400
        return jsonify(error=error), status.HTTP_400_BAD_REQUEST

    else:
        try:

            #############################
            # Success
            #############################

            username = request.json["username"]
            password = request.json["password"]

            user = controller.user_authenticate(username, password)

            action = "get_session"

            if (controller.is_authorized(user, action)):

                gamingsession = controller.new_session(username)
                gamingsession_response = simplejson.dumps(gamingsession.as_hateoas(), indent=2)
                response = make_response(gamingsession_response, status.HTTP_201_CREATED)
                response.headers["X-Total-Count"] = 1
                response.headers["Content-Type"] = "application/json"

                return response
                #return jsonify({'sessionid': new_sessionid}), status.HTTP_201_CREATED

            else:
                error["message"] = "You are not authorized to perform this action."
                error["code"] = 401
                return jsonify(error=error), status.HTTP_401_UNAUTHORIZED

        except AuthenticationFailed:
            error["message"] = "Could not authenticate. Check your credentials."
            error["code"] = 401
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED

@userprofile.route('/sessions/<sessionid>')
def get_session(sessionid):
    '''
    Get information about the sessionid.

    TODO: Implement some kind of authentication and permission system here to
    restrict access to retrieving user information from a sessionid.

    :param sessionid:
    :status 200: Successful request
    :status 400: Not JSON object or missing parameters
    :status 401: Wrong credentials
    :status 404: Sessionid does not exist
    '''

#     required_fields = ["sessionid"]
#     if not request.json or not (set(required_fields).issubset(request.json)):
#         return jsonify({'message': 'Invalid request. Please try again.'}), status.HTTP_400_BAD_REQUEST
#     else:

    error = {}

    if not controller._is_uuid_valid(sessionid):
        error["message"] = "Invalid request."
        error["code"] = 400
        return jsonify(error=error), status.HTTP_400_BAD_REQUEST

    else:
        session = {}
        inactive = False
        if ("inactive" in request.args):
            if request.args["inactive"].lower() == "true":
                inactive = True
        try:

            #############################
            # Success
            #############################

            gamingsession = controller.get_session(sessionid, inactive)

            gamingsession_response = simplejson.dumps(gamingsession.as_hateoas(), indent=2)
            response = make_response(gamingsession_response, status.HTTP_200_OK)
            response.headers["X-Total-Count"] = 1
            response.headers["Content-Type"] = "application/json"

            return response

        except UserNotFoundException:
            error["message"] = "User not found."
            error["code"] = 404
            return jsonify(error=error), status.HTTP_404_NOT_FOUND

        except SessionidNotFoundException:
            error["message"] = "SessionID not found."
            error["code"] = 404
            return jsonify(error=error), status.HTTP_404_NOT_FOUND

        except AuthenticationFailed:
            error["message"] = "Could not authenticate. Check your credentials."
            error["code"] = 401
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED

@userprofile.route('/sessions/<sessionid>', methods = ['DELETE'])
def delete_session(sessionid):
    '''
    Marks the session as inactive.

    TODO: Implement some kind of authentication and permission system here to
    restrict access to deleting a sessionid.

    :param sessionid:
    :status 204: Deleted successfully
    :status 400: Bad parameters (badly formed sessionid)
    :status 401: Wrong credentials
    :status 404: Sessionid does not exist
    '''
    error = {}

    if not controller._is_uuid_valid(sessionid):
        error["message"] = "Invalid request."
        error["code"] = 400
        return jsonify(error=error), status.HTTP_400_BAD_REQUEST

    else:
        try:
            #############################
            # Success
            #############################

            controller.delete_session(sessionid)

            return "", status.HTTP_204_NO_CONTENT

        except SessionidNotFoundException:
            error["message"] = "SessionID not found."
            error["code"] = 404
            return jsonify(error=error), status.HTTP_404_NOT_FOUND

        except AuthenticationFailed:
            error["message"] = "Could not authenticate. Check your credentials."
            error["code"] = 401
            return jsonify(error=error), status.HTTP_401_UNAUTHORIZED


text:
module Awspec::Type
  class Ec2 < Base
    attr_reader :client

    def initialize(id)
      super
      @client = @ec2_client
      @resource = find_ec2(id)
      @id = @resource[:instance_id] if @resource
    end

    states = %w(
      pending running shutting-down
      terminated stopping stopped
    )

    states.each do |state|
      define_method state.tr('-', '_') + '?' do
        @resource[:state][:name] == state
      end
    end

    def has_eip?(ip_address = nil)
      option = {
        filters: [{ name: 'instance-id', values: [@id] }]
      }
      option[:public_ips] = [ip_address] if ip_address
      ret = @ec2_client.describe_addresses(option)
      return ret[:addresses].count == 1 if ip_address
      return ret[:addresses].count > 0 unless ip_address
    end

    def has_security_group?(sg_id)
      sgs = @resource[:security_groups]
      ret = sgs.find do |sg|
        sg[:group_id] == sg_id || sg[:group_name] == sg_id
      end
      return true if ret
      sg2 = find_security_group(sg_id)
      return false unless sg2.tag_name == sg_id
      sgs.find do |sg|
        sg[:group_id] == sg2[:group_id]
      end
    end

    def has_ebs?(volume_id)
      blocks = @resource[:block_device_mappings]
      ret = blocks.find do |block|
        next false unless block[:ebs]
        block[:ebs][:volume_id] == volume_id
      end
      return true if ret
      blocks2 = find_ebs(volume_id)
      blocks2[:attachments].find do |attachment|
        attachment.instance_id == @id
      end
    end
  end
end


text:
package org.apache.camel.component.sql.stored;

import org.apache.camel.builder.RouteBuilder;

public class ProducerClasspathTest extends ProducerTest {

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                // required for the sql component
                getContext().getComponent("sql-stored", SqlStoredComponent.class).setDataSource(db);

                from("direct:query").to("sql-stored:classpath:sql/selectStored.sql").to("mock:query");
            }
        };
    }

}


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.
-->

<tomcat:web-app xmlns:tomcat="http://geronimo.apache.org/xml/ns/j2ee/web/tomcat-1.1">
    <dep:environment xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.1">
      <dep:moduleId>
        <dep:groupId>geronimo</dep:groupId>
        <dep:artifactId>tomcat-test</dep:artifactId>
        <dep:version>1.0</dep:version>
        <dep:type>war</dep:type>
      </dep:moduleId>
      <dep:dependencies/>
      <dep:hidden-classes/>
      <dep:non-overridable-classes/>
    </dep:environment>
    <tomcat:context-root>/test</tomcat:context-root>
    <tomcat:context-priority-classloader>false</tomcat:context-priority-classloader>
    <!--
        <jetty:security>
            <sec:default-principal>
                <sec:principal class="org.apache.geronimo.security.DefaultPrincipal"
                    name="bar"/>
            </sec:default-principal>
        </jetty:security>
    -->
</tomcat:web-app>


text:
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */

#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "ifcpp/model/GlobalDefines.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingObject.h"

namespace IFC4X3
{
	// TYPE IfcFacilityPartCommonTypeEnum = ENUMERATION OF	(ABOVEGROUND	,BELOWGROUND	,JUNCTION	,LEVELCROSSING	,SEGMENT	,SUBSTRUCTURE	,SUPERSTRUCTURE	,TERMINAL	,USERDEFINED	,NOTDEFINED);
	class IFCQUERY_EXPORT IfcFacilityPartCommonTypeEnum : virtual public BuildingObject
	{
	public:
		enum IfcFacilityPartCommonTypeEnumEnum
		{
			ENUM_ABOVEGROUND,
			ENUM_BELOWGROUND,
			ENUM_JUNCTION,
			ENUM_LEVELCROSSING,
			ENUM_SEGMENT,
			ENUM_SUBSTRUCTURE,
			ENUM_SUPERSTRUCTURE,
			ENUM_TERMINAL,
			ENUM_USERDEFINED,
			ENUM_NOTDEFINED
		};

		IfcFacilityPartCommonTypeEnum() = default;
		IfcFacilityPartCommonTypeEnum( IfcFacilityPartCommonTypeEnumEnum e ) { m_enum = e; }
		virtual uint32_t classID() const { return 1019252178; }
		virtual shared_ptr<BuildingObject> getDeepCopy( BuildingCopyOptions& options );
		virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
		static shared_ptr<IfcFacilityPartCommonTypeEnum> createObjectFromSTEP( const std::string& arg, const std::map<int,shared_ptr<BuildingEntity> >& map, std::stringstream& errorStream );
		IfcFacilityPartCommonTypeEnumEnum m_enum;
	};
}


text:
This is client side library extracted from natural language processing library for node

https://github.com/NaturalNode/natural

Installation
------------

You just need to include natural.js in your project and can use following libraries from natural library.

Now you can access following object from natural.

SoundEx
Metaphone
DoubleMetaphone
PorterStemmer
PorterStemmerRu
LancasterStemmer
AggressiveTokenizerRu
AggressiveTokenizer
RegexpTokenizer
WordTokenizer
WordPunctTokenizer
TreebankWordTokenizer
NounInflector
PresentVerbInflector
CountInflector
TfIdf
SentenceAnalyzer
NGrams
JaroWinklerDistance
LevenshteinDistance
DiceCoefficient

All these objects are inside namespace natural

Example
-------

You can use SoundEx using

if(natural.SoundEx.compare('phonetics', 'fonetix'))
  console.log('they sound alike!');

More Usage Examples
-------------------

For more examples visit [natural readme](https://github.com/NaturalNode/natural/blob/master/README.md)

Limitations
-----------

It doesn't yet support [Classifiers](https://github.com/NaturalNode/natural#classifiers) and [Wordnet](https://github.com/NaturalNode/natural#wordnet).


text:
module Dhaka
  module LexerSupport
    class StateMachine
      attr_reader :start_state

      def initialize start_key
        @states = Hash.new do |hash, key|
          new_state = new_state_for_key key
          hash[key] = new_state
          transition_characters(key).each do |char|
            dest_key                    = dest_key_for(key, char)
            dest_state                  = hash[dest_key]
            new_state.transitions[char] = dest_state
          end
          new_state
        end
        @start_state = @states[start_key]
      end

      def to_dot
        Dot::Digraph.new(:fontsize => 10, :shape => :circle, :size => 5) do |g|
          start = 'Start'
          g.node(start, :label => start)
          g.edge(start, @start_state)
          @states.values.each do |state|
            state_attributes = {}
            state_attributes.merge!(:shape => :doublecircle, :label => state.action.to_dot) if state.accepting?
            g.node(state, state_attributes)
            state.transitions.each do |transition_key, dest_state|
              g.edge(state, dest_state, :label => transition_key.inspect)
            end
          end
        end.to_dot
      end
    end
  end
end


text:
package org.eknet.publet.webeditor.actions

import org.eknet.publet.vfs.{ContentResource, Resource, Path}
import org.eknet.publet.webeditor.EditorPaths
import org.eknet.publet.web.util.PubletWebContext

/**
 * @author Eike Kettner eike.kettner@gmail.com
 * @since 04.10.12 11:45
 */
trait ThumbnailUrlUtil {

  /**
   * Returns a full URL to a preview image of the given resource. If it
   * is an image, an URL to a thumbnail is returned, otherwise some
   * place-holder image is returned.
   *
   * @param path the path to the resource
   * @param r the resource used for checking content type
   * @return
   */
  def thumbnailUrl(path: Path, r: Resource) = {
    val ctx = PubletWebContext
    val qp = "maxw="+getThumbnailWidth+"&maxh="+getThumbnailHeight
    val url = if (r.isInstanceOf[ContentResource]
      && r.asInstanceOf[ContentResource].contentType.mime._1 == "image") {

      ctx.urlOf(path.asString)
    } else {
      ctx.urlOf(EditorPaths.editorPath / "img/nopreview.png")
    }
    url + "?thumb&"+qp
  }

  def getThumbnailHeight = 45
  def getThumbnailWidth = 80

}


text:
<!DOCTYPE html>

<link href="resources/grid.css" rel="stylesheet">

This test checks the behavior of the absolutely positioned grid items placed on the implicit grid.


text:
#include "tensorflow/lite/kernels/gemmlowp_support.h"

#include <memory>

#include "tensorflow/lite/kernels/op_macros.h"

namespace tflite {
namespace gemmlowp_support {
namespace {

struct RefCountedGemmlowpContext : public TfLiteExternalContext {
  std::unique_ptr<gemmlowp::GemmContext> gemmlowp_context;
  int num_references = 0;
};

RefCountedGemmlowpContext* GetGemmLowpContext(TfLiteContext* context) {
  return reinterpret_cast<RefCountedGemmlowpContext*>(
      context->GetExternalContext(context, kTfLiteGemmLowpContext));
}

TfLiteStatus Refresh(TfLiteContext* context) {
  auto* ptr = GetGemmLowpContext(context);
  if (ptr != nullptr) {
    ptr->gemmlowp_context->set_max_num_threads(
        context->recommended_num_threads);
  }
  return kTfLiteOk;
}

}  // namespace

void IncrementUsageCounter(TfLiteContext* context) {
  auto* ptr = GetGemmLowpContext(context);
  if (ptr == nullptr) {
    ptr = new RefCountedGemmlowpContext;
    ptr->type = kTfLiteGemmLowpContext;
    ptr->Refresh = Refresh;
    ptr->gemmlowp_context.reset(new gemmlowp::GemmContext());
    if (context->recommended_num_threads != -1) {
      ptr->gemmlowp_context->set_max_num_threads(
          context->recommended_num_threads);
    }
    ptr->num_references = 0;
    context->SetExternalContext(context, kTfLiteGemmLowpContext, ptr);
  }
  ptr->num_references++;
}

void DecrementUsageCounter(TfLiteContext* context) {
  auto* ptr = GetGemmLowpContext(context);
  if (ptr == nullptr) {
    TF_LITE_FATAL(
        "Call to DecrementUsageCounter() not preceded by "
        "IncrementUsageCounter()");
  }
  if (--ptr->num_references == 0) {
    delete ptr;
    context->SetExternalContext(context, kTfLiteGemmLowpContext, nullptr);
  }
}

gemmlowp::GemmContext* GetFromContext(TfLiteContext* context) {
  auto* ptr = GetGemmLowpContext(context);
  if (ptr == nullptr) {
    TF_LITE_FATAL(
        "Call to GetFromContext() not preceded by IncrementUsageCounter()");
  }
  return ptr->gemmlowp_context.get();
}

}  // namespace gemmlowp_support
}  // namespace tflite


text:
using System.Collections.Generic;
using OnTheRoad.Domain.Models;

namespace OnTheRoad.Logic.Contracts
{
    public interface IReviewDataUtils
    {
        void AddUserReview(IReview review);

        IEnumerable<IReview> GetUserReviews(string username);

        IEnumerable<IReview> GetUserReviews(string username, int skip, int take);

        int GetUserReviewsTotal(string username);
    }
}


text:
@interface YLDribbbleLoginViewModel : RVMViewModel

@property (nonatomic, readonly) RACCommand *loginCommand;
@property (nonatomic, strong) NSString *username;
@property (nonatomic, readonly, getter = isLoading) BOOL loading;

@end


text:
//
// Novell.Directory.Ldap.LdapAddRequest.cs
//
// Author:
//   Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//

using Novell.Directory.Ldap.Asn1;
using Novell.Directory.Ldap.Rfc2251;

namespace Novell.Directory.Ldap
{
    /// <summary>
    ///     Represents an Ldap Add Request.
    /// </summary>
    /// <seealso cref="LdapConnection.SendRequest">
    /// </seealso>
    /*
     *       AddRequest ::= [APPLICATION 8] SEQUENCE {
     *               entry           LdapDN,
     *               attributes      AttributeList }
     */
    public class LdapAddRequest : LdapMessage
    {
        /// <summary>
        ///     Constructs an LdapEntry that represents the add request
        /// </summary>
        /// <returns>
        ///     an LdapEntry that represents the add request.
        /// </returns>
        public virtual LdapEntry Entry
        {
            get
            {
                var addreq = (RfcAddRequest) Asn1Object.getRequest();

                var attrs = new LdapAttributeSet();

                // Build the list of attributes
                var seqArray = addreq.Attributes.toArray();
                for (var i = 0; i < seqArray.Length; i++)
                {
                    var seq = (RfcAttributeTypeAndValues) seqArray[i];
                    var attr = new LdapAttribute(((Asn1OctetString) seq.get_Renamed(0)).stringValue());

                    // Add the values to the attribute
                    var set_Renamed = (Asn1SetOf) seq.get_Renamed(1);
                    object[] setArray = set_Renamed.toArray();
                    for (var j = 0; j < setArray.Length; j++)
                    {
                        attr.addValue(((Asn1OctetString) setArray[j]).byteValue());
                    }
                    attrs.Add(attr);
                }

                return new LdapEntry(Asn1Object.RequestDN, attrs);
            }
        }

        /// <summary>
        ///     Constructs a request to add an entry to the directory.
        /// </summary>
        /// <param name="entry">
        ///     The LdapEntry to add to the directory.
        /// </param>
        /// <param name="cont">
        ///     Any controls that apply to the add request,
        ///     or null if none.
        /// </param>
        public LdapAddRequest(LdapEntry entry, LdapControl[] cont)
            : base(ADD_REQUEST, new RfcAddRequest(new RfcLdapDN(entry.DN), makeRfcAttrList(entry)), cont)
        {
        }

        /// <summary>
        ///     Build the attribuite list from an LdapEntry.
        /// </summary>
        /// <param name="entry">
        ///     The LdapEntry associated with this add request.
        /// </param>
        private static RfcAttributeList makeRfcAttrList(LdapEntry entry)
        {
            // convert Java-API LdapEntry to RFC2251 AttributeList
            var attrSet = entry.getAttributeSet();
            var attrList = new RfcAttributeList(attrSet.Count);
            var itr = attrSet.GetEnumerator();
            while (itr.MoveNext())
            {
                var attr = (LdapAttribute) itr.Current;
                var vals = new Asn1SetOf(attr.size());
                var attrEnum = attr.ByteValues;
                while (attrEnum.MoveNext())
                {
                    vals.add(new RfcAttributeValue((sbyte[]) attrEnum.Current));
                }
                attrList.add(new RfcAttributeTypeAndValues(new RfcAttributeDescription(attr.Name), vals));
            }
            return attrList;
        }

        /// <summary>
        ///     Return an Asn1 representation of this add request.
        ///     #return an Asn1 representation of this object.
        /// </summary>
        public override string ToString()
        {
            return Asn1Object.ToString();
        }
    }
}


text:
class VideoSegment < ActiveRecord::Base
  belongs_to :video
  belongs_to :candidate

  scope :unprocessed, :conditions => 'turkee_task_id is NULL'

  SEGMENT_LENGTH = 60   # seconds

  def self.partition(video)
    offset    = 0
    segments  = video.duration / SEGMENT_LENGTH
    remainder = video.duration % SEGMENT_LENGTH

    (1..segments).each do
      create_segment(video, offset, SEGMENT_LENGTH - 1)
      offset+=SEGMENT_LENGTH
    end

    create_segment(video, offset, remainder) unless remainder == 0
  end

  def start_of
    offset
  end

  def end_of
    (offset + duration)
  end

  def self.create_segment(video, offset, duration)
    video.video_segments.create(:offset => offset, :duration => duration)
  end

  def self.reset_turk_tasks
    VideoSegment.update_all(:turkee_task_id => nil)
  end

  def self.create_turk_tasks(title,description,num_assignments,reward,duration)
    hit_urls = []
    VideoSegment.unprocessed.each do |video_segment|
      turk_task = Turkee::TurkeeTask.create_hit(HOST, title, description, :Tran,
                                                num_assignments, reward, duration, 70, :video_segment_id => video_segment.id)

      hit_urls  << turk_task.hit_url

      video_segment.turkee_task_id = turk_task.id
      video_segment.save
    end

    puts "HIT URLs :"
    puts hit_urls.join("\n")
  end
end


text:
import Card from './card';

import React from 'react';

export default class CardList extends React.Component {
  render() {
    return

Cards

        {this.props.cards.map(
          card =>
<Card card={card} />

        )}

;
  }
}


text:
@interface NSCharacterSet (ZWUtility)

+ (NSCharacterSet *)URLAllowedCharacterSet;

@end


text:
<?php

namespace Piwiweb\PhotoalbumBundle\Model;

abstract class AlbumManager implements AlbumManagerInterface
{
    /**
     * Creates an empty album instance
     *
     * @return Album
     */
    public function createAlbum()
    {
        $class = $this->getClass();
        $album = new $class;

        return $album;
    }
}


text:
require 'spec_helper'

describe SpyFu::BuildRequest do
  subject { SpyFu::BuildRequest }

  describe 'build_request' do
    subject { SpyFu::BuildRequest.new('/foo/bar', {}).build_request }

    it 'calls HTTParty' do
      expect(HTTParty).to receive(:get)

      subject
    end

    it 'calls BuildMessage' do
      expect_any_instance_of(SpyFu::BuildMessage).to receive(:call).and_return('')

      subject
    end

    it 'calls BuildSignature' do
      expect_any_instance_of(SpyFu::BuildSignature).to receive(:call).and_return('')

      subject
    end

    it 'sets the headers to use the timestamp and signature' do
      allow_any_instance_of(SpyFu::BuildRequest).to receive(:build_timestamp).and_return('timestamp')
      allow_any_instance_of(SpyFu::BuildSignature).to receive(:call).and_return('signature')

      expect(HTTParty).to receive(:get).with('http://www.spyfu.com/foo/bar',
                                             headers: { 'Authentication' => 'user_id:signature',
                                                        'Timestamp' => 'timestamp' })

      subject
    end
  end

  describe 'join_url_and_query' do
    context 'in query_string' do
      it 'return string' do
        res = subject.new('/foo/bar', q: 'foo', r: 'bar')
        expect(res.join_url_and_query).to eq('http://www.spyfu.com/foo/bar?q=foo&r=bar')
      end

      it 'return string while respecting spaces' do
        res = subject.new('/foo/bar', q: 'foo bar', r: 'baz')
        expect(res.join_url_and_query).to eq('http://www.spyfu.com/foo/bar?q=foo%20bar&r=baz')
      end
    end
  end
end


text:
package org.jkiss.dbeaver.erd.ui.part;

import org.eclipse.gef3.EditPart;
import org.eclipse.gef3.GraphicalEditPart;
import org.eclipse.gef3.RootEditPart;
import org.eclipse.gef3.editparts.AbstractConnectionEditPart;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.erd.model.ERDObject;
import org.jkiss.dbeaver.model.DBPNamedObject;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

/**
 * An ConnectionEditPart base class which is property aware, that is, can handle property change notification events
 * All our ConnectionEditPart are subclasses of this
 *
 * @author Serge Rider
 */
public abstract class PropertyAwareConnectionPart extends AbstractConnectionEditPart implements PropertyChangeListener, DBPNamedObject {
    @NotNull
    public DiagramPart getDiagramPart() {
        RootEditPart root = getRoot();
        if (root == null) {
            throw new IllegalStateException("Diagram part is null. Disposed part?");
        }
        EditPart contents = root.getContents();
        if (contents instanceof DiagramPart) {
            return (DiagramPart) contents;
        }
        throw new IllegalStateException("Diagram part must be top level part");
    }

    @NotNull
    @Override
    public String getName() {
        return ((ERDObject) getModel()).getName();
    }

    protected boolean isEditEnabled() {
        return getRoot().getContents() instanceof DiagramPart && ((DiagramPart) getRoot().getContents()).getDiagram().isLayoutManualAllowed();
    }

    @Override
    public void activate() {
        super.activate();
        ERDObject<?> erdObject = (ERDObject<?>) getModel();
        if (isEditEnabled()) {
            erdObject.addPropertyChangeListener(this);
        }
    }

    @Override
    public void deactivate() {
        super.deactivate();
        if (isEditEnabled()) {
            ERDObject<?> erdObject = (ERDObject<?>) getModel();
            erdObject.removePropertyChangeListener(this);
        }
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {

        String property = evt.getPropertyName();

        switch (property) {
            case ERDObject.PROP_CHILD:
                refreshChildren();
                break;
            case ERDObject.PROP_INPUT:
                refreshTargetConnections();
                break;
            case ERDObject.PROP_OUTPUT:
                refreshSourceConnections();
                break;
        }

		/*
         * if (FlowElement.CHILDREN.equals(prop)) refreshChildren(); else if
		 * (FlowElement.INPUTS.equals(prop)) refreshTargetConnections(); else if
		 * (FlowElement.OUTPUTS.equals(prop)) refreshSourceConnections(); else
		 * if (Activity.PROP_NAME.equals(prop)) refreshVisuals(); // Causes Graph to
		 * re-layout
		 */
        ((GraphicalEditPart) (getViewer().getContents())).getFigure().revalidate();
    }

}