text:
TranslateMessageInfoBar::TranslateMessageInfoBar(
    InfoBarService* owner,
    TranslateInfoBarDelegate* delegate)
    : TranslateInfoBarBase(owner, delegate) {
}

TranslateMessageInfoBar::~TranslateMessageInfoBar() {
}

void TranslateMessageInfoBar::InitWidgets() {
  TranslateInfoBarBase::InitWidgets();

  GtkWidget* hbox = gtk_hbox_new(FALSE, ui::kControlSpacing);
  gtk_util::CenterWidgetInHBox(hbox_, hbox, false, 0);

  std::string text = UTF16ToUTF8(GetDelegate()->GetMessageInfoBarText());
  gtk_box_pack_start(GTK_BOX(hbox), CreateLabel(text.c_str()), FALSE, FALSE, 0);
  string16 button_text = GetDelegate()->GetMessageInfoBarButtonText();
  if (!button_text.empty()) {
    GtkWidget* button =
        gtk_button_new_with_label(UTF16ToUTF8(button_text).c_str());
    Signals()->Connect(button, "clicked",G_CALLBACK(&OnButtonPressedThunk),
                       this);
    gtk_box_pack_start(GTK_BOX(hbox), button, FALSE, FALSE, 0);
  }
}

void TranslateMessageInfoBar::OnButtonPressed(GtkWidget* sender) {
  GetDelegate()->MessageInfoBarButtonPressed();
}


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

<TITLE>
ExceptionWrapper (Oracle - Berkeley DB Java API)
</TITLE>

<META NAME="date" CONTENT="2009-12-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../style.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

Berkeley DB
 version 4.8.26

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.sleepycat.util

Interface ExceptionWrapper

All Known Implementing Classes:
IOExceptionWrapper, RuntimeExceptionWrapper

public interface ExceptionWrapper

Interface implemented by exceptions that can contain nested exceptions.

Method Summary

 Throwable
getCause()

          Returns the nested exception or null if none is present.

 Throwable
getDetail()

          Deprecated. replaced by getCause().

Method Detail

getDetail

Throwable getDetail()

Deprecated. replaced by getCause().

Returns the nested exception or null if none is present.

Returns:
the nested exception or null if none is present.

getCause

Throwable getCause()

Returns the nested exception or null if none is present.

This method is intentionally defined to be the same signature as the
 java.lang.Throwable.getCause method in Java 1.4 and
 greater.  By defining this method to return a nested exception, the Java
 1.4 runtime will print the nested stack trace.

Returns:
the nested exception or null if none is present.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

Berkeley DB
 version 4.8.26

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright (c) 1996-2009 Oracle.  All rights reserved.

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SassyStudio.Editor;

namespace SassyStudio.Compiler.Parsing
{
    public class VariableReference : ComplexItem, IResolvableToken
    {
        public VariableName Name { get; protected set; }
        public override bool Parse(IItemFactory itemFactory, ITextProvider text, ITokenStream stream)
        {
            var name = new VariableName(SassClassifierType.VariableReference);
            if (name.Parse(itemFactory, text, stream))
            {
                Name = name;
                Children.Add(name);
            }

            return Children.Count > 0;
        }

        public ParseItem GetSourceToken()
        {
            return ReverseSearch.Find<VariableDefinition>(this, x => x.Name.Equals(Name));
        }
    }
}


text:
<!DOCTYPE html>

    <title>url.URL#slashes documentation</title>
    <link rel="stylesheet" type="text/css" href="../../../../../../index.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../../highlight.css" />

            member

                Boolean

                |

                :url.URL#slashes

        This document was generated with
        doczar
        at 3:55pm on 8/14/2015


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

#pragma once
/** \file */

#include <dp/sg/algorithm/Config.h>
#include <dp/sg/algorithm/Traverser.h>
#include <list>
#include <map>
#include <set>

namespace dp
{
  namespace sg
  {
    namespace algorithm
    {

      //! Traverser to convert primitives of type PRIMITIVE_TRIANGLES or PRIMITIVE_QUADS to Primitives of type PRIMITIVE_TRIANGLE_STRIPS or PRIMITIVE_QUAD_STRIPS, respectively.
      /** It is strongly recommended to use a VertexUnifyTraverser before using this StrippingTraverser, because it
        * works only on indices. */
      class StrippingTraverser : public ExclusiveTraverser
      {
        public:
          //! Constructor
          DP_SG_ALGORITHM_API StrippingTraverser(void);

          //! Destructor
          DP_SG_ALGORITHM_API virtual ~StrippingTraverser(void);

        protected:
          DP_SG_ALGORITHM_API virtual void handleGeoNode( dp::sg::core::GeoNode * p );

          //! Convert each Primitive of type PRIMITIVE_QUADS or PRIMITIVE_TRIANGLES to PRIMITIVE_QUAD_STRIP and PRIMITIVE_TRIANGLE_STRIP, respectively.
          DP_SG_ALGORITHM_API virtual void handlePrimitive( dp::sg::core::Primitive * p );

          /*! \brief Test whether this Object should be optimized
           *  \param p A pointer to the constant dp::sg::core::Object to test. */
          DP_SG_ALGORITHM_API virtual bool optimizationAllowed( dp::sg::core::ObjectSharedPtr const& p );

        private:
          void changeToStrips( dp::sg::core::Primitive * p );

        private:
          dp::sg::core::PrimitiveSharedPtr  m_strip;
      };

    } // namespace algorithm
  } // namespace sg
} // namespace dp


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

    <meta http-equiv="Content-Type" content="text/html; charset=gb18030">
        <link rel="stylesheet" href="<?= base_url() ?>public/css/font-awesome.min.css">
        <link rel="stylesheet" href="<?= base_url() ?>public/css/bootstrap.min.css">
        <link href='https://fonts.googleapis.com/css?family=Open+Sans:600italic,400,800,700,300' rel='stylesheet' type='text/css'>

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        Toggle navigation

                    </button>

                                OPCIONES

EMPRESA

VANCANTES

Buscar Talentos

Entrevista

Reporte

Evaluación psicométrica

 <?= $empresa->mail ?>

 Salir

Bienvenidos Empresa

Panel de administracion

<img src='<?= base_url() ?>public/img/load.gif' width="64" height="64" />

                        <button type="button" class="close" id="modal-cerrar" data-dismiss="modal" aria-label="Close">×</button>

Información de empresa


text:
<?php

namespace App\ProductBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormViewInterface;

use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ProductItemsType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('field',TextType::class, array('label'=>'Pole', 'required' => false));
        $builder->add('content',TextType::class, array('label'=>'Wartość', 'required' => false));
        $builder->add('description', TextareaType::class, array(
            'label'=>'Opis - niewyświetlany',
           'required' => false,
           'attr' => array('class' => 'tinymce', 'tinymce'=>'{"theme":"simple"}'))
        );
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => \App\ProductBundle\Entity\ProductItems::class,
            )
        );
    }

    public function getName()
    {
        return 'productItems';
    }
}


text:
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `fuel`
--

-- --------------------------------------------------------

--
-- Table structure for table `articles`
--

CREATE TABLE `articles` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `title` varchar(255) collate utf8_unicode_ci NOT NULL default '',
  `slug` varchar(255) collate utf8_unicode_ci NOT NULL default '',
  `author_id` tinyint(3) unsigned NOT NULL default '0',
  `content` text collate utf8_unicode_ci NOT NULL,
  `date_added` datetime NOT NULL default '0000-00-00 00:00:00',
  `published` enum('yes','no') collate utf8_unicode_ci NOT NULL default 'yes',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `authors`
--

