text:
require 'test_helper'

class ClientTest < TinyTds::TestCase

  describe 'With valid credentials' do

    before do
      @client = new_connection
    end

    it 'must not be closed' do
      assert !@client.closed?
      assert @client.active?
    end

    it 'allows client connection to be closed' do
      assert @client.close
      assert @client.closed?
      assert !@client.active?
      action = lambda { @client.execute('SELECT 1 as [one]').each }
      assert_raise_tinytds_error(action) do |e|
        assert_match %r{closed connection}i, e.message, 'ignore if non-english test run'
      end
    end

    it 'has getters for the tds version information (brittle since conf takes precedence)' do
      if sybase_ase?
        assert_equal 7, @client.tds_version
        assert_equal 'DBTDS_5_0 - 5.0 SQL Server', @client.tds_version_info
      else
        assert_equal 9, @client.tds_version
        assert_equal 'DBTDS_7_1/DBTDS_8_0 - Microsoft SQL Server 2000', @client.tds_version_info
      end
    end

    it 'uses UTF-8 client charset/encoding by default' do
      assert_equal 'UTF-8', @client.charset
      assert_equal Encoding.find('UTF-8'), @client.encoding
    end

    it 'has a #escape method used for quote strings' do
      assert_equal "''hello''", @client.escape("'hello'")
    end

    it 'allows valid iconv character set' do
      ['CP850', 'CP1252', 'ISO-8859-1'].each do |encoding|
        client = new_connection(:encoding => encoding)
        assert_equal encoding, client.charset
        assert_equal Encoding.find(encoding), client.encoding
      end
    end

    it 'must be able to use :host/:port connection' do
      client = new_connection :dataserver => nil, :host => ENV['TINYTDS_UNIT_HOST'], :port => ENV['TINYTDS_UNIT_PORT'] || 1433
    end unless sqlserver_azure?

  end

  describe 'With in-valid options' do

    it 'raises an argument error when no :host given and :dataserver is blank' do
      assert_raises(ArgumentError) { new_connection :dataserver => nil, :host => nil }
    end

    it 'raises an argument error when no :username is supplied' do
      assert_raises(ArgumentError) { TinyTds::Client.new :username => nil }
    end

    it 'raises TinyTds exception with undefined :dataserver' do
      options = connection_options :login_timeout => 1, :dataserver => '127.0.0.2'
      action = lambda { new_connection(options) }
      assert_raise_tinytds_error(action) do |e|
        assert [20008,20009].include?(e.db_error_number)
        assert_equal 9, e.severity
        assert_match %r{unable to (open|connect)}i, e.message, 'ignore if non-english test run'
      end
      assert_new_connections_work
    end

    it 'raises TinyTds exception with long query past :timeout option' do
      client = new_connection :timeout => 1
      action = lambda { client.execute("WaitFor Delay '00:00:02'").do }
      assert_raise_tinytds_error(action) do |e|
        assert_equal 20003, e.db_error_number
        assert_equal 6, e.severity
        assert_match %r{timed out}i, e.message, 'ignore if non-english test run'
      end
      assert_client_works(client)
      assert_new_connections_work
    end

    it 'must not timeout per sql batch when not under transaction' do
      client = new_connection :timeout => 2
      client.execute("WaitFor Delay '00:00:01'").do
      client.execute("WaitFor Delay '00:00:01'").do
      client.execute("WaitFor Delay '00:00:01'").do
    end

    it 'must not timeout per sql batch when under transaction' do
      client = new_connection :timeout => 2
      begin
        client.execute("BEGIN TRANSACTION").do
        client.execute("WaitFor Delay '00:00:01'").do
        client.execute("WaitFor Delay '00:00:01'").do
        client.execute("WaitFor Delay '00:00:01'").do
      ensure
        client.execute("COMMIT TRANSACTION").do
      end
    end

    it 'must run this test to prove we account for dropped connections' do
      skip
      begin
        client = new_connection :login_timeout => 2, :timeout => 2
        assert_client_works(client)
        STDOUT.puts "Disconnect network!"
        sleep 10
        STDOUT.puts "This should not get stuck past 6 seconds!"
        action = lambda { client.execute('SELECT 1 as [one]').each }
        assert_raise_tinytds_error(action) do |e|
          assert_equal 20003, e.db_error_number
          assert_equal 6, e.severity
          assert_match %r{timed out}i, e.message, 'ignore if non-english test run'
        end
      ensure
        STDOUT.puts "Reconnect network!"
        sleep 10
        action = lambda { client.execute('SELECT 1 as [one]').each }
        assert_raise_tinytds_error(action) do |e|
          assert_equal 20047, e.db_error_number
          assert_equal 1, e.severity
          assert_match %r{dead or not enabled}i, e.message, 'ignore if non-english test run'
        end
        assert_new_connections_work
      end
    end

    it 'raises TinyTds exception with wrong :username' do
      options = connection_options :username => 'willnotwork'
      action = lambda { new_connection(options) }
      assert_raise_tinytds_error(action) do |e|
        if sqlserver_azure?
          assert_match %r{server name cannot be determined}i, e.message, 'ignore if non-english test run'
        else
          assert_equal sybase_ase? ? 4002 : 18456, e.db_error_number
          assert_equal 14, e.severity
          assert_match %r{login failed}i, e.message, 'ignore if non-english test run'
        end
      end
      assert_new_connections_work
    end

    it 'fails miserably with unknown encoding option' do
      options = connection_options :encoding => 'ISO-WTF'
      action = lambda { new_connection(options) }
      assert_raise_tinytds_error(action) do |e|
        assert_equal 20002, e.db_error_number
        assert_equal 9, e.severity
        assert_match %r{connection failed}i, e.message, 'ignore if non-english test run'
      end
      assert_new_connections_work
    end unless sybase_ase?

  end

end


text:
package com.github.alexkolpa.cashbook.endpoints;

import javax.inject.Inject;
import javax.inject.Provider;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import java.util.List;
import java.util.stream.Collectors;

import com.github.alexkolpa.cashbook.db.ContextProvider;
import com.github.alexkolpa.cashbook.db.SubCategories;
import com.github.alexkolpa.cashbook.models.Category;
import com.github.alexkolpa.cashbook.models.SubCategory;
import com.github.alexkolpa.cashbook.models.mappers.SubCategoryModels;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import me.magnet.relations.entities.tables.records.SubCategoriesRecord;
import org.jboss.resteasy.plugins.guice.RequestScoped;
import org.jooq.DSLContext;

@Path("sub-categories")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RequiredArgsConstructor(access = AccessLevel.PACKAGE, onConstructor = @__(@Inject))
public class SubCategoriesResource {

	private final ContextProvider contextProvider;

	@GET
	public List<SubCategory> listSubCategories() {
		return contextProvider.transactionResult(context -> SubCategories.list(context)
				.stream()
				.map(SubCategoryModels::toModel)
				.collect(Collectors.toList()));
	}

	@POST
	public SubCategory create(SubCategory subCategory) {
		return contextProvider.transactionResult(context -> {
			SubCategoriesRecord record = SubCategoryModels.toRecord(subCategory);
			return SubCategoryModels.toModel(SubCategories.create(context, record));
		});
	}

	@PUT
	@Path("{id:\\d+}")
	public SubCategory update(@PathParam("id") long id, SubCategory subCategory) {
		return contextProvider.transactionResult(context -> SubCategories.update(context, id,
				SubCategoryModels.toRecord(subCategory))
				.map(SubCategoryModels::toModel)
				.orElseThrow(NotFoundException::new));
	}

	@DELETE
	@Path("{id:\\d+}")
	public void delete(@PathParam("id") long id) {
		contextProvider.transaction(
				context -> SubCategories.delete(context, id).orElseThrow(NotFoundException::new));
	}
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe 'responseModel' do
  before :all do
    module MyAPI
      module Entities
        class Kind < Grape::Entity
          expose :title, documentation: { type: 'string', desc: 'Title of the kind.' }
        end

        class Something < Grape::Entity
          expose :text, documentation: { type: 'string', desc: 'Content of something.' }
          expose :kind, using: Kind, documentation: { type: 'MyAPI::Kind', desc: 'The kind of this something.' }
          expose :relation, using: 'MyAPI::Entities::Relation', documentation: { type: 'MyAPI::Relation', desc: 'A related model.' }
        end

        class Relation < Grape::Entity
          expose :name, documentation: { type: 'string', desc: 'Name' }
        end

        class Error < Grape::Entity
          expose :code, documentation: { type: 'string', desc: 'Error code' }
          expose :message, documentation: { type: 'string', desc: 'Error message' }
        end
      end

      class ResponseModelApi < Grape::API
        format :json
        desc 'This returns something or an error',
             entity: Entities::Something,
             http_codes: [
               [200, 'OK', Entities::Something],
               [403, 'Refused to return something', Entities::Error]
             ]

        get '/something/:id' do
          if params[:id] == 1
            something = OpenStruct.new text: 'something'
            present something, with: Entities::Something
          else
            error = OpenStruct.new code: 'some_error', message: 'Some error'
            present error, with: Entities::Error
          end
        end

        add_swagger_documentation
      end
    end
  end

  def app
    MyAPI::ResponseModelApi
  end

  subject do
    get '/swagger_doc/something'
    JSON.parse(last_response.body)
  end

  it 'should document specified models' do
    expect(subject['apis'][0]['operations'][0]['responseMessages']).to eq(
      [
        {
          'code' => 200,
          'message' => 'OK',
          'responseModel' => 'MyAPI::Something'
        },
        {
          'code' => 403,
          'message' => 'Refused to return something',
          'responseModel' => 'MyAPI::Error'
        }
      ]
    )

    expect(subject['models'].keys).to include 'MyAPI::Error'
    expect(subject['models']['MyAPI::Error']).to eq(
      'id' => 'MyAPI::Error',
      'properties' => {
        'code' => { 'type' => 'string', 'description' => 'Error code' },
        'message' => { 'type' => 'string', 'description' => 'Error message' }
      }
    )

    expect(subject['models'].keys).to include 'MyAPI::Something'
    expect(subject['models']['MyAPI::Something']).to eq(
      'id' => 'MyAPI::Something',
      'properties' => {
        'text' => { 'type' => 'string', 'description' => 'Content of something.' },
        'kind' => { '$ref' => 'MyAPI::Kind', 'description' => 'The kind of this something.' },
        'relation' => { '$ref' => 'MyAPI::Relation', 'description' => 'A related model.' }
      }
    )

    expect(subject['models'].keys).to include 'MyAPI::Kind'
    expect(subject['models']['MyAPI::Kind']).to eq(
      'id' => 'MyAPI::Kind',
      'properties' => {
        'title' => { 'type' => 'string', 'description' => 'Title of the kind.' }
      }
    )

    expect(subject['models'].keys).to include 'MyAPI::Relation'
    expect(subject['models']['MyAPI::Relation']).to eq(
      'id' => 'MyAPI::Relation',
      'properties' => {
        'name' => { 'type' => 'string', 'description' => 'Name' }
      }
    )
  end
end


text:
base_cookbook
=============

A sensible base cookbook to make life easy.


text:
package com.learn.stateless.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;

import javax.servlet.Filter;

@Configuration
@ComponentScan
public class StatelessAuthentication {

