text:
package org.apache.kafka.common.requests;

import org.apache.kafka.common.message.UpdateFeaturesResponseData;
import org.apache.kafka.common.message.UpdateFeaturesResponseData.UpdatableFeatureResult;
import org.apache.kafka.common.message.UpdateFeaturesResponseData.UpdatableFeatureResultCollection;
import org.apache.kafka.common.protocol.ApiKeys;
import org.apache.kafka.common.protocol.ByteBufferAccessor;
import org.apache.kafka.common.protocol.Errors;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

/**
 * Possible error codes:
 *
 *   - {@link Errors#CLUSTER_AUTHORIZATION_FAILED}
 *   - {@link Errors#NOT_CONTROLLER}
 *   - {@link Errors#INVALID_REQUEST}
 *   - {@link Errors#FEATURE_UPDATE_FAILED}
 */
public class UpdateFeaturesResponse extends AbstractResponse {

    private final UpdateFeaturesResponseData data;

    public UpdateFeaturesResponse(UpdateFeaturesResponseData data) {
        super(ApiKeys.UPDATE_FEATURES);
        this.data = data;
    }

    public ApiError topLevelError() {
        return new ApiError(Errors.forCode(data.errorCode()), data.errorMessage());
    }

    @Override
    public Map<Errors, Integer> errorCounts() {
        Map<Errors, Integer> errorCounts = new HashMap<>();
        updateErrorCounts(errorCounts, Errors.forCode(data.errorCode()));
        for (UpdatableFeatureResult result : data.results()) {
            updateErrorCounts(errorCounts, Errors.forCode(result.errorCode()));
        }
        return errorCounts;
    }

    @Override
    public int throttleTimeMs() {
        return data.throttleTimeMs();
    }

    @Override
    public String toString() {
        return data.toString();
    }

    @Override
    public UpdateFeaturesResponseData data() {
        return data;
    }

    public static UpdateFeaturesResponse parse(ByteBuffer buffer, short version) {
        return new UpdateFeaturesResponse(new UpdateFeaturesResponseData(new ByteBufferAccessor(buffer), version));
    }

    public static UpdateFeaturesResponse createWithErrors(ApiError topLevelError, Map<String, ApiError> updateErrors, int throttleTimeMs) {
        final UpdatableFeatureResultCollection results = new UpdatableFeatureResultCollection();
        for (final Map.Entry<String, ApiError> updateError : updateErrors.entrySet()) {
            final String feature = updateError.getKey();
            final ApiError error = updateError.getValue();
            final UpdatableFeatureResult result = new UpdatableFeatureResult();
            result.setFeature(feature)
                .setErrorCode(error.error().code())
                .setErrorMessage(error.message());
            results.add(result);
        }
        final UpdateFeaturesResponseData responseData = new UpdateFeaturesResponseData()
            .setThrottleTimeMs(throttleTimeMs)
            .setErrorCode(topLevelError.error().code())
            .setErrorMessage(topLevelError.message())
            .setResults(results)
            .setThrottleTimeMs(throttleTimeMs);
        return new UpdateFeaturesResponse(responseData);
    }
}


text:
package com.norcane.noble.model;

import java.util.Set;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;

@Entity
@Table(name = "nbl_role")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "roles")
    private Set<User> users;

    // -- Getters & Setters

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }
}

redpajama_set_name: RedPajamaGithub


text: chaos the beginning


text:
package nl.vu.cs.ajira.actions.support;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import nl.vu.cs.ajira.data.types.DataProvider;
import nl.vu.cs.ajira.data.types.SimpleData;
import nl.vu.cs.ajira.data.types.Tuple;
import nl.vu.cs.ajira.data.types.TupleFactory;
import nl.vu.cs.ajira.storage.Writable;

/**
 * Data structure used for the parameter specification of a chain of actions.
 */
public class Query implements Writable {

	private final Tuple tuple;

	/**
	 * Constructs a new Query with empty content.
	 */
	public Query() {
		tuple = TupleFactory.newTuple();
	}

	/**
	 * Constructs a new Query with the specified tuple as content.
	 * @param tuple
	 *		the contents of this Query object
	 */
	public Query(Tuple tuple) {
		this.tuple = tuple;
	}

	/**
	 * Constructs a new Query with the specified data as content.
	 * @param data
	 * 		the contents of this Query object
	 */
	public Query(SimpleData... data) {
		this();
		setElements(data);
	}

	/**
	 * Constructs a new Query with the specified data types as content.
	 * @param array
	 * 		a list of class names, specifying the data types of the content
	 */
	public Query(String[] array) throws Exception {
		this();
		SimpleData[] data = new SimpleData[array.length];
		for (int i = 0; i < data.length; ++i)
			data[i] = (SimpleData) Class.forName(array[i]).newInstance();
		setElements(data);
	}

	/**
	 * Sets the content of this Query object to the specified data.
	 * @param data
	 * 		the data to store into this Query
	 */
	public void setElements(SimpleData... data) {
		tuple.set(data);
	}

	/**
	 * Obtains the content of the Query object, as a {@link Tuple}.
	 * @return
	 * 		the content
	 */
	public Tuple getTuple() {
		return tuple;
	}

	@Override
	public void readFrom(DataInput input) throws IOException {
		int nElements = input.readByte();
		SimpleData[] data = new SimpleData[nElements];
		for (int i = 0; i < nElements; ++i) {
			SimpleData el = DataProvider.get().get(input.readByte());
			el.readFrom(input);
			data[i] = el;
		}
		tuple.set(data);
	}

	@Override
	public void writeTo(DataOutput output) throws IOException {
		output.writeByte(tuple.getNElements());
		for (int i = 0; i < tuple.getNElements(); ++i) {
			SimpleData el = tuple.get(i);
			output.writeByte(el.getIdDatatype());
			el.writeTo(output);
		}
	}
}


text:
class NiftyLayoutGenerator < Rails::Generator::Base
  def initialize(runtime_args, runtime_options = {})
    super
    @name = @args.first || 'application'
  end

  def manifest
    record do |m|
      m.directory 'app/views/layouts'
      m.directory 'public/stylesheets'
      m.directory 'app/helpers'

      if options[:haml]
        m.directory 'public/stylesheets/sass'
        m.template "layout.html.haml", "app/views/layouts/#{file_name}.html.haml"
        m.file     "stylesheet.sass",  "public/stylesheets/sass/#{file_name}.sass"
      else
        m.template "layout.html.erb", "app/views/layouts/#{file_name}.html.erb"
        m.file     "stylesheet.css",  "public/stylesheets/#{file_name}.css"
      end
      m.file "helper.rb", "app/helpers/layout_helper.rb"
    end
  end

  def file_name
    @name.underscore
  end

  protected

    def add_options!(opt)
      opt.separator ''
      opt.separator 'Options:'
      opt.on("--haml", "Generate HAML for view, and SASS for stylesheet.") { |v| options[:haml] = v }
    end

    def banner
      <<-EOS
Creates generic layout, stylesheet, and helper files.

USAGE: #{$0} #{spec.name} [layout_name]
EOS
    end
end


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CodeCracker.CSharp.Refactoring
{
    [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ParameterRefactoryCodeFixProvider)), Shared]
    public class ParameterRefactoryCodeFixProvider : CodeFixProvider
    {
        public sealed override ImmutableArray<string> FixableDiagnosticIds =>
            ImmutableArray.Create(DiagnosticId.ParameterRefactory.ToDiagnosticId());

        public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;

        public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            context.RegisterCodeFix(CodeAction.Create("Change to new Class", c => NewClassAsync(context.Document, diagnostic, c), nameof(ParameterRefactoryCodeFixProvider)), diagnostic);
            return Task.FromResult(0);
        }

        private async static Task<Document> NewClassAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var oldClass = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<ClassDeclarationSyntax>().First();
            var oldNamespace = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<NamespaceDeclarationSyntax>().FirstOrDefault();
            var oldMethod = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().First();
            SyntaxNode newRootParameter = null;
            if (oldNamespace == null)
            {
                var newCompilation = AddParameterClassToCompilationUnitAndUpdateClassToUseNamespace((CompilationUnitSyntax)oldClass.Parent, oldClass, oldMethod);
                newRootParameter = root.ReplaceNode(oldClass.Parent, newCompilation);
                return document.WithSyntaxRoot(newRootParameter);
            }
            var newNamespace = AddParameterClassToNamespaceAndUpdateClassToUseNamespace(oldNamespace, oldClass, oldMethod);
            newRootParameter = root.ReplaceNode(oldNamespace, newNamespace).WithAdditionalAnnotations(Formatter.Annotation);
            return document.WithSyntaxRoot(newRootParameter);
        }

        private static List<PropertyDeclarationSyntax> CreateProperties(MethodDeclarationSyntax method)
        {
            var newGetSyntax = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            var newSetSyntax = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            var acessorSyntax = SyntaxFactory.AccessorList(
                SyntaxFactory.Token(SyntaxKind.OpenBraceToken),
                SyntaxFactory.List(new[] { newGetSyntax, newSetSyntax }),
                SyntaxFactory.Token(SyntaxKind.CloseBraceToken));
            var properties = new List<PropertyDeclarationSyntax>();
            foreach (ParameterSyntax param in method.ParameterList.Parameters)
            {
                var property = SyntaxFactory.PropertyDeclaration(param.Type, FirstLetteToUpper(param.Identifier.Text))
                    .WithModifiers(SyntaxFactory.TokenList(new[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword) }))
                    .WithAccessorList(acessorSyntax);
                properties.Add(property);
            }
            return properties;
        }

        private static ClassDeclarationSyntax CreateParameterClass(string newNameClass, MethodDeclarationSyntax oldMethod)
        {
            var properties = CreateProperties(oldMethod);
            return SyntaxFactory.ClassDeclaration(newNameClass)
                .WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(properties))
                .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)));
        }

        private static NamespaceDeclarationSyntax AddParameterClassToNamespaceAndUpdateClassToUseNamespace(NamespaceDeclarationSyntax oldNamespace, ClassDeclarationSyntax oldClass, MethodDeclarationSyntax oldMethod)
        {
            var className = $"NewClass{oldMethod.Identifier.Text}";
            var newParameterClass = CreateParameterClass(className, oldMethod);
            var newNamespace = oldNamespace.ReplaceNode(oldClass, UpdateClassToUseNewParameterClass(className, oldClass, oldMethod))
                .AddMembers(newParameterClass);
            return newNamespace;
        }

        private static ClassDeclarationSyntax UpdateClassToUseNewParameterClass(string className, ClassDeclarationSyntax classOld, MethodDeclarationSyntax methodOld)
        {
            var newParameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier(FirstLetteToLower(className))).WithType(SyntaxFactory.ParseTypeName(className));
            var parameters = SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList<ParameterSyntax>().Add(newParameter));
            var newMethod = methodOld.WithParameterList(parameters);
            var newClass = classOld.ReplaceNode(methodOld, newMethod);
            return newClass;
        }

        private static CompilationUnitSyntax AddParameterClassToCompilationUnitAndUpdateClassToUseNamespace(CompilationUnitSyntax oldCompilation, ClassDeclarationSyntax oldClass, MethodDeclarationSyntax oldMethod)
        {
            var className = $"NewClass{oldMethod.Identifier.Text}";
            var newParameterClass = CreateParameterClass(className, oldMethod);
            var newNamespace = oldCompilation.ReplaceNode(oldClass, UpdateClassToUseNewParameterClass(className, oldClass, oldMethod))
                .AddMembers(newParameterClass);
            return newNamespace;
        }

        private static string FirstLetteToUpper(string text) =>
            string.Concat(text.Replace(text[0].ToString(), text[0].ToString().ToUpper()));

        private static string FirstLetteToLower(string text) =>
            string.Concat(text.Replace(text[0].ToString(), text[0].ToString().ToLower()));
    }
}