CREATE TABLE `authors` (
  `id` tinyint(3) unsigned NOT NULL auto_increment,
  `name` varchar(255) collate utf8_unicode_ci NOT NULL default '',
  `email` varchar(255) collate utf8_unicode_ci NOT NULL default '',
  `bio` text collate utf8_unicode_ci NOT NULL default '',
  `avatar_image` varchar(255) collate utf8_unicode_ci NOT NULL default '',
  `published` enum('yes','no') collate utf8_unicode_ci NOT NULL default 'yes',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


text:
#ifndef RAM_EXAMPLES_HPP_
#define RAM_EXAMPLES_HPP_

#include "relations/ram_computations/rams/ram_params.hpp"

namespace libsnark {

template<typename ramT>
struct ram_example {
    ram_architecture_params<ramT> ap;
    size_t boot_trace_size_bound;
    size_t time_bound;
    ram_boot_trace<ramT> boot_trace;
    ram_input_tape<ramT> auxiliary_input;
};

/**
 * For now: only specialized to TinyRAM
 */
template<typename ramT>
ram_example<ramT> gen_ram_example_simple(const ram_architecture_params<ramT> &ap, const size_t boot_trace_size_bound, const size_t time_bound, const bool satisfiable=true);

/**
 * For now: only specialized to TinyRAM
 */
template<typename ramT>
ram_example<ramT> gen_ram_example_complex(const ram_architecture_params<ramT> &ap, const size_t boot_trace_size_bound, const size_t time_bound, const bool satisfiable=true);

} // libsnark

#include "relations/ram_computations/rams/examples/ram_examples.tcc"

#endif // RAM_EXAMPLES_HPP_


text:
package com.mossle.api.database;

import java.io.Closeable;

import javax.sql.DataSource;

public interface Database extends Closeable {
    public static final String NAME_DEFAULT = "default";

    DataSource getDataSource();

    DataSource getDataSource(String name);
}


text:
goog.provide('lf.backstore.MemoryTable');

goog.require('goog.Promise');
goog.require('lf.Table');
goog.require('lf.structs.map');

goog.requireType('lf.Row');

/**
 * @constructor @struct
 * @implements {lf.Table}
 */
lf.backstore.MemoryTable = function() {
  /**
   * @private {!lf.structs.Map<number, !lf.Row>}
   */
  this.data_ = lf.structs.map.create();
};

/**
 * @param {!Array<number>} ids
 * @return {!Array<!lf.Row>}
 */
lf.backstore.MemoryTable.prototype.getSync = function(ids) {
  // Empty array is treated as "return all rows".
  if (ids.length == 0) {
    return lf.structs.map.values(this.data_);
  }

  var results = [];
  ids.forEach(function(id) {
    var row = this.data_.get(id) || null;
    if (row !== null) {
      results.push(row);
    }
  }, this);

  return results;
};

/** @return {!lf.structs.Map<number, !lf.Row>} */
lf.backstore.MemoryTable.prototype.getData = function() {
  return this.data_;
};

/** @override */
lf.backstore.MemoryTable.prototype.get = function(ids) {
  return goog.Promise.resolve(this.getSync(ids));
};

/** @param {!Array<!lf.Row>} rows */
lf.backstore.MemoryTable.prototype.putSync = function(rows) {
  rows.forEach(function(row) {
    this.data_.set(row.id(), row);
  }, this);
};

/** @override */
lf.backstore.MemoryTable.prototype.put = function(rows) {
  this.putSync(rows);
  return goog.Promise.resolve();
};

/** @param {!Array<number>} ids */
lf.backstore.MemoryTable.prototype.removeSync = function(ids) {
  if (ids.length == 0 || ids.length == this.data_.size) {
    // Remove all.
    this.data_.clear();
  } else {
    ids.forEach(function(id) {
      this.data_.delete(id);
    }, this);
  }
};

/** @override */
lf.backstore.MemoryTable.prototype.remove = function(ids) {
  this.removeSync(ids);
  return goog.Promise.resolve();
};

/** @return {number} */
lf.backstore.MemoryTable.prototype.getMaxRowId = function() {
  if (this.data_.size == 0) {
    return 0;
  }
  return lf.structs.map.keys(this.data_).reduce(function(prev, cur) {
    return prev > cur ? prev : cur;
  }, 0);
};


text:
#include <nokogiri.h>

VALUE cNokogiriXmlSchema;

static void
dealloc(xmlSchemaPtr schema)
{
  NOKOGIRI_DEBUG_START(schema);
  xmlSchemaFree(schema);
  NOKOGIRI_DEBUG_END(schema);
}

/*
 * call-seq:
 *  validate_document(document)
 *
 * Validate a Nokogiri::XML::Document against this Schema.
 */
static VALUE
validate_document(VALUE self, VALUE document)
{
  xmlDocPtr doc;
  xmlSchemaPtr schema;
  xmlSchemaValidCtxtPtr valid_ctxt;
  VALUE errors;

  Data_Get_Struct(self, xmlSchema, schema);
  Data_Get_Struct(document, xmlDoc, doc);

  errors = rb_ary_new();

  valid_ctxt = xmlSchemaNewValidCtxt(schema);

  if (NULL == valid_ctxt) {
    /* we have a problem */
    rb_raise(rb_eRuntimeError, "Could not create a validation context");
  }

#ifdef HAVE_XMLSCHEMASETVALIDSTRUCTUREDERRORS
  xmlSchemaSetValidStructuredErrors(
    valid_ctxt,
    Nokogiri_error_array_pusher,
    (void *)errors
  );
#endif

  xmlSchemaValidateDoc(valid_ctxt, doc);

  xmlSchemaFreeValidCtxt(valid_ctxt);

  return errors;
}

/*
 * call-seq:
 *  validate_file(filename)
 *
 * Validate a file against this Schema.
 */
static VALUE
validate_file(VALUE self, VALUE rb_filename)
{
  xmlSchemaPtr schema;
  xmlSchemaValidCtxtPtr valid_ctxt;
  const char *filename ;
  VALUE errors;

  Data_Get_Struct(self, xmlSchema, schema);
  filename = (const char *)StringValueCStr(rb_filename) ;

  errors = rb_ary_new();

  valid_ctxt = xmlSchemaNewValidCtxt(schema);

  if (NULL == valid_ctxt) {
    /* we have a problem */
    rb_raise(rb_eRuntimeError, "Could not create a validation context");
  }

#ifdef HAVE_XMLSCHEMASETVALIDSTRUCTUREDERRORS
  xmlSchemaSetValidStructuredErrors(
    valid_ctxt,
    Nokogiri_error_array_pusher,
    (void *)errors
  );
#endif

  xmlSchemaValidateFile(valid_ctxt, filename, 0);

  xmlSchemaFreeValidCtxt(valid_ctxt);

  return errors;
}

/*
 * call-seq:
 *  read_memory(string)
 *
 * Create a new Schema from the contents of +string+
 */
static VALUE
read_memory(int argc, VALUE *argv, VALUE klass)
{
  VALUE content;
  VALUE parse_options;
  int parse_options_int;
  xmlSchemaParserCtxtPtr ctx;
  xmlSchemaPtr schema;
  VALUE errors;
  VALUE rb_schema;
  int scanned_args = 0;
  xmlExternalEntityLoader old_loader = 0;

  scanned_args = rb_scan_args(argc, argv, "11", &content, &parse_options);
  if (scanned_args == 1) {
    parse_options = rb_const_get_at(rb_const_get_at(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA"));
  }
  parse_options_int = (int)NUM2INT(rb_funcall(parse_options, rb_intern("to_i"), 0));

  ctx = xmlSchemaNewMemParserCtxt((const char *)StringValuePtr(content), (int)RSTRING_LEN(content));

  errors = rb_ary_new();
  xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);

#ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS
  xmlSchemaSetParserStructuredErrors(
    ctx,
    Nokogiri_error_array_pusher,
    (void *)errors
  );
#endif

  if (parse_options_int & XML_PARSE_NONET) {
    old_loader = xmlGetExternalEntityLoader();
    xmlSetExternalEntityLoader(xmlNoNetExternalEntityLoader);
  }

  schema = xmlSchemaParse(ctx);

  if (old_loader) {
    xmlSetExternalEntityLoader(old_loader);
  }

  xmlSetStructuredErrorFunc(NULL, NULL);
  xmlSchemaFreeParserCtxt(ctx);

  if (NULL == schema) {
    xmlErrorPtr error = xmlGetLastError();
    if (error) {
      Nokogiri_error_raise(NULL, error);
    } else {
      rb_raise(rb_eRuntimeError, "Could not parse document");
    }

    return Qnil;
  }

  rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
  rb_iv_set(rb_schema, "@errors", errors);
  rb_iv_set(rb_schema, "@parse_options", parse_options);

  return rb_schema;
}

/* Schema creation will remove and deallocate "blank" nodes.
 * If those blank nodes have been exposed to Ruby, they could get freed
 * out from under the VALUE pointer.  This function checks to see if any of
 * those nodes have been exposed to Ruby, and if so we should raise an exception.
 */
static int
has_blank_nodes_p(VALUE cache)
{
  long i;

  if (NIL_P(cache)) {
    return 0;
  }

  for (i = 0; i < RARRAY_LEN(cache); i++) {
    xmlNodePtr node;
    VALUE element = rb_ary_entry(cache, i);
    Data_Get_Struct(element, xmlNode, node);
    if (xmlIsBlankNode(node)) {
      return 1;
    }
  }

  return 0;
}

/*
 * call-seq:
 *  from_document(doc)
 *
 * Create a new Schema from the Nokogiri::XML::Document +doc+
 */
static VALUE
from_document(int argc, VALUE *argv, VALUE klass)
{
  VALUE document;
  VALUE parse_options;
  int parse_options_int;
  xmlDocPtr doc;
  xmlSchemaParserCtxtPtr ctx;
  xmlSchemaPtr schema;
  VALUE errors;
  VALUE rb_schema;
  int scanned_args = 0;
  xmlExternalEntityLoader old_loader = 0;

  scanned_args = rb_scan_args(argc, argv, "11", &document, &parse_options);

  Data_Get_Struct(document, xmlDoc, doc);
  doc = doc->doc; /* In case someone passes us a node. ugh. */

  if (scanned_args == 1) {
    parse_options = rb_const_get_at(rb_const_get_at(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA"));
  }
  parse_options_int = (int)NUM2INT(rb_funcall(parse_options, rb_intern("to_i"), 0));

  if (has_blank_nodes_p(DOC_NODE_CACHE(doc))) {
    rb_raise(rb_eArgError, "Creating a schema from a document that has blank nodes exposed to Ruby is dangerous");
  }

  ctx = xmlSchemaNewDocParserCtxt(doc);

  errors = rb_ary_new();
  xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);

#ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS
  xmlSchemaSetParserStructuredErrors(
    ctx,
    Nokogiri_error_array_pusher,
    (void *)errors
  );
#endif

  if (parse_options_int & XML_PARSE_NONET) {
    old_loader = xmlGetExternalEntityLoader();
    xmlSetExternalEntityLoader(xmlNoNetExternalEntityLoader);
  }

  schema = xmlSchemaParse(ctx);

  if (old_loader) {
    xmlSetExternalEntityLoader(old_loader);
  }

  xmlSetStructuredErrorFunc(NULL, NULL);
  xmlSchemaFreeParserCtxt(ctx);

  if (NULL == schema) {
    xmlErrorPtr error = xmlGetLastError();
    if (error) {
      Nokogiri_error_raise(NULL, error);
    } else {
      rb_raise(rb_eRuntimeError, "Could not parse document");
    }

    return Qnil;
  }

  rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
  rb_iv_set(rb_schema, "@errors", errors);
  rb_iv_set(rb_schema, "@parse_options", parse_options);

  return rb_schema;

  return Qnil;
}

void
noko_init_xml_schema()
{
  cNokogiriXmlSchema = rb_define_class_under(mNokogiriXml, "Schema", rb_cObject);

  rb_undef_alloc_func(cNokogiriXmlSchema);

  rb_define_singleton_method(cNokogiriXmlSchema, "read_memory", read_memory, -1);
  rb_define_singleton_method(cNokogiriXmlSchema, "from_document", from_document, -1);

  rb_define_private_method(cNokogiriXmlSchema, "validate_document", validate_document, 1);
  rb_define_private_method(cNokogiriXmlSchema, "validate_file",     validate_file, 1);
}


text:
<?php

namespace Illuminate\Contracts\Cache;

interface Store
{
    /**
     * Retrieve an item from the cache by key.
     *
     * @param  string|array  $key
     * @return mixed
     */
    public function get($key);

    /**
     * Retrieve multiple items from the cache by key.
     *
     * Items not found in the cache will have a null value.
     *
     * @param  array  $keys
     * @return array
     */
    public function many(array $keys);

    /**
     * Store an item in the cache for a given number of minutes.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @param  float|int  $minutes
     * @return void
     */
    public function put($key, $value, $minutes);

    /**
     * Store multiple items in the cache for a given number of minutes.
     *
     * @param  array  $values
     * @param  float|int  $minutes
     * @return void
     */
    public function putMany(array $values, $minutes);

    /**
     * Increment the value of an item in the cache.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return int|bool
     */
    public function increment($key, $value = 1);

    /**
     * Decrement the value of an item in the cache.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return int|bool
     */
    public function decrement($key, $value = 1);

    /**
     * Store an item in the cache indefinitely.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return void
     */
    public function forever($key, $value);

    /**
     * Remove an item from the cache.
     *
     * @param  string  $key
     * @return bool
     */
    public function forget($key);

    /**
     * Remove all items from the cache.
     *
     * @return bool
     */
    public function flush();

    /**
     * Get the cache key prefix.
     *
     * @return string
     */
    public function getPrefix();
}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2016 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
#include "config.h"
#include "mechanismfactory.h"
#include "plain/plain.h"
#include "scram-sha/scram-sha.h"

#include <algorithm>
#include <cctype>
#include <cstring>
#include <iterator>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>

/**
 * In order to keep track of all of the avaliable mechanisms we support
 * we'll store them in a dynamic list so to easy add/remove support for
 * more mechanisms without having to change a ton of code.
 *
 * Each concrete implement of a mechanism should provide a subclass of
 * this class and insert itself into the available_mechs array.
 */
class MechInfo {
public:
    /**
     * Initialize a new mechanism
     *
     * @param nm the IANA registered name for the mechanism (should be
     *           all uppercase)
     * @param en Is the mechanism enabled or not
     * @param mech the Mechanism constant (to avoid the rest of the system
     *             to use string comparisons).
     */
    MechInfo(const char *nm, bool en, const Mechanism &mech) :
        name(nm), enabled(en), mechanism(mech) {
    }

    virtual UniqueMechanismBackend createServerBackend(cbsasl_conn_t& conn) = 0;
    virtual UniqueMechanismBackend createClientBackend(cbsasl_conn_t& conn) = 0;

    const std::string& getName() const {
        return name;
    }

    bool isEnabled() const {
        return enabled;
    }

    /**
     * Some of our backends require support from openssl, which seems
     * to be packaged up differently on our platforms so all mechanisms
     * isn't supported on all platforms.
     *
     * @return true if the mechanism is supported on this platform
     */
    virtual bool isMechanismSupported() = 0;

    void setEnabled(bool enabled) {
        if (isMechanismSupported()) {
            MechInfo::enabled = enabled;
        } else {
            // This mechanism can't be enabled on this platform
            MechInfo::enabled = false;
        }
    }

    const Mechanism& getMechanism() const {
        return mechanism;
    }

protected:

    const std::string name;
    bool enabled;
    Mechanism mechanism;
};

class Scram512MechInfo : public MechInfo {
public:
    Scram512MechInfo()
        : MechInfo(MECH_NAME_SCRAM_SHA512, true, Mechanism::SCRAM_SHA512) {
        setEnabled(isMechanismSupported());
    }

    virtual UniqueMechanismBackend createServerBackend(cbsasl_conn_t& conn) override {
        return UniqueMechanismBackend(new ScramSha512ServerBackend(conn));
    }

    virtual UniqueMechanismBackend createClientBackend(cbsasl_conn_t& conn) override {
        return UniqueMechanismBackend(new ScramSha512ClientBackend(conn));
    }

    virtual bool isMechanismSupported() override {
        return cb::crypto::isSupported(cb::crypto::Algorithm::SHA512);
    }
};

class Scram256MechInfo : public MechInfo {
public:
    Scram256MechInfo()
        : MechInfo(MECH_NAME_SCRAM_SHA256, true, Mechanism::SCRAM_SHA256) {
        setEnabled(isMechanismSupported());
    }

    virtual UniqueMechanismBackend createServerBackend(cbsasl_conn_t& conn) override {
        return UniqueMechanismBackend(new ScramSha256ServerBackend(conn));
    }

    virtual UniqueMechanismBackend createClientBackend(cbsasl_conn_t& conn) override {
        return UniqueMechanismBackend(new ScramSha256ClientBackend(conn));
    }

    virtual bool isMechanismSupported() override {
        return cb::crypto::isSupported(cb::crypto::Algorithm::SHA256);
    }
};

class Scram1MechInfo : public MechInfo {
public:
    Scram1MechInfo()
        : MechInfo(MECH_NAME_SCRAM_SHA1, true, Mechanism::SCRAM_SHA1) {
        setEnabled(isMechanismSupported());
    }

    virtual UniqueMechanismBackend createServerBackend(cbsasl_conn_t& conn) override {
        return UniqueMechanismBackend(new ScramSha1ServerBackend(conn));
    }

    virtual UniqueMechanismBackend createClientBackend(cbsasl_conn_t& conn) override {
        return UniqueMechanismBackend(new ScramSha1ClientBackend(conn));
    }

    virtual bool isMechanismSupported() override {
        return cb::crypto::isSupported(cb::crypto::Algorithm::SHA1);
    }
};

class PlainMechInfo : public MechInfo {
public:
    PlainMechInfo()
        : MechInfo(MECH_NAME_PLAIN, true, Mechanism::PLAIN) { }

    virtual UniqueMechanismBackend createServerBackend(cbsasl_conn_t& conn) override {
        return UniqueMechanismBackend(new PlainServerBackend(conn));
    }

    virtual UniqueMechanismBackend createClientBackend(cbsasl_conn_t& conn) override {
        return UniqueMechanismBackend(new PlainClientBackend(conn));
    }

    virtual bool isMechanismSupported() override {
        return true;
    }
};

static Scram512MechInfo scram512MechInfo;
static Scram256MechInfo scram256MechInfo;
static Scram1MechInfo scram1MechInfo;
static PlainMechInfo plainMechInfo;

static std::array<MechInfo*, 4> availableMechs = {
     { &scram512MechInfo,
       &scram256MechInfo,
       &scram1MechInfo,
       &plainMechInfo
     }
};

void cbsasl_set_available_mechanisms(cbsasl_getopt_fn getopt_fn,
                                     void* context) {
    const char* result = nullptr;
    unsigned int result_len;

    if (getopt_fn(context, nullptr, "sasl mechanisms", &result,
                  &result_len) != CBSASL_OK) {
        return;
    }

    // Disable all
    for (auto& mech : availableMechs) {
        mech->setEnabled(false);
    }

    std::string mechlist(result, result_len);
    std::transform(mechlist.begin(), mechlist.end(), mechlist.begin(), toupper);

    std::istringstream iss(mechlist);
    std::vector<std::string> tokens{std::istream_iterator<std::string>{iss},
                                    std::istream_iterator<std::string>{}};
    for (auto& token : tokens) {
        bool found = false;
        for (auto& mech : availableMechs) {
            if (mech->getName() == token) {
                mech->setEnabled(true);
                found = true;
            }
        }
        if (found) {
            logging::log(logging::Level::Error,
                         "Unknown mech [" + token + "] specified. Ignored");
        } else {
            logging::log(logging::Level::Debug, "Enable mech [" + token + "]");
        }
    }
}

UniqueMechanismBackend MechanismFactory::createServerBackend(cbsasl_conn_t& conn) {

    for (const auto& m : availableMechs) {
        if (m->getMechanism() == conn.mechanism) {
            if (m->isEnabled()) {
                return m->createServerBackend(conn);
            } else {
                logging::log(conn, logging::Level::Error,
                             "Requested disabled mechanism " + m->getName());
                return UniqueMechanismBackend();
            }
        }
    }

    throw std::invalid_argument("MechanismFactory::create() can't be "
                                    "called with an unknown mechanism");
}

UniqueMechanismBackend MechanismFactory::createClientBackend(
    cbsasl_conn_t& conn) {
    for (const auto& m : availableMechs) {
        if (m->getMechanism() == conn.mechanism) {
            if (m->isEnabled()) {
                return m->createClientBackend(conn);
            } else {
                logging::log(conn, logging::Level::Error,
                             "Requested disabled mechanism " + m->getName());
                return UniqueMechanismBackend();
            }
        }
    }

    throw std::invalid_argument("MechanismFactory::create() can't be "
                                    "called with an unknown mechanism");
}

/**
 * Search to see if the mechlist contains the given name
 *
 * @param mechlist the list to search in
 * @param name the name to search for
 * @return true if it contains the given mechanism
 */
static bool containsMechanism(const std::string& mechlist,
                              const std::string& name) {
    size_t pos = 0;

    do {
        pos = mechlist.find(name, pos);
        if (pos == std::string::npos) {
            return false;
        }
        if (pos != 0) {
            if (mechlist.at(pos - 1) != ' ') {
                pos++;
                continue;
            }
        }

        if (mechlist.length() > (pos + name.length())) {
            if (mechlist.at(pos + name.length()) != ' ') {
                pos++;
                continue;
            }
        }
        return true;
    } while (true);
}

static bool isSeparator(const char c) {
    if (c == '-' || std::ispunct(c) == 0) {
        return false;
    }

    return true;
}

Mechanism MechanismFactory::selectMechanism(const std::string& mechlist) {
    std::string uppercase(mechlist);
    std::transform(uppercase.begin(), uppercase.end(), uppercase.begin(),
                   toupper);
    std::replace_if(uppercase.begin(), uppercase.end(), isSeparator, ' ');

    for (const auto & m : availableMechs) {
        if (m->isEnabled() && containsMechanism(uppercase, m->getName())) {
            return m->getMechanism();
        }
    }

    return Mechanism::UNKNOWN;
}

cbsasl_error_t MechanismFactory::list(cbsasl_conn_t* conn, const char* user,
                                      const char* prefix, const char* sep,
                                      const char* suffix, const char** result,
                                      unsigned* len, int* count) {
    if (result == nullptr || conn == nullptr) {
        return CBSASL_BADPARAM;
    }

    try {
        int counter = 0;
        conn->server->list_mechs.clear();
        conn->server->list_mechs.reserve(80);

        if (prefix != nullptr) {
            conn->server->list_mechs.append(prefix);
        }

        bool needSep = false;
        for (const auto& mech : availableMechs) {
            if (mech->isEnabled()) {
                if (needSep) {
                    if (sep == nullptr) {
                        conn->server->list_mechs.append(" ");
                    } else {
                        conn->server->list_mechs.append(sep);
                    }
                } else {
                    needSep = true;
                }
                conn->server->list_mechs.append(mech->getName());
                ++counter;
            }
        }

        if (suffix != nullptr) {
            conn->server->list_mechs.append(suffix);
        }

        *result = conn->server->list_mechs.data();

        if (len != nullptr) {
            *len = (unsigned int)conn->server->list_mechs.length();
        }

        if (count != nullptr) {
            *count = counter;
        }
    } catch (std::bad_alloc) {
        conn->server->list_mechs.resize(0);
        return CBSASL_NOMEM;
    }

    return CBSASL_OK;
}

Mechanism MechanismFactory::toMechanism(const std::string mech) {
    std::string uppercase(mech);
    std::transform(uppercase.begin(), uppercase.end(), uppercase.begin(),
                   toupper);
    if (mech == MECH_NAME_PLAIN) {
        return Mechanism::PLAIN;
    } else if (mech == MECH_NAME_SCRAM_SHA1) {
        return Mechanism::SCRAM_SHA1;
    } else if (mech == MECH_NAME_SCRAM_SHA256) {
        return Mechanism::SCRAM_SHA256;
    } else if (mech == MECH_NAME_SCRAM_SHA512) {
        return Mechanism::SCRAM_SHA512;
    } else {
        return Mechanism::UNKNOWN;
    }
}

std::string MechanismFactory::toString(const Mechanism& mech) {
    switch (mech) {
    case Mechanism::PLAIN:
        return MECH_NAME_PLAIN;
    case Mechanism::SCRAM_SHA1:
        return MECH_NAME_SCRAM_SHA1;
    case Mechanism::SCRAM_SHA256:
        return MECH_NAME_SCRAM_SHA256;
    case Mechanism::SCRAM_SHA512:
        return MECH_NAME_SCRAM_SHA512;
    case Mechanism::UNKNOWN:
        break;
    }
    throw std::invalid_argument("Provided mechanism does not exist");
}


text:
var Ws = require("./ws/ws.js"),
    ws = new Ws();
require("./static");
//require("./ODM");

console.log("Finished!");


text:
"""
Tests of the Mantis check.
"""

from configobj import ConfigObj
import mock
import pytest

try:
    from repoguard.checks import mantis
    _SKIP = False
except ImportError:
    _SKIP = True

_CONFIG_DEFAULT = """
url=http://localhost/mantis/mc/mantisconnect.php?wsdl
user=me
password=secret
check_in_progress=True
check_handler=True
"""

class TestMantisCheck(object):

    pytestmark = pytest.mark.skipif("_SKIP")

    @classmethod
    def setup_class(cls):
        cls._mantis_module = mock.Mock()
        cls.__mantis_class = mantis.base.Mantis
        mantis.base.Mantis = mock.Mock(return_value=cls._mantis_module)

        cls.config = ConfigObj(_CONFIG_DEFAULT.splitlines())
        cls._mantis = mantis.Mantis(mock.Mock(user_id="me"))

    @classmethod
    def teardown_class(cls):
        mantis.base.Mantis = cls.__mantis_class

    def test_no_issue_ids(self):
        self._mantis_module.extract_issues.return_value = list()
        assert not self._mantis.run(self.config).success

    def test_issue_not_exists(self):
        self._mantis_module.extract_issues.return_value = ["1278"]
        self._mantis_module.issue_exists.return_value = False
        assert not self._mantis.run(self.config).success

    def test_issue_not_in_progress(self):
        self._mantis_module.extract_issues.return_value = ["1278"]
        self._mantis_module.issue_exists.return_value = True
        self._mantis_module.issue_get_status.return_value = "assigned"
        assert not self._mantis.run(self.config).success

    def test_issue_not_wrong_handler(self):
        self._mantis_module.extract_issues.return_value = ["1278"]
        self._mantis_module.issue_exists.return_value = True
        self._mantis_module.issue_get_status.return_value = "in_progress"
        self._mantis_module.issue_get_handler.return_value = "anotheruser"
        assert not self._mantis.run(self.config).success

    def test_success(self):
        self._mantis_module.extract_issues.return_value = ["1278"]
        self._mantis_module.issue_exists.return_value = True
        self._mantis_module.issue_get_status.return_value = "in_progress"
        self._mantis_module.issue_get_handler.return_value = "me"
        assert self._mantis.run(self.config).success


text:
accumulators
============

[![Build Status](https://api.shippable.com/projects/53fc7ee1f2cfa3a3088b8d74/badge/master)](https://www.shippable.com/projects/53fc7ee1f2cfa3a3088b8d74)

A set of statistical accumulators for Ruby. There is a range of containers for
different measures, such as count, sum, mean, and mean-variance. You can add values to
the containers, and ask for their respective statistical measures.

Where appropriate the accumulators use incremental algorithms to update their
measures with each addition, so you can add lots of values without needing lots of
memory. (see http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm)

The accumulators can be combined. e.g. if you have two mean-variance
accumulators, each of which has their own mean and variance, you can add them
together to get the mean and variance of the combined samples.

Always remember that floating-point arithmetic is not precise, so if you are
using these accumulators for anything important, and especially if you are
accumulating lots of samples, you should run your own tests on the accuracy of
the calculations. I am not aware of any significant issues, but I make no promises
and provide no assurances as to the accuracy or stability of these
calculations.

Installation
------------
    $ [sudo] gem install accumulators

Example Usage
-------------

    $ irb
    >> require 'accumulators'
    >> meanvar = Accumulators:MeanVariance.new
    >> meanvar.add 1
    >> meanvar.add 2
    >> meanvar.add 3
    >> meanvar.add 4
    >> meanvar.count
    => 4
    >> meanvar.mean
    => 2.5
    >> meanvar.variance
    => 1.0
    >> meanvar.variance(type: :sample)
    => 1.0
    >> meanvar.variance(type: :population)
    => 1.25
    >> meanvar.stddev
    => 1.0
    >> meanvar.stddev(type: :population)
    => 1.118033988749895

Example of combining accumulators
---------------------------------
Accumulators of the same type can be added together. Here we will add three
numbers to one mean-variance accumulator, three to another, and show that their
combined mean and variance is equal to that of the single accumulator which
saw all the values, within the usual constraints of floating-point arithmetic.

    >> mv1 = Accumulators::MeanVariance.new  # sees the first 3 values
    >> mv2 = Accumulators::MeanVariance.new  # sees the second 3 values
    >> mv  = Accumulators::MeanVariance.new  # sees all values
    >>
    >> [1.1, 2.2, 3.3].each {|n| mv1.add n; mv.add n}
    >> [4.4, 5.5, 6.6].each {|n| mv2.add n; mv.add n}
    >>
    >> mv1.mean
    => 2.2
    >> mv1.variance
    => 0.6049999999999998
    >>
    >> mv2.mean
    => 5.5
    >> mv2.variance
    => 0.6049999999999998
    >>
    >> mv.mean
    => 3.8499999999999996
    >> mv.variance
    => 3.025
    >>
    >> mv1.add mv2
    >> mv1.mean
    => 3.8499999999999996
    >> mv1.variance
    >> 3.0249999999999995  # close to 3.025 - discrepancy from floating-point

Available accumulators
----------------------

* Count
* Sum
* MinMax
* Mean
* MeanVariance

TODO
----

* Skew?
* Weighted Means

Contributing to accumulators
----------------------------

* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
* Fork the project
* Start a feature/bugfix branch
* Commit and push until you are happy with your contribution
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

Copyright
---------

Copyright (c) 2010-2011 Gavin Heavyside. See LICENSE.txt for
further details.


text:
jQuery.fn.dragresize = function () {
	var el = $(this);
	var element = elements[el.parent().parent().attr('id')];
	var pic = el.parent().parent().find(".picture");
	var rot = el.parent().find(".rotate");
    this.bind('mousedown', function (e) {
        var pageX = e.pageX;
        var pageY = e.pageY;
		var startX = el.position().left;
		var startY = el.position().top;
		var startW = pic.width();
		var startH = pic.height();
        $(document).bind('mousemove', function (e) {
            var diffX = e.pageX - pageX + startX;
            var diffY = e.pageY - pageY + startY;
			var ratio = Math.min(diffX / startX, diffY / startY);
			if(freeScale == false){
				diffX = startX * ratio;
				diffY = startY * ratio;
			}
			var width = diffX - startX + startW;
			var height = diffY - startY + startH;
            el.css('left', diffX + 'px').css('top', diffY + 'px');
            rot.css('left', diffX + 'px');
			pic.css({'width': width+'px','height':height+'px'});
			element.width = width / zoom;
			element.height = height / zoom;
			return false;
        });
		$(document).bind('mouseup', function (e) {
			$(document).unbind('mousemove');
			$(document).unbind('mouseup');
			sendJSON({
				"id":el.parent().parent().attr('id'),
				"width":element.width,
				"height":element.height
			});
		});
		return false;
    });
    return this;
};

jQuery.fn.dragrotate = function () {
	var el = $(this);
	var parent = el.parent().parent();
	var element = null;
	var pic = null;
	if(parent.hasClass('piccontainer')){
		pic = parent.find(".picture");
		element = elements[parent.attr('id')];
	}else if(parent.hasClass('textcontainer')){
		pic = parent.find(".text");
		element = textElements[parent.attr('id')];
	}
    this.bind('mousedown', function (e) {
        var pageX = e.pageX;
        var pageY = e.pageY;
		var startR = parseFloat(pic.getRotateAngle());
		if(isNaN(startR)){
			startR = 0;
		}
        $(document).bind('mousemove', function (e) {
			var dR = e.pageX - pageX + e.pageY - pageY;
			var diffR = 0;
			if(parent.hasClass('piccontainer')){
				diffR = dR*0.25 + startR;
				pic.rotate(diffR);
			}else if(parent.hasClass('textcontainer')){
				diffR = -dR*0.25 + startR;
				pic.rotate({
					angle: diffR,
					center: ["0%", "0%"]
				});
			}
			element.rotate = diffR;
			return false;
        });
		$(document).bind('mouseup', function (e) {
			$(document).unbind('mousemove');
			$(document).unbind('mouseup');
			sendJSON({
				"id":el.parent().parent().attr('id'),
				"rotate":element.rotate
			});
		});
		return false;
    });
    return this;
};


text:
<?php

namespace Lucid\Module\Template\Tests;

use Lucid\Module\Template\Section;

/**
 * @class SectionTest
 *
 * @package Lucid\Module\Template\Tests
 * @version $Id$
 * @author iwyg <mail@thomas-appel.com>
 */
class SectionTest extends \PHPUnit_Framework_TestCase
{
    /** @test */
    public function itShouldCaptureOuput()
    {
        $section = new Section;

        $section->start();
        echo 'Foo';
        $section->stop();

        $this->assertSame('Foo', $section->getContent());
    }

    /** @test */
    public function itShouldResetBuffer()
    {
        $section = new Section;

        $section->start();
        echo 'Foo';
        $section->stop();

        $this->assertSame('Foo', $section->getContent());

        $section->reset();

        $this->assertSame('', $section->getContent());
    }

    /**
     * @test
     * @expectedException \OutOfBoundsException
     */
    public function itShouldThrowExceptionIfBufferIndexIsOutOfRange()
    {
        $section = new Section;

        $section->start();
        echo 'Foo';
        $section->stop();

        $section->getContent(1);
    }

    /** @test */
    public function itShouldGetContentAsArray()
    {
        $section = new Section;

        $section->start();
        echo 'Foo';
        $section->stop();
        $section->start();
        echo 'Bar';
        $section->stop();

        $this->assertEquals(['Foo', 'Bar'], $section->getContent(null, true));
    }

    /** @test */
    public function itShouldGetContentBufferAtGivenIndex()
    {
        $section = new Section;

        $section->start();
        echo 'Foo';
        $section->stop();
        $section->start();
        echo 'Bar';
        $section->stop();

        $this->assertSame('Foo', $section->getContent(0));
        $this->assertSame('Bar', $section->getContent(1));
    }
}


text:
// methods
import curry from './curry';
import reduce from './reduce';

// utils
import coalesceToArray from './_utils/coalesceToArray';
import isObject from './_utils/isObject';

/**
 * @function getCorrectPartition
 *
 * @description
 * based on the result being truthy or not, return the correct
 * partition (either truthy or falsy)
 *
 * @param {{falsy: (Array<*>|Object), truthy: (Array<*>|Object)}} partitions the truthy and falsy partitions
 * @param {*} result the result to determine the partition
 * @returns {Array<*>|Object} either the truthy or falsy partition
 */
function getCorrectPartition(partitions, result) {
  return result ? partitions.truthy : partitions.falsy;
}

/**
 * @function partitionArray
 *
 * @description
 * partition the array into truthy and falsy values
 *
 * @param {function(*, number, Array<*>)} fn the function that will determine which partition to put the value into
 * @param {Array<*>} array the items to partition
 * @returns {Array<Array<*>>} the partitioned items
 */
function partitionArray(fn, array) {
  const reducedPartitions = reduce(
    (partitions, item, index) => {
      getCorrectPartition(partitions, fn(item, index, array)).push(item);

      return partitions;
    },
    {
      falsy: [],
      truthy: [],
    },
    array
  );

  return [reducedPartitions.truthy, reducedPartitions.falsy];
}

/**
 * @function partitionObject
 *
 * @description
 * partition the array into truthy and falsy values
 *
 * @param {function(*, string, Object)} fn the function that will determine which partition to put the value into
 * @param {Object} object the items to partition
 * @returns {Object} the partitioned items
 */
function partitionObject(fn, object) {
  return reduce(
    (partitions, item, key) => {
      getCorrectPartition(partitions, fn(item, key, object))[key] = item;

      return partitions;
    },
    {
      falsy: {},
      truthy: {},
    },
    object
  );
}

/**
 * @function partition
 *
 * @description
 * partition the collection into truthy and falsy values
 *
 * @param {function(*, (number|string), (Array<*>|Object))}
 * fn the function that will determine which partition to put the value into
 * @param {Array<*>|Object} collection the collection to partition
 * @returns {Array<Array<*>>|Object} the partitioned collection
 */
export default curry(function partition(fn, collection) {
  return isObject(collection) ? partitionObject(fn, collection) : partitionArray(fn, coalesceToArray(collection));
});


text:
// A set of lightweight wrappers which simplify access to Feature protos.
//
// TensorFlow Example proto uses associative maps on top of oneof fields.
// SequenceExample proto uses associative map of FeatureList.
// So accessing feature values is not very convenient.
//
// For example, to read a first value of integer feature "tag":
//   int id = example.features().feature().at("tag").int64_list().value(0)
//
// to add a value:
//   auto features = example->mutable_features();
//   (*features->mutable_feature())["tag"].mutable_int64_list()->add_value(id)
//
// For float features you have to use float_list, for string - bytes_list.
//
// To do the same with this library:
//   int id = GetFeatureValues<int64>("tag", example).Get(0);
//   GetFeatureValues<int64>("tag", &example)->Add(id);
//
// Modification of bytes features is slightly different:
//   auto tag = GetFeatureValues<string>("tag", &example);
//   *tag->Add() = "lorem ipsum";
//
// To copy multiple values into a feature:
//   AppendFeatureValues({1,2,3}, "tag", &example);
//
// GetFeatureValues gives you access to underlying data - RepeatedField object
// (RepeatedPtrField for byte list). So refer to its documentation of
// RepeatedField for full list of supported methods.
//
// NOTE: Due to the nature of oneof proto fields setting a feature of one type
// automatically clears all values stored as another type with the same feature
// key.
//
// This library also has tools to work with SequenceExample protos.
//
// To get a value from SequenceExample.context:
//   int id = GetFeatureValues<protobuf_int64>("tag", se.context()).Get(0);
// To add a value to the context:
//   GetFeatureValues<protobuf_int64>("tag", se.mutable_context())->Add(42);
//
// To add values to feature_lists:
//   AppendFeatureValues({4.0},
//                       GetFeatureList("images", &se)->Add());
//   AppendFeatureValues({5.0, 3.0},
//                       GetFeatureList("images", &se)->Add());
// This will create a feature list keyed as "images" with two features:
//   feature_lists {
//     feature_list {
//       key: "images"
//       value {
//         feature { float_list { value: [4.0] } }
//         feature { float_list { value: [5.0, 3.0] } }
//       }
//     } }
//
// Functions exposed by this library:
//   HasFeature<[FeatureType]>(key, proto) -> bool
//     Returns true if a feature with the specified key, and optionally
//     FeatureType, belongs to the Features or Example proto.
//   HasFeatureList(key, sequence_example) -> bool
//     Returns true if SequenceExample has a feature_list with the key.
//   GetFeatureValues<FeatureType>(key, proto) -> RepeatedField<FeatureType>
//     Returns values for the specified key and the FeatureType.
//     Supported types for the proto: Example, Features.
//   GetFeatureList(key, sequence_example) -> RepeatedPtrField<Feature>
//     Returns Feature protos associated with a key.
//   AppendFeatureValues(begin, end, feature)
//   AppendFeatureValues(container or initializer_list, feature)
//     Copies values into a Feature.
//   AppendFeatureValues(begin, end, key, proto)
//   AppendFeatureValues(container or initializer_list, key, proto)
//     Copies values into Features and Example protos with the specified key.
//
// Auxiliary functions, it is unlikely you'll need to use them directly:
//   GetFeatures(proto) -> Features
//     A convenience function to get Features proto.
//     Supported types for the proto: Example, Features.
//   GetFeature(key, proto) -> Feature*
//     Returns a Feature proto for the specified key, creates a new if
//     necessary. Supported types for the proto: Example, Features.
//   GetFeatureValues<FeatureType>(feature) -> RepeatedField<FeatureType>
//     Returns values of the feature for the FeatureType.

#ifndef TENSORFLOW_EXAMPLE_FEATURE_H_
#define TENSORFLOW_EXAMPLE_FEATURE_H_

#include <iterator>
#include <type_traits>

#include "tensorflow/core/example/example.pb.h"
#include "tensorflow/core/example/feature.pb.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

namespace internal {

// DEPRECATED: Use GetFeature instead.
// TODO(gorban): Update all clients in a followup CL.
// Returns a reference to a feature corresponding to the name.
// Note: it will create a new Feature if it is missing in the example.
Feature& ExampleFeature(const string& name, Example* example);

// Specializations of RepeatedFieldTrait define a type of RepeatedField
// corresponding to a selected feature type.
template <typename FeatureType>
struct RepeatedFieldTrait;

template <>
struct RepeatedFieldTrait<protobuf_int64> {
  using Type = protobuf::RepeatedField<protobuf_int64>;
};

template <>
struct RepeatedFieldTrait<float> {
  using Type = protobuf::RepeatedField<float>;
};

template <>
struct RepeatedFieldTrait<string> {
  using Type = protobuf::RepeatedPtrField<string>;
};

// Specializations of FeatureTrait define a type of feature corresponding to a
// selected value type.
template <typename ValueType, class Enable = void>
struct FeatureTrait;

template <typename ValueType>
struct FeatureTrait<ValueType, typename std::enable_if<
                                   std::is_integral<ValueType>::value>::type> {
  using Type = protobuf_int64;
};

template <typename ValueType>
struct FeatureTrait<
    ValueType,
    typename std::enable_if<std::is_floating_point<ValueType>::value>::type> {
  using Type = float;
};

template <typename T>
struct is_string
    : public std::integral_constant<
          bool,
          std::is_same<char*, typename std::decay<T>::type>::value ||
              std::is_same<const char*, typename std::decay<T>::type>::value> {
};

template <>
struct is_string<string> : std::true_type {};

template <>
struct is_string<::tensorflow::StringPiece> : std::true_type {};

template <typename ValueType>
struct FeatureTrait<
    ValueType, typename std::enable_if<is_string<ValueType>::value>::type> {
  using Type = string;
};

}  //  namespace internal

// Returns true if sequence_example has a feature_list with the specified key.
bool HasFeatureList(const string& key, const SequenceExample& sequence_example);

template <typename T>
struct TypeHasFeatures : std::false_type {};

template <>
struct TypeHasFeatures<Example> : std::true_type {};

template <>
struct TypeHasFeatures<Features> : std::true_type {};

// A family of template functions to return mutable Features proto from a
// container proto. Supported ProtoTypes: Example, Features.
template <typename ProtoType>
typename std::enable_if<TypeHasFeatures<ProtoType>::value, Features*>::type
GetFeatures(ProtoType* proto);

template <typename ProtoType>
typename std::enable_if<TypeHasFeatures<ProtoType>::value,
                        const Features&>::type
GetFeatures(const ProtoType& proto);

// Base declaration of a family of template functions to return a read only
// repeated field of feature values.
template <typename FeatureType>
const typename internal::RepeatedFieldTrait<FeatureType>::Type&
GetFeatureValues(const Feature& feature);

// Returns a read only repeated field corresponding to a feature with the
// specified name and FeatureType. Supported ProtoTypes: Example, Features.
template <typename FeatureType, typename ProtoType>
const typename internal::RepeatedFieldTrait<FeatureType>::Type&
GetFeatureValues(const string& key, const ProtoType& proto) {
  return GetFeatureValues<FeatureType>(GetFeatures(proto).feature().at(key));
}

// Returns a mutable repeated field of a feature values.
template <typename FeatureType>
typename internal::RepeatedFieldTrait<FeatureType>::Type* GetFeatureValues(
    Feature* feature);

// Returns a mutable repeated field corresponding to a feature with the
// specified name and FeatureType. Supported ProtoTypes: Example, Features.
template <typename FeatureType, typename ProtoType>
typename internal::RepeatedFieldTrait<FeatureType>::Type* GetFeatureValues(
    const string& key, ProtoType* proto) {
  ::tensorflow::Feature& feature =
      (*GetFeatures(proto)->mutable_feature())[key];
  return GetFeatureValues<FeatureType>(&feature);
}

// Returns a Feature proto for the specified key, creates a new if necessary.
// Supported types for the proto: Example, Features.
template <typename ProtoType>
Feature* GetFeature(const string& key, ProtoType* proto) {
  return &(*GetFeatures(proto)->mutable_feature())[key];
}

// Returns a repeated field with features corresponding to a feature_list key.
const protobuf::RepeatedPtrField<Feature>& GetFeatureList(
    const string& key, const SequenceExample& sequence_example);

// Returns a mutable repeated field with features corresponding to a
// feature_list key. It will create a new FeatureList if necessary.
protobuf::RepeatedPtrField<Feature>* GetFeatureList(
    const string& feature_list_key, SequenceExample* sequence_example);

template <typename IteratorType>
void AppendFeatureValues(IteratorType first, IteratorType last,
                         Feature* feature) {
  using FeatureType = typename internal::FeatureTrait<
      typename std::iterator_traits<IteratorType>::value_type>::Type;
  std::copy(first, last,
            protobuf::RepeatedFieldBackInserter(
                GetFeatureValues<FeatureType>(feature)));
}

template <typename ValueType>
void AppendFeatureValues(std::initializer_list<ValueType> container,
                         Feature* feature) {
  AppendFeatureValues(container.begin(), container.end(), feature);
}

template <typename ContainerType>
void AppendFeatureValues(const ContainerType& container, Feature* feature) {
  using IteratorType = typename ContainerType::const_iterator;
  AppendFeatureValues<IteratorType>(container.begin(), container.end(),
                                    feature);
}

// Copies elements from the range, defined by [first, last) into the feature
// obtainable from the (proto, key) combination.
template <typename IteratorType, typename ProtoType>
void AppendFeatureValues(IteratorType first, IteratorType last,
                         const string& key, ProtoType* proto) {
  AppendFeatureValues(first, last, GetFeature(key, GetFeatures(proto)));
}

// Copies all elements from the container into a feature.
template <typename ContainerType, typename ProtoType>
void AppendFeatureValues(const ContainerType& container, const string& key,
                         ProtoType* proto) {
  using IteratorType = typename ContainerType::const_iterator;
  AppendFeatureValues<IteratorType>(container.begin(), container.end(), key,
                                    proto);
}

// Copies all elements from the initializer list into a Feature contained by
// Features or Example proto.
template <typename ValueType, typename ProtoType>
void AppendFeatureValues(std::initializer_list<ValueType> container,
                         const string& key, ProtoType* proto) {
  using IteratorType =
      typename std::initializer_list<ValueType>::const_iterator;
  AppendFeatureValues<IteratorType>(container.begin(), container.end(), key,
                                    proto);
}

// Returns true if a feature with the specified key belongs to the Features.
// The template parameter pack accepts zero or one template argument - which
// is FeatureType. If the FeatureType not specified (zero template arguments)
// the function will not check the feature type. Otherwise it will return false
// if the feature has a wrong type.
template <typename... FeatureType>
bool HasFeature(const string& key, const Features& features);

// Returns true if a feature with the specified key belongs to the Example.
// Doesn't check feature type if used without FeatureType, otherwise the
// specialized versions return false if the feature has a wrong type.
template <typename... FeatureType>
bool HasFeature(const string& key, const Example& example) {
  return HasFeature<FeatureType...>(key, GetFeatures(example));
}

// DEPRECATED: use HasFeature instead.
// TODO(gorban): update all clients in a followup CL.
template <typename... FeatureType>
bool ExampleHasFeature(const string& key, const Example& example) {
  return HasFeature<FeatureType...>(key, example);
}

}  // namespace tensorflow
#endif  // TENSORFLOW_EXAMPLE_FEATURE_H_


text:
sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"sap/m/Popover",
	"sap/m/Button",
	"sap/m/VBox",
	"sap/m/Text",
	"sap/m/Toolbar",
	"sap/m/ToolbarSpacer",
	"sap/m/Link"
], function(Controller, Popover, Button, VBox, Text, Toolbar, ToolbarSpacer, Link) {
	"use strict";

	return Controller.extend("sap.m.sample.popoverInitialFocus.Controller", {
		// Handler for the case with default initial focus behaviour
		fnOpenPopoverWithDefaultInitialFocus: function (oEvent) {
			this.getDefaultPopover().openBy(oEvent.oSource);
		},

		// Handler for the case with custom initial focus behaviour
		fnOpenPopoverWithCustomInitialFocus: function (oEvent) {
			this.getCustomPopover().openBy(oEvent.oSource);
		},

		// Creating the Popover with default initial focus
		getDefaultPopover: function (sSourceId) {
			if (!this._oDefaultPopover) {
				this._oDefaultPopover = this.createPopover();
				this._oDefaultPopover.setTitle("Popover with default initial focus");
				this._oDefaultPopover.setFooter(new Toolbar({
					content: [
						new ToolbarSpacer(),
						new Button({
							press: function () { this.getDefaultPopover().close(); }.bind(this),
							text: "Close"
						})
					]
				}));
			}
			return this._oDefaultPopover;
		},

		// Creating the Popover with custom initial focus
		getCustomPopover: function (sSourceId) {
			if (!this._oCustomPopover) {
				this._oCustomPopover = this.createPopover();
				this._oCustomPopover.setTitle("Popover with custom initial focus");
				this._oCustomPopover.setFooter(new Toolbar({
					content: [
						new ToolbarSpacer(),
						new Button({
							id: "closeButton",
							press: function () { this.getCustomPopover().close(); }.bind(this),
							text: "Close"
						})
					]
				}));

				// Setting the initial focus to the 'Close' button in the footer.
				this._oCustomPopover.setInitialFocus("closeButton");
			}
			return this._oCustomPopover;
		},

		createPopover: function () {
			return new Popover({
				content: [
					new VBox({
						items: [
							new Text({
								text: "The link below is the first focusable element in the Popover's content."
							}).addStyleClass("sapUiSmallMarginTopBottom"),
							new Text({
								text: "It will be focused by default unless other control is provided to the 'initialFocus' association of the Popover."
							}).addStyleClass("sapUiSmallMarginBottom"),
							new Link({
								text: "Link"
							})
						]
					})
				],
				contentWidth: "30%"
			}).addStyleClass("sapUiResponsivePadding--content sapUiResponsivePadding--header");
		}
	});
});


text:
package com.facebook.buck.rules.args;

import static org.junit.Assert.assertThat;

import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.TestCellPathResolver;
import com.facebook.buck.rules.macros.AbstractMacroExpanderWithoutPrecomputedWork;
import com.facebook.buck.rules.macros.LocationMacro;
import com.facebook.buck.rules.macros.LocationMacroExpander;
import com.facebook.buck.rules.macros.Macro;
import com.facebook.buck.rules.macros.StringWithMacrosUtils;
import com.facebook.buck.shell.GenruleBuilder;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.google.common.collect.ImmutableList;
import org.hamcrest.Matchers;
import org.junit.Test;

public class StringWithMacrosArgTest {

  private static final ImmutableList<AbstractMacroExpanderWithoutPrecomputedWork<? extends Macro>>
      MACRO_EXPANDERS = ImmutableList.of(new LocationMacroExpander());
  private static final BuildTarget TARGET = BuildTargetFactory.newInstance("//:target");
  private static final CellPathResolver CELL_PATH_RESOLVER =
      TestCellPathResolver.get(new FakeProjectFilesystem());

  private final BuildRuleResolver resolver =
      new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());

  @Test
  public void getDeps() throws NoSuchBuildTargetException {
    SourcePathRuleFinder pathFinder = new SourcePathRuleFinder(resolver);

    BuildRule rule1 =
        GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:rule1"))
            .setOut("out")
            .build(resolver);
    BuildRule rule2 =
        GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:rule2"))
            .setOut("out")
            .build(resolver);

    // Test no embedded macros.
    StringWithMacrosArg noMacrosArg =
        StringWithMacrosArg.of(
            StringWithMacrosUtils.format("--test"),
            MACRO_EXPANDERS,
            TARGET,
            CELL_PATH_RESOLVER,
            resolver);
    assertThat(noMacrosArg.getDeps(pathFinder), Matchers.empty());

    // Test one embedded macros.
    StringWithMacrosArg oneMacrosArg =
        StringWithMacrosArg.of(
            StringWithMacrosUtils.format("--test=%s", LocationMacro.of(rule1.getBuildTarget())),
            MACRO_EXPANDERS,
            TARGET,
            CELL_PATH_RESOLVER,
            resolver);
    assertThat(oneMacrosArg.getDeps(pathFinder), Matchers.contains(rule1));

    // Test multiple embedded macros.
    StringWithMacrosArg multipleMacrosArg =
        StringWithMacrosArg.of(
            StringWithMacrosUtils.format(
                "--test=%s --test2=%s --test3=%s",
                LocationMacro.of(rule1.getBuildTarget()),
                LocationMacro.of(rule2.getBuildTarget()),
                LocationMacro.of(rule1.getBuildTarget())),
            MACRO_EXPANDERS,
            TARGET,
            CELL_PATH_RESOLVER,
            resolver);
    assertThat(multipleMacrosArg.getDeps(pathFinder), Matchers.contains(rule1, rule2, rule1));
  }

  @Test
  public void getInputs() throws NoSuchBuildTargetException {
    BuildRule rule1 =
        GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:rule1"))
            .setOut("out")
            .build(resolver);
    BuildRule rule2 =
        GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:rule2"))
            .setOut("out")
            .build(resolver);

    // Test no embedded macros.
    StringWithMacrosArg noMacrosArg =
        StringWithMacrosArg.of(
            StringWithMacrosUtils.format("--test"),
            MACRO_EXPANDERS,
            TARGET,
            CELL_PATH_RESOLVER,
            resolver);
    assertThat(noMacrosArg.getInputs(), Matchers.empty());

    // Test one embedded macros.
    StringWithMacrosArg oneMacrosArg =
        StringWithMacrosArg.of(
            StringWithMacrosUtils.format("--test=%s", LocationMacro.of(rule1.getBuildTarget())),
            MACRO_EXPANDERS,
            TARGET,
            CELL_PATH_RESOLVER,
            resolver);
    assertThat(oneMacrosArg.getInputs(), Matchers.contains(rule1.getSourcePathToOutput()));

    // Test multiple embedded macros.
    StringWithMacrosArg multipleMacrosArg =
        StringWithMacrosArg.of(
            StringWithMacrosUtils.format(
                "--test=%s --test2=%s --test3=%s",
                LocationMacro.of(rule1.getBuildTarget()),
                LocationMacro.of(rule2.getBuildTarget()),
                LocationMacro.of(rule1.getBuildTarget())),
            MACRO_EXPANDERS,
            TARGET,
            CELL_PATH_RESOLVER,
            resolver);
    assertThat(
        multipleMacrosArg.getInputs(),
        Matchers.contains(
            rule1.getSourcePathToOutput(),
            rule2.getSourcePathToOutput(),
            rule1.getSourcePathToOutput()));
  }

  @Test
  public void appendToCommandLine() throws NoSuchBuildTargetException {
    SourcePathRuleFinder pathFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = DefaultSourcePathResolver.from(pathFinder);

    BuildRule rule1 =
        GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:rule1"))
            .setOut("out")
            .build(resolver);
    BuildRule rule2 =
        GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:rule2"))
            .setOut("out")
            .build(resolver);

    // Test no embedded macros.
    StringWithMacrosArg noMacrosArg =
        StringWithMacrosArg.of(
            StringWithMacrosUtils.format("--test"),
            MACRO_EXPANDERS,
            TARGET,
            CELL_PATH_RESOLVER,
            resolver);
    assertThat(
        Arg.stringifyList(noMacrosArg, pathResolver), Matchers.equalTo(ImmutableList.of("--test")));

    // Test one embedded macros.
    StringWithMacrosArg oneMacrosArg =
        StringWithMacrosArg.of(
            StringWithMacrosUtils.format("--test=%s", LocationMacro.of(rule1.getBuildTarget())),
            MACRO_EXPANDERS,
            TARGET,
            CELL_PATH_RESOLVER,
            resolver);
    assertThat(
        Arg.stringifyList(oneMacrosArg, pathResolver),
        Matchers.equalTo(
            ImmutableList.of(
                String.format(
                    "--test=%s", pathResolver.getAbsolutePath(rule1.getSourcePathToOutput())))));

    // Test multiple embedded macros.
    StringWithMacrosArg multipleMacrosArg =
        StringWithMacrosArg.of(
            StringWithMacrosUtils.format(
                "--test=%s --test2=%s --test3=%s",
                LocationMacro.of(rule1.getBuildTarget()),
                LocationMacro.of(rule2.getBuildTarget()),
                LocationMacro.of(rule1.getBuildTarget())),
            MACRO_EXPANDERS,
            TARGET,
            CELL_PATH_RESOLVER,
            resolver);
    assertThat(
        Arg.stringifyList(multipleMacrosArg, pathResolver),
        Matchers.equalTo(
            ImmutableList.of(
                String.format(
                    "--test=%s --test2=%s --test3=%s",
                    pathResolver.getAbsolutePath(rule1.getSourcePathToOutput()),
                    pathResolver.getAbsolutePath(rule2.getSourcePathToOutput()),
                    pathResolver.getAbsolutePath(rule1.getSourcePathToOutput())))));
  }
}


text:
package org.springframework.boot.actuate.autoconfigure;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.Filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration.ManagementWebSecurityConfigurerAdapter;
import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping;
import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMappingCustomizer;
import org.springframework.boot.actuate.endpoint.mvc.ManagementErrorEndpoint;
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint;
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoints;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

/**
 * Configuration triggered from {@link EndpointWebMvcAutoConfiguration} when a new
 * {@link EmbeddedServletContainer} running on a different port is required.
 *
 * @author Dave Syer
 * @author Stephane Nicoll
 * @see EndpointWebMvcAutoConfiguration
 */
@Configuration
public class EndpointWebMvcChildContextConfiguration {

	private static Log logger = LogFactory
			.getLog(EndpointWebMvcChildContextConfiguration.class);

	@Value("${error.path:/error}")
	private String errorPath = "/error";

	@Autowired(required = false)
	private List<EndpointHandlerMappingCustomizer> mappingCustomizers;

	@Configuration
	protected static class ServerCustomization implements
			EmbeddedServletContainerCustomizer, Ordered {

		@Value("${error.path:/error}")
		private String errorPath = "/error";

		@Autowired
		private ListableBeanFactory beanFactory;

		// This needs to be lazily initialized because EmbeddedServletContainerCustomizer
		// instances get their callback very early in the context lifecycle.
		private ManagementServerProperties managementServerProperties;

		private ServerProperties server;

		@Override
		public int getOrder() {
			return 0;
		}

		@Override
		public void customize(ConfigurableEmbeddedServletContainer container) {
			if (this.managementServerProperties == null) {
				this.managementServerProperties = BeanFactoryUtils
						.beanOfTypeIncludingAncestors(this.beanFactory,
								ManagementServerProperties.class);
				this.server = BeanFactoryUtils.beanOfTypeIncludingAncestors(
						this.beanFactory, ServerProperties.class);
			}
			// Customize as per the parent context first (so e.g. the access logs go to
			// the same place)
			this.server.customize(container);
			// Then reset the error pages
			container.setErrorPages(Collections.<ErrorPage> emptySet());
			// and add the management-specific bits
			container.setPort(this.managementServerProperties.getPort());
			container.setAddress(this.managementServerProperties.getAddress());
			container.setContextPath(this.managementServerProperties.getContextPath());
			container.addErrorPages(new ErrorPage(this.errorPath));
		}

	}

	@Bean
	public DispatcherServlet dispatcherServlet() {
		DispatcherServlet dispatcherServlet = new DispatcherServlet();

		// Ensure the parent configuration does not leak down to us
		dispatcherServlet.setDetectAllHandlerAdapters(false);
		dispatcherServlet.setDetectAllHandlerExceptionResolvers(false);
		dispatcherServlet.setDetectAllHandlerMappings(false);
		dispatcherServlet.setDetectAllViewResolvers(false);

		return dispatcherServlet;
	}

	@Bean
	public HandlerAdapter handlerAdapter(HttpMessageConverters converters) {
		RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter();
		adapter.setMessageConverters(converters.getConverters());
		return adapter;
	}

	/*
	 * The error controller is present but not mapped as an endpoint in this context
	 * because of the DispatcherServlet having had it's HandlerMapping explicitly
	 * disabled. So we expose the same feature but only for machine endpoints.
	 */
	@Bean
	public ManagementErrorEndpoint errorEndpoint(final ErrorAttributes errorAttributes) {
		return new ManagementErrorEndpoint(this.errorPath, errorAttributes);
	}

	/**
	 * Configuration to add {@link HandlerMapping} for {@link MvcEndpoint}s. See
	 * {@link SecureEndpointHandlerMappingConfiguration} for an extended version that also
	 * configures the security filter.
	 */
	@Configuration
	@ConditionalOnMissingClass(name = "org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter")
	protected static class EndpointHandlerMappingConfiguration {

		@Autowired(required = false)
		private List<EndpointHandlerMappingCustomizer> mappingCustomizers;

		@Bean
		public HandlerMapping handlerMapping(MvcEndpoints endpoints,
				ListableBeanFactory beanFactory) {
			Set<MvcEndpoint> set = new HashSet<MvcEndpoint>(endpoints.getEndpoints());
			set.addAll(beanFactory.getBeansOfType(MvcEndpoint.class).values());
			EndpointHandlerMapping mapping = new EndpointHandlerMapping(set);
			// In a child context we definitely want to see the parent endpoints
			mapping.setDetectHandlerMethodsInAncestorContexts(true);
			postProcessMapping(beanFactory, mapping);
			if (this.mappingCustomizers != null) {
				for (EndpointHandlerMappingCustomizer customizer : this.mappingCustomizers) {
					customizer.customize(mapping);
				}
			}
			return mapping;
		}

		/**
		 * Hook to allow additional post processing of {@link EndpointHandlerMapping}.
		 * @param beanFactory the source bean factory
		 * @param mapping the mapping to customize
		 */
		protected void postProcessMapping(ListableBeanFactory beanFactory,
				EndpointHandlerMapping mapping) {
		}

	}

	/**
	 * Extension of {@link EndpointHandlerMappingConfiguration} that also configures the
	 * security filter.
	 */
	@Configuration
	@ConditionalOnClass(WebSecurityConfigurerAdapter.class)
	protected static class SecureEndpointHandlerMappingConfiguration extends
			EndpointHandlerMappingConfiguration {

		@Override
		protected void postProcessMapping(ListableBeanFactory beanFactory,
				EndpointHandlerMapping mapping) {
			// The parent context has the security filter, so we need to get it injected
			// with our EndpointHandlerMapping if we can.
			if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory,
					ManagementWebSecurityConfigurerAdapter.class).length == 1) {
				ManagementWebSecurityConfigurerAdapter bean = beanFactory
						.getBean(ManagementWebSecurityConfigurerAdapter.class);
				bean.setEndpointHandlerMapping(mapping);
			}
			else {
				logger.warn("No single bean of type "
						+ ManagementWebSecurityConfigurerAdapter.class.getSimpleName()
						+ " found (this might make some endpoints inaccessible without authentication)");
			}
		}

	}

	@Configuration
	@ConditionalOnClass({ EnableWebSecurity.class, Filter.class })
	@ConditionalOnBean(name = "springSecurityFilterChain", search = SearchStrategy.PARENTS)
	public static class EndpointWebMvcChildContextSecurityConfiguration {

		@Bean
		public Filter springSecurityFilterChain(HierarchicalBeanFactory beanFactory) {
			BeanFactory parent = beanFactory.getParentBeanFactory();
			return parent.getBean("springSecurityFilterChain", Filter.class);
		}

	}

}