   @Bean
    public Filter characterEncodingFilter() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        return characterEncodingFilter;
    }

}


text:
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2003-2007 Jonathan Turkanis
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)

// See http://www.boost.org/libs/iostreams for documentation.

#ifndef BOOST_IOSTREAMS_DETAIL_RESOLVE_HPP_INCLUDED
#define BOOST_IOSTREAMS_DETAIL_RESOLVE_HPP_INCLUDED

#if defined(_MSC_VER)
# pragma once
#endif

#include <boost/config.hpp> // partial spec, put size_t in std.
#include <cstddef>          // std::size_t.
#include <boost/detail/is_incrementable.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/iostreams/detail/adapter/mode_adapter.hpp>
#include <boost/iostreams/detail/adapter/output_iterator_adapter.hpp>
#include <boost/iostreams/detail/adapter/range_adapter.hpp>
#include <boost/iostreams/detail/config/gcc.hpp>
#include <boost/iostreams/detail/config/overload_resolution.hpp>
#include <boost/iostreams/detail/config/wide_streams.hpp>
#include <boost/iostreams/detail/enable_if_stream.hpp>
#include <boost/iostreams/detail/is_dereferenceable.hpp>
#include <boost/iostreams/detail/is_iterator_range.hpp>
#include <boost/iostreams/detail/select.hpp>
#include <boost/iostreams/detail/wrap_unwrap.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/traits.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/bool.hpp> // true_.
#include <boost/mpl/if.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/type_traits/is_array.hpp>

// Must come last.
#include <boost/iostreams/detail/config/disable_warnings.hpp> // VC7.1 C4224.

namespace boost { namespace iostreams { namespace detail {

//------------------Definition of resolve-------------------------------------//

#ifndef BOOST_IOSTREAMS_BROKEN_OVERLOAD_RESOLUTION //-------------------------//

template<typename Mode, typename Ch, typename T>
struct resolve_traits {
    typedef typename
            mpl::if_<
                boost::detail::is_incrementable<T>,
                output_iterator_adapter<Mode, Ch, T>,
                const T&
            >::type type;
};

# ifndef BOOST_IOSTREAMS_NO_STREAM_TEMPLATES //-------------------------------//

template<typename Mode, typename Ch, typename T>
typename resolve_traits<Mode, Ch, T>::type
resolve( const T& t
         BOOST_IOSTREAMS_DISABLE_IF_STREAM(T)

         // I suspect that the compilers which require this workaround may
         // be correct, but I'm not sure why :(
         #if BOOST_WORKAROUND(BOOST_INTEL_CXX_VERSION, BOOST_TESTED_AT(810)) ||\
             BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3205)) || \
             BOOST_WORKAROUND(BOOST_IOSTREAMS_GCC, BOOST_TESTED_AT(400)) ||\
             BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(1110))
             /**/
         , typename disable_if< is_iterator_range<T> >::type* = 0
         #endif
         )
{
    typedef typename resolve_traits<Mode, Ch, T>::type return_type;
    return return_type(t);
}

template<typename Mode, typename Ch, typename Tr>
mode_adapter< Mode, std::basic_streambuf<Ch, Tr> >
resolve(std::basic_streambuf<Ch, Tr>& sb)
{ return mode_adapter< Mode, std::basic_streambuf<Ch, Tr> >(wrap(sb)); }

template<typename Mode, typename Ch, typename Tr>
mode_adapter< Mode, std::basic_istream<Ch, Tr> >
resolve(std::basic_istream<Ch, Tr>& is)
{ return mode_adapter< Mode, std::basic_istream<Ch, Tr> >(wrap(is)); }

template<typename Mode, typename Ch, typename Tr>
mode_adapter< Mode, std::basic_ostream<Ch, Tr> >
resolve(std::basic_ostream<Ch, Tr>& os)
{ return mode_adapter< Mode, std::basic_ostream<Ch, Tr> >(wrap(os)); }

template<typename Mode, typename Ch, typename Tr>
mode_adapter< Mode, std::basic_iostream<Ch, Tr> >
resolve(std::basic_iostream<Ch, Tr>& io)
{ return mode_adapter< Mode, std::basic_iostream<Ch, Tr> >(wrap(io)); }

template<typename Mode, typename Ch, std::size_t N>
array_adapter<Mode, Ch> resolve(Ch (&array)[N])
{ return array_adapter<Mode, Ch>(array); }

template<typename Mode, typename Ch, typename Iter>
range_adapter< Mode, boost::iterator_range<Iter> >
resolve(const boost::iterator_range<Iter>& rng)
{ return range_adapter< Mode, boost::iterator_range<Iter> >(rng); }

# else // # ifndef BOOST_IOSTREAMS_NO_STREAM_TEMPLATES //---------------------//

template<typename Mode, typename Ch, typename T>
typename resolve_traits<Mode, Ch, T>::type
resolve( const T& t
         BOOST_IOSTREAMS_DISABLE_IF_STREAM(T)
         #if defined(__GNUC__)
         , typename disable_if< is_iterator_range<T> >::type* = 0
         #endif
         )
{
    typedef typename resolve_traits<Mode, Ch, T>::type return_type;
    return return_type(t);
}

template<typename Mode, typename Ch>
mode_adapter<Mode, std::streambuf>
resolve(std::streambuf& sb)
{ return mode_adapter<Mode, std::streambuf>(wrap(sb)); }

template<typename Mode, typename Ch>
mode_adapter<Mode, std::istream>
resolve(std::istream& is)
{ return mode_adapter<Mode, std::istream>(wrap(is)); }

template<typename Mode, typename Ch>
mode_adapter<Mode, std::ostream>
resolve(std::ostream& os)
{ return mode_adapter<Mode, std::ostream>(wrap(os)); }

template<typename Mode, typename Ch>
mode_adapter<Mode, std::iostream>
resolve(std::iostream& io)
{ return mode_adapter<Mode, std::iostream>(wrap(io)); }

template<typename Mode, typename Ch, std::size_t N>
array_adapter<Mode, Ch> resolve(Ch (&array)[N])
{ return array_adapter<Mode, Ch>(array); }

template<typename Mode, typename Ch, typename Iter>
range_adapter< Mode, boost::iterator_range<Iter> >
resolve(const boost::iterator_range<Iter>& rng)
{ return range_adapter< Mode, boost::iterator_range<Iter> >(rng); }

# endif // # ifndef BOOST_IOSTREAMS_NO_STREAM_TEMPLATES //--------------------//
#else // #ifndef BOOST_IOSTREAMS_BROKEN_OVERLOAD_RESOLUTION //----------------//

template<typename Mode, typename Ch, typename T>
struct resolve_traits {
    // Note: test for is_iterator_range must come before test for output
    // iterator.
    typedef typename
            iostreams::select<  // Disambiguation for Tru64.
                is_std_io<T>,
                mode_adapter<Mode, T>,
                is_iterator_range<T>,
                range_adapter<Mode, T>,
                is_dereferenceable<T>,
                output_iterator_adapter<Mode, Ch, T>,
                is_array<T>,
                array_adapter<Mode, T>,
                else_,
                #if !BOOST_WORKAROUND(BOOST_BORLANDC, < 0x600)
                    const T&
                #else
                    T
                #endif
            >::type type;
};

template<typename Mode, typename Ch, typename T>
typename resolve_traits<Mode, Ch, T>::type
resolve(const T& t, mpl::true_)
{   // Bad overload resolution.
    typedef typename resolve_traits<Mode, Ch, T>::type return_type;
    return return_type(wrap(const_cast<T&>(t)));
}

template<typename Mode, typename Ch, typename T>
typename resolve_traits<Mode, Ch, T>::type
resolve(const T& t, mpl::false_)
{
    typedef typename resolve_traits<Mode, Ch, T>::type return_type;
    return return_type(t);
}

template<typename Mode, typename Ch, typename T>
typename resolve_traits<Mode, Ch, T>::type
resolve(const T& t BOOST_IOSTREAMS_DISABLE_IF_STREAM(T))
{ return resolve<Mode, Ch>(t, is_std_io<T>()); }

# if !BOOST_WORKAROUND(BOOST_BORLANDC, < 0x600) && \
     !defined(__GNUC__) // ---------------------------------------------------//

template<typename Mode, typename Ch, typename T>
typename resolve_traits<Mode, Ch, T>::type
resolve(T& t, mpl::true_)
{
    typedef typename resolve_traits<Mode, Ch, T>::type return_type;
    return return_type(wrap(t));
}

template<typename Mode, typename Ch, typename T>
typename resolve_traits<Mode, Ch, T>::type
resolve(T& t, mpl::false_)
{
    typedef typename resolve_traits<Mode, Ch, T>::type return_type;
    return return_type(t);
}

template<typename Mode, typename Ch, typename T>
typename resolve_traits<Mode, Ch, T>::type
resolve(T& t BOOST_IOSTREAMS_ENABLE_IF_STREAM(T))
{ return resolve<Mode, Ch>(t, is_std_io<T>()); }

# endif // Borland 5.x or GCC //--------------------------------//
#endif // #ifndef BOOST_IOSTREAMS_BROKEN_OVERLOAD_RESOLUTION //---------------//

} } } // End namespaces detail, iostreams, boost.

#include <boost/iostreams/detail/config/enable_warnings.hpp> // VC7.1 4224.

#endif // BOOST_IOSTREAMS_DETAIL_RESOLVE_HPP_INCLUDED


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>ScorcH</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" href="styles/bootstrap.css">
        <link rel="stylesheet" href="bower_components/jquery-ui-bootstrap/jquery.ui.theme.css">
        <link rel="stylesheet" href="styles/scorch.css">

                    ScorcH

How to use the heatmap

                            <button id="shuffle_cols" class="btn">Shuffle Columns</button>
                            <button id="shuffle_rows" class="btn">Shuffle Rows</button>
                            <button id="shift_cols" class="btn">Shift Columns</button>
                            <button id="shift_rows" class="btn">Shift Rows</button>

                             <form class="navbar-form pull-left">
                                Number of Rows/Columns: <input id="dim_size" type="text" placeholder="50" />
                                <button id="load_binary" class="btn"> LoadBinary</button>
                            </form>


text:
package com.siyeh.ig.resources;

import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.TypeUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

/**
 * @author Bas Leijdekkers
 */
public class AutoCloseableResourceInspection extends BaseInspection {

  @SuppressWarnings("PublicField")
  public boolean ignoreFromMethodCall = false;

  @Nls
  @NotNull
  @Override
  public String getDisplayName() {
    return InspectionGadgetsBundle.message("auto.closeable.resource.display.name");
  }

  @NotNull
  @Override
  public String getID() {
    return "resource"; // matches Eclipse inspection
  }

  @NotNull
  @Override
  protected String buildErrorString(Object... infos) {
    final PsiExpression expression = (PsiExpression)infos[0];
    final PsiType type = expression.getType();
    assert type != null;
    final String text = type.getPresentableText();
    return InspectionGadgetsBundle.message("auto.closeable.resource.problem.descriptor", text);
  }