text:
package com.cakecatalog.srv.auth.domain;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PortalUserRepository extends JpaRepository<PortalUser, Long> {

  PortalUser findOneByEmail(String email);
}


text:
from neutron.plugins.vmware.extensions import networkgw

class Nvp_networkgw(networkgw.Networkgw):
    """(Deprecated) API extension for Layer-2 Gateway support."""

    @classmethod
    def get_name(cls):
        return "Neutron-NVP Network Gateway"

    @classmethod
    def get_alias(cls):
        return "network-gateway"

    @classmethod
    def get_description(cls):
        return ("Connects Neutron networks with external "
                "networks at layer 2 (deprecated).")

    @classmethod
    def get_namespace(cls):
        return "http://docs.openstack.org/ext/neutron/network-gateway/api/v1.0"


text:
module Griddler
  module Sendigma
    VERSION = "0.0.1"
  end
end


text:
package org.apache.ode.utils.stl;

public interface UnaryFunctionEx<E,V> {
  V apply(E x) throws Exception;
}


text:
require 'spec_helper'
require 'thrift/server/thin_http_server'

describe Thrift::FaradayHTTPClientTransport do

  describe 'examples mocking out the actual network traffic' do

    let(:url) do
      'http://my.domain.com/path/to/service?param=value'
    end

    def expect_faraday_call(expected_body,
                            additional_headers = {},
                            proxy = nil,
                            ssl_verify = true)
      mock_faraday = double('Faraday')
      mock_request = double('request')
      mock_body = double('body')
      mock_response = double('response')

      expected_headers = {
        'Content-Type' => 'application/x-thrift'
      }.merge!(additional_headers)

      expect(mock_request).to receive(:url).with('/path/to/service')
      expect(mock_request).to receive(:headers=).with(expected_headers)
      expect(mock_request).to receive(:body=).with(expected_body)
      expect(mock_response).to receive(:body).and_return('data')
      expect(mock_faraday).to receive(:adapter).with(Faraday.default_adapter)
      expect(mock_faraday).to receive(:post).and_yield(mock_request).
          and_return(mock_response)
      expect(::Faraday).to receive(:new).
        with({
               :url => URI(url),
               :proxy => proxy,
               :ssl => {
                 :verify => ssl_verify
               }
             }).
        and_yield(mock_faraday).
        and_return(mock_faraday)
      # Return the mocked faraday so it can be used to mock the callback.
      mock_faraday
    end

    before(:each) do
      @client = described_class.new(url)
    end

    it 'should always be open' do
      expect(@client).to be_open
      @client.close
      expect(@client).to be_open
    end

    it 'should post via HTTP and return the results' do
      @client.write('a test')
      @client.write(' frame')

      expect_faraday_call('a test frame')

      @client.flush
      expect(@client.read(10)).to eq('data')
    end

    it 'should send custom headers if defined' do
      @client.write('test')
      custom_headers = { 'Cookie' => 'Foo' }

      @client.add_headers(custom_headers)

      expect_faraday_call('test', custom_headers, nil, true)

      @client.flush
    end

    it 'can disable verifying ssl certificates' do
      @client = described_class.new(url, ssl_verify: false)
      @client.write('ssl')
      expect_faraday_call('ssl', {}, nil, false)
      @client.flush
    end

    it 'should use a proxy when asked' do
      proxy = 'http://localhost:8888'
      @client = described_class.new(url, proxy_url: proxy)
      @client.write('proxy')
      expect_faraday_call('proxy', {}, proxy, true)
      @client.flush
    end

    it 'calls faraday callbacks to install middleware' do
      callback = double('callback')
      @client = described_class.new(url, faraday_callback: callback)
      @client.write('callback')
      faraday = expect_faraday_call('callback')
      expect(callback).to receive(:call).with(faraday)
      @client.flush
    end

  end

  context 'with a live thrift service' do

    let(:port) { 59599 }
    let(:handler) { SimpleServiceHandler.new }
    let(:processor) { YetiThriftTest::SimpleService::Processor.new(handler) }
    let(:protocol_factory) { Thrift::JsonProtocolFactory.new }

    let(:transport) do
      Thrift::HTTPClientTransport.new("http://localhost:#{port}")
    end
    let(:protocol) { Thrift::JsonProtocol.new(transport) }
    let(:client) { YetiThriftTest::SimpleService::Client.new(protocol) }

    it 'starts up a server' do
      @server = Thrift::ThinHTTPServer.
        new(processor,
            port: port,
            protocol_factory: protocol_factory)
      thread = Thread.new do
        @server.serve
      end

      sleep(0.5)
      transport.open
      ss = YetiThriftTest::SimpleStruct.new do |ss|
        ss.long = 388219
        ss.int = 21
        ss.str = 'string'
        ss.t_or_f = false
      end
      ss_mod = client.mutate(ss, 19, 'more', true)
      expect(ss_mod.long).to eq(ss.long + 19)
      expect(ss_mod.int).to eq(ss.int + 19)
      expect(ss_mod.str).to eq('stringmore')
      expect(ss_mod.t_or_f).to eq(true)

      transport.close
      thread.kill
      thread.join
    end

  end

end


text:
$(function () {
  let config = {
    wBoundry: 600,
    hBoundry: 400,
    duration: 1000,
    ease: 'easeInOutSine'
  }

  config.outPadding = config.wBoundry * 0.03
  config.wContainer = config.wBoundry * 0.25
  config.hContainer = config.hBoundry * 0.35
  config.wCenter = (config.wBoundry / 2) - (config.wContainer / 2)

  let docStyle = document.documentElement.style
  Object.keys(config).forEach(x => {
    docStyle.setProperty('--' + x, config[x] + 'px')
  })

  let svg = document.querySelector('#paths')
  svg.setAttribute('width', config.wBoundry)
  svg.setAttribute('height', config.hBoundry)

  let rightTopPath = document.createElementNS('http://www.w3.org/2000/svg', 'path')

  let loc = {
    start: {
      x: config.wBoundry - config.outPadding - config.wContainer / 2,
      y: config.hBoundry - config.hContainer - config.outPadding + 20
    },
    end: {
      x: config.wCenter + config.wContainer / 2,
      y: config.hContainer / 2 + config.outPadding
    }
  }

  rightTopPath.setAttribute('id', 'right-top')
  rightTopPath.setAttribute('d',
      `M ${loc.start.x} ${loc.start.y} Q ${loc.start.x} ${loc.end.y} ${loc.end.x} ${loc.end.y}`)

  svg.append(rightTopPath)

  let topCenterPath = document.createElementNS('http://www.w3.org/2000/svg', 'path')

  loc = {
    start: {
      x: config.wCenter + config.wContainer / 2,
      y: config.hContainer / 2 + config.outPadding
    },
    end: {
      x: config.wCenter + config.wContainer / 2,
      y: config.hBoundry - (config.hContainer / 2 + config.outPadding)
    }
  }
  topCenterPath.setAttribute('id', 'top-center')
  topCenterPath.setAttribute('d',
      `M ${loc.start.x} ${loc.start.y} L ${loc.end.x} ${loc.end.y}`)

  svg.append(topCenterPath)

  var tl = anime.timeline({
    autoplay: false
  })

  var rightTop = anime.path('svg #right-top')
  var topCenter = anime.path('svg #top-center')

  let ev = document.querySelector('#event')

  let stateFirst = document.querySelector('#state-first')

  tl.add({
    targets: ev,
    left: rightTop('x'),
    top: rightTop('y'),
    duration: config.duration,
    easing: config.ease
  })
  .add({
    targets: ev,
    easing: config.ease,
    borderRadius: 0,
    width: 100,
    height: 50,
    lineHeight: '50px',
    marginLeft: -50,
    marginTop: -25,
    fontSize: 20,
    duration: config.duration / 2,
    begin: anim => {
      ev.innerText = 'Patch'
    }
  })
  .add({
    targets: ev,
    left: topCenter('x'),
    top: topCenter('y'),
    duration: config.duration,
    easing: config.ease
  })
  .add({
    targets: ev,
    opacity: 0,
    easing: config.ease,
    duration: config.duration / 2,
    offset: '-=' + config.duration / 1.5,
    rotate: '30deg'
  })
  .add({
    targets: stateFirst,
    opacity: 1,
    easing: config.ease,
    duration: config.duration / 3,
    offset: '-=' + config.duration / 2.5,
    begin: x => {
      $(stateFirst).css('display', 'block')
    }
  })

  tl.play()
})


text:
require 'spec_helper'

RSpec.describe RedisTest do
  describe '#start' do
    describe "log_to_stdout = false" do
      it "starts fine" do
        expect(RedisTest.started?).to be_falsey
        RedisTest.start
        expect(RedisTest.started?).to be_truthy
        RedisTest.stop
        expect(RedisTest.started?).to be_falsey
      end
    end

    describe "log_to_stdout = true" do
      it "starts fine" do
        expect(RedisTest.started?).to be_falsey
        RedisTest.start(log_to_stdout: true)
        expect(RedisTest.started?).to be_truthy
        RedisTest.stop
        expect(RedisTest.started?).to be_falsey
      end
    end
  end
end


text:
<?php
namespace Resource\Bundle\UserBundle\Service;

class PercolateNotifier {

    protected $odm;
    protected $rabbit;

    public function __construct($odm, $rabbit) {
        $this->odm = $odm;
        $this->rabbit = $rabbit;
    }

    public function process($json, $document) {
        $data = json_decode($json, true);
        $matches = $data['matches'];
        foreach($matches as $match ) {
            $idSearch = $match['_id'];
            $search = $this->odm
                ->getManager()
                ->getRepository('ResourceUserBundle:Search')
                ->findOneById($idSearch);
            if(isset($search)) {
                $userId = $search->getUserid();
                $user = $this->odm->getManager()
                    ->getRepository('ResourceUserBundle:User')
                    ->findOneById($userId);
                if(isset($user)) {
                    $this->notify($user, $search, $document);
                }
            }
        }

    }

    protected function notify($user, $search, $document ) {
        //todo
        //test user os
        //addapt notification service to various os
        $doc = json_decode($document, true);
        $docId = $doc['id'];
        $this->rabbit->sendPushMessage(
            $user,
            'Y en a pas loin',
            array(
                'type'=>'around',
                'id'=>$docId
            )
        );
    }
}


text:
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="description" content="">
	<meta name="author" content="">
    <link rel="shortcut icon" href="/static/ico/favicon/taskwetu_favicon_32.png">

	<title>TaskWetu</title>
	<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,400italic,700,800" rel="stylesheet" type="text/css">
	<link href="https://fonts.googleapis.com/css?family=Raleway:300,200,100" rel="stylesheet" type="text/css">

	<link href="/static/css/bootstrap.main.min.css" rel="stylesheet">
	<link rel="stylesheet" href="/static/fonts/font-awesome-4/css/font-awesome.min.css">

	<link href="/static/css/style-template.css" rel="stylesheet">

404

Sorry, but this page doesn't exists!

Would you like to go home?

© 2014 TaskWetu


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/english/styles.css" type="text/css">

	<title>EST Doc Dental's English page - (Nihonbashi, Tokyo)</title>

					English-speaking Dentist in Nihonbashi, Tokyo
					Natural White Dental Office

					Address
					9-15-1 Nihonbashi kabutocho, Chuo-ku Tokyo

