text:
#ifndef __NODE_MAPSERV_MAP_H__
#define __NODE_MAPSERV_MAP_H__

/**
 * @file map.hpp
 * @brief This declares the primary `Map` class.
 */

/// The node-mapserv version string
#define NODE_MAPSERV_VERSION "0.1.5"

// Standard headers
#include <string>
#include <map>

// Node headers
#include <v8.h>
#include <node.h>
#include <node_buffer.h>

// Mapserver headers
#include "mapserver.h"
extern "C" {
#include "mapserv.h"
}

// Node-mapserv headers
#include "error.hpp"

/// Throw an exception generated from a `char` string
#define THROW_CSTR_ERROR(TYPE, STR)                             \
  return ThrowException(Exception::TYPE(String::New(STR)));

/// Assign to a local V8 `Function` variable from the function arguments
#define ASSIGN_FUN_ARG(I, VAR)                              \
  if (args.Length() <= (I) || !args[I]->IsFunction())       \
    THROW_CSTR_ERROR(TypeError,                             \
                     "Argument " #I " must be a function"); \
  VAR = Local<Function>::Cast(args[I]);

/// Create a local V8 `Function` variable from the function arguments
#define REQ_FUN_ARG(I, VAR) \
  Local<Function> VAR;      \
  ASSIGN_FUN_ARG(I, VAR);

/// Create an `UTF8` V8 string variable from the function arguments
#define REQ_STR_ARG(I, VAR)                               \
  if (args.Length() <= (I) || !args[I]->IsString())       \
    THROW_CSTR_ERROR(TypeError,                           \
                     "Argument " #I " must be a string"); \
  String::Utf8Value VAR(args[I]->ToString());

/// Create a local V8 `External` variable from the function arguments
#define REQ_EXT_ARG(I, VAR)                             \
  if (args.Length() <= (I) || !args[I]->IsExternal())   \
    THROW_CSTR_ERROR(TypeError,                         \
                     "Argument " #I " invalid");        \
  Local<External> VAR = Local<External>::Cast(args[I]);

/// Assign to a local V8 `Object` variable from the function arguments
#define ASSIGN_OBJ_ARG(I, VAR)                             \
  if (args.Length() <= (I) || !args[I]->IsObject())        \
    THROW_CSTR_ERROR(TypeError,                            \
                     "Argument " #I " must be an object"); \
  VAR = Local<Object>(args[I]->ToObject());

/// Create a local V8 `Object` variable from the function arguments
#define REQ_OBJ_ARG(I, VAR) \
  Local<Object> VAR;        \
  ASSIGN_OBJ_ARG(I, VAR);

using namespace std;
using namespace node;
using namespace v8;

/**
 * @brief The primary class in the module representing a mapserver Map
 *
 * This class wraps an instance of a mapserver `mapObj`.  The `FromFile` and
 * `FromString` class constructor methods enable the map to be instantiated
 * from a mapfile using the non-blocking callback paradigm where the work is
 * carried out in a separate thread.
 *
 * Once instantiated the `mapserv` method is exposed to javascript clients
 * which allow calls to be made to the underlying mapserv functionality.  Again
 * this is performed asynchronously to prevent blocking of the main Node.js
 * event loop.
 */
class Map: ObjectWrap {
public:

  /// Initialise the class
  static void Init(Handle<Object> target);

  /// Instantiate a `Map` instance from a mapfile
  static Handle<Value> FromFileAsync(const Arguments& args);

  /// Instantiate a `Map` instance from a map string
  static Handle<Value> FromStringAsync(const Arguments& args);

  /// Wrap the `mapserv` CGI functionality
  static Handle<Value> MapservAsync(const Arguments& args);

private:

  /// The function template for creating new `Map` instances.
  static Persistent<FunctionTemplate> map_template;

  /// The string "data"
  static Persistent<String> data_symbol;
  /// The string "headers"
  static Persistent<String> headers_symbol;

  /// The underlying mapserver data structure that the class wraps
  mapObj *map;

  /// The structure used when performing asynchronous operations
  struct Baton {
    /// The asynchronous request
    uv_work_t request;
    /// The function executed upon request completion
    Persistent<Function> callback;
    /// A message set when the request fails
    MapserverError *error;

    /// The mapObj generated by the request
    mapObj *map;
  };

  /// The context used by asynchronous constructor methods
  struct MapfileBaton: Baton {
    /// The mapfile source from which to create a mapObj
    string mapfile;
  };

  /// The structure containing mapserver output
  struct gdBuffer {
    unsigned char *data;
    int size;
    int owns_data;
  };

  /// Asynchronous context used in method calls
  struct MapBaton: Baton {
    /// The `Map` object from which the call originated
    Map *self;
    /// The request body
    string body;
    /// The Content-Type header
    char *content_type;
    /// The buffer containing the mapserv response
    gdBuffer *buffer;
    /// The CGI environment variables
    std::map<string, string> env;
  };

  /// Instantiate a Map from a mapObj
  Map(mapObj *map) :
    map(map)
  {
    // should throw an error here if !map
  }

  /// Clear up the mapObj
  ~Map() {
    if (map) {
      msFreeMap(map);
    }
  }

  /// Instantiate an object
  static Handle<Value> New(const Arguments& args);

  /// Asynchronously create a `mapObj` from a file path
  static void FromFileWork(uv_work_t *req);

  /// Return the new `Map` instance to the caller
  static void FromFileAfter(uv_work_t *req);

  /// Asynchronouysly create a `mapObj` from a mapfile string
  static void FromStringWork(uv_work_t *req);

  /// Return the new `Map` instance to the caller
  static void FromStringAfter(uv_work_t *req);

  /// Asynchronously execute a mapserv request
  static void MapservWork(uv_work_t *req);

  /// Return the mapserv response to the caller
  static void MapservAfter(uv_work_t *req);

  /// Get a CGI environment variable
  static char* GetEnv(const char *name, void* thread_context);

  /// Get the mapserver output as a buffer
  static gdBuffer* msIO_getStdoutBufferBytes(void);

  /// Create a map object for use in a mapserv request
  static mapObj* LoadMap(mapservObj *mapserv, mapObj *src);

  /// Free data zero-copied to a `Buffer`
  static void FreeBuffer(char *data, void *hint) {
    msFree(data);
    data = NULL;
  }
};

/**
 * @def REQ_STR_ARG(I, VAR)
 *
 * This throws a `TypeError` if the argument is of the wrong type.
 *
 * @param I A zero indexed integer representing the variable to
 * extract in the `args` array.
 * @param VAR The symbol name of the variable to be created.

 * @def ASSIGN_FUN_ARG(I, VAR)
 *
 * This throws a `TypeError` if the argument is of the wrong type.
 *
 * @param I A zero indexed integer representing the variable to
 * extract in the `args` array.
 * @param VAR The symbol name of the variable to be created.

 * @def REQ_FUN_ARG(I, VAR)
 *
 * This defines a `Local<Function>` variable and then delegates to the
 * `ASSIGN_FUN_ARG` macro.

 * @def REQ_EXT_ARG(I, VAR)
 *
 * This throws a `TypeError` if the argument is of the wrong type.
 *
 * @param I A zero indexed integer representing the variable to
 * extract in the `args` array.
 * @param VAR The symbol name of the variable to be created.

 * @def ASSIGN_OBJ_ARG(I, VAR)
 *
 * This throws a `TypeError` if the argument is of the wrong type.
 *
 * @param I A zero indexed integer representing the variable to
 * extract in the `args` array.
 * @param VAR The symbol name of the variable to be created.

 * @def REQ_OBJ_ARG(I, VAR)
 *
 * This defines a `Local<Object>` variable and then delegates to the
 * `ASSIGN_OBJ_ARG` macro.

 * @def THROW_CSTR_ERROR(TYPE, STR)
 *
 * This returns from the containing function throwing an error of a
 * specific type.
 *
 * @param TYPE The symbol name of the exception to be thrown.
 * @param STR The `char` string to set as the error message.

 * @struct Map::gdBuffer
 *
 * This structure is used to capture data output from mapserver.  It is
 * inspired by code in the PHP Mapserver MapScript module.

 * @struct Map::Baton
 *
 * This represents a standard interface used to transfer data
 * structures between threads when using libuv asynchronously. See
 * <http://kkaefer.github.com/node-cpp-modules> for details.
 */

#endif  /* __NODE_MAPSERV_MAP_H__ */


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Menu = void 0;

var _react = _interopRequireWildcard(require("react"));

var _reactDom = _interopRequireDefault(require("react-dom"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _DomHandler = _interopRequireDefault(require("../utils/DomHandler"));

var _classnames = _interopRequireDefault(require("classnames"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var Menu =
/*#__PURE__*/
function (_Component) {
  _inherits(Menu, _Component);

  function Menu(props) {
    var _this;

    _classCallCheck(this, Menu);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(Menu).call(this, props));
    _this.onMenuClick = _this.onMenuClick.bind(_assertThisInitialized(_this));
    return _this;
  }

  _createClass(Menu, [{
    key: "onMenuClick",
    value: function onMenuClick() {
      if (this.documentClickListener) {
        this.selfClick = true;
      }
    }
  }, {
    key: "onItemClick",
    value: function onItemClick(event, item) {
      if (item.disabled) {
        event.preventDefault();
        return;
      }

      if (!item.url) {
        event.preventDefault();
      }

      if (item.command) {
        item.command({
          originalEvent: event,
          item: item
        });
      }

      if (this.props.popup) {
        this.hide(event);
      }
    }
  }, {
    key: "onItemKeyDown",
    value: function onItemKeyDown(event, item) {
      var listItem = event.currentTarget.parentElement;

      switch (event.which) {
        //down
        case 40:
          var nextItem = this.findNextItem(listItem);

          if (nextItem) {
            nextItem.children[0].focus();
          }

          event.preventDefault();
          break;
        //up

        case 38:
          var prevItem = this.findPrevItem(listItem);

          if (prevItem) {
            prevItem.children[0].focus();
          }

          event.preventDefault();
          break;

        default:
          break;
      }
    }
  }, {
    key: "findNextItem",
    value: function findNextItem(item) {
      var nextItem = item.nextElementSibling;
      if (nextItem) return _DomHandler.default.hasClass(nextItem, 'p-disabled') || !_DomHandler.default.hasClass(nextItem, 'p-menuitem') ? this.findNextItem(nextItem) : nextItem;else return null;
    }
  }, {
    key: "findPrevItem",
    value: function findPrevItem(item) {
      var prevItem = item.previousElementSibling;
      if (prevItem) return _DomHandler.default.hasClass(prevItem, 'p-disabled') || !_DomHandler.default.hasClass(prevItem, 'p-menuitem') ? this.findPrevItem(prevItem) : prevItem;else return null;
    }
  }, {
    key: "toggle",
    value: function toggle(event) {
      if (this.props.popup) {
        if (this.documentClickListener) {
          this.selfClick = true;
        }

        if (this.container.offsetParent) this.hide(event);else this.show(event);
      }
    }
  }, {
    key: "show",
    value: function show(event) {
      var _this2 = this;

      this.container.style.zIndex = String(this.props.baseZIndex + _DomHandler.default.generateZIndex());
      this.container.style.display = 'block';
      setTimeout(function () {
        _DomHandler.default.addClass(_this2.container, 'p-menu-overlay-visible');

        _DomHandler.default.removeClass(_this2.container, 'p-menu-overlay-hidden');
      }, 1);

      _DomHandler.default.absolutePosition(this.container, event.currentTarget);

      this.bindDocumentListeners();

      if (this.props.onShow) {
        this.props.onShow(event);
      }
    }
  }, {
    key: "hide",
    value: function hide(event) {
      var _this3 = this;

      if (this.container) {
        _DomHandler.default.addClass(this.container, 'p-menu-overlay-hidden');

        _DomHandler.default.removeClass(this.container, 'p-menu-overlay-visible');

        setTimeout(function () {
          if (_this3.container) {
            _this3.container.style.display = 'none';

            _DomHandler.default.removeClass(_this3.container, 'p-menu-overlay-hidden');
          }
        }, 150);
      }

      if (this.props.onHide) {
        this.props.onHide(event);
      }

      this.unbindDocumentListeners();
      this.selfClick = false;
    }
  }, {
    key: "bindDocumentListeners",
    value: function bindDocumentListeners() {
      var _this4 = this;

      if (!this.documentClickListener) {
        this.documentClickListener = function (event) {
          if (_this4.selfClick) _this4.selfClick = false;else _this4.hide(event);
        };

        document.addEventListener('click', this.documentClickListener);
      }

      if (!this.documentResizeListener) {
        this.documentResizeListener = function (event) {
          if (_this4.container.offsetParent) {
            _this4.hide(event);
          }
        };

        window.addEventListener('resize', this.documentResizeListener);
      }
    }
  }, {
    key: "unbindDocumentListeners",
    value: function unbindDocumentListeners() {
      if (this.documentClickListener) {
        document.removeEventListener('click', this.documentClickListener);
        this.documentClickListener = null;
      }

      if (this.documentResizeListener) {
        window.removeEventListener('resize', this.documentResizeListener);
        this.documentResizeListener = null;
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.unbindDocumentListeners();
    }
  }, {
    key: "renderSubmenu",
    value: function renderSubmenu(submenu, index) {
      var _this5 = this;

      var className = (0, _classnames.default)('p-submenu-header', submenu.className, {
        'p-disabled': submenu.disabled
      });
      var items = submenu.items.map(function (item, index) {
        return _this5.renderMenuitem(item, index);
      });
      return _react.default.createElement(_react.default.Fragment, {
        key: submenu.label + '_' + index
      }, _react.default.createElement("li", {
        className: className,
        style: submenu.style,
        role: "presentation"
      }, submenu.label), items);
    }
  }, {
    key: "renderSeparator",
    value: function renderSeparator(index) {
      return _react.default.createElement("li", {
        key: 'separator_' + index,
        className: "p-menu-separator",
        role: "separator"
      });
    }
  }, {
    key: "renderMenuitem",
    value: function renderMenuitem(item, index) {
      var _this6 = this;

      var className = (0, _classnames.default)('p-menuitem', item.className, {
        'p-disabled': item.disabled
      });
      var iconClassName = (0, _classnames.default)(item.icon, 'p-menuitem-icon');
      var icon = item.icon ? _react.default.createElement("span", {
        className: iconClassName
      }) : null;
      return _react.default.createElement("li", {
        key: item.label + '_' + index,
        className: className,
        style: item.style,
        role: "none"
      }, _react.default.createElement("a", {
        href: item.url || '#',
        className: "p-menuitem-link",
        role: "menuitem",
        target: item.target,
        onClick: function onClick(e) {
          return _this6.onItemClick(e, item);
        },
        onKeyDown: function onKeyDown(e) {
          return _this6.onItemKeyDown(e, item);
        }
      }, icon, _react.default.createElement("span", {
        className: "p-menuitem-text"
      }, item.label)));
    }
  }, {
    key: "renderItem",
    value: function renderItem(item, index) {
      if (item.separator) {
        return this.renderSeparator(index);
      } else {
        if (item.items) return this.renderSubmenu(item, index);else return this.renderMenuitem(item, index);
      }
    }
  }, {
    key: "renderMenu",
    value: function renderMenu() {
      var _this7 = this;

      return this.props.model.map(function (item, index) {
        return _this7.renderItem(item, index);
      });
    }
  }, {
    key: "renderElement",
    value: function renderElement() {
      var _this8 = this;

      if (this.props.model) {
        var className = (0, _classnames.default)('p-menu p-component', this.props.className, {
          'p-menu-dynamic p-menu-overlay': this.props.popup
        });
        var menuitems = this.renderMenu();
        return _react.default.createElement("div", {
          id: this.props.id,
          className: className,
          style: this.props.style,
          ref: function ref(el) {
            return _this8.container = el;
          },
          onClick: this.onMenuClick
        }, _react.default.createElement("ul", {
          className: "p-menu-list p-reset",
          role: "menu"
        }, menuitems));
      } else {
        return null;
      }
    }
  }, {
    key: "render",
    value: function render() {
      var element = this.renderElement();
      if (this.props.appendTo) return _reactDom.default.createPortal(element, this.props.appendTo);else return element;
    }
  }]);

  return Menu;
}(_react.Component);

exports.Menu = Menu;

_defineProperty(Menu, "defaultProps", {
  id: null,
  model: null,
  popup: false,
  style: null,
  className: null,
  autoZIndex: true,
  baseZIndex: 0,
  appendTo: null,
  onShow: null,
  onHide: null
});

_defineProperty(Menu, "propTypes", {
  id: _propTypes.default.string,
  model: _propTypes.default.array,
  popup: _propTypes.default.bool,
  style: _propTypes.default.object,
  className: _propTypes.default.string,
  autoZIndex: _propTypes.default.bool,
  baseZIndex: _propTypes.default.number,
  appendTo: _propTypes.default.any,
  onShow: _propTypes.default.func,
  onHide: _propTypes.default.func
});

redpajama_set_name: RedPajamaGithub


text:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;

public class Main {

	public static void main(String[] args){

		//----- crear archivo de txt ------------------------

		FileReader fr = null;
		try {
			fr = new FileReader("texto.txt");
		} catch (FileNotFoundException e) {
			System.out.println("el fichero no existe");
		}

		//crear un lector de buffers
		BufferedReader br = new BufferedReader(fr);

		StreamTokenizer st = new StreamTokenizer(br);

		int tipoTokenizer = 0, contadorPalabras = 0, contadorNumeros = 0, contadorLineas=0;
		boolean salir = false;
		do{
			try {
				tipoTokenizer = st.nextToken();
			} catch (IOException e) {
				e.printStackTrace();
			}
			switch (tipoTokenizer) {
				case StreamTokenizer.TT_EOF:
					salir=true;
					break;
				case StreamTokenizer.TT_EOL:
					contadorLineas = contadorLineas+1;
					break;
				case StreamTokenizer.TT_NUMBER:
					contadorNumeros=contadorNumeros+1;
					break;
				case StreamTokenizer.TT_WORD:
					contadorPalabras=contadorPalabras+1;
					break;
				default:
					break;
			}
		}
		while(salir==false);

		System.out.println("lineas : " + contadorLineas);
		System.out.println("palabras : " + contadorPalabras);
		System.out.println("numeros : " + contadorNumeros);

		Integer total ;
		total = contadorLineas + contadorNumeros + contadorPalabras;

		System.out.println("numero de tokens total:" + total);
	}

}


text:
using System.Xml.Linq;
using NWebDav.Server;
using NWebDav.Server.Props;
using NWebDav.Server.Stores;

namespace YaR.Clouds.WebDavStore.CustomProperties
{
    public class DavHref<TEntry> : DavString<TEntry> where TEntry : IStoreItem
    {
        /// <summary>
        /// Name of the property (static).
        /// </summary>
        // ReSharper disable once StaticMemberInGenericType
        public static readonly XName PropertyName = WebDavNamespaces.DavNs + "href";

        /// <summary>
        /// Name of the property.
        /// </summary>
        public override XName Name => PropertyName;
    }
}


text:
"""myequipment URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from rentals.urls import router as rentals_router
from rest_framework_jwt.views import obtain_jwt_token

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include(rentals_router.urls)),
    url(r'^jwt-token', obtain_jwt_token),
    url(r'^rentals/', include('rentals.urls', namespace='rentals')),
    url(r'^', include('django.contrib.staticfiles.urls')),
]


text:
<?php

namespace Ivory\HttpAdapter\Event\Cookie\Jar;

use Ivory\HttpAdapter\Event\Cookie\CookieFactory;
use Ivory\HttpAdapter\Event\Cookie\CookieFactoryInterface;
use Ivory\HttpAdapter\Event\Cookie\CookieInterface;
use Ivory\HttpAdapter\Message\InternalRequestInterface;
use Ivory\HttpAdapter\Message\ResponseInterface;

/**
 * @author GeLo <geloen.eric@gmail.com>
 */
class CookieJar implements CookieJarInterface
{
    /**
     * @var CookieFactoryInterface
     */
    private $cookieFactory;

    /**
     * @var CookieInterface[]
     */
    private $cookies = [];

    /**
     * @param CookieFactoryInterface|null $cookieFactory
     */
    public function __construct(CookieFactoryInterface $cookieFactory = null)
    {
        $this->setCookieFactory($cookieFactory ?: new CookieFactory());
    }

    /**
     * {@inheritdoc}
     */
    public function getCookieFactory()
    {
        return $this->cookieFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function setCookieFactory(CookieFactoryInterface $cookieFactory)
    {
        $this->cookieFactory = $cookieFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function clean()
    {
        foreach ($this->cookies as $cookie) {
            if ($cookie->isExpired()) {
                $this->removeCookie($cookie);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function clear($domain = null, $path = null, $name = null)
    {
        foreach ($this->cookies as $cookie) {
            if ($domain !== null && !$cookie->matchDomain($domain)) {
                continue;
            }

            if ($path !== null && !$cookie->matchPath($path)) {
                continue;
            }

            if ($name !== null && $cookie->getName() !== $name) {
                continue;
            }

            $this->removeCookie($cookie);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function hasCookies()
    {
        return !empty($this->cookies);
    }

    /**
     * {@inheritdoc}
     */
    public function getCookies()
    {
        return $this->cookies;
    }

    /**
     * {@inheritdoc}
     */
    public function setCookies(array $cookies)
    {
        $this->clear();
        $this->addCookies($cookies);
    }

    /**
     * {@inheritdoc}
     */
    public function addCookies(array $cookies)
    {
        foreach ($cookies as $cookie) {
            $this->addCookie($cookie);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removeCookies(array $cookies)
    {
        foreach ($cookies as $cookie) {
            $this->removeCookie($cookie);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function hasCookie(CookieInterface $cookie)
    {
        return array_search($cookie, $this->cookies, true) !== false;
    }

    /**
     * {@inheritdoc}
     */
    public function addCookie(CookieInterface $cookie)
    {
        if (!$cookie->hasName() || $this->hasCookie($cookie)) {
            return;
        }

        if (!$cookie->hasValue()) {
            $this->clear(
                $cookie->getAttribute(CookieInterface::ATTR_DOMAIN),
                $cookie->getAttribute(CookieInterface::ATTR_PATH),
                $cookie->getName()
            );

            return;
        }

        foreach ($this->cookies as $jarCookie) {
            if (!$cookie->compare($jarCookie)) {
                continue;
            }

            if ($cookie->getExpires() > $jarCookie->getExpires()) {
                $this->removeCookie($jarCookie);
                continue;
            }

            if ($cookie->getValue() !== $jarCookie->getValue()) {
                $this->removeCookie($jarCookie);
                continue;
            }

            return;
        }

        $this->cookies[] = $cookie;
    }

    /**
     * {@inheritdoc}
     */
    public function removeCookie(CookieInterface $cookie)
    {
        unset($this->cookies[array_search($cookie, $this->cookies, true)]);
        $this->cookies = array_values($this->cookies);
    }

    /**
     * {@inheritdoc}
     */
    public function populate(InternalRequestInterface $request)
    {
        foreach ($this->cookies as $cookie) {
            if (!$cookie->isExpired() && $cookie->match($request)) {
                $request = $request->withAddedHeader('Cookie', (string) $cookie);
            }
        }

        return $request;
    }

    /**
     * {@inheritdoc}
     */
    public function extract(InternalRequestInterface $request, ResponseInterface $response)
    {
        foreach ($response->getHeader('Set-Cookie') as $header) {
            $cookie = $this->cookieFactory->parse($header);

            if (!$cookie->hasAttribute(CookieInterface::ATTR_DOMAIN)) {
                $cookie->setAttribute(CookieInterface::ATTR_DOMAIN, $request->getUri()->getHost());
            }

            $this->addCookie($cookie);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function count()
    {
        return count($this->cookies);
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->cookies);
    }
}


text:
<?php

/**
 * Cancel handler for edit forms. Unlocks the object
 * if there was a lock held on it, then forwards to
 * the specified return location.
 */

if (! User::require_admin ()) {
	$this->redirect ('/admin');
}

// unlock cancelled object
$lock = new Lock ($_GET['type'], $_GET['id']);
$lock->remove ();

$this->redirect ($_GET['return']);

?>


text:
function [ output_args ] = neurIO_nev( input_args )
%NEURIO_NEV Summary of this function goes here
%   Detailed explanation goes here

end


text:
package org.codehaus.groovy.runtime;

import groovy.lang.Closure;

import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * This class is a general adapter to adapt a closure to any Java interface.
 *

 * @author Ben Yu
 * @author Jochen Theodorou
 * Jul 27, 2006 3:50:51 PM
 */
public class ConvertedClosure extends ConversionHandler implements Serializable {
    private final String methodName;
    private static final long serialVersionUID = 1162833713450835227L;

    /**
     * to create a ConvertedClosure object.
     * @param closure the closure object.
     */
    public ConvertedClosure(Closure closure, String method) {
        super(closure);
        this.methodName = method;
    }

    public ConvertedClosure(Closure closure) {
        this(closure,null);
    }

    @Override
    public Object invokeCustom(Object proxy, Method method, Object[] args)
    throws Throwable {
        if (methodName!=null && !methodName.equals(method.getName())) return null;
        return ((Closure) getDelegate()).call(args);
    }

}


text:
import argparse

from utils.config import get_config
from model.flowbot import Flowbot

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--train', action='store_true')
    parser.add_argument('--bot', default='lstm_attention')
    args = parser.parse_args()

    testing = not args.train
    config = get_config(args.bot)
    flowbot = Flowbot(config, testing)

    if testing:
        flowbot.interact()
    else:
        flowbot.train()

if __name__=='__main__':
    main()


text:
describe 'MedicationEvents' do
  describe 'Manage medication events' do
    let(:user) { create :user }

    before :each do
      DatabaseCleaner.clean
      Timecop.freeze 2016, 01, 31, 10, 00
    end

    after :each do
      Timecop.return
    end

    it 'adds an event and displays the results' do
      DatabaseCleaner.clean

      visit new_medication_event_url(as: user)
      expect {
        fill_in 'Date and time', with: (Time.now - 3600)
        fill_in 'Dose', with: '10.5'
        select 'humalog', from: 'Insulin'
        click_button 'Add'
      }.to change(MedicationEvent, :count).by 1

      within 'th' do
        expect(page).to have_content 'Sunday January 31st'
      end
      expect(page).to have_content '09:00'
      expect(page).to have_content '10.5'
      expect(page).to have_content 'humalog'
    end

    it 'edits an event' do
      DatabaseCleaner.clean
      Timecop.freeze 1992, 06, 15, 18, 11 do
        medication_event = create(:medication_event, datetime: '1992-06-15 12:00:00', dose: '7', insulin: 'humalog')
        visit medication_events_path(as: user)
        click_link '12:00'
        expect(page).to have_content 'Meds'
        expect(page).to have_content 'Delete'
      end
    end

    it 'adds several measurements' do
      DatabaseCleaner.clean

      visit new_medication_event_url(as: user)
      fill_in 'Date and time', with: Time.now - 3600
      fill_in 'Dose', with: '10.5'
      select 'humalog', from: 'Insulin'
      click_button 'Add'

      expect(page.all('td').map { |cell| cell.text }).to eq ['09:00', 'Meds', '10.5 u', 'humalog']

      visit new_medication_event_url(as: user)
      fill_in 'Date and time', with: Time.now - 86400
      fill_in 'Dose', with: '5.5'
      select 'humalog', from: 'Insulin'
      click_button 'Add'

      visit new_medication_event_url(as: user)
      fill_in 'Date and time', with: Time.now - 24000
      fill_in 'Dose', with: '8.0'
      select 'lantus', from: 'Insulin'
      click_button 'Add'

      expect(page).to have_content 'Sunday January 31st'
      expect(page).to have_content '09:00'
      expect(page).to have_content '03:20'

      expect(page).to have_content 'Saturday January 30th'
      expect(page).to have_content '10:00'

      click_link '10:00'
      expect(page).to have_content 'Meds'
      expect(page).to have_field 'Date and time'
      expect(page).to have_select 'Insulin', options: ['humalog', 'lantus']
      expect(page).to have_selector 'input[type=submit][value="Update"]'
      expect(page).to have_link 'Delete', href: '/meds/2'
      expect(page).to have_link 'Back', href: '/'

      click_link 'Delete'
      expect(MedicationEvent.count).to eq 2
      expect(page).to have_link 'Add Meds', href: '/meds/new'
      expect(page).to_not have_content 'Sunday January 28th'
    end
  end
end


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Package gr.forth.ics.graph (FlexiGraph Reference)
</TITLE>

<META NAME="date" CONTENT="2010-10-19">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
gr.forth.ics.graph

Packages that use gr.forth.ics.graph

gr.forth.ics.graph

gr.forth.ics.graph.algo

gr.forth.ics.graph.algo.transitivity
Object-oriented transitive closure and reduction algorithms.

gr.forth.ics.graph.event

gr.forth.ics.graph.io
Input/Output utilities for reading/writing graphs.

gr.forth.ics.graph.io.gml

gr.forth.ics.graph.io.pajek

gr.forth.ics.graph.layout

gr.forth.ics.graph.layout.circular

gr.forth.ics.graph.layout.forces2d

gr.forth.ics.graph.layout.random

gr.forth.ics.graph.metrics

gr.forth.ics.graph.path

Classes in gr.forth.ics.graph used by gr.forth.ics.graph

Direction

          The direction that an eligible Edge sbetween two Nodes should have.

Edge

          An edge that connects two nodes.

Edge.Orientation

          The kinds of relationship that two edges may have.

Graph

          A modifiable graph.

Graph.OrderManager

          Provides methods for reordering (in terms of iteration) the elements of a graph.

GraphForwarder

Hint

          Runtime performance hints that can be used by graph implementations.

InspectableGraph

          A read-only graph.

InspectableGraphForwarder

Node

          A Node is the basic element of a Graph.

SecondaryGraph

          Flexible Graph implementation, which can contain (adopt) nodes and edges from any other graph.

Tuple

          Entity that can be decorated with custom entries.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.algo

Direction

          The direction that an eligible Edge sbetween two Nodes should have.

Edge

          An edge that connects two nodes.

FoldingGraph

Graph

          A modifiable graph.

InspectableGraph

          A read-only graph.

Node

          A Node is the basic element of a Graph.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.algo.transitivity

Graph

          A modifiable graph.

InspectableGraph

          A read-only graph.

Node

          A Node is the basic element of a Graph.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.event

Edge

          An edge that connects two nodes.

InspectableGraph

          A read-only graph.

Node

          A Node is the basic element of a Graph.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.io

Graph

          A modifiable graph.

InspectableGraph

          A read-only graph.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.io.gml

Graph

          A modifiable graph.

InspectableGraph

          A read-only graph.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.io.pajek

Graph

          A modifiable graph.

InspectableGraph

          A read-only graph.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.layout

Edge

          An edge that connects two nodes.

InspectableGraph

          A read-only graph.

Node

          A Node is the basic element of a Graph.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.layout.circular

InspectableGraph

          A read-only graph.

Node

          A Node is the basic element of a Graph.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.layout.forces2d

Edge

          An edge that connects two nodes.

InspectableGraph

          A read-only graph.

Node

          A Node is the basic element of a Graph.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.layout.random

InspectableGraph

          A read-only graph.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.metrics

Direction

          The direction that an eligible Edge sbetween two Nodes should have.

InspectableGraph

          A read-only graph.

Node

          A Node is the basic element of a Graph.

Tuple

          Entity that can be decorated with custom entries.

Classes in gr.forth.ics.graph used by gr.forth.ics.graph.path

Direction

          The direction that an eligible Edge sbetween two Nodes should have.

Edge

          An edge that connects two nodes.

InspectableGraph

          A read-only graph.

Node

          A Node is the basic element of a Graph.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
describe("mnAdminServersController", function () {
  var $scope;
  var mnDialogService;
  var mnAdminServersService;
  var mnAdminTasksService;
  var mnAdminService;
  var mnAdminServersListItemService;
  var $state;
  var promise;
  var $stateParams;
  var $timeout;
  var mnAdminSettingsAutoFailoverService;

  beforeEach(angular.mock.module('mnAdminServers'));

  beforeEach(inject(function ($injector) {
    promise = new specRunnerHelper.MockedPromise();
    var $rootScope = $injector.get('$rootScope');
    var $controller = $injector.get('$controller');
    mnDialogService = $injector.get('mnDialogService');
    mnAdminServersService = $injector.get('mnAdminServersService');
    mnAdminTasksService = $injector.get('mnAdminTasksService');
    mnAdminService = $injector.get('mnAdminService');
    mnAdminServersListItemService = $injector.get('mnAdminServersListItemService');
    mnAdminSettingsAutoFailoverService = $injector.get('mnAdminSettingsAutoFailoverService');
    $state = $injector.get('$state');
    $timeout = $injector.get('$timeout');
    $stateParams = $injector.get('$stateParams');

    spyOn(mnAdminServersService, 'populateFailoverWarningsModel');
    spyOn(mnAdminServersService, 'populateRebalanceModel');
    spyOn(mnAdminServersService, 'populatePerNodeRepalanceProgress');
    spyOn(mnDialogService, 'open');
    spyOn($state, 'go');
    spyOn(mnAdminServersService, 'postAndReload').and.returnValue(promise);
    spyOn(mnAdminServersService, 'onStopRebalance').and.returnValue(promise);
    spyOn(mnDialogService, 'removeLastOpened');
    spyOn(mnAdminSettingsAutoFailoverService, 'getAutoFailoverSettings').and.returnValue(promise);
    spyOn(mnAdminSettingsAutoFailoverService, 'resetAutoFailOverCount').and.returnValue(promise);

    $scope = $rootScope.$new();

    $controller('mnAdminServersController', {'$scope': $scope});
  }));

  it('should be properly initialized', function () {
    expect($scope.addServer).toEqual(jasmine.any(Function));
    expect($scope.onRebalance).toEqual(jasmine.any(Function));
    expect($scope.onStopRebalance).toEqual(jasmine.any(Function));
    expect($scope.onStopRecovery).toEqual(jasmine.any(Function));
    expect($scope.resetAutoFailOverCount).toEqual(jasmine.any(Function));
  });

  it('should reset auto failover count', function () {
    expect($scope.isResetAutoFailOverCountSuccess).toBe(undefined);
    $scope.resetAutoFailOverCount();
    expect($scope.isResetAutoFailOverCountSuccess).toBe(true);
    $timeout.flush();
    expect($scope.isAutoFailOverCountAvailable).toBe(false);
    expect($scope.isResetAutoFailOverCountSuccess).toBe(false);
  });

  it('should display additional confiramtion on stop rebalance error', function () {
    spyOn(mnDialogService, 'getLastOpened').and.returnValue(false);
    promise.setResponse(undefined, 400).switchOn('error');
    mnAdminService.model.details = {stopRebalanceUri: "stopRebalanceUri"};
    $scope.onStopRebalance();
    expect(mnDialogService.open).toHaveBeenCalledWith({
      template: '/angular/app/mn_admin/servers/stop_rebalance_dialog/mn_admin_servers_stop_rebalance_dialog.html',
      scope: $scope
    });
  });

  it('should display close additional confiramtion dialog on success', function () {
    spyOn(mnDialogService, 'getLastOpened').and.returnValue(true);
    expect($scope.mnDialogStopRebalanceDialogLoading).toBe(undefined);
    mnAdminService.model.details = {stopRebalanceUri: "stopRebalanceUri"};
    promise.switchOn('success');
    $scope.onStopRebalance()
    expect(mnDialogService.removeLastOpened).toHaveBeenCalled();
    expect($scope.mnDialogStopRebalanceDialogLoading).toBe(false);
  });

  it('should react on getAutoFailoverSettings deps changes', function () {
    $scope.$apply();
    expect(mnAdminSettingsAutoFailoverService.getAutoFailoverSettings.calls.count()).toBe(1);

    mnAdminService.model.nodes = 'test';
    $scope.$apply();
    expect(mnAdminSettingsAutoFailoverService.getAutoFailoverSettings.calls.count()).toBe(2);

    mnAdminTasksService.model.inRecoveryMode = 'test';
    $scope.$apply();
    expect(mnAdminSettingsAutoFailoverService.getAutoFailoverSettings.calls.count()).toBe(3);

    mnAdminTasksService.model.isLoadingSamples = 'test';
    $scope.$apply();
    expect(mnAdminSettingsAutoFailoverService.getAutoFailoverSettings.calls.count()).toBe(4);
    expect($scope.isAutoFailOverCountAvailable).toBe(false);

    mnAdminServersService.model.mayRebalanceWithoutSampleLoading = 'test';
    promise.setResponse({count: 1});
    $scope.$apply();
    expect(mnAdminSettingsAutoFailoverService.getAutoFailoverSettings.calls.count()).toBe(5);
    expect($scope.isAutoFailOverCountAvailable).toBe(true);
  });

  it('should react on populateFailoverWarningsModel deps changes', function () {
    $scope.$apply();
    expect(mnAdminServersService.populateFailoverWarningsModel.calls.count()).toBe(1);
    $scope.mnAdminServiceModel = {details: {failoverWarnings: 'test'}};
    $scope.$apply();
    expect(mnAdminServersService.populateFailoverWarningsModel.calls.count()).toBe(2);
  });

  it('should react on populateRebalanceModel deps changes', function () {
    $scope.$apply();
    expect(mnAdminServersService.populateRebalanceModel.calls.count()).toBe(1);

    mnAdminService.model = {details: undefined};
    $scope.$apply();
    expect(mnAdminServersService.populateRebalanceModel.calls.count()).toBe(1);

    mnAdminService.model = {details: {nodes: 'test'}};
    $scope.$apply();
    expect(mnAdminServersService.populateRebalanceModel.calls.count()).toBe(1);

    mnAdminService.model = {details: {nodes: 'test'}};
    mnAdminService.model.nodes = {};
    $scope.$apply();
    expect(mnAdminServersService.populateRebalanceModel.calls.count()).toBe(2);

    mnAdminTasksService.model.inRecoveryMode = 'test';
    $scope.$apply();
    expect(mnAdminServersService.populateRebalanceModel.calls.count()).toBe(3);

    mnAdminTasksService.model.isLoadingSamples = 'test';
    $scope.$apply();
    expect(mnAdminServersService.populateRebalanceModel.calls.count()).toBe(4);

    mnAdminService.model.details.rebalanceStatus = 'test';
    $scope.$apply();
    expect(mnAdminServersService.populateRebalanceModel.calls.count()).toBe(5);

    mnAdminService.model.details.balanced = 'test';
    $scope.$apply();
    expect(mnAdminServersService.populateRebalanceModel.calls.count()).toBe(6);

    mnAdminService.model.nodes.unhealthyActive = 'test'
    $scope.$apply();
    expect(mnAdminServersService.populateRebalanceModel.calls.count()).toBe(7);

    mnAdminService.model.nodes.pending = 'test';
    $scope.$apply();
    expect(mnAdminServersService.populateRebalanceModel.calls.count()).toBe(8);
  });

  it('should react on populatePerNodeRepalanceProgress deps changes', function () {
    $scope.$apply();
    expect(mnAdminServersService.populatePerNodeRepalanceProgress.calls.count()).toBe(1);

    mnAdminService.model.nodes = undefined;
    mnAdminTasksService.model.tasksRebalance = 'test';
    $scope.$apply();
    expect(mnAdminServersService.populatePerNodeRepalanceProgress.calls.count()).toBe(1);

    mnAdminService.model.nodes = {allNodes: 'test'};
    $scope.$apply();
    expect(mnAdminServersService.populatePerNodeRepalanceProgress.calls.count()).toBe(2);

    mnAdminTasksService.model.tasksRebalance = 'test2';
    $scope.$apply();
    expect(mnAdminServersService.populatePerNodeRepalanceProgress.calls.count()).toBe(3);
  });

  it('should open add server dialog', function () {
    $scope.addServer();
    expect(mnDialogService.open).toHaveBeenCalledWith({
      template: '/angular/app/mn_admin/servers/add_dialog/mn_admin_servers_add_dialog.html',
      scope: $scope
    });
  });

  it('should run rebalance', function () {
    mnAdminServersListItemService.model.pendingEject = [{otpNode: 'test'}, {otpNode: 'test2'}];
    mnAdminService.model.nodes = {allNodes: [{otpNode: 'test'}, {otpNode: 'test2'}]};
    mnAdminService.model.details = {controllers: {rebalance: {uri: "test"}}};

    $scope.onRebalance();
    expect(mnAdminServersService.postAndReload).toHaveBeenCalledWith('test', {
      knownNodes: 'test,test2',
      ejectedNodes: 'test,test2'
    });
    expect($state.go.calls.count()).toBe(1);
  });

  it('should stop recovery', function () {
    mnAdminTasksService.model.stopRecoveryURI = 'stopRecoveryURI';
    $scope.onStopRecovery();
    expect(mnAdminServersService.postAndReload).toHaveBeenCalledWith('stopRecoveryURI');
  });
});


text:
package com.spurdow.rvlazyscrollexample;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import com.spurdow.rvlazyscroll.RVLazyScroll;

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

public class MainActivity extends AppCompatActivity {

    public LinearLayoutManager mLinearLayoutManager = null;
    public StaggeredGridLayoutManager mStaggeredGridLayoutManager = null;
    public GridLayoutManager mGridLayoutManager = null;
    public PersonAdapter mAdapter = null;
    public RecyclerView mRecyclerView;

    public RVLazyScroll<Person> linearLazyScroll ;
    public RVLazyScroll<Person> staggeredLazyScroll;
    public RVLazyScroll<Person> gridLazyScroll ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        List<Person> mock = new ArrayList<>();
        mock.add(new Person("Black Widow"));
        mock.add(new Person("Thor"));
        mock.add(new Person("Peter"));
        mock.add(new Person("John"));
        mock.add(new Person("Hulk"));
        mock.add(new Person("Captain America"));
        mock.add(new Person("Dead Pool"));
        mock.add(new Person("Hawk Eye"));

        mAdapter = new PersonAdapter(mock);
        mRecyclerView.setHasFixedSize(true);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        mStaggeredGridLayoutManager = new StaggeredGridLayoutManager(2 , StaggeredGridLayoutManager.VERTICAL);

        mGridLayoutManager = new GridLayoutManager(this , 2 , LinearLayoutManager.VERTICAL , false);

        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

        linearLazyScroll = new RVLazyScroll<Person>(mLinearLayoutManager , 2) {
            @Override
            public List<Person> onLoadMore(int offset) {
                return new ArrayList<Person>(){{
                    add(new Person("Another Hulk"));
                    add(new Person("Another SpiderMan"));
                    add(new Person("Another Thor"));
                }};
            }

            @Override
            public void onDoneLoad(List<Person> newListOfdata) {
                if(newListOfdata != null && newListOfdata.size() >0) {
                    for (Person newP : newListOfdata) {
                        mAdapter.add(newP);
                    }
                }
            }
        };

        staggeredLazyScroll = new RVLazyScroll<Person>(mStaggeredGridLayoutManager) {
            @Override
            public List<Person> onLoadMore(int offset) {
                return new ArrayList<Person>(){{
                    add(new Person("Another Hulk"));
                    add(new Person("Another SpiderMan"));
                    add(new Person("Another Thor"));
                }};
            }

            @Override
            public void onDoneLoad(List<Person> newListOfdata) {
                if(newListOfdata != null && newListOfdata.size() >0) {
                    for (Person newP : newListOfdata) {
                        mAdapter.add(newP);
                    }
                }
            }
        };

        gridLazyScroll = new RVLazyScroll<Person>(mGridLayoutManager) {
            @Override
            public List<Person> onLoadMore(int offset) {
                return new ArrayList<Person>(){{
                    add(new Person("Another Hulk"));
                    add(new Person("Another SpiderMan"));
                    add(new Person("Another Thor"));
                }};
            }

            @Override
            public void onDoneLoad(List<Person> newListOfdata) {
                if(newListOfdata != null && newListOfdata.size() >0) {
                    for (Person newP : newListOfdata) {
                        mAdapter.add(newP);
                    }
                }
            }
        };

        mRecyclerView.addOnScrollListener(linearLazyScroll);

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        removeOnScrollListener();
       switch(item.getItemId()){
           case R.id.ic_action_grid:

                mRecyclerView.setLayoutManager(mGridLayoutManager);
                mRecyclerView.addOnScrollListener(gridLazyScroll);
               break;
           case R.id.ic_action_staggered_grid:

               mRecyclerView.setLayoutManager(mStaggeredGridLayoutManager);
               mRecyclerView.addOnScrollListener(staggeredLazyScroll);
               break;
           case R.id.ic_action_linear:

               mRecyclerView.setLayoutManager(mLinearLayoutManager);
               mRecyclerView.addOnScrollListener(linearLazyScroll);
               break;
       }
        return super.onOptionsItemSelected(item);
    }

    private void removeOnScrollListener(){
        if(mRecyclerView.getLayoutManager() instanceof LinearLayoutManager){
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
            if(linearLayoutManager instanceof GridLayoutManager){
                mRecyclerView.removeOnScrollListener(gridLazyScroll);
            }else {
                mRecyclerView.removeOnScrollListener(linearLazyScroll);
            }
        }else if(mRecyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager){
            mRecyclerView.removeOnScrollListener(staggeredLazyScroll);
        }
    }
}


text:
import urllib
import simplejson

def PatSearch(searchString):

    query = urllib.urlencode({'q' : searchString})
    url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \
      % (query)
    search_results = urllib.urlopen(url)
    json = simplejson.loads(search_results.read())
    results = json['responseData']['results']
    for i in results:
        print i['title'] + ': ' + i['url']

if __name__ == '__main__':
    PatSearch('synovate')


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.20 at 12:48:21 PM GMT
//

package weka.core.pmml.jaxbbindings;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;

/**
 *
Java class for GAP.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="GAP">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="true"/>
 *     <enumeration value="false"/>
 *     <enumeration value="unknown"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlEnum
public enum GAP {

    @XmlEnumValue("false")
    FALSE("false"),
    @XmlEnumValue("true")
    TRUE("true"),
    @XmlEnumValue("unknown")
    UNKNOWN("unknown");
    private final String value;

    GAP(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static GAP fromValue(String v) {
        for (GAP c: GAP.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v.toString());
    }

}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'yunpian'

require 'minitest/autorun'
require 'webmock/minitest'

module I18n
  class << self
    attr_accessor :locale
  end
end


text:
package org.syncope.console.pages.panels;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.event.IEvent;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
import org.syncope.client.to.ConnInstanceTO;
import org.syncope.client.to.ResourceTO;
import org.syncope.client.util.ConnConfPropUtils;
import org.syncope.console.pages.BaseModalPage;
import org.syncope.console.pages.ResourceModalPage.ResourceEvent;
import org.syncope.console.pages.panels.ResourceDetailsPanel.DetailsModEvent;
import org.syncope.console.rest.ConnectorRestClient;
import org.syncope.console.wicket.markup.html.form.AjaxCheckBoxPanel;
import org.syncope.console.wicket.markup.html.form.AjaxNumberFieldPanel;
import org.syncope.console.wicket.markup.html.form.AjaxPasswordFieldPanel;
import org.syncope.console.wicket.markup.html.form.AjaxTextFieldPanel;
import org.syncope.console.wicket.markup.html.form.FieldPanel;
import org.syncope.console.wicket.markup.html.form.MultiValueSelectorPanel;
import org.syncope.console.wicket.markup.html.form.MultiValueSelectorPanel.MultiValueSelectorEvent;
import org.syncope.types.ConnConfProperty;

public class ResourceConnConfPanel extends Panel {

    private static final long serialVersionUID = -7982691107029848579L;

    /**
     * Logger.
     */
    protected static final Logger LOG =
            LoggerFactory.getLogger(ResourceConnConfPanel.class);

    /**
     * GuardedString is not in classpath.
     */
    private static final String GUARDED_STRING =
            "org.identityconnectors.common.security.GuardedString";

    /**
     * GuardedByteArray is not in classpath.
     */
    private static final String GUARDED_BYTE_ARRAY =
            "org.identityconnectors.common.security.GuardedByteArray";

    /**
     * Number java types.
     */
    private static final List<Class> NUMBER = Arrays.asList(new Class[]{
                Integer.class,
                Double.class,
                Long.class,
                Float.class,
                Number.class,
                Integer.TYPE,
                Long.TYPE,
                Double.TYPE,
                Float.TYPE});

    @SpringBean
    private ConnectorRestClient connRestClient;

    private List<ConnConfProperty> connConfProperties;

    private WebMarkupContainer connConfPropContainer;

    private AjaxLink check;

    private boolean createFlag;

    private ResourceTO resourceTO;

    public ResourceConnConfPanel(
            final String id,
            final ResourceTO resourceTO,
            final boolean createFlag) {

        super(id);
        setOutputMarkupId(true);

        this.createFlag = createFlag;
        this.resourceTO = resourceTO;

        connConfProperties = getConnConfProperties();

        connConfPropContainer =
                new WebMarkupContainer("connectorPropertiesContainer");
        connConfPropContainer.setOutputMarkupId(true);
        add(connConfPropContainer);

        check = new IndicatingAjaxLink("check", new ResourceModel("check")) {

            private static final long serialVersionUID =
                    -4199438518229098169L;

            @Override
            public void onClick(final AjaxRequestTarget target) {

                ConnInstanceTO connectorTO =
                        connRestClient.read(
                        resourceTO.getConnectorId());

                connectorTO.setConfiguration(
                        ConnConfPropUtils.joinConnInstanceProperties(
                        connectorTO.getConfigurationMap(),
                        ConnConfPropUtils.getConnConfPropertyMap(
                        resourceTO.getConnConfProperties())));

                if (connRestClient.check(
                        connectorTO).booleanValue()) {
                    info(getString("success_connection"));
                } else {
                    error(getString("error_connection"));
                }

                target.add(((BaseModalPage) getPage()).getFeedbackPanel());
            }
        };

        check.setEnabled(!connConfProperties.isEmpty());
        connConfPropContainer.add(check);

        /*
         * the list of overridable connector properties
         */
        connConfPropContainer.add(new ListView<ConnConfProperty>(
                "connectorProperties",
                new PropertyModel(this, "connConfProperties")) {

            private static final long serialVersionUID = 9101744072914090143L;

            @Override
            protected void populateItem(final ListItem<ConnConfProperty> item) {
                final ConnConfProperty property = item.getModelObject();

                final Label label = new Label("connPropAttrSchema",
                        property.getSchema().getDisplayName() == null
                        || property.getSchema().getDisplayName().isEmpty()
                        ? property.getSchema().getName()
                        : property.getSchema().getDisplayName());

                item.add(label);

                final FieldPanel field;

                boolean required = false;

                boolean isArray = false;

                if (GUARDED_STRING.equalsIgnoreCase(
                        property.getSchema().getType())
                        || GUARDED_BYTE_ARRAY.equalsIgnoreCase(
                        property.getSchema().getType())) {

                    field = new AjaxPasswordFieldPanel(
                            "panel",
                            label.getDefaultModelObjectAsString(),
                            new Model(),
                            true);

                    ((PasswordTextField) field.getField()).setResetPassword(
                            false);

                    required = property.getSchema().isRequired();

                } else {
                    Class propertySchemaClass;

                    try {
                        propertySchemaClass = ClassUtils.forName(
                                property.getSchema().getType(),
                                ClassUtils.getDefaultClassLoader());
                    } catch (Exception e) {
                        LOG.error("Error parsing attribute type", e);
                        propertySchemaClass = String.class;
                    }

                    if (NUMBER.contains(propertySchemaClass)) {
                        field = new AjaxNumberFieldPanel(
                                "panel",
                                label.getDefaultModelObjectAsString(),
                                new Model(),
                                ClassUtils.resolvePrimitiveIfNecessary(
                                propertySchemaClass),
                                true);

                        required = property.getSchema().isRequired();
                    } else if (Boolean.class.equals(propertySchemaClass)
                            || boolean.class.equals(propertySchemaClass)) {
                        field = new AjaxCheckBoxPanel(
                                "panel",
                                label.getDefaultModelObjectAsString(),
                                new Model(),
                                true);
                    } else {

                        field = new AjaxTextFieldPanel(
                                "panel",
                                label.getDefaultModelObjectAsString(),
                                new Model(),
                                true);

                        required = property.getSchema().isRequired();
                    }

                    if (String[].class.equals(propertySchemaClass)) {
                        isArray = true;
                    }
                }

                field.setTitle(property.getSchema().getHelpMessage());

                if (isArray) {
                    field.removeRequiredLabel();

                    if (property.getValues().isEmpty()) {
                        property.getValues().add(null);
                    }

                    final MultiValueSelectorPanel multiFields =
                            new MultiValueSelectorPanel<String>(
                            "panel",
                            new PropertyModel<List<String>>(property, "values"),
                            String.class,
                            field,
                            true);

                    item.add(multiFields);
                } else {
                    if (required) {
                        field.addRequiredLabel();
                    }

                    field.getField().add(
                            new AjaxFormComponentUpdatingBehavior("onchange") {

                                private static final long serialVersionUID =
                                        -1107858522700306810L;

                                @Override
                                protected void onUpdate(
                                        final AjaxRequestTarget target) {
                                    send(getPage(), Broadcast.BREADTH,
                                            new ConnConfModEvent(
                                            target, connConfProperties));
                                }
                            });

                    field.setNewModel(property.getValues());
                    item.add(field);
                }

                resourceTO.getConnConfProperties().add(property);
            }
        });
    }

    /**
     * Get overridable properties.
     *
     * @return overridable properties.
     */
    private List<ConnConfProperty> getConnConfProperties() {

        final List<ConnConfProperty> props = new ArrayList<ConnConfProperty>();

        if (!createFlag && !resourceTO.getConnConfProperties().isEmpty()) {
            props.addAll(resourceTO.getConnConfProperties());
        } else {
            resourceTO.getConnConfProperties().clear();

            final Long connectorId = resourceTO.getConnectorId();

            if (connectorId != null && connectorId > 0) {
                for (ConnConfProperty property :
                        connRestClient.getConnectorProperties(connectorId)) {

                    if (property.isOverridable()) {
                        props.add(property);
                    }
                }
            }
        }

        return props;
    }

    @Override
    public void onEvent(final IEvent<?> event) {
        if (event.getPayload() instanceof DetailsModEvent) {
            // connectro change: update properties and forward event
            final AjaxRequestTarget target =
                    ((ResourceEvent) event.getPayload()).getTarget();

            connConfProperties = getConnConfProperties();
            check.setEnabled(!connConfProperties.isEmpty());

            target.add(connConfPropContainer);

            // get configuration properties and send a new event
            send(getPage(), Broadcast.BREADTH,
                    new ConnConfModEvent(target, connConfProperties));

        } else if (event.getPayload() instanceof MultiValueSelectorEvent) {
            // multi value connector property change: forward event
            final AjaxRequestTarget target =
                    ((MultiValueSelectorEvent) event.getPayload()).getTarget();

            send(getPage(), Broadcast.BREADTH,
                    new ConnConfModEvent(target, connConfProperties));
        }
    }

    /**
     * Connector configuration properties modification event.
     */
    public static class ConnConfModEvent extends ResourceEvent {

        private List<ConnConfProperty> configuration;

        /**
         * Constructor.
         *
         * @param target request target.
         * @param target connector configuration properties.
         */
        public ConnConfModEvent(
                final AjaxRequestTarget target,
                final List<ConnConfProperty> conf) {
            super(target);
            this.configuration = conf;
        }

        public List<ConnConfProperty> getConfiguration() {
            return configuration;
        }
    }
}


text:
package br.com.command.modelos;

import android.os.AsyncTask;
import android.util.Log;

import br.com.command.util.ExternalService;
import br.com.command.util.OnStatusChangeListener;
/**
 * Created by danielmarcoto on 17/11/15.
 */
public class SomPiscina {
    public final static int ID = 17;
    private OnStatusChangeListener onStatusChangeListener;
    private ExternalService externalService;
    private StatusController statusController;

    public SomPiscina(){
        this.externalService = ExternalService.getInstance();
        this.statusController = StatusController.getInstance();
    }

    public void setOnStatusChangeListener(OnStatusChangeListener onStatusChangeListener) {
        this.onStatusChangeListener = onStatusChangeListener;
    }

    public void ligar(){

        new AsyncTask<String, Integer, String>(){
            @Override
            protected String doInBackground(String... strings) {
                String response = externalService
                        .callRemote("Ligar som da piscina",
                                "O micro system da piscina será ligada");

                return response;
            }

            @Override
            protected void onPostExecute(String response) {
                super.onPostExecute(response);

                Log.i("Log", "Response: " + response);

                if (response.startsWith("Erro")){
                    statusController.setSomPiscina(false);
                } else {
                    statusController.setSomPiscina(true);
                }

                if (onStatusChangeListener != null)
                    onStatusChangeListener.onChange(statusController.isSomPiscina());
            }
        }.execute();
    }

    public void desligar(){

        new AsyncTask<String, Integer, String>(){
            @Override
            protected String doInBackground(String... strings) {
                String response = externalService
                        .callRemote("Desligar som da piscina",
                                "O micro system da piscina será desligada");

                return response;
            }

            @Override
            protected void onPostExecute(String response) {
                super.onPostExecute(response);

                Log.i("Log", "Response: " + response);

                if (response.startsWith("Erro")){
                    statusController.setSomPiscina(true);
                } else {
                    statusController.setSomPiscina(false);
                }

                if (onStatusChangeListener != null)
                    onStatusChangeListener.onChange(statusController.isSomPiscina());
            }
        }.execute();
    }

}


text: Home Page


text:
<?xml version="1.0"?>

<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
<document>

    <title>Scripting with ECMAScript</title>

      This page is a brief introduction to scripting SVG documents with
      ECMAScript, and how Batik's ECMAScript environment can be extended.

      <title>Scripting basics</title>

        As the ECMAScript language (the standardised version of JavaScript)
        is one of the most popular scripting languages, and as the SVG
        specification states that an SVG conforming implementation must
        support it, SVG documents processed by Batik support scripting
        with ECMAScript using Mozilla's ECMAScript interpreter,
        Rhino.

        There are two places in an SVG file where you can put scripts.

        The first one is in the script
        element, where you can place any code, including function
        definitions, to be executed just before the document
        SVGLoad event is fired.

      <source><![CDATA[<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">

</svg>]]></source>

        You can also attach script to respond to user or document
        events using attributes on SVG elements. As shown in the
        previous example, the scripting language must be set on
        the script element. However, for event handling
        the default language type text/ecmascript
        is assumed. If you want to change it you can use
        the contentScriptType attribute on the
        svg element.

        The event attribute can contain any script code to execute when the
        event reaches the element (as described by the
        DOM event flow)
        in either the bubbling or at-target phases.  The following example
        will change the rect to be filled in blue when it is
        clicked.

      <source><![CDATA[<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
  <rect x="0" y="0" width="10" height="10"
        onclick="evt.target.setAttribute('fill', 'blue')"/>
</svg>]]></source>

        Note that inside the event attribute script, there is a variable
        called evt that is a reference to the
        Event
        object that represents the event that is being handled.

        For more information on using scripting in SVG you can have a look at:

          the scripting
            chapter of the SVG specification, for advanced information on
          scripting in SVG, and

          the ECMAScript
            specification, for advanced information on the ECMAScript
          language.

      <title>Using Rhino features</title>

        Rhino has a number of features beyond those supported by standard
        ECMAScript interpreters, and these can be used with Batik.  One
        useful feature is that ECMAScript code can use Java classes and
        objects, and not just the standard ECMAScript primitive types and
        host objects exposed by Batik.

        To create an instance of a Java class from ECMAScript, you first need
        to import the package in which it resides.  This is done using the
        importPackage global function that Rhino provides.
        For example, to import the javax.swing.JFrame class,
        you use:

      <source>importPackage(Packages.javax.swing);</source>

        This then exposes a global property for each class in the
        javax.swing package that you can use to create a new
        object of this class, similar to a import javax.swing.*;
        statement in Java.  We can use the exposed JFrame
        property to create a new instance of this class:

      <source>var frame = new JFrame("My test frame");</source>

        Note how an ECMAScript string value is passed as the parameter to
        JFrame's constructor.  Rhino will attempt to convert
        ECMAScript values into appropriate Java primitive types or objects
        to make underlying constructor or method calls.  In this instance,
        the ECMAScript string value is converted into a
        java.lang.String object to be passed to the constructor.

        Now that we have a reference to this Java object, we can call any
        method on it as we usually would from Java code.  The following
        complete example demonstrates this, where clicking the green
        circle will pop up a frame:

      <source><![CDATA[<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
  <circle cx="50" cy="50" r="50" fill="green" onclick="showFrame()"/>

</svg>]]></source>

        For more information on scripting Java classes from ECMAScript code,
        see Rhino's
        Scripting
          Java document.

      <title>Customizing the Rhino interpreter</title>

        A useful example of customization of the Rhino interpreter comes from
        the fact that the ECMAScript specification doesn't provide any
        predefined I/O facilities to interact with the console. However, it is
        very common for ECMAScript compatible languages to provide a function
        named print to output messages to the console. We will
        describe here an example of cutomization of the Batik Rhino
        interpreter to add such functionality to it.

        You should first subclass the default Batik ECMAScript interpreter to
        add the functionality to it as below.

      <source>import org.apache.batik.script.rhino.RhinoInterpreter;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.PropertyException;

public class ExtendedRhinoInterpreter extends RhinoIntepreter {

    public ExtendedRhinoInterpreter() {

        // Array of functions to put in the global object.
        final String[] names = { "print" }
        try {
            // Add the functions to the global object.
            getGlobalObject().defineFunctionProperties
                (names, ExtendedRhinoIntepreter.class,
                 ScriptableObject.DONTENUM);
        } catch (PropertyException e) {
            throw new Error(e);
        }
    }

    public static void print(Context cx, Scriptable thisObj,
                             Object[] args, Function funObj) {
        for (int i = 0; i < args.length; i++) {
            if (i > 0) {
                System.out.print(" ");
            }

            // Convert the ECMAScript value into a string form.
            String s = Context.toString(args[i]);
            System.out.print(s);
        }
        System.out.println();
    }
}</source>

        Now, you need to tell to Batik to use this interpreter instead of the
        default one.  For that, you must first define a factory to create
        instances of your interpreter.

      <source>import org.apache.batik.script.Interpreter;
import org.apache.batik.script.InterpreterFactory;

public class ExtendedRhinoInterpreterFactory implements InterpreterFactory {

    public Interpreter createInterpreter() {
        return new ExtendedRhinoInterpreter();
    }
}</source>

        Then, you must build an
        IntepreterPool
        that will use this factory, and then set the pool on the
        BridgeContext
        of your application.

      <source>org.apache.batik.bridge.BridgeContext ctx = ...;
org.apache.batik.script.InterpreterPool pool =
    new org.apache.batik.script.InterpreterPool();
pool.putInterpreterFactory("text/ecmascript",
                           new ExtendedRhinoInterpreterFactory());
ctx.setIntepreterPool(pool);</source>

        For example if you are using the Batik SVG browser application you
        should be able to use the previous piece of code on a subclass of the
        JSVGCanvas
        class in the createBridgeContext() method.

        For further information on working with Rhino, consult the
        Rhino website.

</document>


text:
package io.druid.query.aggregation.datasketches.theta;

import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.druid.jackson.DefaultObjectMapper;

public class SketchEstimateWithErrorBoundsTest
{

  @Test
  public void testSerde() throws IOException
  {
    ObjectMapper mapper = new DefaultObjectMapper();

    SketchEstimateWithErrorBounds est = new SketchEstimateWithErrorBounds(100.0,101.5,98.5,2);

    Assert.assertEquals(est, mapper.readValue(
            mapper.writeValueAsString(est), SketchEstimateWithErrorBounds.class));
  }

}


text:
import java.util.Arrays;

public class _0462MinimumMovesToEqualArrayElementsII {
    public int minMoves2(int[] nums) {
        Arrays.sort(nums);
        int l = nums.length;
        int median = nums[l / 2];
        int moves = 0;
    	for (int i = 0; i < l; i++) moves += (int)Math.abs(nums[i] - median);
    	return moves;
    }
}


text:
class AppListControllerDelegate;
class Profile;

namespace base {
class Time;
}
namespace app_list {

class AppResult : public SearchResult,
                  public AppContextMenuDelegate {
 public:
  ~AppResult() override;

  void UpdateFromLastLaunched(const base::Time& current_time,
                              const base::Time& last_launched);
 protected:
  AppResult(Profile* profile,
            const std::string& app_id,
            AppListControllerDelegate* controller,
            bool is_recommendation);

  // Marked const in order to be able to use in derived class in const methods.
  Profile* profile() const {
    return profile_;
  }

  const std::string& app_id() const {
    return app_id_;
  }

  // Marked const in order to be able to use in derived class in const methods.
  AppListControllerDelegate* controller() const {
    return controller_;
  }

 private:
  Profile* profile_;
  const std::string app_id_;
  AppListControllerDelegate* controller_;

  DISALLOW_COPY_AND_ASSIGN(AppResult);
};

}  // namespace app_list

#endif  // CHROME_BROWSER_UI_APP_LIST_SEARCH_APP_RESULT_H_


text:
<?php
if (!defined('ON_ROOT')) { include 'views/404.php'; die();}

$ROUTES = array(
  'admin' => array(
    'install' => array(
      'controller' =>'InstallController',
      'methods' => array('GET', 'POST'),
    ),
    'settings' => array(
      'controller' => 'SettingsController',
      'methods' => array('GET', 'POST'),
    ),
    'change_password' => array(
      'controller' => 'ChangePasswordController',
      'methods' => array('GET', 'POST'),
    ),
  ),
  'user' => array(
    'login' => array(
      'controller' => 'LoginController',
       'methods' => array('POST'),
    ),
    'logout' => array(
      'controller' => 'LogoutController',
      'methods' => array('GET'),
    ),
  ),
  'person' => array(
    'main' => array(
      'controller' => 'MainController',
      'methods' => array('GET'),
    ),
    'view' => array(
      'controller' => 'ViewController',
      'methods' => array('GET')
    ),
    'add_spouse' => array(
      'controller' => 'AddSpouseController',
      'methods' => array('GET', 'POST'),
    ),
    'add_child' => array(
      'controller' => 'AddChildController',
      'methods' => array('GET', 'POST')
    ),
    'delete' => array(
      'controller' => 'DeleteController',
      'methods' => array('GET')
    ),
    'edit' => array(
      'controller' => 'EditController',
      'methods' => array('GET', 'POST'),
    ),
  ),
);


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v12/common/asset_types.proto

package com.google.ads.googleads.v12.common;

public interface CalloutAssetOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v12.common.CalloutAsset)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * Required. The callout text.
   * The length of this string should be between 1 and 25, inclusive.
   *

   *
   * string callout_text = 1 [(.google.api.field_behavior) = REQUIRED];
   * @return The calloutText.
   */
  java.lang.String getCalloutText();
  /**
   *

   * Required. The callout text.
   * The length of this string should be between 1 and 25, inclusive.
   *

   *
   * string callout_text = 1 [(.google.api.field_behavior) = REQUIRED];
   * @return The bytes for calloutText.
   */
  com.google.protobuf.ByteString
      getCalloutTextBytes();

  /**
   *

   * Start date of when this asset is effective and can begin serving, in
   * yyyy-MM-dd format.
   *

   *
   * string start_date = 2;
   * @return The startDate.
   */
  java.lang.String getStartDate();
  /**
   *

   * Start date of when this asset is effective and can begin serving, in
   * yyyy-MM-dd format.
   *

   *
   * string start_date = 2;
   * @return The bytes for startDate.
   */
  com.google.protobuf.ByteString
      getStartDateBytes();

  /**
   *

   * Last date of when this asset is effective and still serving, in yyyy-MM-dd
   * format.
   *

   *
   * string end_date = 3;
   * @return The endDate.
   */
  java.lang.String getEndDate();
  /**
   *

   * Last date of when this asset is effective and still serving, in yyyy-MM-dd
   * format.
   *

   *
   * string end_date = 3;
   * @return The bytes for endDate.
   */
  com.google.protobuf.ByteString
      getEndDateBytes();

  /**
   *

   * List of non-overlapping schedules specifying all time intervals for which
   * the asset may serve. There can be a maximum of 6 schedules per day, 42 in
   * total.
   *

   *
   * repeated .google.ads.googleads.v12.common.AdScheduleInfo ad_schedule_targets = 4;
   */
  java.util.List<com.google.ads.googleads.v12.common.AdScheduleInfo>
      getAdScheduleTargetsList();
  /**
   *

   * List of non-overlapping schedules specifying all time intervals for which
   * the asset may serve. There can be a maximum of 6 schedules per day, 42 in
   * total.
   *

   *
   * repeated .google.ads.googleads.v12.common.AdScheduleInfo ad_schedule_targets = 4;
   */
  com.google.ads.googleads.v12.common.AdScheduleInfo getAdScheduleTargets(int index);
  /**
   *

   * List of non-overlapping schedules specifying all time intervals for which
   * the asset may serve. There can be a maximum of 6 schedules per day, 42 in
   * total.
   *

   *
   * repeated .google.ads.googleads.v12.common.AdScheduleInfo ad_schedule_targets = 4;
   */
  int getAdScheduleTargetsCount();
  /**
   *

   * List of non-overlapping schedules specifying all time intervals for which
   * the asset may serve. There can be a maximum of 6 schedules per day, 42 in
   * total.
   *

   *
   * repeated .google.ads.googleads.v12.common.AdScheduleInfo ad_schedule_targets = 4;
   */
  java.util.List<? extends com.google.ads.googleads.v12.common.AdScheduleInfoOrBuilder>
      getAdScheduleTargetsOrBuilderList();
  /**
   *

   * List of non-overlapping schedules specifying all time intervals for which
   * the asset may serve. There can be a maximum of 6 schedules per day, 42 in
   * total.
   *

   *
   * repeated .google.ads.googleads.v12.common.AdScheduleInfo ad_schedule_targets = 4;
   */
  com.google.ads.googleads.v12.common.AdScheduleInfoOrBuilder getAdScheduleTargetsOrBuilder(
      int index);
}


text:
package com.InfinityRaider.AgriCraft.proxy;

import net.minecraft.item.ItemStack;

public class ServerProxy extends CommonProxy {
    @Override
    public ClientProxy getClientProxy() {return null;}

    @Override
    public void registerRenderers() {}

    @Override
    public void hideItemInNEI(ItemStack stack) {}

    @Override
    public void registerEventHandlers() {super.registerEventHandlers();}
}


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

<TITLE>
I-Index
</TITLE>

<META NAME="date" CONTENT="2011-03-30">

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

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A C D E G H I L M N O P R S T V W

I

InvalidLicenseStringException - Exception in org.spdx.spdxspreadsheet
Exceptions related to License Strings stored in the spreadsheet.
InvalidLicenseStringException(String) -
Constructor for exception org.spdx.spdxspreadsheet.InvalidLicenseStringException

InvalidLicenseStringException(String, Throwable) -
Constructor for exception org.spdx.spdxspreadsheet.InvalidLicenseStringException

InvalidSPDXAnalysisException - Exception in org.spdx.rdfparser
Exception for invalid SPDX Documents
InvalidSPDXAnalysisException(String) -
Constructor for exception org.spdx.rdfparser.InvalidSPDXAnalysisException

InvalidSPDXAnalysisException(String, Throwable) -
Constructor for exception org.spdx.rdfparser.InvalidSPDXAnalysisException

isStandardLicenseID(String) -
Static method in class org.spdx.rdfparser.SPDXLicenseInfoFactory

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A C D E G H I L M N O P R S T V W


text:
'use strict';

/**
 * Module dependencies
 */

var hbs = require('express-hbs'),
    _   = require('lodash');

function meta_title(context, options) {

  var output = '';

  if (this.meta_title) {
    output = _.escape(this.meta_title);
  }

  return new hbs.handlebars.SafeString(output);
}

module.exports = meta_title;


text:
package org.oscm.ws;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.wsdl.xml.WSDLLocator;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.xml.sax.InputSource;

import org.oscm.logging.Log4jLogger;
import org.oscm.logging.LoggerFactory;
import org.oscm.types.enumtypes.LogMessageIdentifier;

/**
 * WSDL locator implementation to load a WSDL and all related imports using the
 * specified credentials.
 *
 * @author Mike Jäger
 *
 */
public class BasicAuthWSDLLocator implements WSDLLocator {

    private final static Log4jLogger logger = LoggerFactory
            .getLogger(WSDLLocator.class);

    private String userName;
    private String password;
    private String wsdlBaseURL;
    private String importLocation;
    private InputStream in;

    public BasicAuthWSDLLocator(String wsdlBaseURL, String userName,
            String password) {
        this.wsdlBaseURL = wsdlBaseURL;
        this.userName = userName;
        this.password = password;
    }

    private InputSource createInputSource(String url) throws IOException {
        final HttpClient client = new HttpClient();
        final String proxyHost = System.getProperty("http.proxyHost");
        final String proxyPort = System.getProperty("http.proxyPort", "80");
        if (proxyHost != null && proxyHost.trim().length() > 0) {
            try {
                client.getHostConfiguration().setProxy(proxyHost.trim(),
                        Integer.parseInt(proxyPort));
            } catch (NumberFormatException e) {
                logger.logError(Log4jLogger.SYSTEM_LOG, e,
                        LogMessageIdentifier.ERROR_USE_PROXY_DEFINITION_FAILED);
            }
        }

        // Set credentials if specified:
        URL targetURL = new URL(url);
        if (userName != null && userName.length() > 0) {
            client.getParams().setAuthenticationPreemptive(true);
            final Credentials credentials = new UsernamePasswordCredentials(
                    userName, password);
            client.getState().setCredentials(
                    new AuthScope(targetURL.getHost(), targetURL.getPort(),
                            AuthScope.ANY_REALM), credentials);
        }

        // Retrieve content:
        // opening a local resource isn't supported by apache
        // instead open stream directly
        if (targetURL.getProtocol().startsWith("file")) {
            in = targetURL.openStream();
            return new InputSource(in);
        }
        final GetMethod method = new GetMethod(url);
        final int status = client.executeMethod(method);
        if (status != HttpStatus.SC_OK) {
            throw new IOException("Error " + status + " while retrieving "
                    + url);
        }
        in = method.getResponseBodyAsStream();
        return new InputSource(in);
    }

    @Override
    public InputSource getBaseInputSource() {
        try {
            return createInputSource(wsdlBaseURL);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getBaseURI() {
        return wsdlBaseURL;
    }

    @Override
    public InputSource getImportInputSource(String parentLocation,
            String importLocation) {
        this.importLocation = importLocation;
        try {
            if (parentLocation == null) {
                return createInputSource(importLocation);
            } else {
                URL parentUrl = new URL(parentLocation);
                return createInputSource(new URL(parentUrl, importLocation)
                        .toString());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getLatestImportURI() {
        return importLocation;
    }

    @Override
    public void close() {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // ignore, stream is already closed
            }
        }
    }
}