text:
![logo](https://raw.github.com/slikts/wtmap/master/src/images/icon-128.png)

WT map
======

WT map is a Chrome extension that modifies the browser-based map in
[War Thunder](http://warthunder.com/). It can be used with multi-monitor
setups or on a different device from the one running the game. The purpose
of the extension is to help improve situational awareness by adding a level
of nicety to the map presentation.

Using WT map is currently
[within the Terms of Service](http://www.reddit.com/r/Warthunder/comments/1l5489/war_thunder_tactical_map_useful_app_for_android/cc4zudq)
of the game.

Features
--------

![Map screenshot](https://raw.github.com/slikts/wtmap/master/screenshot.png)

![Options screenshot](https://raw.github.com/slikts/wtmap/master/options.png)

 * Different plane icons for fighters, bombers and attackers
 * Plane icons show plane orientation
 * Close to real-time update rate
 * Automatic map centering and zooming on player
 * Configurable plane icon size
 * Option to reduce CPU load
 * Summary of total map objects by kind for both teams
 * Automatic optimal map sizing
 * Options to enable or disable state and indicator panel updating
 * Disables less useful panels like chat, HUD messages
 * Ground units never obscure plane icons
 * Info about spotted enemies, distance to closest enemy and number of allies
   in title bar
 * Off-screen aircraft are displayed at the map edge when zoomed in:
   ![Panning](https://raw.github.com/slikts/wtmap/master/pan.gif)

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

The extension can be installed from its [Chrome Web Store page](https://chrome.google.com/webstore/detail/gmhaddmfnmddbjgobfjfghpjlbgmeiop).

Usage
-----

The enhanced map can be opened from the extension options page. It's recommended
to bookmark the map page for easy access. War Thunder needs to be running
for the map to work.

To use the map on a different device from the one running the game,
the correct map location should be set in the options. For instance,
if the local IP address of the PC running the game was 192.168.1.1,
the map location would be http://192.168.1.1:8111/. The game process (aces.exe)
may need to be allowed through the firewall. If one of the devices is wireless
and the other wired, the local network needs to be configured to allow
them to connect.

Notes
-----

By default the extension only has permission to access http://localhost:8111/
and the permissions to access other map locations are requested separately
if needed and removed if not used.

The extension works by monkey-patching the code used in the original map.
It doesn't modify the map in-place but recreates it in a special page
because the Chrome content scripts can only access page DOM and not their
JavaScript environment.

The features added by this extension mostly don't depend on Chrome-specific
functionality and should be easily portable to other platforms.

The idea of making this extension comes from the
[War Thunder tactical map](https://play.google.com/store/apps/details?id=net.junkcode.warthundertacticalmap)
Android app.

The icons for the planes are P-39 for fighters, IL-2 for attackers
and Ju 88 for bombers.

Changelog
---------

**0.2.6** [2013-12-18]

 * Fix title info not updating properly if player is not spawned
 * Fix map scale resetting after map info updated
 * Display map size and scale and grid size in map panel caption
 * Decrease CPU usage
 * Make it possible to disable or enable panels in-line
 * Add separate map object totals for allied an enemy objects
 * Make panel layout automatic, map always tries to take the maximum space
 * Usability tweaks

**0.2.5** [2013-12-18]

 * Add support for the new "state" panel in 1.37
 * Fix an issue with persistent zoom levels

**0.2.4** [2013-12-18]

 * Display off-screen aircraft when zoomed in

**0.2.3** [2013-12-17]

 * Fixed zoom bug

**0.2.2** [2013-12-17]

 * Added advanced options to disable cockpit gauge, chat and HUD message panels
 * Significantly increased polling rate of map objects (configurable)
 * Added automatic persistent zoom instead of a configuration option

**0.2.1** [2013-12-16]

 * Removed proximity alerts

**0.1.7** [2013-12-16]

 * Made it possible to set proximity alert volume or radius to 0 to disable it
 * Fixed the centered map panning out of bounds

**0.1.6** [2013-12-15]

 * Added relative alert levels
 * Various fixes

**0.1.5** [2013-12-15]

 * Added configurable map centering and zooming on player

**0.1.4** [2013-12-14]

 * Initial release

Licence
-------

The project is available under the MIT licence.


text:
package com.logitags.cibet.it;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.ldap.LdapName;

import org.apache.log4j.Logger;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.cibethelper.base.CoreTestBase;
import com.cibethelper.ejb.RemoteEJB;
import com.cibethelper.ejb.RemoteEJBImpl;
import com.cibethelper.ejb.SecuredRemoteEJBImpl;
import com.cibethelper.ejb.SimpleEjb;
import com.cibethelper.entities.AbstractTEntity;
import com.cibethelper.entities.ITComplexEntity;
import com.cibethelper.entities.TCompareEntity;
import com.cibethelper.entities.TComplexEntity;
import com.cibethelper.entities.TComplexEntity2;
import com.cibethelper.entities.TEntity;
import com.cibethelper.servlet.ArquillianTestServlet1;
import com.logitags.cibet.config.ConfigurationService;
import com.logitags.cibet.resource.ParameterSequenceComparator;
import com.logitags.cibet.resource.ParameterType;
import com.logitags.cibet.resource.ResourceParameter;
import com.logitags.cibet.sensor.common.Invoker;
import com.logitags.cibet.sensor.ejb.CibetRemoteContext;
import com.logitags.cibet.sensor.ejb.CibetRemoteContextFactory;
import com.logitags.cibet.sensor.ejb.RemoteEJBInvoker;
import com.logitags.cibet.sensor.ejb.RemoteEjbInvocationHandler;

@RunWith(Arquillian.class)
public class RemoteEjbIT extends AbstractArquillian {

   private static Logger log = Logger.getLogger(RemoteEjbIT.class);

   @Deployment(testable = false)
   public static WebArchive createDeployment() {
      String warName = RemoteEjbIT.class.getSimpleName() + ".war";
      WebArchive archive = ShrinkWrap.create(WebArchive.class, warName);
      archive.setWebXML("it/web2.xml");

      archive.addClasses(AbstractArquillian.class, CoreTestBase.class, AbstractTEntity.class, TEntity.class,
            TComplexEntity.class, TComplexEntity2.class, ITComplexEntity.class, TCompareEntity.class, RemoteEJB.class,
            RemoteEJBImpl.class, SimpleEjb.class, ArquillianTestServlet1.class, RemoteEJB.class, RemoteEJBImpl.class,
            SecuredRemoteEJBImpl.class, SimpleEjb.class);

      File[] cibet = Maven.resolver().loadPomFromFile("pom.xml").resolve("com.logitags:cibet-jpa").withTransitivity()
            .asFile();
      archive.addAsLibraries(cibet);

      archive.addAsWebInfResource("META-INF/persistence-it.xml", "classes/META-INF/persistence.xml");
      archive.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");

      log.debug(archive.toString(true));
      archive.as(ZipExporter.class).exportTo(new File("target/" + warName), true);

      return archive;
   }

   @Before
   public void beforeRemoteEjbIT() {
      log.debug("execute before()");
      new ConfigurationService().initialise();
      com.logitags.cibet.context.Context.start();
      com.logitags.cibet.context.Context.sessionScope().setUser(USER);
      com.logitags.cibet.context.Context.sessionScope().setTenant(TENANT);
      log.debug("end execute before()");
   }

   @After
   public void afterAbstractArquillian() throws Exception {
      com.logitags.cibet.context.Context.end();
   }

   @Test
   public void executeLocalRemoteEJBInvoker() throws Exception {
      log.debug("start executeLocalRemoteEJBInvoker()");
      Set<ResourceParameter> params = new TreeSet<ResourceParameter>(new ParameterSequenceComparator());

      URL url = Thread.currentThread().getContextClassLoader().getResource("jndi_.properties");
      log.debug("url=" + url);
      Properties properties = new Properties();
      properties.load(url.openStream());

      String lookupName = "ejb:/" + this.getClass().getSimpleName() + "/RemoteEJBImpl!com.cibethelper.ejb.RemoteEJB";
      if (APPSERVER.equals(TOMEE)) {
         lookupName = "global/" + this.getClass().getSimpleName() + "/RemoteEJBImpl!com.cibethelper.ejb.RemoteEJB";
      }

      ResourceParameter rp = new ResourceParameter(RemoteEjbInvocationHandler.JNDI_NAME, String.class.getName(),
            lookupName, ParameterType.INTERNAL_PARAMETER, 1);
      params.add(rp);
      ResourceParameter rp1 = new ResourceParameter("param1", String.class.getName(), "myParam1",
            ParameterType.METHOD_PARAMETER, 2);
      params.add(rp1);
      ResourceParameter rp2 = new ResourceParameter("param2", int.class.getName(), 15, ParameterType.METHOD_PARAMETER,
            3);
      params.add(rp2);
      ResourceParameter rp3 = new ResourceParameter("param3", int.class.getName(), 34, ParameterType.METHOD_PARAMETER,
            4);
      params.add(rp3);
      ResourceParameter rp4 = new ResourceParameter("param4", byte[].class.getName(), "wossel".getBytes(),
            ParameterType.METHOD_PARAMETER, 5);
      params.add(rp4);
      TEntity entity = new TEntity("ja", 88, "mys");
      ResourceParameter rp5 = new ResourceParameter("param5", TEntity.class.getName(), entity,
            ParameterType.METHOD_PARAMETER, 6);
      params.add(rp5);
      ResourceParameter rp6 = new ResourceParameter("param6", Long.class.getName(), 900L,
            ParameterType.METHOD_PARAMETER, 7);
      params.add(rp6);
      ResourceParameter rp7 = new ResourceParameter(RemoteEjbInvocationHandler.JNDI_CONTEXT, Properties.class.getName(),
            properties, ParameterType.INTERNAL_PARAMETER, 8);
      params.add(rp7);

      Invoker invoker = RemoteEJBInvoker.createInstance();
      List<Object> result = (List<Object>) invoker.execute(null, null, "testInvoke", params);
      assertNotNull(result);
      assertEquals(6, result.size());
   }

   @Test
   public void executeRemoteEJBInvokerNoContext() throws Exception {
      log.debug("start executeRemoteEJBInvokerNoContext()");
      Set<ResourceParameter> params = new TreeSet<ResourceParameter>(new ParameterSequenceComparator());
      Invoker invoker = RemoteEJBInvoker.createInstance();
      try {
         List<Object> result = (List<Object>) invoker.execute(null, null, "testInvoke", params);
         fail();
      } catch (Exception e) {
         assertEquals("Failed to find resource parameter " + RemoteEjbInvocationHandler.JNDI_CONTEXT, e.getMessage());
      }
   }

   @Test
   public void executeRemoteEJBInvokerNoJndiname() throws Exception {
      log.debug("start executeRemoteEJBInvokerNoJndiname()");
      Set<ResourceParameter> params = new TreeSet<ResourceParameter>(new ParameterSequenceComparator());
      ResourceParameter rp7 = new ResourceParameter(RemoteEjbInvocationHandler.JNDI_CONTEXT, Properties.class.getName(),
            new Properties(), ParameterType.INTERNAL_PARAMETER, 8);
      params.add(rp7);

      Invoker invoker = RemoteEJBInvoker.createInstance();
      try {
         List<Object> result = (List<Object>) invoker.execute(null, null, "testInvoke", params);
         fail();
      } catch (Exception e) {
         assertEquals("Failed to find resource parameter " + RemoteEjbInvocationHandler.JNDI_NAME, e.getMessage());
      }
   }

   @Test
   public void invokeRemoteEJBHandler() throws Throwable {
      log.debug("start invokeRemoteEJBHandler()");
      TEntity entity = new TEntity("ja", 88, "mys");
      Object[] params = new Object[] { "kll", 15, 34, "wossel".getBytes(), entity, new Long(900L) };

      URL url = Thread.currentThread().getContextClassLoader().getResource("jndi_.properties");
      log.debug("url=" + url);
      Properties properties = new Properties();
      properties.load(url.openStream());

      Method m = RemoteEJBImpl.class.getMethod("testInvoke", String.class, int.class, int.class, byte[].class,
            TEntity.class, Long.class);
      Constructor<RemoteEjbInvocationHandler> constr = RemoteEjbInvocationHandler.class
            .getDeclaredConstructor(Object.class, Hashtable.class, String.class);
      constr.setAccessible(true);

      RemoteEjbInvocationHandler handler = constr.newInstance(new RemoteEJBImpl(), properties, "x");
      List<Object> result = (List<Object>) handler.invoke(new Object(), m, params);
      assertNotNull(result);
      assertEquals(6, result.size());
   }

   @Test
   public void invokeRemoteEJBHandlerName() throws Throwable {
      log.debug("start invokeRemoteEJBHandlerName()");
      TEntity entity = new TEntity("ja", 88, "mys");
      Object[] params = new Object[] { "kll", 15, 34, "wossel".getBytes(), entity, new Long(900L) };

      URL url = Thread.currentThread().getContextClassLoader().getResource("jndi_.properties");
      log.debug("url=" + url);
      Properties properties = new Properties();
      properties.load(url.openStream());

      Method m = RemoteEJBImpl.class.getMethod("testInvoke", String.class, int.class, int.class, byte[].class,
            TEntity.class, Long.class);
      Name name = new LdapName("CN=Steve Kille,O=Isode Limited,C=GB");

      Constructor<RemoteEjbInvocationHandler> constr = RemoteEjbInvocationHandler.class
            .getDeclaredConstructor(Object.class, Hashtable.class, Name.class);
      constr.setAccessible(true);
      RemoteEjbInvocationHandler handler = constr.newInstance(new RemoteEJBImpl(), properties, name);

      List<Object> result = (List<Object>) handler.invoke(new Object(), m, params);
      assertNotNull(result);
      assertEquals(6, result.size());
   }

   @Test
   public void invokeRemoteEJBHandlerNoName() throws Throwable {
      log.debug("start invokeRemoteEJBHandlerNoName()");
      TEntity entity = new TEntity("ja", 88, "mys");
      Object[] params = new Object[] { "kll", 15, 34, "wossel".getBytes(), entity, new Long(900L) };

      URL url = Thread.currentThread().getContextClassLoader().getResource("jndi_.properties");
      log.debug("url=" + url);
      Properties properties = new Properties();
      properties.load(url.openStream());

      Method m = RemoteEJBImpl.class.getMethod("testInvoke", String.class, int.class, int.class, byte[].class,
            TEntity.class, Long.class);

      Constructor<RemoteEjbInvocationHandler> constr = RemoteEjbInvocationHandler.class
            .getDeclaredConstructor(Object.class, Hashtable.class, String.class);
      constr.setAccessible(true);
      RemoteEjbInvocationHandler handler = constr.newInstance(new RemoteEJBImpl(), properties, (String) null);

      try {
         List<Object> result = (List<Object>) handler.invoke(new Object(), m, params);
         fail();
      } catch (IllegalArgumentException e) {
      }
   }

   @Test
   public void getInitialContextNoNative() throws Throwable {
      log.debug("start getInitialContextNoNative()");
      URL url = Thread.currentThread().getContextClassLoader().getResource("jndi_.properties");
      Properties properties = new Properties();
      properties.load(url.openStream());

      CibetRemoteContextFactory fac = new CibetRemoteContextFactory();
      try {
         Context ctx = fac.getInitialContext(properties);
      } catch (NamingException e) {
         Assert.fail();
      }
   }

   @Test
   public void getInitialContext() throws Throwable {
      log.debug("start getInitialContext()");
      URL url = Thread.currentThread().getContextClassLoader().getResource("jndi_.properties");
      Properties properties = new Properties();
      properties.load(url.openStream());
      String cl = (String) properties.get(Context.INITIAL_CONTEXT_FACTORY);
      properties.put(CibetRemoteContext.NATIVE_INITIAL_CONTEXT_FACTORY, cl);

      CibetRemoteContextFactory fac = new CibetRemoteContextFactory();
      CibetRemoteContext ctx = (CibetRemoteContext) fac.getInitialContext(properties);
      assertNotNull(ctx);
   }

   @Test(expected = IllegalArgumentException.class)
   public void getInitialContextNull() throws Throwable {
      log.debug("start getInitialContextNull()");
      CibetRemoteContextFactory fac = new CibetRemoteContextFactory();
      fac.getInitialContext(null);
   }

   @Test
   public void lookup() throws Throwable {
      log.debug("start lookup()");
      URL url = Thread.currentThread().getContextClassLoader().getResource("jndi_.properties");
      Properties properties = new Properties();
      properties.load(url.openStream());
      String cl = (String) properties.get(Context.INITIAL_CONTEXT_FACTORY);
      log.debug("INITIAL_CONTEXT_FACTORY: " + cl);
      properties.put(CibetRemoteContext.NATIVE_INITIAL_CONTEXT_FACTORY, cl);

      CibetRemoteContextFactory fac = new CibetRemoteContextFactory();
      CibetRemoteContext ctx = (CibetRemoteContext) fac.getInitialContext(properties);
      assertNotNull(ctx);

      String lookupName = this.getClass().getSimpleName() + "/RemoteEJBImpl!com.cibethelper.ejb.RemoteEJB";
      if (APPSERVER.equals(TOMEE)) {
         lookupName = "global/" + lookupName;
      }

      RemoteEJB ejb = (RemoteEJB) ctx.lookup(lookupName);
      assertNotNull(ejb);
   }

}