103-0026 Japan

					03-6661-2672

					qqmk9kx9k@sirius.ocn.ne.jp

			Message

					Dr.Suzuki

					Nowadays, "clean teeth" is considered as an esthetic care similar to face and body one. Natural White is an oral care salon focused on cosmetic dentistry. From cleaning which keep your oral health to whitening, we have various menus for letting your teeth white. We propose best solution for your white teeth with the woman director and piece in mind aromatherapy.

			Business Hours for English-speaking

    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun
    Holiday

    11:00〜15:00
    ●
    ●
    ×
    ●
    ●
    ●
    ×
    ×

    15:00〜16:00
    ●
    ●
    ×
    ●
    ●
    ×
    ×
    ×

    16:00〜20:00
    ●
    ●
    ●
    ●
    ●
    ×
    ×
    ×

			English Level

Fluent in English

Fluent in conversational English

Japanese interpreter is required

			Services

General Dentistry

Implants

Esthetic Dentistry

Pediatric Dentistry

Orthodontic

			Insurance

We accept Japanese National Health Insurance

We also accept private insurance

				Access:
				The Clinic is only a 2 minute walk from Nihonbashi Station on the Toei Asakusa Line or only a 1 minute walk from Kayabachō Station on the Tozai Line.

            Payment Method

JPY Cash

Credit Card

AMERICAN EXPRESS

Master Card

VISA

Diners Club

Union Pay

JCB

Traveler's Check

			This page is operated by EST Doc Corp. Nihonbashi, Tokyo Natural White Dental Office

			このページは、株式会社EST Docが運営しています


text:
<title>HsacAcceptanceTests.FitTests.ReturnArrayAsSymbol</title><meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/><link rel='stylesheet' type='text/css' href='css/fitnesse.css'/>
HsacAcceptanceTests.FitTests.ReturnArrayAsSymbol

Return array as symbol

Sometimes it might be desirable to be able to store an array returned from a test in a symbol and to compare entries of that array with values in later tests.

To use this feature, implement a method in your fixture that returns a String array. For an example, see the asArray method of the CompareValuesFixture class. To use an array entry in comparison with an expected output, add a $ to the end of the columnname (see Symbol and array comparison).

The array is 1 based instead of 0 based.

Demonstration

First store value1 and value2 as array in symbol myArray.

		CompareValues

		value1
		value2
		=asArray?

		1
		2
		myArray  = [1, 2]

Compare first and second entry from array with new value1.

		CompareValues

		value1
		value1?$

		1
		1 (myArray.1)

		2
		2 (myArray.2)

Tip: to see how the output is in case of a failure, change value1.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.ai.metricsadvisor.implementation.models;

import com.azure.ai.metricsadvisor.administration.models.AnomalyDetectorDirection;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The SmartDetectionCondition model. */
@Fluent
public final class SmartDetectionCondition {
    /*
     * sensitivity, value range : (0, 100]
     */
    @JsonProperty(value = "sensitivity", required = true)
    private double sensitivity;

    /*
     * detection direction
     */
    @JsonProperty(value = "anomalyDetectorDirection", required = true)
    private AnomalyDetectorDirection anomalyDetectorDirection;

    /*
     * The suppressCondition property.
     */
    @JsonProperty(value = "suppressCondition", required = true)
    private SuppressCondition suppressCondition;

    /**
     * Get the sensitivity property: sensitivity, value range : (0, 100].
     *
     * @return the sensitivity value.
     */
    public double getSensitivity() {
        return this.sensitivity;
    }

    /**
     * Set the sensitivity property: sensitivity, value range : (0, 100].
     *
     * @param sensitivity the sensitivity value to set.
     * @return the SmartDetectionCondition object itself.
     */
    public SmartDetectionCondition setSensitivity(double sensitivity) {
        this.sensitivity = sensitivity;
        return this;
    }

    /**
     * Get the anomalyDetectorDirection property: detection direction.
     *
     * @return the anomalyDetectorDirection value.
     */
    public AnomalyDetectorDirection getAnomalyDetectorDirection() {
        return this.anomalyDetectorDirection;
    }

    /**
     * Set the anomalyDetectorDirection property: detection direction.
     *
     * @param anomalyDetectorDirection the anomalyDetectorDirection value to set.
     * @return the SmartDetectionCondition object itself.
     */
    public SmartDetectionCondition setAnomalyDetectorDirection(AnomalyDetectorDirection anomalyDetectorDirection) {
        this.anomalyDetectorDirection = anomalyDetectorDirection;
        return this;
    }

    /**
     * Get the suppressCondition property: The suppressCondition property.
     *
     * @return the suppressCondition value.
     */
    public SuppressCondition getSuppressCondition() {
        return this.suppressCondition;
    }

    /**
     * Set the suppressCondition property: The suppressCondition property.
     *
     * @param suppressCondition the suppressCondition value to set.
     * @return the SmartDetectionCondition object itself.
     */
    public SmartDetectionCondition setSuppressCondition(SuppressCondition suppressCondition) {
        this.suppressCondition = suppressCondition;
        return this;
    }
}


text:
const getSequence = sequence => ({
  length: Number(sequence.$.length),
  mw: Number(sequence.$.mass),
});

module.exports = getSequence;


text:
package com.pearmilk.legian.model;

/**
 * Created with IntelliJ IDEA.
 * User: matteopelati
 * Date: 21/11/13
 * Time: 10:41 AM
 * To change this template use File | Settings | File Templates.
 */
public class ParamModel extends AbstractModel {

    String name;
    String expr;

    public ParamModel(String name, String expr) {
        this.name = name;
        this.expr = expr;
    }

    public String getName() {
        return name;
    }

    public String getExpr() {
        return expr;
    }
}


text:
package org.apache.ode.utils;

import java.lang.reflect.Method;

public class Reflect {

	/**
	 * Generates a unique method signature string for a
	 * java.lang.reflect.Method. Necessary b/c Method is not Serializable.
	 *
	 * @param method
	 * @return
	 */
	public static String generateMethodSignature(Method method) {
		StringBuffer sb = new StringBuffer(64);

		sb.append(method.getName());
		sb.append("(");

		Class[] types = method.getParameterTypes();
		for (int i = 0; i < types.length; ++i) {
			if (i > 0) {
				sb.append(",");
			}
			sb.append(types[i].getName());
		}

		sb.append(")");
		return sb.toString();
	}
}


text:
require 'inifile'

class Chef
  module Provisioning
    module AzureRM
      class Credentials
        CONFIG_PATH = "#{ENV['HOME']}/.azure/credentials"

        def initialize
          config_file = ENV['AZURE_CONFIG_FILE'] || File.expand_path(CONFIG_PATH)
          if File.file?(config_file)
            @credentials = IniFile.load(File.expand_path(config_file))
          else
            Chef::Log.warn "#{CONFIG_PATH} was not found or not accessible." unless File.file?(config_file)
          end
        end

        def azure_credentials_for_subscription(subscription_id)
          tenant_id = ENV['AZURE_TENANT_ID'] || @credentials[subscription_id]['tenant_id']
          client_id = ENV['AZURE_CLIENT_ID'] || @credentials[subscription_id]['client_id']
          client_secret = ENV['AZURE_CLIENT_SECRET'] || @credentials[subscription_id]['client_secret']
          token_provider = MsRestAzure::ApplicationTokenProvider.new(tenant_id, client_id, client_secret)
          MsRest::TokenCredentials.new(token_provider)
        end

        def self.singleton
          @credentials ||= Credentials.new
        end
      end
    end
  end
end


text:
Создаем обычные сертификаты для домена по умолчанию

```
mkdir -p /etc/nginx/ssl
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt
```

Настраиваем nginx:
`nano /etc/nginx/sites-available/default`

```
server {
	listen 80 default_server;
	listen [::]:80 default_server;
	server_name _;

	root /var/www/html;
	index index.html index.htm index.nginx-debian.html;

	location ~ /.well-known {
		allow all;
	}
}

server{
	listen 443 ssl default_server;
	root /var/www/html;

	ssl_certificate     /etc/nginx/ssl/nginx.crt;
	ssl_certificate_key /etc/nginx/ssl/nginx.key;

	location ~ /.well-known {
		allow all;
	}
}
```

Генерируем сертификат
```
letsencrypt certonly -a webroot --webroot-path=/var/www/html -d my_host --email my_email --text
```

# Генерация сертификата без nginx
```
letsencrypt certonly -d my_host --email my_email --text
```

# Генерирация dh4096.pem
```
openssl dhparam -out /etc/letsencrypt/live/my_host/dh4096.pem 4096
```

# Модификация файлов Nginx

Вставляем строчки в раздел http nginx.conf
```
	sendfile            on;
	tcp_nopush          on;
	tcp_nodelay         on;
	keepalive_timeout   70;
	types_hash_max_size 2048;

	ssl_session_cache   shared:SSL:10m;
	ssl_session_timeout 5m;
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
	ssl_stapling on;

	# Cерверные шифры имеют больший приоритет, чем клиентские шифры
	ssl_prefer_server_ciphers on;

	# Разрешённые шифры
	ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
	#ssl_ciphers kEECDH+AES128:kEECDH:kEDH:-3DES:kRSA+AES128:kEDH+3DES:DES-CBC3-SHA:!RC4:!aNULL:!eNULL:!MD5:!EXPORT:!LOW:!SEED:!CAMELLIA:!IDEA:!PSK:!SRP:!SSLv2;
	#ssl_ciphers         HIGH:!aNULL:!MD5;

	# Разрешаем серверу для валидации сертификата прикреплять OCSP-ответы
	#ssl_stapling on;
	#ssl_stapling_verify on;
	#ssl_trusted_certificate /etc/pki/tls/certs/ca-bundle.crt;
	#resolver 8.8.8.8 [2001:4860:4860::8888];

	include             /etc/nginx/mime.types;
	default_type        application/octet-stream;

	client_max_body_size 256m;
	charset  utf-8;
	gzip  on;
	index   index.php index.html index.htm;
```

Для домена делаем:

```
server {
	listen 80;
	server_name my_host;
	rewrite ^(.*)$ https://$server_name$1 permanent;
}

server {
	listen       443 ssl;
	server_name  my_host;
	root         /var/www/html;

	ssl_certificate     /etc/letsencrypt/live/my_host/cert.pem;
	ssl_certificate_key /etc/letsencrypt/live/my_host/privkey.pem;
	ssl_dhparam /etc/letsencrypt/live/my_host/dh4096.pem;

	# Сайт доступен только по https
	#add_header Strict-Transport-Security 'max-age=604800';

	# Запретить показывать сайт во фрейме11
	add_header X-Frame-Options DENY;

	# Использовать отданный сервером Сontent-type, вместо автоматического его определения
	add_header X-Content-Type-Options nosniff;

	# Активировать XSS-защиту:
	add_header X-XSS-Protection "1; mode=block";

	# http proxy to 10.0.0.1:80
	location / {
		proxy_pass                          http://10.0.0.1/;
		proxy_set_header Host               $host;
		proxy_set_header X-Real-IP          $remote_addr;
		proxy_set_header X-Forwarded-For    $remote_addr;
		proxy_set_header SERVER_PROTOCOL    $server_protocol;
		proxy_set_header SERVER_PORT        $server_port;
		proxy_set_header SERVER_NAME        $server_name;
		proxy_set_header REMOTE_USER        $remote_user;
		proxy_set_header REMOTE_PORT        $remote_port;
		proxy_set_header HTTPS              $https;
		proxy_set_header REQUEST_URI        $request_uri;
		proxy_set_header SCRIPT_NAME        /redmine;
		proxy_set_header QUERY_STRING       $query_string;
	}
```