  @Nullable
  @Override
  public JComponent createOptionsPanel() {
    return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message("auto.closeable.resource.returned.option"),
                                          this, "ignoreFromMethodCall");
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new AutoCloseableResourceVisitor();
  }

  private class AutoCloseableResourceVisitor extends BaseInspectionVisitor {

    @Override
    public void visitNewExpression(PsiNewExpression expression) {
      super.visitNewExpression(expression);
      checkExpression(expression);
    }

    @Override
    public void visitMethodCallExpression(PsiMethodCallExpression expression) {
      super.visitMethodCallExpression(expression);
      if (ignoreFromMethodCall) {
        return;
      }
      checkExpression(expression);
    }

    private void checkExpression(PsiExpression expression) {
      if (!PsiUtil.isLanguageLevel7OrHigher(expression) || !TypeUtils.expressionHasTypeOrSubtype(expression, "java.lang.AutoCloseable")) {
        return;
      }
      final PsiVariable variable = ResourceInspection.getVariable(expression);
      if (variable instanceof PsiResourceVariable) {
        return;
      }
      if (ResourceInspection.isResourceEscapingFromMethod(variable, expression)) {
        return;
      }
      registerError(expression, expression);
    }
  }
}


text:
from .. import Provider as SsnProvider

class Provider(SsnProvider):

    def ssn(self):
        """
        Returns an Israeli identity number, known as Teudat Zehut ("tz").

        https://en.wikipedia.org/wiki/Israeli_identity_card
        """

        newID = str(self.generator.random.randrange(111111, 99999999))
        newID = newID.zfill(8)
        theSum = 0
        indexRange = [0, 2, 4, 6]
        for i in indexRange:
            digit = newID[i]
            num = int(digit)
            theSum = theSum + num
            num = int(newID[i + 1]) * 2
            if num > 9:
                num = int(str(num)[0]) + int(str(num)[1])
            theSum = theSum + num
        lastDigit = theSum % 10
        if lastDigit != 0:
            lastDigit = 10 - lastDigit

        return str(newID) + str(lastDigit)


text:
Security Advisory

		Back to advisories

		<?php get_template_part('advisories/advisory-side'); ?>

Auth bypass in /lib/base.php (oC-SA-2012-011)

10th August 2012

Risk level: High

Description

/lib/base.php before ownCloud 4.0.8 does not properly validate the user_id session variable via WebDAV, which allows authenticated attackers to gain access to other users files.

Affected Software

ownCloud Server < 4.0.8 (CVE-2012-5336)

Action Taken

Acknowledgements

The ownCloud team thanks the following people for their research and responsible disclosure of the above advisory:

Lukas Reschke - ownCloud Inc. (lukas@owncloud.org) - Vulnerability discovery and disclosure.


text:
package vanadis.extrt;

import vanadis.core.collections.Generic;
import vanadis.objectmanagers.InstanceSummary;
import vanadis.objectmanagers.ManagedFeatureSummary;
import vanadis.osgi.Reference;
import vanadis.osgi.Registration;

import java.util.Collection;
import java.util.Iterator;

abstract class AbstractManagedFeatureSummary implements ManagedFeatureSummary {

    private final String name;

    private final String featureClass;

    private final Collection<InstanceSummary> summaries;

    static Collection<InstanceSummary> refsSummaries(Injector<?> injector) {
        Collection<InstanceSummary> instanceSummaries = Generic.list();
        for (Reference<?> registration : injector.getReferences()) {
            instanceSummaries.add(new InstanceSummaryImpl(registration));
        }
        return instanceSummaries;
    }

    static Collection<InstanceSummary> regsSummaries(Exposer<?> regs) {
        Collection<InstanceSummary> instanceSummaries = Generic.list();
        for (Registration<?> registration : regs) {
            instanceSummaries.add(new InstanceSummaryImpl(registration));
        }
        return instanceSummaries;
    }

    AbstractManagedFeatureSummary(String name, String featureClass, Collection<InstanceSummary> summaries) {
        this.name = name;
        this.featureClass = featureClass;
        this.summaries = summaries;
    }

    int summariesCount() {
        return summaries.size();
    }

    @Override
    public boolean isActive() {
        return !summaries.isEmpty();
    }

    @Override
    public String getFeatureClass() {
        return featureClass;
    }

    @Override
    public Iterator<InstanceSummary> iterator() {
        return summaries.iterator();
    }

    @Override
    public String getName() {
        return name;
    }
}