# Обновление сертификата LetsEncrypt

```
letsencrypt renew -a webroot --webroot-path=/var/www/html
```

В Cron добавить строчку
```
23            03      1       *       *       letsencrypt renew -a webroot --webroot-path=/var/www/html && service nginx reload
```

# Материалы

1. [Nginx и https. Получаем класс А+](https://habrahabr.ru/post/252821/)
1. [Проверка качества защиты вашего сервера](https://www.ssllabs.com/ssltest/index.html)
1. [Создание самоподписанного сертификата](https://www.digitalocean.com/community/tutorials/how-to-create-an-ssl-certificate-on-nginx-for-ubuntu-14-04)
1. [How To Secure Nginx with Let's Encrypt on Ubuntu 16.04](https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04)


text:
exports.run = function(client, message, args, result, prefix) {
  var ballAnswers = ['no', 'yes', 'i guess', 'i\'m not sure', 'you will know soon', 'that\'s a tricky question!', 'Better not tell you now', 'my sources say no', 'returns True', 'returns False'];
  var ballEmoji = [':wink:', ':thinking:', ':thumbsup:', ':joy:', ':face_palm:', ':crystal_ball:', ':heart_eyes:'];

  if (!result) {
  message.channel.send('Did you ask a question? Try again!')
} else {
  message.channel.send('[**8ball**] :crystal_ball: ' + message.author.username + ' asked `' + result + '`, and my answer is `' + ballAnswers[Math.floor(Math.random()*ballAnswers.length)] + '` ' + ballEmoji[Math.floor(Math.random()*ballEmoji.length)])
}
}


text:
(function() {

    'use strict';

    angular
        .module('app.<%= moduleName %>')
        .factory('<%= factoryName %>Factory', <%= factoryName %>Factory);

    function <%= factoryName %>Factory() {

        return{
            test: test
        }

        function test(search){

            // some awesome code

        }

    }
}());


text:
<?php
namespace PayPal;
use PayPal\AbstractResponseType;

class DoExpressCheckoutPaymentResponseType  extends AbstractResponseType
  {

	/**
	 *
	 * @access public

	 * @namespace ebl

	 * @var DoExpressCheckoutPaymentResponseDetailsType
	 */
	public $DoExpressCheckoutPaymentResponseDetails;

	/**
	 *
	 * @access public

	 * @namespace ns

	 * @var FMFDetailsType
	 */
	public $FMFDetails;

}


text:
package com.ptoceti.osgi.obix.domain;

public class DomainException extends Exception{

	/**
	 *
	 */
	private static final long serialVersionUID = 1528521210323220324L;

	public DomainException(String message){
		super(message);
	}

	public DomainException(String message, Throwable cause ){
		super(message, cause);
	}

	public DomainException(Throwable cause ){
		super(cause);
	}
}


text:
import {TodoApp} from './index_common';
import {bootstrapApp} from '../../../../@angular/platform-browser/src/worker_app';

export function main() {
  bootstrapApp(TodoApp);
}


text:
package wdl.transforms.base.wdlom2wom.graph

import cats.syntax.apply._
import cats.syntax.validated._
import cats.syntax.traverse._
import cats.instances.list._
import common.validation.ErrorOr.{ErrorOr, _}
import wdl.model.draft3.graph.expression.TypeEvaluator.ops._
import wdl.model.draft3.graph.GraphElementValueConsumer.ops._
import wdl.model.draft3.graph.UnlinkedValueGenerator.ops._
import wdl.transforms.base.linking.graph._
import wdl.transforms.base.wdlom2wom.WorkflowDefinitionElementToWomWorkflowDefinition
import wdl.transforms.base.wdlom2wom.WorkflowDefinitionElementToWomWorkflowDefinition.GraphLikeConvertInputs
import wdl.transforms.base.wdlom2wom.expression.WdlomWomExpression
import wdl.model.draft3.elements._
import wdl.model.draft3.graph._
import wdl.model.draft3.graph.expression.{FileEvaluator, TypeEvaluator, ValueEvaluator}
import wdl.shared.transforms.wdlom2wom.WomGraphMakerTools
import wom.callable.Callable
import wom.graph.GraphNodePort.OutputPort
import wom.graph._
import wom.graph.expression.{AnonymousExpressionNode, PlainAnonymousExpressionNode}
import wom.types.{WomAnyType, WomBooleanType, WomType}

object IfElementToGraphNode {
  def convert(a: ConditionalNodeMakerInputs)
             (implicit expressionValueConsumer: ExpressionValueConsumer[ExpressionElement],
              fileEvaluator: FileEvaluator[ExpressionElement],
              typeEvaluator: TypeEvaluator[ExpressionElement],
              valueEvaluator: ValueEvaluator[ExpressionElement]): ErrorOr[Set[GraphNode]] = {
    val conditionExpression = a.node.conditionExpression
    val graphElements = a.node.graphElements

    val conditionWomExpressionV: ErrorOr[WdlomWomExpression] = WdlomWomExpression.make(conditionExpression, a.linkableValues)
    val conditionExpressionNodeValidation: ErrorOr[AnonymousExpressionNode] = conditionWomExpressionV flatMap { conditionWomExpression =>
      AnonymousExpressionNode.fromInputMapping(WomIdentifier("if_condition"), conditionWomExpression, a.linkablePorts, PlainAnonymousExpressionNode.apply) }

    val conditionVariableTypeValidation: ErrorOr[Unit] = conditionExpression.evaluateType(a.linkableValues) flatMap {
      case WomBooleanType | WomAnyType => ().validNel
      case other => s"Invalid type for condition variable: ${other.stableName}".invalidNel
    }

    final case class RequiredOuterPorts(valueGeneratorPorts: Map[String, OutputPort], completionPorts: Map[String, CallNode])

    val foundOuterGeneratorsValidation: ErrorOr[RequiredOuterPorts] = {
      val required: ErrorOr[Set[UnlinkedConsumedValueHook]] = graphElements.toList.traverse { element => element.graphElementConsumedValueHooks(a.availableTypeAliases, a.callables) }.map(_.toSet.flatten)
      val generated: ErrorOr[Set[GeneratedValueHandle]] = graphElements.toList.traverse { element => element.generatedValueHandles(a.availableTypeAliases, a.callables) }.map(_.toSet.flatten)

      def makeLink(hook: UnlinkedConsumedValueHook): (String, OutputPort) = {
        val name = a.linkableValues(hook).linkableName
        val port = a.linkablePorts(name)
        name -> port
      }

      (required, generated) mapN { (r, g) =>
        val requiredOuterValues = r collect {
          case hook@UnlinkedIdentifierHook(id) if !g.exists(_.linkableName == id) => makeLink(hook)
          case hook@UnlinkedCallOutputOrIdentifierAndMemberAccessHook(first, second) if !g.exists(_.linkableName == first) && !g.exists(_.linkableName == s"$first.$second") => makeLink(hook)
        }
        val requiredCompletionPorts = r collect {
          case UnlinkedAfterCallHook(upstreamCallName) if !g.exists {
            case GeneratedCallFinishedHandle(`upstreamCallName`) => true
            case _ => false
          } => upstreamCallName -> a.upstreamCalls.values.find(_.localName == upstreamCallName).get
        }

        RequiredOuterPorts(requiredOuterValues.toMap, requiredCompletionPorts.toMap)
      }
    }

    (conditionExpressionNodeValidation, conditionVariableTypeValidation, foundOuterGeneratorsValidation) flatMapN { (expressionNode, _, foundOuterGenerators) =>
      val ogins: Set[GraphNode] = (foundOuterGenerators.valueGeneratorPorts.toList map { case (name: String, port: OutputPort) =>
        OuterGraphInputNode(WomIdentifier(name), port, preserveScatterIndex = true)
      }).toSet

      val graphLikeConvertInputs = GraphLikeConvertInputs(graphElements.toSet, ogins, foundOuterGenerators.completionPorts, a.availableTypeAliases, a.workflowName,
                                                          insideAScatter = a.insideAnotherScatter,
                                                          convertNestedScatterToSubworkflow = a.convertNestedScatterToSubworkflow,
                                                          allowNestedInputs = a.allowNestedInputs,
                                                          a.callables)
      val innerGraph: ErrorOr[Graph] = WorkflowDefinitionElementToWomWorkflowDefinition.convertGraphElements(graphLikeConvertInputs)

      innerGraph map { ig =>
        val withOutputs = WomGraphMakerTools.addDefaultOutputs(ig)
        val generatedAndNew = ConditionalNode.wireInConditional(withOutputs, expressionNode)
        generatedAndNew.nodes
      }
    }
  }
}

final case class ConditionalNodeMakerInputs(node: IfElement,
                                            upstreamCalls: Map[String, CallNode],
                                            linkableValues: Map[UnlinkedConsumedValueHook, GeneratedValueHandle],
                                            linkablePorts: Map[String, OutputPort],
                                            availableTypeAliases: Map[String, WomType],
                                            workflowName: String,
                                            insideAnotherScatter: Boolean,
                                            convertNestedScatterToSubworkflow : Boolean,
                                            allowNestedInputs: Boolean,
                                            callables: Map[String, Callable])


text:
package com.HQHub.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.HQHub.DAO.UserDAO;
import com.HQHub.pojo.User;
import com.alibaba.fastjson.JSON;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String username;
	private String phone;
	private String password;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");

		PrintWriter out = response.getWriter();

		String type = request.getParameter("type");
		switch (type) {

		case"login":

			phone = request.getParameter("phone");
			password = request.getParameter("password");

			User user = UserDAO.loginValidate(phone, password);

		    out.println(JSON.toJSON(user));
			break;

		case "register":

			username = request.getParameter("username");
			password = request.getParameter("password");
			phone = request.getParameter("phone");

			boolean accept = !UserDAO.registerValidate(phone);
			if (accept) {
				User u = new User(username, password, phone);
				boolean flag = UserDAO.Add(u);
				if (flag) {
					out.println("success");
				} else {
					out.println("fail");
				}
			} else {
				out.println("already");
			}
			break;

		}

		out.flush();
		out.close();

	}

}


text:
#include <linux/input.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>

#include "common.h"
#include "device.h"
#include "screen_ui.h"

const char* HEADERS[] = { "Volume up/down to move highlight;",
                          "power button to select.",
                          "",
                          NULL };

const char* ITEMS[] = { "reboot system now",
                        "apply update from ADB",
                        "wipe data/factory reset",
                        "wipe cache partition",
                        NULL };

class MakoUI : public ScreenRecoveryUI
{
public:
    MakoUI() :
        consecutive_power_keys(0) {
    }

    virtual KeyAction CheckKey(int key) {
        if (IsKeyPressed(KEY_POWER) && key == KEY_VOLUMEUP) {
            return TOGGLE;
        }
        if (key == KEY_POWER) {
            ++consecutive_power_keys;
            if (consecutive_power_keys >= 7) {
                return REBOOT;
            }
        } else {
            consecutive_power_keys = 0;
        }
        return ENQUEUE;
    }

private:
    int consecutive_power_keys;
};

class MakoDevice : public Device
{
public:
    MakoDevice() :
        ui(new MakoUI) {
    }

    RecoveryUI* GetUI() { return ui; }

    int HandleMenuKey(int key_code, int visible) {
        if (visible) {
            switch (key_code) {
            case KEY_DOWN:
            case KEY_VOLUMEDOWN:
                return kHighlightDown;

            case KEY_UP:
            case KEY_VOLUMEUP:
                return kHighlightUp;

            case KEY_POWER:
                return kInvokeItem;
            }
        }

        return kNoAction;
    }

    BuiltinAction InvokeMenuItem(int menu_position) {
        switch (menu_position) {
        case 0: return REBOOT;
        case 1: return APPLY_ADB_SIDELOAD;
        case 2: return WIPE_DATA;
        case 3: return WIPE_CACHE;
        default: return NO_ACTION;
        }
    }

    const char* const* GetMenuHeaders() { return HEADERS; }
    const char* const* GetMenuItems() { return ITEMS; }

private:
    RecoveryUI* ui;
};

Device* A66_device() {
    return new A66Device;
}


text:
A set of example systems built with actors in order of their complexity:

 * [Ping Pong](ping-pong/)


text:
import ApiBase from "../Api"

module Model{
    export module Api{
        export class SecondaryIndividualItem extends ApiBase{
            getUrl(){
                return 'http://localhost/api/secondary_individual_item/'
            }
        }
    }
}

export default Model.Api.SecondaryIndividualItem


text:
function StockResource($resource){
  return $resource('/api/v1/stocks', {userId:'@id'}, {
    get: {method: 'GET', isArray: true},
    create: {method: 'POST'},
    delete: {method: 'DELETE', isArray: true}
  });
};

angular
.module('app')
.factory('StockResource', StockResource);


text:
System.register(["./isWhitespaceOrReplacementCharacter"], function (exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    function isAllWhitespaceOrReplacementCharacters(characters) {
        for (var _i = 0, characters_1 = characters; _i < characters_1.length; _i++) {
            var ch = characters_1[_i];
            if (!isWhitespaceOrReplacementCharacter_1.isWhitespaceOrReplacementCharacter(ch)) {
                return false;
            }
        }
        return true;
    }
    exports_1("isAllWhitespaceOrReplacementCharacters", isAllWhitespaceOrReplacementCharacters);
    var isWhitespaceOrReplacementCharacter_1;
    return {
        setters: [
            function (isWhitespaceOrReplacementCharacter_1_1) {
                isWhitespaceOrReplacementCharacter_1 = isWhitespaceOrReplacementCharacter_1_1;
            }
        ],
        execute: function () {
        }
    };
});


text:
extern crate gluon_language_server;
extern crate languageserver_types;

extern crate jsonrpc_core;
extern crate serde_json;
extern crate serde;

mod support;

use std::io::Write;

use languageserver_types::{Hover, MarkedString, Position, TextDocumentPositionParams,
                           TextDocumentIdentifier};

fn hover<W: ?Sized>(stdin: &mut W, id: u64, uri: &str, position: Position)
    where W: Write,
{
    let hover = support::method_call("textDocument/hover",
                                     id,
                                     TextDocumentPositionParams {
                                         text_document: TextDocumentIdentifier { uri: uri.into() },
                                         position: position,
                                     });

    support::write_message(stdin, hover).unwrap();
}

const STREAM_SOURCE: &'static str = r#"
let prelude = import "std/prelude.glu"
and { Option, Num } = prelude
and { (+) } = prelude.num_Int

type Stream_ a =
    | Value a (Stream a)
    | Empty
and Stream a = Lazy (Stream_ a)

let from f : (Int -> Option a) -> Stream a =
        let from_ i =
                lazy (\_ ->
                    match f i with
                        | Some x -> Value x (from_ (i + 1))
                        | None -> Empty
                )
        in from_ 0

{ from }
"#;

#[test]
fn simple_hover() {
    let hover: Hover = support::send_rpc(|mut stdin| {

        support::did_open(stdin, "test", "123");

        hover(stdin,
              2,
              "test",
              Position {
                  line: 0,
                  character: 2,
              });
    });

    assert_eq!(hover,
               Hover {
                   contents: vec![MarkedString::String("Int".into())],
                   range: None,
               });
}

#[test]
fn identifier() {
    let hover: Hover = support::send_rpc(|mut stdin| {
        let src = r#"
let test = 1
test
"#;
        support::did_open(stdin, "test", src);

        hover(stdin,
              2,
              "test",
              Position {
                  line: 2,
                  character: 2,
              });
    });

    assert_eq!(hover,
               Hover {
                   contents: vec![MarkedString::String("Int".into())],
                   range: None,
               });
}

#[test]
fn stream() {
    let hover: Hover = support::send_rpc(|mut stdin| {

        support::did_open(stdin, "stream", STREAM_SOURCE);

        hover(stdin,
              2,
              "stream",
              Position {
                  line: 13,
                  character: 29,
              });
    });

    assert_eq!(hover,
               Hover {
                   contents: vec![MarkedString::String("Int".into())],
                   range: None,
               });
}


text:
'''A few pure-python statistical tools to avoid the need to install scipy. '''
from __future__ import division # Division of integers with / should never round!
from math import exp, log, sqrt, gamma, lgamma, erf
import itertools

__author__ = "dpark@broadinstitute.org, irwin@broadinstitute.org"

try:
    # Python 3.4
    from statistics import mean, median
except ImportError:
    # Python <3.4, avoid numpy if these two methods are all we really need
    def mean(l):
        if len(l)>0:
            return float(sum(l))/len(l)
        else:
            raise Exception("empty list for mean")
    def median(l):
        if len(l)>0:
            half = len(l) // 2
            l.sort()
            if len(l) % 2 == 0:
                return (l[half-1] + l[half]) / 2.0
            else:
                return l[half]
        else:
            raise Exception("empty list for median")

def product(iter_obj) :
    prod = 1
    for x in iter_obj :
        prod *= x
    return prod

def chi2_contingency(contingencyTable, correction = True) :
    """ contingencyTable is a sequence of m sequences, each of length n.
        Return an estimate using the chi-square distribution of the two-tailed
            p-value for an m x n contingency table against the null hypothesis
            that the row and column criteria are independent. This is not as
            accurate as fisher_exact, but is faster (and is implemented for all
            m and n).
        If correction is True and there is 1 degree of freedom, apply Yates's
            correction for continuity, i.e., adjust each observed value
            by 0.5 towards the corresponding expected value, which brings
            the result closer to the Fisher exact test result.
        Not recommended if any of the counts or expected counts are
            less than 5.
    """
    # scipy equivalent:  scipy.stats.chi2_contingency(contingencyTable)[1]

    if len(contingencyTable) == 0 :
        return 1.0
    if len(set(map(len, contingencyTable))) != 1 :
        raise ValueError('Not all rows have the same length')

    # Eliminate rows and columns with 0 sum
    colSums = [sum(row[col] for row in contingencyTable)
               for col in range(len(contingencyTable[0]))]
    table = [[x for x, colSum in zip(row, colSums) if colSum != 0]
             for row in contingencyTable if sum(row) != 0]

    if len(table) < 2 or len(table[0]) < 2 :
        return 1.0

    m = len(table)
    n = len(table[0])
    rowSums = [sum(row) for row in table]
    colSums = [sum(row[col] for row in table) for col in range(n)]
    N = sum(rowSums)
    expect = [[rowSums[i] * colSums[j] / N for j in range(n)] for i in range(m)]
    if correction and m == n == 2 :
        def corr(i, j) :
            if expect[i][j] > table[i][j] :
                return min(table[i][j] + 0.5, expect[i][j])
            else :
                return max(table[i][j] - 0.5, expect[i][j])
        table = [[corr(i, j) for j in range(n)] for i in range(m)]
    chisq = sum((table[i][j] - expect[i][j]) ** 2 / expect[i][j]
                for j in range(n)
                for i in range(m))
    pval = 1 - pchisq(chisq, (m - 1) * (n - 1))
    return pval

def fisher_exact(contingencyTable) :
    """ Fisher exact test for the 2 x n case.
        contingencyTable is a sequence of 2 length-n sequences of integers.
        Return the two-tailed p-value against the null hypothesis that the row
            and column criteria are independent, using Fisher's exact test.
        For n larger than 2, this is very slow, O(S^(n-1)), where S is the
            smaller of the two row sums. Better to use chi2_contingency unless
            one of the row sums is small.
        Handles m x n contingencyTable with m > 2 if it can be reduced to the
            2 x n case by transposing or by removing rows that are all 0s. Also
            handles degenerate cases of 0 or 1 row by returning 1.0.
    """
    if len(contingencyTable) == 0 :
        return 1.0
    if len(set(map(len, contingencyTable))) != 1 :
        raise ValueError('Not all rows have the same length')
    if any(x != int(x) for row in contingencyTable for x in row) :
        raise ValueError('Some table entry is not an integer')
    if any(x < 0 for row in contingencyTable for x in row) :
        raise ValueError('Some table entry is negative')

    # Eliminate rows and columns with 0 sum
    colSums = [sum(row[col] for row in contingencyTable)
               for col in range(len(contingencyTable[0]))]
    table = [[x for x, colSum in zip(row, colSums) if colSum != 0]
             for row in contingencyTable if sum(row) != 0]

    if len(table) < 2 or len(table[0]) < 2 :
        return 1.0

    if len(table) > len(table[0]) :
        table = list(zip(*table)) # Transpose

    m = len(table)
    n = len(table[0])
    if m != 2 :
        raise NotImplementedError('More than 2 non-zero rows and columns.')

    # Put row with smaller sum first. Makes the loop iterations simpler.
    table.sort(key = sum)
    # Put column with largest sum last. Makes loop quick rejection faster.
    table = list(zip(*table)) # Transpose
    table.sort(key = sum)
    table = list(zip(*table)) # Transpose back

    # There are many optimizations possible for the following code, but it would
    #     still be O(S^(n-1)) so it would still be too slow for anything
    #     sizeable, and it's usable as it for small things.

    rowSums = [sum(row) for row in table]
    colSums = [sum(row[col] for row in table) for col in range(n)]

    logChooseNrowSum = log_choose(sum(rowSums), rowSums[0])

    def prob_of_table(firstRow) :
        return exp(sum(log_choose(cs, a) for cs, a in zip(colSums, firstRow)) -
                   logChooseNrowSum)

    p0 = prob_of_table(table[0])
    result = 0
    for firstRowM1 in itertools.product(*[range(min(rowSums[0], colSums[i]) + 1)
                                         for i in range(n - 1)]) :
        lastElmt = rowSums[0] - sum(firstRowM1)
        if lastElmt < 0 or lastElmt > colSums[-1] :
            continue
        prob = prob_of_table(firstRowM1 + (lastElmt,))
        if prob <= p0 + 1e-9 : # (1e-9 handles floating point round off)
            result += prob

    return result

def log_choose(n, k) :
    # Return log(n choose k). Compute using lgamma(x + 1) = log(x!)
    if not (0 <= k <=n) :
        raise ValueError('%d is negative or more than %d' % (k, n))
    return lgamma(n + 1) - lgamma(k + 1) - lgamma(n - k + 1)

def gammainc_halfint(s, x) :
    """ Lower incomplete gamma function =
            integral from 0 to x of t ** (s-1) exp(-t) dt divided by gamma(s),
        i.e., the fraction of gamma that you get if you integrate only until
            x instead of all the way to infinity.
        Implemented here only if s is a positive multiple of 0.5.
    """
    # scipy equivalent: scipy.special.gammainc(s,x)

    if s <= 0 :
        raise ValueError('%s is not positive' % s)
    if x < 0 :
        raise ValueError('%s < 0' % x)
    if s * 2 != int(s * 2) :
        raise NotImplementedError('%s is not a multiple of 0.5' % s)

    # Handle integers analytically
    if s == int(s) :
        term = 1
        total = 1
        for k in range(1, int(s)) :
            term *= x /  k
            total += term
        return 1 - exp(-x) * total

    # Otherwise s is integer + 0.5. Decrease to 0.5 using recursion formula:
    result = 0.0
    while s > 1 :
        result -= x ** (s - 1) * exp(-x) / gamma(s)
        s = s - 1
    # Then use gammainc(0.5, x) = erf(sqrt(x))
    result += erf(sqrt(x))
    return result

def pchisq(x, k) :
    "Cumulative distribution function of chi squared with k degrees of freedom."
    if k < 1 or k != int(k) :
        raise ValueError('%s is not a positive integer' % k)
    if x < 0 :
        raise ValueError('%s < 0' % x)
    return gammainc_halfint(k / 2, x / 2)


text:
	<title>日期计算</title>

开始日期:
<input id="begin-date-input" type="date" placeholder="格式:2018-08-09" />

假期天数:
<input id="calculate-days" type="number" placeholder="这里填假期天数" />

截止日期:
<input id="end-date-input" type="date" placeholder="格式:2018-08-09"  >

<button onclick="onClickCalculateButton()">计   算</button>


text:
<!DOCTYPE html>
<html>
  <head>
    <title>Listing 4.6</title>
    <script type="text/javascript" src="../scripts/assert.js"></script>
    <link href="../styles/assert.css" rel="stylesheet" type="text/css">
  </head>

  <body>
    <script type="text/javascript">

      var ninja = function myNinja(){                                  //#1
        assert(ninja == myNinja,                                       //#2
               "This function is named two things at once!");          //#2
      };

      ninja();                                                         //#3

      assert(typeof myNinja == "undefined",                            //#4
             "But myNinja isn't defined outside of the function.");    //#4

    </script>
  </body>
</html>


text:
package model;

import pagelets.HeaderModel;
import pagelets.WordsModel;

public class IndexPageModel {

    private HeaderModel headerModel;
    private WordsModel wordsModel;

    public IndexPageModel(final HeaderModel headerModel, final WordsModel wordsModel) {
        this.headerModel = headerModel;
        this.wordsModel = wordsModel;
    }

    public WordsModel getWordsModel() {
        return wordsModel;
    }

    public HeaderModel getHeaderModel() {
        return headerModel;
    }

}


text:
class Destination {

  constructor(id, country="", city="") {
    this.id = id;
    this.country = country;
    this.city = city;
  }

  toString() {
    return JSON.stringify(this);
  }

}

module.exports = Destination;


text:
module Azure::Reservations::Mgmt::V2019_04_01_preview
  module Models
    #
    # Defines values for InstanceFlexibility
    #
    module InstanceFlexibility
      On = "On"
      Off = "Off"
    end
  end
end


text:
package com.spencerwi.hamcrestJDK8Time.matchers;

import org.junit.Test;

import java.time.LocalDate;
import java.time.temporal.ChronoField;

import static com.spencerwi.hamcrestJDK8Time.matchers.IsSame.same;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;

public class IsSameLocalDateTest {

    @Test
    public void matchesIfSpecifiedFieldHasTheSameValue(){
        LocalDate januaryFirst1970 = LocalDate.of(1970, 1, 1);
        LocalDate decemberThirtyFirst1970 = LocalDate.of(1970, 12, 30);

        assertThat(januaryFirst1970, is(same(ChronoField.YEAR).as(decemberThirtyFirst1970)));
    }

    @Test
    public void doesNotMatchIfSpecifiedFieldHasDifferentValue(){
        LocalDate januaryFirst1970 = LocalDate.of(1970, 1, 1);
        LocalDate decemberThirtyFirst1970 = LocalDate.of(1970, 12, 30);

        assertThat(januaryFirst1970, is(not(same(DAY_OF_MONTH).as(decemberThirtyFirst1970))));
        assertThat(januaryFirst1970, is(not(same(MONTH_OF_YEAR).as(decemberThirtyFirst1970))));
    }
}


text:
require 'json'
require 'rest-client'
require 'parallel'
require 'active_support/core_ext/hash/indifferent_access'
require 'papercall/models/submission'
require 'papercall/models/rating'
require 'papercall/models/feedback'

module Papercall
  # Fetches submissions from Papercall REST API
  # Params:
  class RestFetcher < Fetcher
    SUBMISSIONS_URL = 'https://www.papercall.io/api/v1/submissions'.freeze

    def initialize()
      @output = Papercall.configuration.output
      api_key = Papercall.configuration.API_KEY
      raise ArgumentError, 'Missing API_KEY for access to Papercall. Please refer to documentation for instructions on setting this value.' unless api_key
      @auth_hash = { Authorization: api_key }
      @submitted = []
      @accepted = []
      @rejected = []
      @waitlist = []
      @declined = []
    end

    def submission_url(state, per_page: 150)
      "#{SUBMISSIONS_URL}?state=#{state}&per_page=#{per_page}"
    end

    def papercall(papercall_url)
      raw_results =
        RestClient::Request.execute(method: :get,
                                    url: papercall_url,
                                    headers: @auth_hash) # :timeout => 120
      if raw_results
        JSON.parse(raw_results).map {|r| r.with_indifferent_access}
      else
        []
      end
    end

    def fetch(*states)
      states = [%i[submitted accepted rejected waitlist declined]] if states == [[:all]]
      states.flatten.each do |state|
        next unless state
        start_time = Time.now
        print "Fetching #{state} submissions from PaperCall API..." if @output
        submissions = papercall(submission_url(state.to_s))
        instance_variable_set("@#{state}_raw", submissions)
        instance_variable_set("@#{state}", submissions.map {|s| Submission.new(s)})
        puts "finished in #{Time.now - start_time} seconds." if @output
      end
      fetch_ratings
      fetch_feedback
    end

    def fetch_ratings
      start_time = Time.now
      print 'Fetching ratings for all submissions from Papercall API...' if @output

      Parallel.each(analysis, in_threads: 128) do |submission|
        if submission.ratings.empty?
          ratings_url = "#{SUBMISSIONS_URL}/#{submission.id}/ratings"
          ratings = papercall(ratings_url).map {|r| Rating.new(r)}
          submission.ratings = ratings
        end
        #submission.ratings = [] unless submission.ratings
      end
      puts "finished in #{Time.now - start_time} seconds." if @output
    end

    def fetch_feedback
      start_time = Time.now
      print 'Fetching feedback for all submissions from Papercall API...' if @output
      Parallel.each(analysis, in_threads:  128) do |submission|
        if submission.feedback.empty?
          feedback_url = "#{SUBMISSIONS_URL}/#{submission.id}/feedback"
          submission.feedback = papercall(feedback_url).map {|f| Feedback.new(f)}
        end
        #submission.feedback = [] unless submission.feedback
      end
      puts "finished in #{Time.now - start_time} seconds." if @output
    end
  end
end


text:
package org.lognet.springboot.grpc.security;

import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ClientInterceptors;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;

/**
 * Adds Authorization header with configured authentication scheme token supplied by tokeSupplier to each intercepted client call
 */

public class AuthClientInterceptor implements ClientInterceptor {
    private AuthHeader authHeader;

    public AuthClientInterceptor(AuthHeader authHeader) {
        this.authHeader = authHeader;
    }
    public AuthClientInterceptor(AuthHeader.AuthHeaderBuilder authHeaderBuilder) {
        this(authHeaderBuilder.build());
    }

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions, Channel next) {
        return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>(next.newCall(methodDescriptor, callOptions)) {
            @Override
            protected void checkedStart(Listener<RespT> responseListener, Metadata headers) throws Exception {
                delegate().start(responseListener, authHeader.attach(headers));
            }
        };
    }
}


text:
package net.spals.appbuilder.mapstore.dynamodb

import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec
import com.amazonaws.services.dynamodbv2.document.{PrimaryKey, RangeKeyCondition}
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType
import com.google.common.annotations.VisibleForTesting
import net.spals.appbuilder.mapstore.core.model.MapRangeOperator.{Extended, Standard}
import net.spals.appbuilder.mapstore.core.model.{MapQueryOptions, MapStoreKey}
import net.spals.appbuilder.mapstore.core.model.TwoValueMapRangeKey.TwoValueHolder

import scala.compat.java8.OptionConverters._

/**
  * Shared utilities for [[DynamoDBMapStorePlugin]]
  * and [[DynamoDBMapStoreIndexPlugin]].
  *
  * @author tkral
  */
private[dynamodb] object DynamoDBMapStoreUtil {

  private[dynamodb] def createAttributeType(fieldType: Class[_]): ScalarAttributeType = {
    fieldType match {
      case booleanType if booleanType.equals(classOf[Boolean]) => ScalarAttributeType.B
      case byteType if byteType.equals(classOf[Byte]) => ScalarAttributeType.N
      case doubleType if doubleType.equals(classOf[Double]) => ScalarAttributeType.N
      case floatType if floatType.equals(classOf[Float]) => ScalarAttributeType.N
      case intType if intType.equals(classOf[Int]) => ScalarAttributeType.N
      case javaBooleanType if javaBooleanType.equals(classOf[java.lang.Boolean]) => ScalarAttributeType.B
      case javaNumberType if classOf[java.lang.Number].isAssignableFrom(javaNumberType) => ScalarAttributeType.N
      case longType if longType.equals(classOf[Long]) => ScalarAttributeType.N
      case shortType if shortType.equals(classOf[Short]) => ScalarAttributeType.N
      case _ => ScalarAttributeType.S
    }
  }

  @VisibleForTesting
  private[dynamodb] def createPrimaryKey(key: MapStoreKey): PrimaryKey = {
    key.getRangeField.asScala
      .map(rangeField => new PrimaryKey(key.getHashField, key.getHashValue, rangeField, key.getRangeKey.getValue))
      .getOrElse(new PrimaryKey(key.getHashField, key.getHashValue))
  }

  @VisibleForTesting
  private[dynamodb] def createQuerySpec(
    key: MapStoreKey,
    options: MapQueryOptions
  ): QuerySpec = {
    val querySpec = new QuerySpec().withHashKey(key.getHashField, key.getHashValue)
    createRangeKeyCondition(key).foreach(rangeKeyCondition => querySpec.withRangeKeyCondition(rangeKeyCondition))

    querySpec.withScanIndexForward(options.getOrder == MapQueryOptions.Order.ASC)
    options.getLimit.asScala.foreach(limit => querySpec.withMaxResultSize(limit))
    querySpec
  }

  @VisibleForTesting
  private[dynamodb] def createRangeKeyCondition(key: MapStoreKey): Option[RangeKeyCondition] = {
    key.getRangeField.asScala.flatMap(rangeField => {
      val rangeKeyCondition = new RangeKeyCondition(rangeField)
      (key.getRangeKey.getOperator, key.getRangeKey.getValue) match {
        case (Standard.ALL, _) => Option.empty[RangeKeyCondition]
        case (Standard.NONE, _) => Option.empty[RangeKeyCondition]
        case (Standard.BETWEEN, rValue) =>
          Option(rangeKeyCondition.between(rValue.asInstanceOf[TwoValueHolder[_]].getValue1,
            rValue.asInstanceOf[TwoValueHolder[_]].getValue2))
        case (Standard.EQUAL_TO, rValue) => Option(rangeKeyCondition.eq(rValue))
        case (Standard.GREATER_THAN, rValue) => Option(rangeKeyCondition.gt(rValue))
        case (Standard.GREATER_THAN_OR_EQUAL_TO, rValue) => Option(rangeKeyCondition.ge(rValue))
        case (Standard.LESS_THAN, rValue) => Option(rangeKeyCondition.lt(rValue))
        case (Standard.LESS_THAN_OR_EQUAL_TO, rValue) => Option(rangeKeyCondition.le(rValue))
        case (Extended.STARTS_WITH, rValue) => Option(rangeKeyCondition.beginsWith(rValue.asInstanceOf[String]))
        case (operator, _) =>
          throw new IllegalArgumentException(s"DynamoDB cannot support the operator $operator")
      }
    })
  }
}


text:
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :provider
      t.string :uid
      t.string :name
      t.string :token
      t.string :secret
      t.string :profile_image

      t.timestamps null: false
    end
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

	<meta http-equiv="X-UA-Compatible" content="IE=edge" />

	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title></title>

									Новая модель доступна для покупки в «М.Видео».

									Письмо не отображается корректно?

Телевизоры и цифровое ТВ

Ноутбуки

Планшеты

Apple

Смартфоны
и сотовые телефоны

Электронные книги

Фото и видео

Аудио

Красота и здоровье

Малая бытовая техника

Крупная бытовая техника

Автотехника

Игры и развлечения

Компьютерные
программы

Аксессуары

									Вы можете отписаться и не получать информацию об акциях, распродажах и спецпредложениях.

									Данное сообщение отправлено автоматически и не требует ответа.

									Чтобы регулярно и без проблем получать рассылку от «М.Видео», пожалуйста, добавьте адрес m.video@sender.mvideo.ru в свою адресную книгу.

									Цены и скидки на товары действительны на момент отправки данного письма в городе:

									ООО «М.видео Менеджмент», ОГРН 1057746840095.

Юридический адрес: 105066, Россия, Москва, ул. Нижняя Красносельская, дом 40/12, корп. 20.

																  Copyright © М.Видео, 2017

																Политика конфиденциальности


text:
package com.streamsets.datacollector.restapi;

import io.swagger.annotations.Api;
import io.swagger.jaxrs.Reader;
import io.swagger.jaxrs.config.ReaderListener;
import io.swagger.models.Swagger;
import io.swagger.models.auth.BasicAuthDefinition;

@Api
public class SwaggerReaderListener implements ReaderListener {
  public void beforeScan(Reader reader, Swagger swagger) {
  }

  public void afterScan(Reader reader, Swagger swagger) {
    swagger.securityDefinition("basic", new BasicAuthDefinition());
  }
}


text:
package com.ja.smarkdown.location.file;

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

import javax.inject.Inject;

import com.ja.smarkdown.model.LocationHandler;
import com.ja.smarkdown.model.ResourceInfo;
import com.ja.smarkdown.model.config.Location;

public class FileLocationHandler implements LocationHandler {

	@Inject
	private FileListingProvider listing;
	@Inject
	private FileDocumentProvider documents;

	private List<Location> locations = new ArrayList<Location>();

	@Override
	public List<String> listDocuments() {
		return listing.getDocuments(locations);
	}

	@Override
	public ResourceInfo loadDocument(final String resource) {
		return documents.getDocument(locations, resource);
	}

	@Override
	public void add(final Location location) {
		locations.add(location);
	}

}


text:
'use strict'

module.exports = function randray(arr) {
  if (!Array.isArray(arr))
    throw new Error('argument must be an array')

  const len = arr.length

  if (!len)
    return null

  return arr[Math.floor(Math.random() * len)]
}


text:
package org.spoofax.interpreter.library.ssl;

import java.io.IOException;

import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.library.IOAgent;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.terms.util.TermUtils;

public class SSL_fputc extends AbstractPrimitive {

    protected SSL_fputc() {
        super("SSL_fputc", 0, 2);
    }

    @Override
    public boolean call(IContext env, Strategy[] sargs, IStrategoTerm[] targs) throws InterpreterException {

        if(!(TermUtils.isInt(targs[0])))
            return false;
        if(!(TermUtils.isInt(targs[1])))
            return false;

        SSLLibrary or = (SSLLibrary) env.getOperatorRegistry(SSLLibrary.REGISTRY_NAME);

        IOAgent agent = or.getIOAgent();

        try {
            agent.writeChar(TermUtils.toJavaInt(targs[1]), TermUtils.toJavaInt(targs[0]));
        } catch(IOException e) {
            throw new InterpreterException(e);
        }

        env.setCurrent(targs[1]);
        return true;
    }
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 15.10.6.2-9-e-1
description: >
    RegExp.prototype.exec - the removed step 9.e won't affected
    current algorithm
includes: [runTestCase.js]
---*/

function testcase() {
        var str = "Hello World!";
        var regObj = new RegExp("World");
        var result = false;
        result = regObj.exec(str).toString() === "World";
        return result;
    }
runTestCase(testcase);


text:
package org.apache.hadoop.hive.ql.udf.generic;

import junit.framework.TestCase;

import org.apache.hadoop.hive.common.type.Date;
import org.apache.hadoop.hive.common.type.Timestamp;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF.DeferredJavaObject;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF.DeferredObject;
import org.apache.hadoop.hive.serde2.io.DateWritableV2;
import org.apache.hadoop.hive.serde2.io.TimestampWritableV2;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.io.Text;

public class TestGenericUDFDateFormat extends TestCase {

  public void testDateFormatStr() throws HiveException {
    GenericUDFDateFormat udf = new GenericUDFDateFormat();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableStringObjectInspector;
    Text fmtText = new Text("EEEE");
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory
        .getPrimitiveWritableConstantObjectInspector(TypeInfoFactory.stringTypeInfo, fmtText);
    ObjectInspector[] arguments = { valueOI0, valueOI1 };

    udf.initialize(arguments);

    // date str
    runAndVerifyStr("2015-04-05", fmtText, "Sunday", udf);
    runAndVerifyStr("2015-04-06", fmtText, "Monday", udf);
    runAndVerifyStr("2015-04-07", fmtText, "Tuesday", udf);
    runAndVerifyStr("2015-04-08", fmtText, "Wednesday", udf);
    runAndVerifyStr("2015-04-09", fmtText, "Thursday", udf);
    runAndVerifyStr("2015-04-10", fmtText, "Friday", udf);
    runAndVerifyStr("2015-04-11", fmtText, "Saturday", udf);
    runAndVerifyStr("2015-04-12", fmtText, "Sunday", udf);

    // ts str
    runAndVerifyStr("2015-04-05 10:30:45", fmtText, "Sunday", udf);
    runAndVerifyStr("2015-04-06 10:30:45", fmtText, "Monday", udf);
    runAndVerifyStr("2015-04-07 10:30:45", fmtText, "Tuesday", udf);
    runAndVerifyStr("2015-04-08 10:30:45", fmtText, "Wednesday", udf);
    runAndVerifyStr("2015-04-09 10:30", fmtText, "Thursday", udf);
    runAndVerifyStr("2015-04-10 10:30:45.123", fmtText, "Friday", udf);
    runAndVerifyStr("2015-04-11T10:30:45", fmtText, "Saturday", udf);
    runAndVerifyStr("2015-04-12 10", fmtText, "Sunday", udf);
  }

  public void testWrongDateStr() throws HiveException {
    GenericUDFDateFormat udf = new GenericUDFDateFormat();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableStringObjectInspector;
    Text fmtText = new Text("EEEE");
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory
        .getPrimitiveWritableConstantObjectInspector(TypeInfoFactory.stringTypeInfo, fmtText);
    ObjectInspector[] arguments = {valueOI0, valueOI1};

    udf.initialize(arguments);
    runAndVerifyStr("2016-02-30 10:30:45", fmtText, "Tuesday", udf);
    runAndVerifyStr("2014-01-32", fmtText, "Saturday", udf);
    runAndVerifyStr("01/14/2014", fmtText, null, udf);
    runAndVerifyStr(null, fmtText, null, udf);
  }

  public void testDateFormatDate() throws HiveException {
    GenericUDFDateFormat udf = new GenericUDFDateFormat();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableDateObjectInspector;
    Text fmtText = new Text("EEEE");
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory
        .getPrimitiveWritableConstantObjectInspector(TypeInfoFactory.stringTypeInfo, fmtText);
    ObjectInspector[] arguments = { valueOI0, valueOI1 };

    udf.initialize(arguments);

    runAndVerifyDate("2015-04-05", fmtText, "Sunday", udf);
    runAndVerifyDate("2015-04-06", fmtText, "Monday", udf);
    runAndVerifyDate("2015-04-07", fmtText, "Tuesday", udf);
    runAndVerifyDate("2015-04-08", fmtText, "Wednesday", udf);
    runAndVerifyDate("2015-04-09", fmtText, "Thursday", udf);
    runAndVerifyDate("2015-04-10", fmtText, "Friday", udf);
    runAndVerifyDate("2015-04-11", fmtText, "Saturday", udf);
    runAndVerifyDate("2015-04-12", fmtText, "Sunday", udf);
  }

  public void testDateFormatTs() throws HiveException {
    GenericUDFDateFormat udf = new GenericUDFDateFormat();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableTimestampObjectInspector;
    Text fmtText = new Text("EEEE");
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory
        .getPrimitiveWritableConstantObjectInspector(TypeInfoFactory.stringTypeInfo, fmtText);
    ObjectInspector[] arguments = { valueOI0, valueOI1 };

    udf.initialize(arguments);

    runAndVerifyTs("2015-04-08 10:30:45", fmtText, "Wednesday", udf);
    runAndVerifyTs("2015-04-05 10:30:45", fmtText, "Sunday", udf);
    runAndVerifyTs("2015-04-06 10:30:45", fmtText, "Monday", udf);
    runAndVerifyTs("2015-04-07 10:30:45", fmtText, "Tuesday", udf);
    runAndVerifyTs("2015-04-08 10:30:45", fmtText, "Wednesday", udf);
    runAndVerifyTs("2015-04-09 10:30:45", fmtText, "Thursday", udf);
    runAndVerifyTs("2015-04-10 10:30:45.123", fmtText, "Friday", udf);
    runAndVerifyTs("2015-04-11 10:30:45.123456789", fmtText, "Saturday", udf);
    runAndVerifyTs("2015-04-12 10:30:45", fmtText, "Sunday", udf);
  }

  public void testNullFmt() throws HiveException {
    GenericUDFDateFormat udf = new GenericUDFDateFormat();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableStringObjectInspector;
    Text fmtText = null;
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory
        .getPrimitiveWritableConstantObjectInspector(TypeInfoFactory.stringTypeInfo, fmtText);
    ObjectInspector[] arguments = { valueOI0, valueOI1 };

    udf.initialize(arguments);

    runAndVerifyStr("2015-04-05", fmtText, null, udf);
  }

  public void testWrongFmt() throws HiveException {
    GenericUDFDateFormat udf = new GenericUDFDateFormat();
    ObjectInspector valueOI0 = PrimitiveObjectInspectorFactory.writableStringObjectInspector;
    Text fmtText = new Text("Q");
    ObjectInspector valueOI1 = PrimitiveObjectInspectorFactory
        .getPrimitiveWritableConstantObjectInspector(TypeInfoFactory.stringTypeInfo, fmtText);
    ObjectInspector[] arguments = { valueOI0, valueOI1 };

    udf.initialize(arguments);

    runAndVerifyStr("2015-04-05", fmtText, null, udf);
  }

  private void runAndVerifyStr(String str, Text fmtText, String expResult, GenericUDF udf)
      throws HiveException {
    DeferredObject valueObj0 = new DeferredJavaObject(str != null ? new Text(str) : null);
    DeferredObject valueObj1 = new DeferredJavaObject(fmtText);
    DeferredObject[] args = { valueObj0, valueObj1 };
    Text output = (Text) udf.evaluate(args);
    assertEquals("date_format() test ", expResult, output != null ? output.toString() : null);
  }

  private void runAndVerifyDate(String str, Text fmtText, String expResult, GenericUDF udf)
      throws HiveException {
    DeferredObject valueObj0 = new DeferredJavaObject(str != null ? new DateWritableV2(
        Date.valueOf(str)) : null);
    DeferredObject valueObj1 = new DeferredJavaObject(fmtText);
    DeferredObject[] args = { valueObj0, valueObj1 };
    Text output = (Text) udf.evaluate(args);
    assertEquals("date_format() test ", expResult, output != null ? output.toString() : null);
  }

  private void runAndVerifyTs(String str, Text fmtText, String expResult, GenericUDF udf)
      throws HiveException {
    DeferredObject valueObj0 = new DeferredJavaObject(str != null ? new TimestampWritableV2(
        Timestamp.valueOf(str)) : null);
    DeferredObject valueObj1 = new DeferredJavaObject(fmtText);
    DeferredObject[] args = { valueObj0, valueObj1 };
    Text output = (Text) udf.evaluate(args);
    assertEquals("date_format() test ", expResult, output != null ? output.toString() : null);
  }
}


text:
Run with:

```sh
# gcc -o <output_path> [<inputs>,...]
gcc -o ./build/main multiple-files/main.m multiple-files/Message.m -framework Foundation
```

## Resources

- https://stackoverflow.com/questions/5550717/c-header-files-good-practice


text:
# Disallow the use of the Object constructor (no-new-object)

The `Object` constructor is used to create new generic objects in JavaScript, such as:

```js
var myObject = new Object();
```

However, this is no different from using the more concise object literal syntax:

```js
var myObject = {};
```

For this reason, many prefer to always use the object literal syntax and never use the `Object` constructor.

While there are no performance differences between the two approaches, the byte savings and conciseness of the object literal form is what has made it the de facto way of creating new objects.

## Rule Details

This rule aims to eliminate use of the `Object` constructor. As such, it warns whenever `new Object` is found in code.

The following patterns are considered problems:

```js
/*eslint no-new-object: "error"*/

var myObject = new Object();

var myObject = new Object;
```

The following patterns are not considered problems:

```js
/*eslint no-new-object: "error"*/

var myObject = new CustomObject();

var myObject = {};
```

## When Not To Use It

If you wish to allow the use of the `Object` constructor, you can safely turn this rule off.

## Related Rules

* [no-array-constructor](no-array-constructor.md)
* [no-new-wrappers](no-new-wrappers.md)


text:
/**
 * Main game object.
 */

var transitions = null;
var run = false;
var ran = false;

function PixelEvolution(width, height, renderer, parent, state, transparent, antialias)
{
    // game variables
    this._pause = false;
    this._showMinimap = false;

    this._level = 0;
    Phaser.Game.call(this, width, height, renderer, parent, state, transparent, antialias);
}

PixelEvolution.prototype = Object.create(Phaser.Game.prototype);
PixelEvolution.prototype.constructor = PixelEvolution;

//preload all sprites in advance before actually starting the game.
function preload(){
};

function create()
{
    //Add all different states/phases
    //general
    this.state.add('boot', boot);
    this.state.add('loader', loader);
    this.state.add('menu', mainMenu);
    this.state.add('evolution', evolution);
    this.state.add('end', end);

    //phases
    this.state.add('pixel', pixelPhase);
    this.state.add('pacman', pacmanPhase);
    this.state.add('dungeon', dungeonPhase);
    this.state.add('rpg', rpgPhase);

    //initialise music
    pixelEvolution._music = this.add.audio('music');
    pixelEvolution._sfx = this.add.audio('music');

    pixelEvolution._music.addMarker('8bbg1', 41.629, 7.696, 1, true);
    pixelEvolution._music.addMarker('bg1', 0.028, 10.216, 1, true);
    pixelEvolution._music.addMarker('bg2', 10.244, 10.214, 1, true);
    pixelEvolution._music.addMarker('bg3', 20.458, 10.238, 1, true);
    pixelEvolution._music.addMarker('bg4', 30.696, 10.188, 1, true);

    pixelEvolution._sfx.addMarker('chat', 40.884, 0.314, 1, false);
    pixelEvolution._sfx.addMarker('itempickup', 41.198, 0.494, 1, false);

    //and start the menu one
    this.state.start('boot');

    //set up transition plugin to smoothly transition between states.
    transitions = this.game.plugins.add(Phaser.Plugin.StateTransition);
    transitions.settings({
        duration: 700,
        properties: {
            alpha: 0,
            scale: {
                x: 1.5,
                y: 1.5
            }
        }
    });
};

PixelEvolution.prototype.update = function(time){
    //super(), neccesary for it to function
    Phaser.Game.prototype.update.call(this, time);

    if(run) {
        run = false;
        this.switchLevel();

    }

    if((this.input.activePointer.isDown || this.input.keyboard.isDown(Phaser.Keyboard.ENTER) || this.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) && this._bg){
        this._bg.destroy();
        this._continue.destroy();
        this._message.destroy();
        this._pause = false;
    }
}

PixelEvolution.prototype.switchLevel = function() {
    switch(this._level) {
        case 1: transitions.to('pixel');
                console.log("level1");
                ran = false;
                break;
        case 2: transitions.to('pixel');
                console.log("level2");
                ran = false;
                break;
        case 3: transitions.to('evolution');
                console.log("level3");
                ran = false;
                break;
        case 4: transitions.to('pacman');
                console.log("level4");
                ran = false;
                break;
        case 5: transitions.to('pacman');
                console.log("level5");
                ran = false;
                break;
        case 6: transitions.to('evolution');
                console.log("level6");
                ran = false;
                break;
        case 7: transitions.to('dungeon');
                console.log("level7");
                ran = false;
                break;
        case 8: transitions.to('dungeon');
                console.log("level8");
                ran = false;
                break;
        case 9: transitions.to('evolution');
                console.log("level9");
                ran = false;
                break;
        case 10: transitions.to('end');
                console.log("Fin");
                break;
    }
}

//Displays a message on the screen and 'types it out' (animation).
PixelEvolution.prototype.showMessage = function(message){
    //this._pause = true;

    if(this._bg){
        this._bg.destroy();
        this._continue.destroy();
        this._message.destroy();
        this._pause = false;
    }

    //show background
    this._bg = this.add.tileSprite(0, this.camera.height-150, this.camera.width, 150, 'message_bg');
    this._bg.scale.setTo(3.2,3.2);
    this._bg.fixedToCamera = true;

    //this._continue = this.add.text(this.camera.width - 150, this.camera.height - 30, "Continue..", { font: "14px 'Press Start 2P'", fill: "#000" });
    this._continue = this.add.sprite(this.camera.width - 20, this.camera.height - 15, 'space');
    this._continue.fixedToCamera = true;
    this._continue.anchor.setTo(1,1);
    this._continue.scale.setTo(1.25, 1.25);

    //show text
    this._message = this.add.text(50, this.camera.height - 70, "", { font: "14px 'Press Start 2P'", fill: "#000" });
    this._message.lineSpacing = 7;
    this._message.anchor.setTo(0,0.5);
    this._message.fixedToCamera = true;
    this._message.realMessage = message;

    //type the text out.
    var count = 0;
    var speed = 3;
    this._message.update = function(){
        count++;
        if(count%speed){
            this.setText(this.realMessage.substring(0, Math.round(count/speed)));
        }
    }
}

// Instantiate game object.
var pixelEvolution = new PixelEvolution(800, 608, Phaser.AUTO, 'game', {
    preload: preload,
    create: create
}, false, true);
//        NOTE: To use Phaser.AUTO instead of Phaser.CANVAS, you have to run a local server.

// DEBUG: links to change between states/phases manually
$('#menuLink').click(function(){    pixelEvolution._level = 0; transitions.to('menu'); });

$('#pixelLink1').click(function(){   pixelEvolution._level = 0; transitions.to('pixel'); });
$('#pixelLink2').click(function(){   pixelEvolution._level = 1; transitions.to('pixel'); });
$('#pixelLink3').click(function(){   pixelEvolution._level = 2; transitions.to('pixel'); });

$('#pacmanLink1').click(function(){  pixelEvolution._level = 3; transitions.to('pacman'); });
$('#pacmanLink2').click(function(){  pixelEvolution._level = 4; transitions.to('pacman'); });
$('#pacmanLink3').click(function(){  pixelEvolution._level = 5; transitions.to('pacman'); });

$('#dungeonLink1').click(function(){ pixelEvolution._level = 6; transitions.to('dungeon'); });
$('#dungeonLink2').click(function(){ pixelEvolution._level = 7; transitions.to('dungeon'); });
$('#dungeonLink3').click(function(){ pixelEvolution._level = 8; transitions.to('dungeon'); });

$('#rpgLink').click(function(){     pixelEvolution._level = 9; transitions.to('rpg'); });


text:
package org.eclipse.swt.examples.addressbook;

public interface FindListener {

public boolean find();

}


text:
<?php
require_once('vendor/autoload.php');


text:
'use strict';

angular
  .module('reflect.calendar')
  .directive('mwlCalendarDay', function() {

    return {
      templateUrl: 'src/templates/calendarDayView.html',
      restrict: 'EA',
      require: '^mwlCalendar',
      scope: {
        events: '=',
        currentDay: '=',
        onEventClick: '=',
        dayViewStart: '=',
        dayViewEnd: '=',
        dayViewSplit: '='
      },
      controller: function($scope, $timeout, moment, calendarHelper, calendarConfig) {

        var vm = this;
        var dayViewStart, dayViewEnd;

        vm.calendarConfig = calendarConfig;

        function updateDays() {
          dayViewStart = moment($scope.dayViewStart || '00:00', 'HH:mm');
          dayViewEnd = moment($scope.dayViewEnd || '23:00', 'HH:mm');
          vm.dayViewSplit = parseInt($scope.dayViewSplit);
          vm.hourHeight = (60 / $scope.dayViewSplit) * 30;
          vm.hours = [];
          var dayCounter = moment(dayViewStart);
          for (var i = 0; i <= dayViewEnd.diff(dayViewStart, 'hours'); i++) {
            vm.hours.push({
              label: dayCounter.format(calendarConfig.dateFormats.hour)
            });
            dayCounter.add(1, 'hour');
          }
        }

        var originalLocale = moment.locale();

        $scope.$on('calendar.refreshView', function() {

          if (originalLocale !== moment.locale()) {
            originalLocale = moment.locale();
            updateDays();
          }

          vm.view = calendarHelper.getDayView($scope.events, $scope.currentDay, dayViewStart.hours(), dayViewEnd.hours(), vm.hourHeight);

        });

        updateDays();

      },
      controllerAs: 'vm'
    };

  });


text:
NaN_and_Infinity_must_have_parens: {
    options = {};
    input: {
        Infinity.toString();
        NaN.toString();
    }
    expect: {
        (1/0).toString();
        NaN.toString();         // transformation to 0/0 dropped
    }
}

NaN_and_Infinity_should_not_be_replaced_when_they_are_redefined: {
    options = {};
    input: {
        var Infinity, NaN;
        Infinity.toString();
        NaN.toString();
    }
    expect: {
        var Infinity, NaN;
        Infinity.toString();
        NaN.toString();
    }
}


text:
Fluent-Web-Design
=================

Fine-Tuned Responsive Web Design


text:
<?php
namespace Dp\Observer;

abstract class SensorAbstract
{
	protected $min;
	protected $max;

	public function __construct($min, $max)
	{
		$this->min	= $min;
		$this->max	= $max;
	}
}