text:
**NOTE:** Flexvolume is deprecated. Out-of-tree CSI driver is the recommended way to write volume drivers in Kubernetes. See this doc [here](https://github.com/kubernetes/community/blob/master/sig-storage/volume-plugin-faq.md#kubernetes-volume-plugin-faq-for-storage-vendors) for more information.

Flexvolume enables users to write their own drivers and add support for their volumes in Kubernetes. Vendor drivers should be installed in the volume plugin path on every node, and on master if the driver requires attach capability (unless `--enable-controller-attach-detach` Kubelet option is set to false, but this is highly discouraged because it is a legacy mode of operation).

Flexvolume is a GA feature from Kubernetes 1.8 release onwards.

## Prerequisites

Install the vendor driver on all nodes (also on master nodes if "--enable-controller-attach-detach" Kubelet option is enabled) in the plugin path. Path for installing the plugin: `<plugindir>/<vendor~driver>/<driver>`. The default plugin directory is `/usr/libexec/kubernetes/kubelet-plugins/volume/exec/`. It can be changed in kubelet via the `--volume-plugin-dir` flag, and in controller manager via the `--flex-volume-plugin-dir` flag.

For example to add a `cifs` driver, by vendor `foo` install the driver at: `/usr/libexec/kubernetes/kubelet-plugins/volume/exec/foo~cifs/cifs`

The vendor and driver names must match flexVolume.driver in the volume spec, with '~' replaced with '/'. For example, if `flexVolume.driver` is set to `foo/cifs`, then the vendor is `foo`, and driver is `cifs`.

## Dynamic Plugin Discovery
Beginning in v1.8, Flexvolume supports the ability to detect drivers on the fly. Instead of requiring drivers to exist at system initialization time or having to restart kubelet or controller manager, drivers can be installed, upgraded/downgraded, and uninstalled while the system is running.
For more information, please refer to the [design document](https://git.k8s.io/design-proposals-archive/storage/flexvolume-deployment.md).

## Automated Plugin Installation/Upgrade
One possible way to install and upgrade your Flexvolume drivers is by using a DaemonSet. See [Recommended Driver Deployment Method](https://git.k8s.io/design-proposals-archive/storage/flexvolume-deployment.md#recommended-driver-deployment-method) for details, and see [here](https://git.k8s.io/examples/staging/volumes/flexvolume/deploy/) for an example.

## Plugin details
The plugin expects the following call-outs are implemented for the backend drivers. Some call-outs are optional. Call-outs are invoked from Kubelet and Controller Manager.

### Driver invocation model:

#### Init:
Initializes the driver. Called during Kubelet & Controller manager initialization. On success, the function returns a capabilities map showing whether each Flexvolume capability is supported by the driver.
Current capabilities:
* `attach` - a boolean field indicating whether the driver requires attach and detach operations. This field is *required*, although for backward-compatibility the default value is set to `true`, i.e. requires attach and detach.
See [Driver output](#driver-output) for the capabilities map format.
```
<driver executable> init
```

#### Attach:
Attach the volume specified by the given spec on the given node. On success, returns the device path where the device is attached on the node. Called from Controller Manager.

This call-out does not pass "secrets" specified in Flexvolume spec. If your driver requires secrets, do not implement this call-out and instead use "mount" call-out and implement attach and mount in that call-out.

```
<driver executable> attach <json options> <node name>
```

#### Detach:
Detach the volume from the node. Called from Controller Manager.
```
<driver executable> detach <mount device> <node name>
```

#### Wait for attach:
Wait for the volume to be attached on the remote node. On success, the path to the device is returned. Called from Controller Manager. The timeout should be 10m (based on https://git.k8s.io/kubernetes/pkg/kubelet/volumemanager/volume_manager.go#L88 )

```
<driver executable> waitforattach <mount device> <json options>
```

#### Volume is Attached:
Check the volume is attached on the node. Called from Controller Manager.

```
<driver executable> isattached <json options> <node name>
```

#### Mount device:
Mount device mounts the device to a global path which individual pods can then bind mount. Called only from Kubelet.

This call-out does not pass "secrets" specified in Flexvolume spec. If your driver requires secrets, do not implement this call-out and instead use "mount" call-out and implement attach and mount in that call-out.

```
<driver executable> mountdevice <mount dir> <mount device> <json options>
```

#### Unmount device:
Unmounts the global mount for the device. This is called once all bind mounts have been unmounted. Called only from Kubelet.

```
<driver executable> unmountdevice <mount device>
```
In addition to the user-specified options and [default JSON options](#default-json-options), the following options capturing information about the pod are passed through and generated automatically.

```
kubernetes.io/pod.name
kubernetes.io/pod.namespace
kubernetes.io/pod.uid
kubernetes.io/serviceAccount.name
```

#### Mount:
Mount the volume at the mount dir. This call-out defaults to bind mount for drivers which implement attach & mount-device call-outs. Called only from Kubelet.

```
<driver executable> mount <mount dir> <json options>
```

#### Unmount:
Unmount the volume. This call-out defaults to bind mount for drivers which implement attach & mount-device call-outs. Called only from Kubelet.

```
<driver executable> unmount <mount dir>
```

See [lvm] & [nfs] for a quick example on how to write a simple flexvolume driver.

### Driver output:

Flexvolume expects the driver to reply with the status of the operation in the
following format.

```
{
	"status": "<Success/Failure/Not supported>",
	"message": "<Reason for success/failure>",
	"device": "<Path to the device attached. This field is valid only for attach & waitforattach call-outs>"
	"volumeName": "<Cluster wide unique name of the volume. Valid only for getvolumename call-out>"
	"attached": <True/False (Return true if volume is attached on the node. Valid only for isattached call-out)>
    "capabilities": <Only included as part of the Init response>
    {
        "attach": <True/False (Return true if the driver implements attach and detach)>
    }
}
```

### Default Json options

In addition to the flags specified by the user in the Options field of the FlexVolumeSource, the following flags (set through their corresponding FlexVolumeSource fields) are also passed to the executable.
Note: Secrets are passed only to "mount/unmount" call-outs.

```
"kubernetes.io/fsType":"<FS type>",
"kubernetes.io/readwrite":"<rw>",
"kubernetes.io/fsGroup":"<FS group>",
"kubernetes.io/mountsDir":"<string>",
"kubernetes.io/pvOrVolumeName":"<Volume name if the volume is in-line in the pod spec; PV name if the volume is a PV>"

"kubernetes.io/pod.name":"<string>",
"kubernetes.io/pod.namespace":"<string>",
"kubernetes.io/pod.uid":"<string>",
"kubernetes.io/serviceAccount.name":"<string>",

"kubernetes.io/secret/key1":"<secret1>"
...
"kubernetes.io/secret/keyN":"<secretN>"
```

### Example of Flexvolume

Please refer to the [Flexvolume example directory]. See [nginx-lvm.yaml] & [nginx-nfs.yaml] for a quick example on how to use Flexvolume in a pod.

[lvm]: https://git.k8s.io/examples/staging/volumes/flexvolume/lvm
[nfs]: https://git.k8s.io/examples/staging/volumes/flexvolume/nfs
[nginx-lvm.yaml]: https://git.k8s.io/examples/staging/volumes/flexvolume/nginx-lvm.yaml
[nginx-nfs.yaml]: https://git.k8s.io/examples/staging/volumes/flexvolume/nginx-nfs.yaml
[Flexvolume example directory]: https://git.k8s.io/examples/staging/volumes/flexvolume/


text:
package org.drools.core.base;

import org.drools.core.common.EventFactHandle;
import org.drools.core.factmodel.traits.Thing;
import org.drools.core.factmodel.traits.Trait;
import org.drools.core.facttemplates.FactTemplate;
import org.drools.core.util.MathUtils;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;

public class ValueType<T>
    implements
    Externalizable {

    private static final long      serialVersionUID  = 510l;

    public static final ValueType  NULL_TYPE         = new ValueType( "null",
                                                                      null,
                                                                      SimpleValueType.NULL);
    // primitive types
    public static final ValueType  PCHAR_TYPE        = new ValueType( "char",
                                                                      Character.TYPE,
                                                                      SimpleValueType.CHAR );
    public static final ValueType  PBYTE_TYPE        = new ValueType( "byte",
                                                                      Byte.TYPE,
                                                                      SimpleValueType.INTEGER );
    public static final ValueType  PSHORT_TYPE       = new ValueType( "short",
                                                                      Short.TYPE,
                                                                      SimpleValueType.INTEGER );
    public static final ValueType  PINTEGER_TYPE     = new ValueType( "int",
                                                                      Integer.TYPE,
                                                                      SimpleValueType.INTEGER );
    public static final ValueType  PLONG_TYPE        = new ValueType( "long",
                                                                      Long.TYPE,
                                                                      SimpleValueType.INTEGER );
    public static final ValueType  PFLOAT_TYPE       = new ValueType( "float",
                                                                      Float.TYPE,
                                                                      SimpleValueType.DECIMAL );
    public static final ValueType  PDOUBLE_TYPE      = new ValueType( "double",
                                                                      Double.TYPE,
                                                                      SimpleValueType.DECIMAL );
    public static final ValueType  PBOOLEAN_TYPE     = new ValueType( "boolean",
                                                                      Boolean.TYPE,
                                                                      SimpleValueType.BOOLEAN );

    // wrapper types
    public static final ValueType  CHAR_TYPE         = new ValueType( "Character",
                                                                      Character.class,
                                                                      SimpleValueType.CHAR );
    public static final ValueType  BYTE_TYPE         = new ValueType( "Byte",
                                                                      Byte.class,
                                                                      SimpleValueType.INTEGER);
    public static final ValueType  SHORT_TYPE        = new ValueType( "Short",
                                                                      Short.class,
                                                                      SimpleValueType.INTEGER );
    public static final ValueType  INTEGER_TYPE      = new ValueType( "Integer",
                                                                      Integer.class,
                                                                      SimpleValueType.INTEGER );
    public static final ValueType  LONG_TYPE         = new ValueType( "Long",
                                                                      Long.class,
                                                                      SimpleValueType.INTEGER );
    public static final ValueType  FLOAT_TYPE        = new ValueType( "Float",
                                                                      Float.class,
                                                                      SimpleValueType.DECIMAL );
    public static final ValueType  DOUBLE_TYPE       = new ValueType( "Double",
                                                                      Double.class,
                                                                      SimpleValueType.DECIMAL );
    public static final ValueType  BOOLEAN_TYPE      = new ValueType( "Boolean",
                                                                      Boolean.class,
                                                                      SimpleValueType.BOOLEAN );

    public static final ValueType  NUMBER_TYPE         = new ValueType( "Number",
                                                                        Number.class,
                                                                        SimpleValueType.DATE );

    public static final ValueType  BIG_DECIMAL_TYPE  = new BigDecimalValueType();

    public static final ValueType  BIG_INTEGER_TYPE  = new BigIntegerValueType();

    // other types
    public static final ValueType  DATE_TYPE         = new ValueType( "Date",
                                                                      Date.class,
                                                                      SimpleValueType.DATE );
    public static final ValueType  ARRAY_TYPE        = new ValueType( "Array",
                                                                      Object[].class,
                                                                      SimpleValueType.LIST );

    public static final ValueType  STRING_TYPE       = new StringValueType();

    public static final ValueType  OBJECT_TYPE       = new ValueType( "Object",
                                                                      Object.class,
                                                                      SimpleValueType.OBJECT );
    public static final ValueType  FACTTEMPLATE_TYPE = new ValueType( "FactTemplate",
                                                                      FactTemplate.class,
                                                                      SimpleValueType.UNKNOWN );
    public static final ValueType  EVENT_TYPE        = new ValueType( "Event",
                                                                      EventFactHandle.class,
                                                                      SimpleValueType.OBJECT );
    public static final ValueType  QUERY_TYPE        = new ValueType( "Query",
                                                                      DroolsQuery.class,
                                                                      SimpleValueType.OBJECT );

    public static final ValueType  TRAIT_TYPE        = new ValueType( "Trait",
                                                                      Thing.class,
                                                                      SimpleValueType.OBJECT );

    public static final ValueType  CLASS_TYPE        = new ValueType( "Class",
                                                                      Class.class,
                                                                      SimpleValueType.OBJECT );

    private String           name;
    private Class<T>         classType;
    private int              simpleType;

    public ValueType() {
        this(null, null, 0);
    }

    private ValueType(final String name,
                      final Class<T> classType,
                      final int simpleType) {
        this.name = name;
        this.classType = classType;
        this.simpleType = simpleType;
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name        = (String)in.readObject();
        classType   = (Class<T>)in.readObject();
        simpleType  = in.readInt();
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(name);
        out.writeObject(classType);
        out.writeInt(simpleType);
    }

    private Object readResolve() throws java.io.ObjectStreamException {
        return determineValueType( this.classType );
    }

    /* (non-Javadoc)
     * @see org.kie.base.ValueTypeInterface#getName()
     */
    public String getName() {
        return this.name;
    }

    /* (non-Javadoc)
     * @see org.kie.base.ValueTypeInterface#getClassType()
     */
    public Class<T> getClassType() {
        return this.classType;
    }

    /* (non-Javadoc)
     * @see org.kie.base.ValueTypeInterface#getSimpleType()
     */
    public int getSimpleType() {
        return this.simpleType;
    }

    public static ValueType determineValueType(final Class<?> clazz) {
        if ( clazz == null ) {
            return ValueType.NULL_TYPE;
        }

        // primitives
        if ( clazz == FactTemplate.class ) {
            return ValueType.FACTTEMPLATE_TYPE;
        } else if ( clazz == DroolsQuery.class ) {
            return ValueType.QUERY_TYPE;
        } else if ( clazz == Character.TYPE ) {
            return ValueType.PCHAR_TYPE;
        } else if ( clazz == Byte.TYPE ) {
            return ValueType.PBYTE_TYPE;
        } else if ( clazz == Short.TYPE ) {
            return ValueType.PSHORT_TYPE;
        } else if ( clazz == Integer.TYPE ) {
            return ValueType.PINTEGER_TYPE;
        } else if ( clazz == Long.TYPE ) {
            return ValueType.PLONG_TYPE;
        } else if ( clazz == Float.TYPE ) {
            return ValueType.PFLOAT_TYPE;
        } else if ( clazz == Double.TYPE ) {
            return ValueType.PDOUBLE_TYPE;
        } else if ( clazz == Boolean.TYPE ) {
            return ValueType.PBOOLEAN_TYPE;
        }

        // Number Wrappers
        if ( clazz == Character.class ) {
            return ValueType.CHAR_TYPE;
        } else if ( clazz == Byte.class ) {
            return ValueType.BYTE_TYPE;
        } else if ( clazz == Short.class ) {
            return ValueType.SHORT_TYPE;
        } else if ( clazz == Integer.class ) {
            return ValueType.INTEGER_TYPE;
        } else if ( clazz == Long.class ) {
            return ValueType.LONG_TYPE;
        } else if ( clazz == Float.class ) {
            return ValueType.FLOAT_TYPE;
        } else if ( clazz == Double.class ) {
            return ValueType.DOUBLE_TYPE;
        } else if ( clazz == Boolean.class ) {
            return ValueType.BOOLEAN_TYPE;
        }  else if ( clazz == BigDecimal.class ) {
            return ValueType.BIG_DECIMAL_TYPE;
        } else if ( clazz == BigInteger.class ) {
            return ValueType.BIG_INTEGER_TYPE;
        } else if ( Number.class.isAssignableFrom( clazz ) ) {
            return ValueType.NUMBER_TYPE;
        }

        // Other Object types
        if ( isDateType( clazz ) ) {
            return ValueType.DATE_TYPE;
        } else if ( clazz.isArray() ) {
            return ValueType.ARRAY_TYPE;
        } else if ( clazz == String.class ) {
            return ValueType.STRING_TYPE;
        } else if ( clazz == EventFactHandle.class ) {
            return ValueType.EVENT_TYPE;
        } else if ( clazz == Class.class ) {
            return ValueType.CLASS_TYPE;
        }
        else if ( Thing.class.isAssignableFrom( clazz ) || clazz.isAnnotationPresent( Trait.class ) ) {
            return ValueType.TRAIT_TYPE;
        } else {
            return ValueType.OBJECT_TYPE;
        }
    }

    public static boolean isDateType( Class<?> clazz ) {
        return Date.class.isAssignableFrom( clazz );
    }

    public String toString() {
        return "ValueType = '" + this.name + "'";
    }

    public int hashCode() {
        return this.name.hashCode();
    }

    public boolean equals(final Object object) {
        if ( object == this ) {
            return true;
        } else if (object instanceof ValueType) {
            ValueType   that    = (ValueType)object;
            return classType == that.classType &&
                   simpleType == that.simpleType &&
                   (name == that.name || name != null && name.equals(that.name));
        }
        return false;
    }

    /* (non-Javadoc)
     * @see org.kie.base.ValueTypeInterface#isBoolean()
     */
    public boolean isBoolean() {
        return ((this.classType == Boolean.class) || (this.classType == Boolean.TYPE));
    }

    public boolean isDate() {
        return this.classType == Date.class;
    }

    /* (non-Javadoc)
     * @see org.kie.base.ValueTypeInterface#isNumber()
     */
    public boolean isNumber() {
        return ( this.simpleType == SimpleValueType.INTEGER ||
                 this.simpleType == SimpleValueType.DECIMAL ||
                 this.simpleType == SimpleValueType.CHAR ||
                 this.simpleType == SimpleValueType.NUMBER ) ;
    }

    /* (non-Javadoc)
     * @see org.kie.base.ValueTypeInterface#isIntegerNumber()
     */
    public boolean isIntegerNumber() {
        return this.simpleType == SimpleValueType.INTEGER;
    }

    /* (non-Javadoc)
     * @see org.kie.base.ValueTypeInterface#isFloatNumber()
     */
    public boolean isFloatNumber() {
        return this.simpleType == SimpleValueType.DECIMAL;
    }

    /* (non-Javadoc)
     * @see org.kie.base.ValueTypeInterface#isChar()
     */
    public boolean isChar() {
        return this.simpleType == SimpleValueType.CHAR;
    }

    /* (non-Javadoc)
     * @see org.kie.base.ValueTypeInterface#isEvent()
     */
    public boolean isEvent() {
        return this.classType == EventFactHandle.class;
    }

    public T coerce(Object value) {
        return (T)value;
    }

    public static class StringValueType extends ValueType<String> {
        public StringValueType() {
            super("String", String.class, SimpleValueType.STRING);
        }

        @Override
        public String coerce( Object value ) {
            if (value == null) {
                return null;
            }
            return value instanceof String ? (String)value : value.toString();
        }
    }

    public static class BigIntegerValueType extends ValueType<BigInteger> {
        public BigIntegerValueType() {
            super("BigInteger", BigInteger.class, SimpleValueType.NUMBER);
        }

        @Override
        public BigInteger coerce( Object value ) {
            if (value == null) {
                return null;
            }
            return MathUtils.getBigInteger( value );
        }
    }

    public static class BigDecimalValueType extends ValueType<BigDecimal> {
        public BigDecimalValueType() {
            super("BigDecimal", BigDecimal.class, SimpleValueType.NUMBER);
        }

        @Override
        public BigDecimal coerce( Object value ) {
            if (value == null) {
                return null;
            }
            return MathUtils.getBigDecimal( value );
        }
    }
}


text:
Copyright (c) 2016 Guilherme Andrade

__Version:__ 1.0.0

__Authors:__ Guilherme Andrade ([`erlzquad(at)gandrade(dot)net`](mailto:erlzquad(at)gandrade(dot)net)).

`erlzquad`: An Erlang quadtree implementation with Z-order curve indexing
---------

### What is it? ###

`erlzquad` is an Erlang implementation of [quadtrees](https://en.wikipedia.org/wiki/Quadtree) which makes use of a [Z-order curve](https://en.wikipedia.org/wiki/Z-order_curve) as a way to speed up adding objects in bulk as well as querying arbitrary areas.

* Objects can be anything; a bounding-box -fetching function, which receives an object and returns a 4-tuple `{Left, Bottom, Right, Top}` is therefore a mandatory argument when adding;
* Coordinates are, for now, restricted to non-negative values that start on {0, 0} and may go up to the specified width and height;
* Explicit Z-index calculation code is included for levels up to 8 (inclusive); from that point on we recurse and the whole thing becomes slower than a turtle.

```erlang

Object = #square{id = 'a square', x = 1000, y = 750, side = 10},
GetBox = fun(#square{x = X, y = Y, side = S}) -> {X - S/2, Y - S/2, X + S/2, Y + S/2} end,

Q1 = erlzquad:new_qtree(4000, 3000, 1),
Q2 = erlzquad:add_objects([Object], GetBox, Q1),
Results1 = erlzquad:query_area(0, 0, 2000, 1500, Q2), % 1 result:  [#square{...}]
Results2 = erlzquad:query_area(2000, 1500, 0, 0, Q2).  % 0 results: []

```

### Concerning native compilation (HiPE) ###

Define 'COMPILE_NATIVE_ERLZQUAD' (e.g. "rebar compile -DCOMPILE_NATIVE_ERLZQUAD") for LOLSPEED™ in case that's your thing.

## Modules ##

erlzquad


text:
function Controller() {
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "serviceDates";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    $.__views.serviceDates = Ti.UI.createWindow({
        backgroundColor: "#fff",
        layout: "vertical",
        navBarHidden: true,
        title: "Service Schedule",
        backButtonTitle: "",
        id: "serviceDates"
    });
    $.__views.serviceDates && $.addTopLevelView($.__views.serviceDates);
    $.__views.header = Ti.UI.createView({
        width: Ti.UI.FILL,
        height: Titanium.UI.SIZE,
        backgroundColor: "#fff",
        id: "header"
    });
    $.__views.serviceDates.add($.__views.header);
    $.__views.lbl_serviceLocation = Ti.UI.createLabel({
        width: Ti.UI.SIZE,
        height: Ti.UI.SIZE,
        color: "#000",
        font: {
            fontSize: "18dp"
        },
        id: "lbl_serviceLocation",
        text: "Location: "
    });
    $.__views.header.add($.__views.lbl_serviceLocation);
    $.__views.TV_serviceDates = Ti.UI.createTableView({
        id: "TV_serviceDates"
    });
    $.__views.serviceDates.add($.__views.TV_serviceDates);
    exports.destroy = function() {};
    _.extend($, $.__views);
    arguments[0] || {};
    var serviceDatesProcessing = require("serviceDatesProcessing");
    var locObj = {
        cagaddressid: "00010BROAD0601617000",
        address: "1617 BROADWAY",
        addressWCity: "1617 BROADWAY, CINC",
        cagjuris: "CINC",
        cagjurisName: "CINCINNATI",
        cagrecid: "00860002036801617B",
        aliasflg: "",
        isInterpolatedRecord: false,
        I_Parity: "",
        I_addmastr_X: "",
        I_addmastr_Y: "",
        I_addr_RightLeftSide: "",
        "\n 	LocatorType": 7,
        StreetNameID: "BROAD06",
        StreetSegmentFID: "HAM50903",
        StreetSegmentID: "3368506153033685351848",
        USState: "OH",
        buildingid: "GJ1536132284",
        cagaddressstatus: "ASSIGNED",
        cagaddresstype: "BLD",
        "\n 	caggroupparcelid": "008600020368",
        cagparcelid: "008600020368",
        cagplace: "",
        cagstreetname: "BROADWAY",
        cagstreetsuffix: "",
        cityid: "CINC",
        condoflg: "",
        countyCode: "HAM",
        floor: "",
        multiunit: "",
        BLDG_LinkType: "",
        originallocation: "",
        streetdir: "",
        streetfrac: "",
        streetno: "1617",
        streetnoSFX: "",
        tanAssetID: "S-HAM50903",
        unitid: "",
        usngcode: "GJ1536132284",
        x_coord: "1398488.795060",
        y_coord: "411760.4230",
        x_intp: "1398525.9880",
        y_intp: "411757.626240",
        zipcode: "45202"
    };
    $.lbl_serviceLocation.text = "Location: " + locObj.addressWCity;
    serviceDatesProcessing.getCombinedServicesfromServer($, locObj.cagaddressid);
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
<?php

namespace tests\aik099\PHPUnit\Integration;

use Mockery as m;
use tests\aik099\PHPUnit\Fixture\SetupEventFixture;

class EventDispatchingTest extends \PHPUnit_Framework_TestCase
{

	/**
	 * Test description.
	 *
	 * @return void
	 */
	public function testSetupEvent()
	{
		/*
		 * BrowserTestCase::TEST_SETUP_EVENT
		 * - SauceLabsBrowserConfiguration::onTestSetup (called, verified)
		 *
		 * BrowserTestCase::TEST_ENDED_EVENT
		 * - IsolatedSessionStrategy::onTestEnd (called, verified)
		 * - SauceLabsBrowserConfiguration::onTestEnded (called, verified)
		 *
		 * BrowserTestCase::TEST_SUITE_ENDED_EVENT
		 * - SharedSessionStrategy::onTestSuiteEnd
		 *
		 * BrowserTestCase::TEST_FAILED_EVENT
		 * - SharedSessionStrategy::onTestFailed
		 */

		$result = new \PHPUnit_Framework_TestResult();

		$suite = SetupEventFixture::suite('tests\\aik099\\PHPUnit\\Fixture\\SetupEventFixture');
		$suite->run($result);

		$this->assertTrue($result->wasSuccessful(), 'All sub-tests passed');
	}

}


text:
require 'help_test'

class TestSelectorCondition  < ActiveSupport::TestCase

  def test_should_transform_sql_conditions_to_ruby_select_conditions_with_one_where
    condition = Plant::Selector::Condition.new(["(users.name = 'Joe')"], User)

    assert_equal "(users.name == 'Joe')", condition.to_ruby
  end

  def test_should_transform_sql_conditions_to_ruby_select_conditions_with_several_wheres
    condition = Plant::Selector::Condition.new(["(users.name = 'Joe' or users.age = 10)", "(users.age = 30)"], User)

    assert_equal "(users.name == 'Joe' or users.age == 10) and (users.age == 30)", condition.to_ruby
  end

  def test_with_inequality_operators
    condition = Plant::Selector::Condition.new(["(users.age <= 10)"], User)

    assert_equal "(users.age <= 10)", condition.to_ruby
  end

end


text:
Binaries for Bitcoin version 0.3.21 are available at:
  https://sourceforge.net/projects/digibyte/files/Bitcoin/digibyte-0.3.21/

Changes and new features from the 0.3.20 release include:

* Universal Plug and Play support.  Enable automatic opening of a port for incoming connections by running digibyte or digibyted with the - -upnp=1 command line switch or using the Options dialog box.

* Support for full-precision digibyte amounts.  You can now send, and digibyte will display, digibyte amounts smaller than 0.01.  However, sending fewer than 0.01 digibytes still requires a 0.01 digibyte fee (so you can send 1.0001 digibytes without a fee, but you will be asked to pay a fee if you try to send 0.0001).

* A new method of finding digibyte nodes to connect with, via DNS A records. Use the -dnsseed option to enable.

For developers, changes to digibyte's remote-procedure-call API:

* New rpc command "sendmany" to send digibytes to more than one address in a single transaction.

* Several bug fixes, including a serious intermittent bug that would sometimes cause digibyted to stop accepting rpc requests.

* -logtimestamps option, to add a timestamp to each line in debug.log.

* Immature blocks (newly generated, under 120 confirmations) are now shown in listtransactions.


text:
import React from 'react'

import SubscriptionStreamsContainer from './streams/SubscriptionStreamsContainer'
import TrendingStreamsContainer from './streams/TrendingStreamsContainer'
import TrendingTopicsContainer from './topics/TrendingTopicsContainer'

export default ({
  isSignedIn
}) => (

    {
      (isSignedIn) ? (

My Subscriptions

          <SubscriptionStreamsContainer />

      ) : null
    }

🚀 Trending Streams

    <TrendingStreamsContainer />

Explore by Topic

    <TrendingTopicsContainer />

)


text:
package archutil

func mips64Supported() error {
	return check(Binarymips64)
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>groovy.test (Groovy 2.1.7)</title>
<meta name="date" content="2013-09-05">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

groovy.test

Classes

GroovyAssert


text:
package com.ameron32.apps.projectbandit.core;

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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;

import com.ameron32.apps.projectbandit.LoadingAsyncTask;
import com.ameron32.apps.projectbandit.R;
import com.ameron32.apps.projectbandit.adapter.GameListAdapter;
import com.ameron32.apps.projectbandit.adapter.GameListAdapter.GameChangeListener;
import com.ameron32.apps.projectbandit.manager.CharacterManager;
import com.ameron32.apps.projectbandit.manager.CharacterManager.OnCharacterManagerInitializationCompleteListener;
import com.ameron32.apps.projectbandit.manager.ContentManager;
import com.ameron32.apps.projectbandit.manager.GameManager;
import com.ameron32.apps.projectbandit.manager.GameManager.OnGameManagerInitializationCompleteListener;
import com.ameron32.apps.projectbandit.manager.MessageManager;
import com.ameron32.apps.projectbandit.manager.ObjectManager;
import com.ameron32.apps.projectbandit.manager.UserManager;
import com.ameron32.apps.projectbandit.manager.UserManager.OnUserManagerInitializationCompleteListener;
import com.ameron32.apps.projectbandit.object.Game;
import com.crashlytics.android.Crashlytics;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ui.ParseLoginBuilder;

public class GatewayActivity extends
    ActionBarActivity implements
    GameChangeListener {

  private static final String TAG = GatewayActivity.class.getSimpleName();
  private static final Class<ExpandedCoreActivity> PRIMARY_ACTIVITY = ExpandedCoreActivity.class;

  private RecyclerView mRecyclerView;

  private Activity getActivity() {
    return GatewayActivity.this;
  }

  @Override protected void onCreate(
      Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Crashlytics.start(this);
    setContentView(R.layout.activity_gateway);

    mRecyclerView = (RecyclerView) findViewById(R.id.lv_game_list);
    LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setHasFixedSize(true);
  }

  @Override protected void onResume() {
    super.onResume();

    /**
     * IF USER IS ALREADY LOGGED IN, CONTINUE TO MAIN ACTIVITY. IF USER IS NOT
     * LOGGED IN, GOTO LOGIN ACTIVITY. WILL GO TO MAIN ACTIVITY AFTER SUCCESSFUL
     * LOGIN. WILL ABORT--finish()--IF CANCELLED.
     */
    if (!UserManager.get().isLoggedIn()) {
      UserManager.destroy();
      GameManager.destroy();
      CharacterManager.destroy();
      ObjectManager.destroy();
      MessageManager.destroy();
      ContentManager.destroy();
      startLoginActivity();
      // not logged in. exit onResume()
      return;
    }

    // logged in, continue
    loadGame();
  }

  /**
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   * LOGIN ACTIVITY RELATED SECTION
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   */

  private static final int LOGIN_REQUEST_CODE = 4647;

  private void startLoginActivity() {
    ParseLoginBuilder builder = new ParseLoginBuilder(getActivity());
    builder.setAppLogo(R.drawable.ic_launcher);
    startActivityForResult(builder.build(), LOGIN_REQUEST_CODE);
    // exit to ParseLogin
  }

  @Override protected void onActivityResult(
      int requestCode, int resultCode,
      Intent arg2) {
    // return from ParseLogin
    if (requestCode == LOGIN_REQUEST_CODE) {
      if (resultCode == RESULT_OK) {
        loadGame();
      }
    }
  }

  /**
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   * GAME LOADING AND SELECTION RELATED SECTION
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   */

  public volatile boolean lock = false;

  private void loadGame() {
    // use local current game, if possible
    if (GameManager.get().getCurrentGame() != null) {
      // reload current game
      Log.i(TAG, "restoring game from GameManager.");
      oneGame(GameManager.get().getCurrentGame());
      // restore single game from local data
      return;
    }

    // use local list of games, if possible
    if (UserManager.get().getStoredGamesOfCurrentUser() != null
        && !(UserManager.get().getStoredGamesOfCurrentUser().isEmpty())) {
      Log.i(TAG, "loading local list of available games.");
      multipleGames(UserManager.get().getStoredGamesOfCurrentUser());
      // display a list of games from local data
      return;
    }

    // LAST RESORT: no games stored, pull from server
    pullGamesFromServer();
  }

  /**
   * TODO: add a refresh process to the Gateway Activity
   * Button or Pull-to-Refresh
   */
  private void pullGamesFromServer() {
    Log.i(TAG, "pulling Games from Server.");

    // LOAD GAMES FROM SERVER
    // only one load should pass through lock
    // prevents simultaneous racing loads
    if (!lock) {
      lock = true;

      GameManager.get().selectAGame(new FindCallback<Game>() {

        @Override public void done(
            List<Game> games,
            ParseException e) {
          lock = false;
          if (e == null) {
            switch (games.size()) {
            case 0:
              noGames();
              break;
            case 1:
              oneGame(games.get(0));
              break;
            default:
              multipleGames(games);
            }
          }
        }
      });
    }
  }

  private void noGames() {
    // do not continueToStructureActivity() without a game
    Log.i(TAG, "game returned with no results.");
    final String message = "You are not registered for any games. Contact an administrator.";
    Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();

    /**
     * STOP!
     */
    // TODO: create a process to allow a User to:
    // -- request a game OR
    // -- start their own
  }

  private void oneGame(Game game) {
    // select this game, transparently
    Log.i(TAG, "game returned with one result.");
    List<Game> games = new ArrayList<Game>();
    games.add(game);
    UserManager.get().setGamesOfCurrentUser(games);
    changeGame(game);
  }

  private void multipleGames(
      final List<Game> games) {
    // offer a GameList for the User to choose which game to commit
    Log.i(TAG, "game returned with several results.");
    UserManager.get().setGamesOfCurrentUser(games);
    GameListAdapter mAdapter = new GameListAdapter(games, this);
    mRecyclerView.setAdapter(mAdapter);
    // TODO: convert OnClickListener within GameListAdapter to
    // OnItemClickListener here
  }

  @Override public void onGameChange(
      Game game) {
    changeGame(game);
  }

  private void changeGame(Game game) {
    GameManager.get().changeGame(game);
    performLoading();
  }

  /**
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   * PRE-ACTIVITY LOADING SECTION
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   */

  private void performLoading() {
    // PERFORM PRE-ACTIVITY INITIALIZATIONS OF SINGLETON MANAGERS
    new LoadingAsyncTask(new LoadingAsyncTask.OnLoadingListener() {

      @Override public void onLoadingComplete(
          boolean successful) {
        if (!successful) {
          Toast.makeText(getActivity(), "Initialization failed.", Toast.LENGTH_SHORT).show();
          return;
        }

        // successful
        allInitializationsComplete();
      }

      @Override public void onLoading(
          Boolean[] completed) {
        final String m = "onLoading(): " + completed[0] +","+ completed[1] +","+ completed[2];
        Log.d(LoadingAsyncTask.class.getSimpleName(), m);
      }
    }).execute();
  }

  private void allInitializationsComplete() {
    /*
     * MOVE to PrimaryActivity after loading
     */
    Intent beginStructureActivity = new Intent(getActivity(), PRIMARY_ACTIVITY);
    startActivity(beginStructureActivity);
    finish();
  }
}


text:
package codes.thischwa.bacoma.model.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.mail.javamail.ConfigurableMimeFileTypeMap;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class ServletUtil {
	private static ConfigurableMimeFileTypeMap mimeTypeMap = new ConfigurableMimeFileTypeMap();
	public static final MediaType MEDIATYPE_TEXT_CSS = new MediaType("text", "css");

	static {
		mimeTypeMap.setMappings("application/json json JSON");
	}

	public static String getMimeType(String fileName) {
		return mimeTypeMap.getContentType(fileName);
	}

	public static MediaType parseMediaType(String path) {
		String mimeType = getMimeType(path);
		if(mimeType.equals("text/css"))
			return MEDIATYPE_TEXT_CSS;
		return MediaType.parseMediaType(mimeType);
	}

	public static HttpServletRequest getCurrentRequest() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder");
		Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes);
		HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
		Assert.state(servletRequest != null, "Could not find current HttpServletRequest");
		return servletRequest;
	}

	public static String getBaseUrl() {
		HttpServletRequest req = getCurrentRequest();
		StringBuffer url = req.getRequestURL();
		String uri = req.getRequestURI();
		String ctx = req.getContextPath();
		String base = url.substring(0, url.length() - uri.length() + ctx.length()) + "/";
		return base;
	}

	public static void establishContentType(String fileName, HttpServletResponse resp) {
		if(StringUtils.isBlank(fileName))
			return;
		String contentType = getMimeType(fileName);
		if(StringUtils.isNotBlank(contentType))
			resp.setContentType(contentType);
	}

	public static String fetchContent(Part part, String key) {
		final String partHeader = part.getHeader("content-disposition");
		for(String content : partHeader.split(";")) {
			if(content.trim().startsWith(key)) {
				return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
			}
		}
		return null;
	}

	public static void write(Path reqPath, HttpServletResponse resp) throws IOException {
		if(!Files.exists(reqPath)) {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		InputStream in = Files.newInputStream(reqPath, StandardOpenOption.READ);
		write(in, resp);
		resp.setStatus(HttpServletResponse.SC_OK);
	}

	public static void write(String classPathPath, HttpServletResponse resp) throws IOException {
		Resource requestedResource = new ClassPathResource(classPathPath);
		if(!requestedResource.exists()) {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			throw new FileNotFoundException(requestedResource.getURI().toString());
		}
		MediaType mt = ServletUtil.parseMediaType(classPathPath);
		resp.setContentType(mt.toString());
		write(requestedResource.getInputStream(), resp);
		resp.setStatus(HttpServletResponse.SC_OK);
	}

	private static void write(InputStream in, HttpServletResponse resp) throws IOException {
		OutputStream out = resp.getOutputStream();
		int len = FileCopyUtils.copy(in, out);
		resp.setContentLength(len);
		out.flush();
	}
}


text:
layout: page
title: Jacqueline Shepherd's 90th Birthday
date: 2016-05-24
author: Kathy Schaefer
tags: weekly links, java
status: published
summary: Vestibulum tincidunt, justo eget condimentum suscipit, nulla dui condimentum arcu.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 05/20/2016
  endDate: 05/24/2016
  ctyhocn: CHASFHX
  groupCode: JS9B
published: true
---
Duis ac tortor pharetra, efficitur metus non, gravida erat. Nullam id augue nec nisl consectetur condimentum non porttitor est. Sed interdum sapien vehicula consequat tristique. Sed vitae auctor ipsum. Etiam sed lobortis est, eget semper urna. In eget ligula pretium, commodo ante at, commodo augue. Quisque egestas maximus enim, eu posuere nisi lobortis at. Nam non consectetur nisi. Pellentesque euismod commodo sem, at dictum dui tincidunt eget.

* Sed tristique arcu at ornare eleifend
* In sed metus ultricies, pharetra arcu maximus, consectetur urna
* Sed finibus purus in tincidunt tincidunt
* Cras dapibus magna eget lectus euismod, id varius eros vestibulum.

Nam a urna quis purus laoreet tincidunt. Phasellus sit amet porta elit. Integer ut interdum nisl. Nulla pulvinar sollicitudin augue ac faucibus. Vivamus rhoncus tellus sodales, molestie metus vel, egestas nisl. Nulla elementum consectetur ante. Aliquam ut lectus et diam efficitur aliquam a vel velit.
Suspendisse erat est, elementum ac pharetra a, porta at ex. Curabitur pretium, tellus eu euismod efficitur, erat felis vestibulum magna, et vehicula tortor quam a nisi. Integer efficitur sodales dignissim. Morbi sed est ac ante malesuada fermentum. In molestie nibh vel suscipit efficitur. Mauris mattis, sapien in viverra blandit, magna ante varius magna, in placerat massa nunc sit amet nulla. Etiam ipsum mauris, scelerisque et fringilla aliquam, posuere sed est. Nunc sed massa pretium, malesuada justo vitae, lacinia velit. Fusce et pulvinar ante.


text:
An easy way to have a password field in your form that include an option to reveal or hide the stored value.

## Installation

    gem 'password_reveal_input-simple_form'

## Usage

    <%= f.input :password, as: :password_reveal %>

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
{% load i18n admin_static %}<!DOCTYPE html>
{% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %}

<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}" />
{% block extrastyle %}{% endblock %}
{% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% block stylesheet_rtl %}{% static "admin/css/rtl.css" %}{% endblock %}" />{% endif %}

{% block extrahead %}{% endblock %}
{% block blockbots %}<meta name="robots" content="NONE,NOARCHIVE" />{% endblock %}

{% load i18n %}

    {% if not is_popup %}

        {% block branding %}{% endblock %}

        {% block usertools %}
        {% if has_permission %}

            {% block welcome-msg %}
                {% trans 'Welcome,' %}
                {% firstof user.get_short_name user.get_username %}.
            {% endblock %}
            {% block userlinks %}
                {% if site_url %}
                    {% trans 'View site' %} /
                {% endif %}
                {% if user.is_active and user.is_staff %}
                    {% url 'django-admindocs-docroot' as docsroot %}
                    {% if docsroot %}
                        {% trans 'Documentation' %} /
                    {% endif %}
                {% endif %}
                {% if user.has_usable_password %}
                {% trans 'Change password' %} /
                {% endif %}
                {% trans 'Log out' %}
            {% endblock %}

        {% endif %}
        {% endblock %}
        {% block nav-global %}{% endblock %}

    {% block breadcrumbs %}

    {% trans 'Home' %}
    {% if title %} › {{ title }}{% endif %}

    {% endblock %}
    {% endif %}

    {% block messages %}
        {% if messages %}

{% for message in messages %}

{{ message|capfirst }}

        {% endfor %}

        {% endif %}
    {% endblock messages %}

        {% block pretitle %}{% endblock %}
        {% block content_title %}{% if title %}
{{ title }}
{% endif %}{% endblock %}
        {% block content %}
        {% block object-tools %}{% endblock %}
        {{ content }}
        {% endblock %}
        {% block sidebar %}{% endblock %}

    {% block footer %}

{% endblock %}


text:
Ext.Loader.setConfig({enabled: true});

Ext.Loader.setPath('Ext.ux', '../ux');

Ext.require([
    'Ext.tip.QuickTipManager',
    'Ext.container.Viewport',
    'Ext.layout.*',
    'Ext.form.Panel',
    'Ext.form.Label',
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.tree.*',
    'Ext.selection.*',
    'Ext.tab.Panel',
    'Ext.ux.layout.Center'
]);

//
// This is the main layout definition.
//
Ext.onReady(function(){

    Ext.tip.QuickTipManager.init();

    // This is an inner body element within the Details panel created to provide a "slide in" effect
    // on the panel body without affecting the body's box itself.  This element is created on
    // initial use and cached in this var for subsequent access.
    var detailEl;

    // Gets all layouts examples
    var layoutExamples = [];
    Ext.Object.each(getBasicLayouts(), function(name, example) {
        layoutExamples.push(example);
    });

    Ext.Object.each(getCombinationLayouts(), function(name, example){
        layoutExamples.push(example);
    });

    Ext.Object.each(getCustomLayouts(), function(name, example){
        layoutExamples.push(example);
    });

    // This is the main content center region that will contain each example layout panel.
    // It will be implemented as a CardLayout since it will contain multiple panels with
    // only one being visible at any given time.

    var contentPanel = {
         id: 'content-panel',
         region: 'center', // this is what makes this panel into a region within the containing layout
         layout: 'card',
         margins: '2 5 5 0',
         activeItem: 0,
         border: false,
         items: layoutExamples
    };

    var store = Ext.create('Ext.data.TreeStore', {
        root: {
            expanded: true
        },
        proxy: {
            type: 'ajax',
            url: 'tree-data.json'
        }
    });

    // Go ahead and create the TreePanel now so that we can use it below
     var treePanel = Ext.create('Ext.tree.Panel', {
        id: 'tree-panel',
        title: 'Sample Layouts',
        region:'north',
        split: true,
        height: 360,
        minSize: 150,
        rootVisible: false,
        autoScroll: true,
        store: store
    });

    // Assign the changeLayout function to be called on tree node click.
    treePanel.getSelectionModel().on('select', function(selModel, record) {
        if (record.get('leaf')) {
            Ext.getCmp('content-panel').layout.setActiveItem(record.getId() + '-panel');
             if (!detailEl) {
                var bd = Ext.getCmp('details-panel').body;
                bd.update('').setStyle('background','#fff');
                detailEl = bd.createChild(); //create default empty div
            }
            detailEl.hide().update(Ext.getDom(record.getId() + '-details').innerHTML).slideIn('l', {stopAnimation:true,duration: 200});
        }
    });

    // This is the Details panel that contains the description for each example layout.
    var detailsPanel = {
        id: 'details-panel',
        title: 'Details',
        region: 'center',
        bodyStyle: 'padding-bottom:15px;background:#eee;',
        autoScroll: true,
        html: '
When you select a layout from the tree, additional details will display here.
'
    };

    // Finally, build the main layout once all the pieces are ready.  This is also a good
    // example of putting together a full-screen BorderLayout within a Viewport.
    Ext.create('Ext.Viewport', {
        layout: 'border',
        title: 'Ext Layout Browser',
        items: [{
            xtype: 'box',
            id: 'header',
            region: 'north',
            html: '
 Ext.Layout.Browser
',
            height: 30
        },{
            layout: 'border',
            id: 'layout-browser',
            region:'west',
            border: false,
            split:true,
            margins: '2 0 5 5',
            width: 275,
            minSize: 100,
            maxSize: 500,
            items: [treePanel, detailsPanel]
        },
            contentPanel
        ],
        renderTo: Ext.getBody()
    });
});


text:
from datetime import datetime, timedelta

from dino.db.manager.users import UserManager
from dino.exceptions import NoSuchChannelException
from dino.exceptions import NoSuchRoomException
from dino.exceptions import UnknownBanTypeException
from dino.utils import b64d

from test.db import BaseDatabaseTest

__author__ = 'Oscar Eriksson <oscar.eriks@gmail.com>'

class UserManagerTest(BaseDatabaseTest):
    _act = None

    @staticmethod
    def _publish(activity: dict, external=False) -> None:
        UserManagerTest._act = activity

    def setUp(self):
        self.set_up_env('redis')
        self.env.publish = UserManagerTest._publish
        self._act = None
        self.env.db = self.db
        self.manager = UserManager(self.env)

    def tearDown(self):
        self.db.redis.flushall()
        self.env.cache._flushall()

    def test_get_users_for_room(self):
        self._create_channel()
        self._create_room()
        users = self.manager.get_users_for_room(UserManagerTest.ROOM_ID)
        self.assertEqual(0, len(users))

    def test_get_users_for_room_after_join(self):
        self._create_channel()
        self._create_room()
        self._join()
        users = self.manager.get_users_for_room(UserManagerTest.ROOM_ID)
        self.assertEqual(1, len(users))
        self.assertEqual(UserManagerTest.USER_ID, users[0]['uuid'])
        self.assertEqual(UserManagerTest.USER_NAME, users[0]['name'])

    def test_kick_user(self):
        self._create_channel()
        self._create_room()
        self.manager.kick_user(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID)
        self.assertIsNotNone(UserManagerTest._act)
        self.assertEqual(UserManagerTest._act['target']['objectType'], 'room')
        self.assertEqual(UserManagerTest._act['object']['id'], BaseDatabaseTest.USER_ID)
        self.assertEqual(UserManagerTest._act['target']['id'], BaseDatabaseTest.ROOM_ID)

    def test_kick_user_is_base64(self):
        self._create_channel()
        self._create_room()
        self.manager.kick_user(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID)
        self.assertIsNotNone(UserManagerTest._act)
        self.assertEqual(UserManagerTest._act['target']['objectType'], 'room')
        self.assertEqual(b64d(UserManagerTest._act['object']['displayName']), BaseDatabaseTest.USER_NAME)
        self.assertEqual(b64d(UserManagerTest._act['target']['displayName']), BaseDatabaseTest.ROOM_NAME)

    def test_ban_user_globally(self):
        self._create_channel()
        self._create_room()
        self.manager.ban_user(BaseDatabaseTest.USER_ID, BaseDatabaseTest.ROOM_ID, '5m', 'global')
        self.assertIsNotNone(UserManagerTest._act)
        self.assertEqual(UserManagerTest._act['object']['id'], BaseDatabaseTest.USER_ID)
        self.assertEqual(UserManagerTest._act['target']['objectType'], 'global')
        self.assertNotIn('id', UserManagerTest._act['target'])
        self.assertEqual(b64d(UserManagerTest._act['object']['displayName']), BaseDatabaseTest.USER_NAME)

    def test_ban_user_channel(self):
        self._create_channel()
        self._create_room()
        self.manager.ban_user(BaseDatabaseTest.USER_ID, BaseDatabaseTest.CHANNEL_ID, '5m', 'channel')
        self.assertIsNotNone(UserManagerTest._act)
        self.assertEqual(UserManagerTest._act['object']['id'], BaseDatabaseTest.USER_ID)
        self.assertEqual(UserManagerTest._act['target']['id'], BaseDatabaseTest.CHANNEL_ID)
        self.assertEqual(UserManagerTest._act['target']['objectType'], 'channel')
        self.assertEqual(b64d(UserManagerTest._act['object']['displayName']), BaseDatabaseTest.USER_NAME)

    def test_ban_user_room(self):
        self._create_channel()
        self._create_room()
        self.manager.ban_user(BaseDatabaseTest.USER_ID, BaseDatabaseTest.ROOM_ID, '5m', 'room')
        self.assertIsNotNone(UserManagerTest._act)
        self.assertEqual(UserManagerTest._act['object']['id'], BaseDatabaseTest.USER_ID)
        self.assertEqual(UserManagerTest._act['target']['id'], BaseDatabaseTest.ROOM_ID)
        self.assertEqual(UserManagerTest._act['target']['objectType'], 'room')
        self.assertEqual(b64d(UserManagerTest._act['object']['displayName']), BaseDatabaseTest.USER_NAME)

    def test_ban_user_no_room(self):
        self._create_channel()
        self.assertRaises(NoSuchRoomException, self.manager.ban_user, BaseDatabaseTest.USER_ID, BaseDatabaseTest.ROOM_ID, '5m', 'room')

    def test_ban_user_no_channel(self):
        self.assertRaises(NoSuchChannelException, self.manager.ban_user, BaseDatabaseTest.USER_ID, BaseDatabaseTest.CHANNEL_ID, '5m', 'channel')

    def test_ban_use_unknown_type(self):
        self.assertRaises(UnknownBanTypeException, self.manager.ban_user, BaseDatabaseTest.USER_ID, BaseDatabaseTest.CHANNEL_ID, '5m', 'something-unknown')

    def test_remove_ban_unknown_type(self):
        self._create_channel()
        self._create_room()
        self.assertRaises(UnknownBanTypeException, self.manager.remove_ban, BaseDatabaseTest.USER_ID, BaseDatabaseTest.CHANNEL_ID, 'something-unknown')

    def test_remove_ban_channel(self):
        self._create_channel()
        self._create_room()
        self.assertFalse(self.db.is_banned_from_channel(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID)[0])

        timestamp = str(int((datetime.utcnow() + timedelta(minutes=5)).timestamp()))
        self.db.ban_user_channel(BaseDatabaseTest.USER_ID, timestamp, '5m',  BaseDatabaseTest.CHANNEL_ID)
        self.assertTrue(self.db.is_banned_from_channel(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID)[0])

        self.manager.remove_ban(BaseDatabaseTest.USER_ID, BaseDatabaseTest.CHANNEL_ID, 'channel')
        self.assertFalse(self.db.is_banned_from_channel(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID)[0])

    def test_remove_ban_room(self):
        self._create_channel()
        self._create_room()
        self.assertFalse(self.db.is_banned_from_room(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID)[0])

        timestamp = str(int((datetime.utcnow() + timedelta(minutes=5)).timestamp()))
        self.db.ban_user_room(BaseDatabaseTest.USER_ID, timestamp, '5m',  BaseDatabaseTest.ROOM_ID)
        self.assertTrue(self.db.is_banned_from_room(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID)[0])

        self.manager.remove_ban(BaseDatabaseTest.USER_ID, BaseDatabaseTest.ROOM_ID, 'room')
        self.assertFalse(self.db.is_banned_from_room(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID)[0])

    def test_remove_ban_globally(self):
        self._create_channel()
        self._create_room()
        self.assertFalse(self.db.is_banned_globally(BaseDatabaseTest.USER_ID)[0])

        timestamp = str(int((datetime.utcnow() + timedelta(minutes=5)).timestamp()))
        self.db.ban_user_global(BaseDatabaseTest.USER_ID, timestamp, '5m')
        self.assertTrue(self.db.is_banned_globally(BaseDatabaseTest.USER_ID)[0])

        self.manager.remove_ban(BaseDatabaseTest.USER_ID, BaseDatabaseTest.CHANNEL_ID, 'global')
        self.assertFalse(self.db.is_banned_globally(BaseDatabaseTest.USER_ID)[0])

    def test_get_banned_users_is_empty(self):
        self._create_channel()
        self._create_room()
        banned = self.manager.get_banned_users()
        self.assertEqual({'channels', 'rooms', 'global'}, set(banned.keys()))
        self.assertEqual(0, len(banned['channels']))
        self.assertEqual(0, len(banned['rooms']))
        self.assertEqual(0, len(banned['global']))

    def test_get_banned_users_channel(self):
        self._create_channel()
        self._create_room()

        timestamp = str(int((datetime.utcnow() + timedelta(minutes=5)).timestamp()))
        self.db.ban_user_channel(BaseDatabaseTest.USER_ID, timestamp, '5m',  BaseDatabaseTest.CHANNEL_ID)

        banned = self.manager.get_banned_users()
        self.assertEqual({'channels', 'rooms', 'global'}, set(banned.keys()))
        self.assertEqual(1, len(banned['channels']))
        self.assertEqual(0, len(banned['rooms']))
        self.assertEqual(0, len(banned['global']))
        self.assertEqual(BaseDatabaseTest.USER_NAME,
                         b64d(banned['channels'][BaseDatabaseTest.CHANNEL_ID]['users'][BaseDatabaseTest.USER_ID]['name']))

    def test_get_banned_users_room(self):
        self._create_channel()
        self._create_room()

        timestamp = str(int((datetime.utcnow() + timedelta(minutes=5)).timestamp()))
        self.db.ban_user_room(BaseDatabaseTest.USER_ID, timestamp, '5m',  BaseDatabaseTest.ROOM_ID)

        banned = self.manager.get_banned_users()
        self.assertEqual({'channels', 'rooms', 'global'}, set(banned.keys()))
        self.assertEqual(0, len(banned['channels']))
        self.assertEqual(1, len(banned['rooms']))
        self.assertEqual(0, len(banned['global']))
        self.assertEqual(BaseDatabaseTest.USER_NAME,
                         b64d(banned['rooms'][BaseDatabaseTest.ROOM_ID]['users'][BaseDatabaseTest.USER_ID]['name']))

    def test_get_banned_users_globally(self):
        self._create_channel()
        self._create_room()

        timestamp = str(int((datetime.utcnow() + timedelta(minutes=5)).timestamp()))
        self.db.ban_user_global(BaseDatabaseTest.USER_ID, timestamp, '5m')

        banned = self.manager.get_banned_users()
        self.assertEqual({'channels', 'rooms', 'global'}, set(banned.keys()))
        self.assertEqual(0, len(banned['channels']))
        self.assertEqual(0, len(banned['rooms']))
        self.assertEqual(1, len(banned['global']))
        self.assertEqual(BaseDatabaseTest.USER_NAME,
                         b64d(banned['global'][BaseDatabaseTest.USER_ID]['name']))

    def test_get_super_users(self):
        self.assertEqual(0, len(self.manager.get_super_users()))

    def test_get_super_users_after_create(self):
        self.manager.create_super_user(BaseDatabaseTest.OTHER_USER_NAME, BaseDatabaseTest.OTHER_USER_ID)
        super_users = self.manager.get_super_users()
        self.assertEqual(1, len(super_users))
        self.assertEqual(BaseDatabaseTest.OTHER_USER_ID, super_users[0]['uuid'])
        self.assertEqual(BaseDatabaseTest.OTHER_USER_NAME, super_users[0]['name'])

    def test_create_super_user_empty_id(self):
        self.manager.create_super_user(BaseDatabaseTest.USER_NAME, '')
        self.assertEqual(0, len(self.manager.get_super_users()))

    def test_create_super_user_empty_name(self):
        self.manager.create_super_user('', BaseDatabaseTest.USER_ID)
        self.assertEqual(0, len(self.manager.get_super_users()))

    def test_add_channel_admin(self):
        self._create_channel()
        self._create_room()
        self.assertFalse(self.db.is_admin(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID))
        self.manager.add_channel_admin(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID)
        self.assertTrue(self.db.is_admin(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID))

    def test_add_channel_owner(self):
        self._create_channel()
        self._create_room()
        self.db.remove_owner_channel(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID)
        self.assertFalse(self.db.is_owner_channel(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID))
        self.manager.add_channel_owner(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID)
        self.assertTrue(self.db.is_owner_channel(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID))

    def test_add_room_owner(self):
        self._create_channel()
        self._create_room()
        self.db.remove_owner(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID)
        self.assertFalse(self.db.is_owner(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID))
        self.manager.add_room_owner(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID)
        self.assertTrue(self.db.is_owner(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID))

    def test_add_room_moderator(self):
        self._create_channel()
        self._create_room()
        self.assertFalse(self.db.is_moderator(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID))
        self.manager.add_room_moderator(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID)
        self.assertTrue(self.db.is_moderator(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID))

    def test_remove_channel_admin(self):
        self._create_channel()
        self._create_room()
        self.assertFalse(self.db.is_admin(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID))

        self.manager.add_channel_admin(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID)
        self.assertTrue(self.db.is_admin(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID))

        self.manager.remove_channel_admin(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID)
        self.assertFalse(self.db.is_admin(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID))

    def test_remove_channel_owner(self):
        self._create_channel()
        self._create_room()
        self.assertTrue(self.db.is_owner_channel(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID))

        self.manager.remove_channel_owner(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID)
        self.assertFalse(self.db.is_owner_channel(BaseDatabaseTest.CHANNEL_ID, BaseDatabaseTest.USER_ID))

    def test_remove_room_owner(self):
        self._create_channel()
        self._create_room()
        self.assertTrue(self.db.is_owner(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID))

        self.manager.remove_room_owner(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID)
        self.assertFalse(self.db.is_owner(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID))

    def test_remove_room_moderator(self):
        self._create_channel()
        self._create_room()
        self.assertFalse(self.db.is_moderator(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID))

        self.manager.add_room_moderator(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID)
        self.assertTrue(self.db.is_moderator(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID))

        self.manager.remove_room_moderator(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID)
        self.assertFalse(self.db.is_moderator(BaseDatabaseTest.ROOM_ID, BaseDatabaseTest.USER_ID))


text:
/**
 * Check if the given element has the given class
 * @param  {String}   elem              Element selector
 * @param  {String}   falseCase         Whether to check for the class to exist
 *                                      or not
 * @param  {String}   expectedClassName The class name to check
 * @param  {Function} done              Function to execute when finished
 */
module.exports = (elem, falseCase, expectedClassName, done) => {
    /**
     * List of all the classes of the element
     * @type {Array}
     */
    const classesList = browser.getAttribute(elem, 'className').split(' ');

    if (falseCase === 'does not have') {
        expect(classesList).to.not
            .include(
                expectedClassName,
                `Element ${elem} should not have the class ${expectedClassName}`
            );
    } else {
        expect(classesList).to
            .include(
                expectedClassName,
                `Element ${elem} should have the class ${expectedClassName}`
            );
    }

    done();
};


text:
const handler = require('../db/migration-handler')

module.exports.up = handler(async function (db) {
  const modifications = db.collection('modifications')
  const results = await modifications.updateMany(
    {
      type: 'add-trip-pattern',
      transitMode: null
    },
    {
      $set: {transitMode: 0}
    }
  )
  console.log(`Modified ${results.modifiedCount} modifications`)
})

module.exports.down = handler(function () {})


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;

namespace Microsoft.CodeAnalysis.ExtractInterface
{
    internal class ExtractInterfaceOptionsResult
    {
        public static readonly ExtractInterfaceOptionsResult Cancelled = new ExtractInterfaceOptionsResult(isCancelled: true);

        public bool IsCancelled { get; private set; }
        public IEnumerable<ISymbol> IncludedMembers { get; private set; }
        public string InterfaceName { get; private set; }
        public string FileName { get; private set; }

        public ExtractInterfaceOptionsResult(bool isCancelled, IEnumerable<ISymbol> includedMembers, string interfaceName, string fileName)
        {
            this.IsCancelled = isCancelled;
            this.IncludedMembers = includedMembers;
            this.InterfaceName = interfaceName;
            this.FileName = fileName;
        }

        private ExtractInterfaceOptionsResult(bool isCancelled)
        {
            IsCancelled = isCancelled;
        }
    }
}