text:
'use strict';

(function(window, angular, _) {

  //  __        ___ _
  //  \ \      / (_) |___  ___  _ __
  //   \ \ /\ / /| | / __|/ _ \| '_ \
  //    \ V  V / | | \__ \ (_) | | | |
  //     \_/\_/  |_|_|___/\___/|_| |_|
  //
  // region wilson

  function Wilson(module) {

    var _instance               = this;
    var _module                 = module;
    var _appConfig              = null;
    var _cache                  = { components: {}, behaviors: {}, services: {}, filters: {} };

    var _compileProvider        = null;
    var _controllerProvider     = null;
    var _filterProvider         = null;
    var _provider               = null;
    var _activePage             = null;
    var _activeRouteInfo        = {};
    var _componentMap           = {};
    var _preloadQueue           = [];

    //   ____       _            _         __  __      _   _               _
    //  |  _ \ _ __(_)_   ____ _| |_ ___  |  \/  | ___| |_| |__   ___   __| |___
    //  | |_) | '__| \ \ / / _` | __/ _ \ | |\/| |/ _ \ __| '_ \ / _ \ / _` / __|
    //  |  __/| |  | |\ V / (_| | ||  __/ | |  | |  __/ |_| | | | (_) | (_| \__ \
    //  |_|   |_|  |_| \_/ \__,_|\__\___| |_|  |_|\___|\__|_| |_|\___/ \__,_|___/
    //
    // region private methods

    /**
     * Return an appropriately formatted directive name given a prefix and name.
     *
     * @param prefix  - The prefix to prepended to the name
     * @param name    - The actual name to be formatted
     */
    function getDirectiveName(prefix, constructName) {
      return prefix + _.upperFirst(_.camelCase(constructName));
    }

    /**
     * Get component element markup tag
     */
    function getComponentTag(componentName) {
      var tagName =  _appConfig.app.selectors.component + '-' + _.kebabCase(componentName);
      return '<' + tagName + '></' + tagName + '>';
    }

    /**
     * Validates the name, type and definition of a wilson construct
     *
     * @param type - Type of construct - service, filter, behavior or component
     * @param name - Name of service, filter, behavior or component
     * @param def  - Primary service, filter, behavior or component-controller definition
     */
    function validateDefinition(type, name, def) {

      // Basic Validations for type and name here
      if (!_.isString(name)) { throw new Error(type + ' name must be a string!!!'); }
      if (!type)             { throw new Error('Failed to validate definition params. Type is null or undefined!!'); }

      // Definition checks here
      var error   = null;
      var prefix  = (type === 'component') ? 'controller' : 'primary';

      if (!_.isFunction(def) && _.isEmpty(def))        { error = 'definition is empty and cannot be processed.'; }
      else if (!_.isFunction(def) && !_.isArray(def))  { error = 'definition must be a Function or an Array!!!'; }

      if (error) { throw new Error((type + ' [' + name + '] ' + prefix + ' ' + error)); }
    }

    /**
     * Create a specialized component controller. This specialized controller will instantiate a new component instance using
     * the ComponentFactoryService and register it with the wilson instance.
     *
     * @param name                - The name of this component (kebabCase, with no prefix -- the pure component name)
     * @param controller          - The controller definition for the component
     * @param config              - The entire component configuration object
     * @returns [string|Function] - A new controller definition that represents the specialized component controller
     */
    function createComponentController(name, controller, config) {
      return ['ComponentFactoryService', 'WilsonUtils', '$scope', '$element', '$attrs',
        function(ComponentFactoryService, WilsonUtils, $scope, $element, $attrs) {
          var parent        = _instance.getActiveComponent(_instance.findComponentId($element));
          var componentId   = WilsonUtils.generateUUID();

          // Decorate componentId onto $element reference
          $element.data('wilsonComponentId', componentId);

          // Instantiate the new component and register the returned component $scope with the wilson instance
          _componentMap[componentId] = ComponentFactoryService.create(componentId, name, controller, this, parent, $scope, $element, $attrs, config);

          // Listen for component destroy to de-register
          $scope.on.event('$destroy', function() { delete _componentMap[componentId]; });
        }
      ];
    }

    /**
     * Create a specialized behavior definition. This specialized definition will create a wrapping link method around
     * the original link that can extend/decorate the $scope if needed. Currently this method simply decorates a
     * WilsonEventHelper instance if this is not a component scope)
     *
     * @param definition                      - The original behavior definition
     * @returns {[string,string, Function]}   - The actual behavior definition that wraps the original
     */
    function createBehaviorDefinition(definition) {
      return ['$injector', 'WilsonEventHelper', function($injector, WilsonEventHelper) {
        var behaviorConfig  = $injector.invoke(definition);
        var originalLink    = behaviorConfig.link;
        var invokeTarget    = _.isArray(definition) ? definition[definition.length - 1] : definition;

        if (originalLink) {
          behaviorConfig.link = function($scope, $element, $attrs, controller) {
            if (!$scope.hasOwnProperty('on')) { $scope.on = new WilsonEventHelper($scope); }
            originalLink.apply(invokeTarget, [$scope, $element, $attrs, controller]);
          };
        }

        return behaviorConfig;
      }];
    }

    /**
     * Validate and declare a given set of routes onto the given routeProvider instance. Facilitates all route setup
     * for a given set of configured application routes.
     *
     * @param routes          - A collection of route objects
     * @param routeProvider   - The angular routeProvider instance on which to declare the routes
     */
    function defineAppRoutes(routes, routeProvider) {
      // Enforce null route
      var nullRouteIdx = _.findIndex(routes, { path: null });

      if (nullRouteIdx === -1)              { throw new Error('Null route MUST be specified in routes!');       }
      if (nullRouteIdx < routes.length - 1) { throw new Error('Null route MUST be the last specified route!');  }

      // Define Application URL Routes
      _.each(routes, function(routeInfo) { createRoute(routeInfo, routes, routeProvider); });
    }

    /**
     * Get all configured route options associated with a given matched route path. Given a path and the complete
     * set of routes, return a cloned copy of the configured options for the route matching the specified path.
     *
     * @param matchedPath   - The path of the route
     * @param routes        - The collection of route objects to search
     * @returns {Object}    - A copy of the route options for the route that matches the given path (empty object if no match found)
     */
    function getRouteOptions(matchedPath, routes) {
      // find the matching route configuration for the given path
      // If no matching route was found then default to the null path route
      var routeConfig   = _.find(routes, { path: matchedPath });
      routeConfig       = routeConfig || _.find(routes, { path: null });

      // return the options from the matching route
      return (routeConfig && routeConfig.options) ? _.clone(routeConfig.options) : { };
    }

    /**
     * Define a route for the application from a given path and resulting state. The
     * given path will become a route that will map to the given state. The site control
     * component will then use the mapped state for a route to load the appropriate top-level
     * workflow component and compile it into the view.
     *
     * @param routeInfo     - The route definition data for this explicit route
     * @param routes        - The collection of all route objects
     * @param routeProvider - The angular routeProvider reference on which to declare the final route definition
     */
    function createRoute(routeInfo, routes, routeProvider) {
      // Determine early failures
      if (!routeProvider)                 { throw new Error('No RouteProvider included! Cannot create route!'); }
      if (_.isUndefined(routeInfo.path))  { throw new Error('Route information is invalid! Missing path definition: \n' + JSON.stringify(routeInfo, undefined, 2)); }

      // Create routing data for this route
      var routingData = {
        controller:     function() { _activePage = routeInfo.component; },
        template:       getComponentTag(routeInfo.component),
        componentName:  routeInfo.component,
        resolve: {
          title:      ['$rootScope', 'WilsonRouter', function($rootScope, WilsonRouter) {
            _.merge($rootScope, { page: { title: WilsonRouter.getTitleText(routeInfo.title) } });
            return $rootScope.page.title;
          }],
          component:  ['$route', '$q', '$location', '$window', 'WilsonRouter', 'WilsonUtils', 'ComponentLoaderService',
            function($route, $q, $location, $window, WilsonRouter, WilsonUtils, ComponentLoaderService) {
              var currentRoute  = $location.path();
              var options       = getRouteOptions($route.current.originalPath, routes);
              var activeInfo    = _.extend({}, options, routeInfo.defaultParams || {}, $route.current.params);

              // Set Active Route Info
              WilsonUtils.replaceObject(_activeRouteInfo, activeInfo);

              // Handle special routing functionality via IRouteService
              return WilsonRouter.handleRouteChange(currentRoute, options, routeInfo).then(function() {
                // Load the route component
                return ComponentLoaderService.load(routeInfo.component);
              }).then(function(data) {
                // Force a reload to update if out of date component
                if (data.version !== angular.wilson.config.app.version) { $window.location.reload(); }
                return data;
              }).catch(function(error) { return $q.reject(error); });
            }
          ],
          dependencies: ['$q', 'WilsonRouter', function($q, WilsonRouter) {
            var promises = [];

            // Call load dependencies on IRouteService if exposed (this method should return a $q promise)
            promises.push(WilsonRouter.loadDependencies(routeInfo));
            promises.push(WilsonRouter.loadSession());

            return $q.allSettled(promises);
          }],
          retryOriginalRoute: ['$location', '$route', 'localStorageService', function($location, $route, localStorageService) {
            var retryRoute    = localStorageService.get('retryRoute');

            // If we have the retryRoute object, then we need to setup our retry
            if (_.isObject(retryRoute) && $location.path() === retryRoute.path) {
              // If this is a subsequent attempt, then continue
              if (retryRoute.attempt > 0) {
                if (retryRoute.originalPath && retryRoute.path !== retryRoute.originalPath) {
                  localStorageService.remove('retryRoute');
                  $location.path(retryRoute.originalPath);
                }
              } else {
                retryRoute.attempt++;
                localStorageService.add('retryRoute', retryRoute);
              }
            } else {
              localStorageService.remove('retryRoute');
            }
          }]
        }
      };

      // Declare routes on the routeProvider
      if (routeInfo.path !== null)  { routeProvider.when(routeInfo.path, routingData); }
      else                          { routeProvider.otherwise(routingData); }
    }

    // endregion

    //   ____        _     _ _        __  __      _   _               _
    //  |  _ \ _   _| |__ | (_) ___  |  \/  | ___| |_| |__   ___   __| |___
    //  | |_) | | | | '_ \| | |/ __| | |\/| |/ _ \ __| '_ \ / _ \ / _` / __|
    //  |  __/| |_| | |_) | | | (__  | |  | |  __/ |_| | | | (_) | (_| \__ \
    //  |_|    \__,_|_.__/|_|_|\___| |_|  |_|\___|\__|_| |_|\___/ \__,_|___/
    //
    // region public methods

    /***** Public config property *****/
    this.config = _appConfig;

    /***** Public routeInfo virtual property *****/
    Object.defineProperty(this, 'routeInfo', {
      get: function() { return _.cloneDeep(_activeRouteInfo); }
    });

    /**
     * Sets the app config object.
     *
     * @param config - Object to be set as the new _appConfig
     */
    this.setAppConfig = function setAppConfig(config) { this.config = _appConfig = config; };

    /**
     * Get the currently active page name
     */
    this.getActivePage = function getActivePage() { return _activePage; };

    /**
     * Get a currently active component by componentId
     */
    this.getActiveComponent = function getActiveComponent(componentId) { return _componentMap[componentId]; };

    /**
     * Get an info string of components that are available.
     */
    this.getActiveComponentList = function getActiveComponentList() {
      return _.map(_componentMap, function(component) { return component });
    };

    /**
     * Get the containing componentId for the given jQuery DOM element reference
     */
    this.findComponentId = function findComponentId(jqElement) {
      if (!jqElement || !jqElement.length) { return null; }     // If no element provided, then null

      // Return the componentId or the recursively found value
      return jqElement.data().wilsonComponentId || this.findComponentId(jqElement.parent());
    };

    /**
     * Destroy an active component
     */
    this.destroyComponent = function destroyComponent(componentId) {
      var component = this.getActiveComponent(componentId);

      // Remove the component if it exists
      if (component) { component.$destroy(); }
    };

    /**
     * Declare special route handler service on Angular.
     *
     * @param definition  - Array or Function definition of the service
     */
    this.router = function defineRouter(definition) { this.service('WilsonRouteService', definition); };

    /**
     * Declare a filter on Angular.
     *
     * @param name          - Filter Name
     * @param definition    - Array or Function definition of the filter
     */
    this.filter = function defineFilter(name, definition) {
      validateDefinition('filter', name, definition);

      var filterName = _.camelCase(name);

      if (!_cache.filters[filterName]) {

        var provider = _filterProvider || _module;
        var filter   = provider.filter || provider.register;

        filter(filterName, _.isArray(definition) ? definition : function() {
          return definition;
        });

        // Mark as cached
        _cache.filters[filterName] = true;
      }
    };

    /**
     * Declare an element-based directive on Angular. This element will represent
     * a reusable component. Component definitions must have an explicit controller declared.
     *
     * @param name          - Component Name
     * @param definition    - Object definition of the component directive
     */
    this.component = function defineComponent(name, config) {
      if (!_appConfig) { return _preloadQueue.push({ type: 'component', args: arguments }); }

      var directiveName = getDirectiveName(_appConfig.app.selectors.component, name);

      if (!_cache.components[directiveName]) {

        // Initialize the config with defaults
        var fullConfig = {
          restrict:       'EA',
          templateUrl:    name.toLowerCase(),
          replace:        true,
          scope:          {}
        };

        // Extend default parameters
        _.extend(fullConfig, config);

        // Validate Component Definition
        validateDefinition('component', name, fullConfig.controller);

        // Build and set controller and link method -- passing the original controller and link
        fullConfig.controller = createComponentController(name, fullConfig.controller, fullConfig);

        // Create a new directive for the component
        var provider = _compileProvider || _module;
        provider.directive(directiveName, function() { return fullConfig; });

        // Mark as cached
        _cache.components[directiveName] = true;
      }
    };

    /**
     * Declare an attribute-based directive on Angular.
     *
     * @param name          - Behavior Name
     * @param definition    - Function or Array definition of the behavior directive
     */
    this.behavior = function defineBehavior(name, definition) {
      if (!_appConfig) { return _preloadQueue.push({ type: 'behavior', args: arguments }); }

      var directiveName = getDirectiveName(_appConfig.app.selectors.behavior, name);

      if (!_cache.behaviors[directiveName]) {
        // Validate Directive Definition
        validateDefinition('behavior', name, definition)

        // Determine if we are loading this dynamically with compileProvider
        var provider = _compileProvider || _module;

        // Create a new directive for this behavior
        provider.directive(directiveName, createBehaviorDefinition(definition));

        // Mark as cached
        _cache.behaviors[directiveName] = true;
      }
    };

    /**
     * Declare a service on Angular.
     *
     * @param name          - Service Name
     * @param definition    - Array or Function definition of the service
     */
    this.service = function defineService(name, definition) {
      validateDefinition('service', name, definition);

      if (!_cache.services[name]) {
        var provider = _provider || _module;
        provider.factory(name, definition);

        // Mark as cached
        _cache.services[name] = true;
      }
    };

    // Added convenience Aliases for services
    this.class    = this.service;
    this.factory  = this.service;
    this.utility  = this.service;
    this.resource = this.service;

    // endregion

    //    ___       _ _   _       _ _          _   _
    //   |_ _|_ __ (_) |_(_) __ _| (_)______ _| |_(_) ___  _ __
    //    | || '_ \| | __| |/ _` | | |_  / _` | __| |/ _ \| '_ \
    //    | || | | | | |_| | (_| | | |/ / (_| | |_| | (_) | | | |
    //   |___|_| |_|_|\__|_|\__,_|_|_/___\__,_|\__|_|\___/|_| |_|
    //
    // region initialization

    // Angular Module Config Routine
    _module.config(['$interpolateProvider', '$locationProvider', 'i18nextServiceProvider', '$routeProvider', 'localStorageServiceProvider', '$compileProvider', '$controllerProvider', '$filterProvider', '$provide',
      function wilsonConfig($interpolateProvider, $locationProvider, i18nextServiceProvider, $routeProvider, localStorageServiceProvider, $compileProvider, $controllerProvider, $filterProvider, $provide) {

        var config = angular.wilson.config;

        // Store our Providers
        _compileProvider    = $compileProvider;
        _controllerProvider = $controllerProvider;
        _filterProvider     = $filterProvider;
        _provider           = $provide;

        // Disable Class/Comment and Debug Info for Performance
        _compileProvider.commentDirectivesEnabled(false);
        _compileProvider.cssClassDirectivesEnabled(false);
        _compileProvider.debugInfoEnabled(config.debugInfoEnabled);

        // use square brackets so they don't collide with handlebars;
        // plus, square goes with angular... get it?
        $interpolateProvider.startSymbol('[[');
        $interpolateProvider.endSymbol(']]');

        // Configure the i18n provider
        i18nextServiceProvider.init({
          lng: config.i18n.lng,
          resStore: config.i18n.resStore,
          ns: {
            namespaces: config.i18n.namespaces
          },
          fallbackToDefaultNS: false,
          nsseparator: ':::',
          keyseparator: '::',
          useCookie: false,
          useLocalStorage:            config.i18n.useLocalStorage, // need to be true in production
          localStorageExpirationTime: config.i18n.localStorageExpirationTime,
          supportedLngs:              _.map(config.i18n.supportedLngs, 'locale'),
          languageData:               config.i18n.supportedLngs,
          fallbackLng:                config.i18n.fallbackLng,
          sendMissing:                config.i18n.sendMissing, // need to be false in prod
          sendMissingTo: 'all',
          resPostPath: '/locales/add/__lng__/__ns__',
          resSetPath: '/client/locales/__lng__/__ns__.json',
          resGetPath: '/client/locales/__lng__/__ns__.json'
        });

        localStorageServiceProvider.setPrefix(config.app.localStoragePrefix || 'wilson');

        $locationProvider.html5Mode(true).hashPrefix('!');

        // Declare Routes on Angular
        defineAppRoutes(config.routes, $routeProvider);
      }
    ]);

    // Angular Module Config Routine
    _module.run(['$rootScope', '$templateCache', '$location', '$timeout', 'WilsonUtils', 'WilsonLogger', 'ComponentLoaderService',
      function wilsonRun($rootScope, $templateCache, $location, $timeout, WilsonUtils, WilsonLogger, ComponentLoaderService) {

        // Local No Operation Function
        var noop = function() {};

        // Decorate utilities and logger onto this wilson instance
        _instance.utils = WilsonUtils;
        _instance.log   = WilsonLogger;

        //   ____             _     ____                         _   _      _
        //  |  _ \ ___   ___ | |_  / ___|  ___ ___  _ __   ___  | | | | ___| |_ __   ___ _ __ ___
        //  | |_) / _ \ / _ \| __| \___ \ / __/ _ \| '_ \ / _ \ | |_| |/ _ \ | '_ \ / _ \ '__/ __|
        //  |  _ < (_) | (_) | |_   ___) | (_| (_) | |_) |  __/ |  _  |  __/ | |_) |  __/ |  \__ \
        //  |_| \_\___/ \___/ \__| |____/ \___\___/| .__/ \___| |_| |_|\___|_| .__/ \___|_|  |___/
        //                                         |_|                       |_|
        // region rootScope helpers

        // Set Default Page Title  TODO: Drive this from a config setting
        $rootScope.page = { title: 'Wilson' };

        /**
         * Method to trigger an angular digest.
         *
         * @param fn
         */
        $rootScope.triggerDigest = function rootTriggerDigest() { return $timeout(noop); };

        /**
         * Method to bind a given function and context to run and then trigger an angular digest cycle.
         *
         * @param method
         * @param context
         * @returns {*}
         */
        $rootScope.bindToDigest = function rootBindToDigest(method, context) {
          context = context || this;

          var bound = function() {
            method.apply(context, arguments);
            $rootScope.triggerDigest();
          };

          return method ? bound : noop;
        };

        // endregion

        //   ____           _                 _ _
        //  |  _ \ _ __ ___| | ___   __ _  __| (_)_ __   __ _
        //  | |_) | '__/ _ \ |/ _ \ / _` |/ _` | | '_ \ / _` |
        //  |  __/| | |  __/ | (_) | (_| | (_| | | | | | (_| |
        //  |_|   |_|  \___|_|\___/ \__,_|\__,_|_|_| |_|\__, |
        //                                              |___/
        // region preloading

        // Declare any pre-loaded items on this wilson instance
        _.each(_preloadQueue, function(item) { _instance[item.type].apply(_instance, item.args); });

        // Preload any marked route components
        var cleanup = $rootScope.$on('$locationChangeSuccess', function() {
          var loaded = {};
          _.each(_instance.config.routes, function(route) {
            if (route.preload && !loaded[route.component]) {
              loaded[route.component] = ComponentLoaderService.load(route.component);
            }
          });

          cleanup();  // Remove this one-time handling operation
        });

        // endregion

      }
    ]);

    // endregion

  }

  // endregion

  /**
   * Wilson Angular Module Declaration and Framework Instantiation
   */
  var wilsonModule  = angular.module('wilson', ['ngRoute', 'LocalStorageModule', 'wilson.config', 'wilson.router', 'wilson.i18n', 'wilson.utils', 'wilson.decorators', 'wilson.logger', 'wilson.coreTemplates']);
  var wilson        = new Wilson(wilsonModule);

  // Set Global window and angular instance references
  angular.wilson = window.wilson = wilson;

})(this, angular, _);


text:
<title>IM_BENCHMARK(3) manual page</title>

Table of Contents

Name

im_benchmark - do something complicated

Synopsis

#include <vips/vips.h>

 int im_benchmark( IMAGE *in, IMAGE *out )

Description

im_benchmark(3)

performs a complicated operation (based on a real example of VIPS usage)
on a  LABPACK image. It is useful for benchmarking the VIPS threading system.
It  should speed up (mostly) linearly with more CPUs.

Returned Values

The
function returns 0 on success and -1 on error.

Table of Contents

Name

Synopsis

Description

Returned Values

redpajama_set_name: RedPajamaGithub


text:
<f:layout name="WS-Sidebar" />

		<f:section name="Title">Gruppe bearbeiten</f:section>

		<f:section name="Content">
			<f:form action="aktualisieren" object="{group}" objectName="group" class="form-horizontal" id="form-aktualisieren">

					Stamm

						<f:form.textfield class="form-control" value="{group.superordinatedUnit.name}" disabled="disabled" />
						<f:form.hidden property="superordinatedUnit" id="superordinatedUnit" />

				<f:form.validationResults for="group.name">
					<f:if condition="{validationResults.flattenedErrors}">
						<f:then>

						</f:then>
						<f:else>

						</f:else>
					</f:if>
				</f:form.validationResults>
					Name

						<f:form.textfield class="form-control" property="name" id="name" />
				<f:form.validationResults for="group.name">
					<f:if condition="{validationResults.flattenedErrors}">
						<f:for each="{validationResults.errors}" as="error">
							<f:translate id="{error.code}" arguments="{error.arguments}" locale="de" package="Neos.Flow" source="ValidationErrors">{error.message}</f:translate>
						</f:for>
					</f:if>
				</f:form.validationResults>

				<f:form.validationResults for="group.slug">
					<f:if condition="{validationResults.flattenedErrors}">
						<f:then>

						</f:then>
						<f:else>

						</f:else>
					</f:if>
				</f:form.validationResults>
					Kurzname

						<f:form.textfield class="form-control" property="slug" id="slug" />
				<f:form.validationResults for="group.slug">
					<f:if condition="{validationResults.flattenedErrors}">
						<f:for each="{validationResults.errors}" as="error">
							<f:translate id="{error.code}" arguments="{error.arguments}" locale="de" package="Neos.Flow" source="ValidationErrors">{error.message}</f:translate>
						</f:for>
					</f:if>
				</f:form.validationResults>

			</f:form>

		</f:section>

		<f:section name="Sidebar">

Optionen

			<f:form.button type="submit" form="form-aktualisieren" class="btn btn-block btn-primary">Gruppe aktualisieren</f:form.button>
			<f:render partial="OptionsCancel" />
		</f:section>


text:
class AcceptHelper
  include Redmine::I18n

  def self.generate_accept_button (issue)
     # accepting closed tickets should not be possible
     status_id =  issue[:status_id]
     issue_status = IssueStatus.find(status_id)
     if issue_status[:is_closed] == true
       return ""
     end

     accept_status_name = Setting.plugin_accept[:accept_status]
     individual_status = Setting.plugin_accept[:accept_individual_status]
     # if accept_status is defined per tracker, use the specific accept_status
     if individual_status == 'individual_status_for_each_tracker'
       tracker_id = Tracker.where(id: issue.tracker_id)[0].id
       accept_status_name = Setting.plugin_accept['accept_status_' + tracker_id.to_s]
     end
     accept_status =  IssueStatus.where(name: accept_status_name)

     # generate the button code - since there appears to be no explicit hook for the menu buttons, use js to insert the button
     if accept_status.empty?
       accept_id = IssueStatus.first[:id].to_s
     else
       accept_id = accept_status[0][:id].to_s
     end
     user_id = User.current.id.to_s

     html = ''

      return html
  end
end


text:
using GhostRunner.Models;
using GhostRunner.SL;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GhostRunner.Tests.SL
{
    [TestClass]
    public class PackageCacheServiceTests
    {
        private PackageCacheService _packageCacheService;

        [TestInitialize]
        public void Initialize()
        {
            _packageCacheService = new PackageCacheService(new TestContext());
        }

        [TestMethod]
        public void GetAllProjectPackageCache()
        {
            IList<PackageCache> ghostRunnerPackageCache = _packageCacheService.GetAllProjectPackageCache("d4708c0d-721e-426e-b49e-35990687db22");

            Assert.AreEqual(2, ghostRunnerPackageCache.Count);
        }

        [TestMethod]
        public void UpdatePackageCache()
        {
            IList<PackageCache> ghostRunnerPackageCache = _packageCacheService.GetAllProjectPackageCache("d4708c0d-721e-426e-b49e-35990687db22");

            Assert.AreEqual(2, ghostRunnerPackageCache.Count);

            Assert.IsTrue(ghostRunnerPackageCache[0].Store);

            _packageCacheService.UpdatePackageCache(ghostRunnerPackageCache[0].ExternalId, false);

            IList<PackageCache> updatedGhostRunnerPackageCache = _packageCacheService.GetAllProjectPackageCache("d4708c0d-721e-426e-b49e-35990687db22");

            Assert.AreEqual(2, updatedGhostRunnerPackageCache.Count);

            Assert.IsFalse(updatedGhostRunnerPackageCache[0].Store);
        }

        [TestMethod]
        public void DeletePackageCache()
        {
            IList<PackageCache> ghostRunnerPackageCache = _packageCacheService.GetAllProjectPackageCache("d4708c0d-721e-426e-b49e-35990687db22");

            Assert.AreEqual(2, ghostRunnerPackageCache.Count);

            _packageCacheService.DeletePackageCache(ghostRunnerPackageCache[0].ExternalId, String.Empty);

            IList<PackageCache> updatedGhostRunnerPackageCache = _packageCacheService.GetAllProjectPackageCache("d4708c0d-721e-426e-b49e-35990687db22");

            Assert.AreEqual(1, updatedGhostRunnerPackageCache.Count);
        }
    }
}


text:
''' All config variables
'''
from os import environ
ENVIRONMENT_VAR_PREFIX = 'LUNCHTIME_'

class Config(object):
    ''' Class to wrap around config variables
    '''
    def __init__(self):
        ''' Parse os.environ and set all members. The environment variables can have the same
            format as the variable names below, but prefixed by LUNCHTIME_
        '''
        self.ALLOWED_SLACK_ROOMS = ['lunch', 'lunch-test']
        self.CHERRYPY_PORT = 9999
        self.SLACK_REQUEST_TOKEN = ''
        self.INCOMING_WEBOOK_URL = ''
        for name, value in environ.iteritems():
            name = name.replace(ENVIRONMENT_VAR_PREFIX, '')
            if hasattr(self, name):
                setattr(self, name, value)


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

<title>C-Index</title>
<meta name="date" content="2016-03-04">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C E F G H I J L M N P Q R S T X

C

clearJourneys() - Method in class se.mah.k3lara.skaneAPI.model.Journeys

clearJourneys() - Method in class se.mah.k3lara.skaneAPI.model.Lines

compareTo(Station) - Method in class se.mah.k3lara.skaneAPI.model.Station

compareTo(Station) - Method in class se.mah.k3lara.skaneAPI.view.Station

Constants - Class in se.mah.k3lara.skaneAPI.control

Constants() - Constructor for class se.mah.k3lara.skaneAPI.control.Constants

A B C E F G H I J L M N P Q R S T X

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
include(CheckCCompilerFlag)

macro(add_compiler_flags)
	foreach(flag ${ARGN})
		string(REGEX REPLACE "[-.+/:= ]" "_" _flag_esc "${flag}")

		check_c_compiler_flag("${flag}" check_c_compiler_flag_${_flag_esc})

		if (check_c_compiler_flag_${_flag_esc})
			set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}")
		endif()
	endforeach()
endmacro()


text:
require './lib/player'

class QPlayer < Player
  attr_reader :actions, :q_table,
    :learning_rate, :discount, :epsilon, :r,
    :old_score, :old_state, :action_taken_index

  # constructor
  def initialize(game)
    super(game)

    @actions = %i[ left right ]

    @learning_rate = 0.2
    @discount = 0.9
    @epsilon = 0.9

    @r = Random.new
  end

  # This method will be called on game start, the returned string will be printed
  #
  # @return [String]
  def start
    Signal.trap('INT') do # SIGINT = control-C
      game.stop!
    end

    <<-HINT.strip_heredoc.freeze
      Play the game with <QPlayer>. Lean back and watch the algorithm to learn playing the game.
      Quit game: [ctrl]+[c]
    HINT
  end

  # get the AI's input
  #
  # @return [Symbol] one of :left, :right, (:exit)
  def input
    sleep 0.05 # to follow the computed actions

    if q_table.nil?
      initialize_random_q_table
    else
      calculate_q_table_state
    end

    # capture current stuff
    @old_score = game.score
    @old_state = x

    # maybe do something random (chance: epsilon)
    @action_taken_index =
      if r.rand > epsilon
        r.rand(actions.length).round
      else
        q_table[x].each_with_index.max[1]
      end

    actions[action_taken_index]
  end

  # This method will be called on game stop, the returned string will be printed
  #
  # @return [String]
  def stop
    <<~TEXT.strip_heredoc
      Q-Table:

      #{([:state] + actions).flatten}
      #{q_table.length.times.map { |i| ([i] + q_table[i]).flatten.to_s }.join("\n")}

      #{super}
    TEXT
  end

  private

  def calculate_q_table_state
    reward =
      if old_score < game.score
        1
      elsif old_score > game.score
        -1
      else
        0
      end

    q_table[old_state][action_taken_index] =
      q_table[old_state][action_taken_index] + learning_rate * (
      reward + discount * q_table[x].max - q_table[old_state][action_taken_index]
      )
  end

  # initialize the Q table
  def initialize_random_q_table
    @q_table = Array.new(game.map_size) { Array.new(actions.length) }

    game.map_size.times do |s|
      actions.length.times do |a|
        q_table[s][a] = r.rand
      end
    end
  end
end


text:
package reseller.pages;

import org.openqa.selenium.WebDriver;

/**
 * Created by rusu on 3/24/15.
 */
public class ModalPendingRequest extends BasePage {
    public ModalPendingRequest(WebDriver driver) {
        super(driver);
    }
}


text:
ION.append({

	/**
	 * Ionize notification window
	 * Launch a notification window creation
	 *
	 * @param	type    string 	    type of notification. Can be : error, notice, success
	 * @param	message string	    Notification message
	 */
	notification: function(type, message)
	{
		new MUI.Window({
			loadMethod: 'html',
			closeAfter: 2500,
			type: 'notification',
			cssClass: 'notification ',
			content: '
' + message + '
',
			width: 350,
			height: 50,
			y: 1,
			padding:  { top: 15, right: 12, bottom: 5, left: 12 },
			shadowBlur: 5,
			bodyBgColor: [250, 250, 250]
		});
	},

	/**
	 * Ionize Add Confirmation modal window
	 *
	 * @param	id          string		Window ID
	 * @param	button      string		Button or any element ID on wich add the link
	 * @param	callback    string		URL or JS function called in case of user confirmation
	 * @param	msg         string		Element name to update after the request success
	 * @param	options     object		options
	 *
	 */
	addConfirmation: function(id, button, callback, msg, options)
	{
		$(button).addEvent('click', function(e)
		{
			e.stop();
			ION.confirmation(id, callback, msg, options);
		});
	},

	/**
	 * Ionize Confirmation modal window
	 * Opens a windows with yes / no buttons
	 *
	 * @param	id          string		Window ID
	 * @param	callback    string		URL or Callback JS function to call if yes answer
	 * @param	msg         string		Message
	 * @param	wOptions    object		Window extended options
	 *
	 */
	confirmation: function(id, callback, msg, wOptions)
	{

		// Get the buttons container
		wButtons = ION._getConfirmationButtons(id, callback);

		// Window question message
		var wMsg = (Lang.get(msg)) ? Lang.get(msg) : msg ;

		// Message HTML Element & window content container
		var wMessage = new Element('div', {'class':'message'}).set('text', wMsg);		// Message
		var wContent = new Element('div').adopt(wMessage, wButtons);					// Windows content final container

		// Window options
		var options = {
			id: 'w' + id,
			content: wContent,
			title: Lang.get('ionize_modal_confirmation_title'),
			cssClass:'confirmation',
			draggable: true,
			y: 150,
			padding: { top: 15, right: 15, bottom: 8, left: 15 }
		}

		// Extends the window options
		if (typeOf(wOptions) != 'null') {options =  Object.append(options, wOptions);}

		// Open the confirmation modal window
		new MUI.Modal(options);
	},

	/**
	 * Modal windows
	 *
	 */
	error: function(msg, wOptions)
	{
		var options = ION._getModalOptions('error', msg);
		new MUI.Modal(options);
	},

	alert: function(msg, wOptions)
	{
		var options = ION._getModalOptions('alert', msg);
		new MUI.Modal(options);
	},

	information: function(msg, wOptions)
	{
		var options = ION._getModalOptions('information', msg);
		new MUI.Modal(options);
	},

	/**
	 * Ionize generic form window
	 * Use to load a window which contains a form
	 *
	 * @param	string		Window ID.
	 * @param	string		Window Form ID
	 * @param	string		Lang translation key or string as title of the window
	 * @param	string		URL called in case of form validation
	 * @param	object		Window extended options
	 *
	 */
	formWindow: function(id, form, title, wUrl, wOptions, data)
	{
		// Cleans URLs
		wUrl = ION.cleanUrl(wUrl);

		// Window options
		var options  =
		{
			id: 'w' + id,
			title: (typeOf(Lang.get(title)) == 'null') ? title : Lang.get(title),
			container: document.body,
			content: {
				url: admin_url + wUrl,
				method:'post',
				data: data,
				onLoaded: function(element, content)
				{
					// Get the form action URL and adds 'true' so the transport is set to XHR
					var formUrl = $(form).getProperty('action');

					// Set the form submit button action and send the DOM Element to update with the according URL
					ION.setFormSubmit(form, ('bSave' + id), formUrl);

					// Add the cancel event if cancel button exists
					// All buttons name starts with 'b'
					if (bCancel = $('bCancel' + id))
					{
						bCancel.addEvent('click', function(e)
						{
							e.stop();
							MUI.get('w' + id).close();
						});
					}

					// Event on save button
					/*
					if (bSave = $('bSave' + id))
					{
						bSave.addEvent('click', function(e)
						{
							e.stop();

							// closeFunc is needed for IE8
							var closeFunc = function()
							{
								MUI.get('w' + id).close();
							}
							closeFunc.delay(50);
						});
					}
					*/

					// Window resize
					if (typeOf(wOptions) != 'null' && wOptions.resize == true)
					{
						ION.windowResize(id);
					}
				}
			},
			padding: { top: 12, right: 12, bottom: 10, left: 12 },
			maximizable: false,
			contentBgColor: '#fff'
		};

		// Extends the window options
		if (typeOf(wOptions) != 'null') { options =  Object.append(options, wOptions);}

		// Window creation
		new MUI.Window(options);
	},

	/**
	 * Opens a data window, without buttons
	 * Usefull for editing a list
	 *
	 */
	dataWindow: function(id, title, wUrl, wOptions, data)
	{
		// Cleans URLs
		wUrl = ION.cleanUrl(wUrl);

		var options  =
		{
			id: 'w' + id,
			title: (typeOf(Lang.get(title)) == 'null') ? title : Lang.get(title),
			container: document.body,
//			evalResponse: true,
			content: {
				url: admin_url + wUrl,
				data: data,
				method: 'post',
				onLoaded: function(element, content)
				{
					// Window resize
					if (typeOf(wOptions) != 'null' && wOptions.resize == true)
					{
						ION.windowResize(id);
					}
				}
			},
			width: 310,
			height: 130,
			y: 80,
			padding: { top: 12, right: 12, bottom: 10, left: 12 },
			maximizable: false,
			contentBgColor: '#fff'
		};

		// Memorize and restore Size & Position
		if (wOptions && wOptions.memorizeSize == true)
		{
			if (Cookie.read('w' + id))
			{
				var cookie = new Hash.Cookie('w' + id, {duration: 365});

				wOptions =  Object.append(wOptions,
				{
					'width': cookie.get('width'),
					'height': cookie.get('height'),
					'y': cookie.get('top'),
					'x': cookie.get('left')
				});
			}

			wOptions.onResize = function()
			{
				var cookie = new Hash.Cookie(this.windowEl.id, {duration: 365});
				cookie.erase();
				cookie.extend(this.windowEl.getCoordinates());
			}
		}

		// Extends the window options
		if (typeOf(wOptions) != 'null') { options = Object.append(options, wOptions);}

		// Window creation
		return new MUI.Window(options);
	},

	_getModalOptions: function(type, msg)
	{
		// Window message
		var wMsg = (Lang.get(msg)) ? Lang.get(msg) : msg ;

		var btnOk = new Element('button', {'class':'button yes right mr35'}).set('text', Lang.get('ionize_button_ok'));

		var button = new Element('div', {'class':'buttons'}).adopt(btnOk);

		// Message HTML Element & window content container
		var wMessage = new Element('div', {'class':'message'}).set('html', wMsg);
		var wContent = new Element('div').adopt(wMessage, button);

		// Window options
		var id = new Date().getTime();
		var options = {
			id: 'w' + id,
			content: wContent,
			title: Lang.get('ionize_modal_' + type + '_title'),
			cssClass: type,
			draggable: true,
			y: 150,
			padding: { top: 15, right: 15, bottom: 8, left: 15 }
		}

		// Event on btn No : Simply close the window
		btnOk.addEvent('click', function()
		{
			MUI.get('w' + id).close();
		}.bind(this));

		return options;
	},

	/**
	 * Returns the buttons yes/no HTMLDOMElement
	 *
	 * @param	string		Window ID (to link with the close button)
	 * @param	string		URL or Callback JS function to call if yes answer
	 * @param	string		Element to update after url completion
	 * @param	string		URL of the update element
	 *
	 */
	_getConfirmationButtons:  function(id, callback)
	{
		// Btn Yes / No creation
		var btnYes = new Element('button', {'class':'button yes right'}).set('text', Lang.get('ionize_button_confirm'));
		var btnNo = new Element('button', {'class':'button no right'}).set('text', Lang.get('ionize_button_cancel'));

		// Event on btn No : Simply close the window
		btnNo.addEvent('click', function()
		{
			MUI.get('w' + id).close();
		}.bind(this));

		// Event on btn Yes
		btnYes.addEvent('click', function()
		{
			/*
			 * Check if callback is an  URL or a JS callback function
			 * No RegExp check on URL because some URL can be passed without "http://"
			 * if fact you wish to use a regexp : var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
			 * An URL is supposing containing "/"
			 * Case URL : 		Form sending
			 * Case Callback : 	Execution of callback function
			 *
			 */
			// URL case
			if ( (callback + '').indexOf('/') > -1 )
			{
				if (typeOf(callback) != 'function')
				{
					// Send the standard form object
					ION.sendForm(callback);
				}
				else
				{
					callback();
				}
			}
			// Callback case
			else
			{
				callback();
			}

			// Close the modal window
			MUI.get('w' + id).close();

		}.bind(this));

		// Buttons container
		return new Element('div', {'class':'buttons'}).adopt(btnYes, btnNo)
	},

	/**
	 * Resizes one window based on its content
	 *
	 * @param	String		Windows ID, without the Mocha prefix (w)
	 *
	 */
	windowResize: function(id, size, resize, centered )
	{
		var mps = $('mainPanel').getSize();
		var window = $('w' + id).retrieve('instance');
		var windowEl = $('w' + id).getElement('.mochaContent');

		// resize = (typeOf(resize) == 'null') ? 'both' : resize;
		// var resizeHeight = !!(resize == 'both' || resize == 'height');
		// var resizeWidth = !!(resize == 'both' || resize == 'width');
		var centered = !! (typeOf(centered) == 'null');

		// windows content size
		var cs = false;
		var gotSize = windowEl.getSize();

		if (typeOf(size) == 'object')
		{
			cs = {};
			if (typeOf(size.width) != 'null') { cs['x'] = size.width; } else { cs['x'] = gotSize.x };
			if (typeOf(size.height) != 'null') { cs['y'] = size.height; } else { cs['y'] = gotSize.y };
		}
		else
		{
			cs = gotSize;
		}

		if ((cs.y + 80) < mps.y)
		{
			window.resize({height: cs.y + 10, width: cs.x, centered:centered, top:70 });
		}
		else
		{
			window.resize({height: mps.y - 30, width: cs.x, centered:centered, top:70 });
		}

	},

	/**
	 * Closes one window
	 *
	 * @param	Mixed	Window DOM Element or String of Complete window ID
	 *
	 */
	closeWindow: function(id)
	{
		if (typeOf(id) == 'string')
			id = $(id);

		if (typeOf(id) == 'element')
		{
			MUI.get(id).close();
		}
	}
});


text:
layout: book
title: The Markdown Guide Book
description: "Learn Markdown in 60 pages. The Markdown Guide book includes everything you need to get started and master Markdown syntax."
---

The Markdown Guide

By Matt Cone

Learn Markdown in 60 pages. The Markdown Guide book includes everything you need to get started and master Markdown syntax.

✔   Professional quality PDF and EPUB files (DRM-free)

✔   Unlimited free lifetime updates

✔   100% satisfaction guaranteed

        Buy now for $5

        Read free sample

The Markdown Guide is also available on Leanpub and Amazon.

      {% include image.html file="/assets/images/book-cover.jpg" alt="Markdown Guide book cover" class="img-fluid float-center" width="95" %}

Read by professionals working at:

Take your Markdown skills to the next level.

Master the power of Markdown and take full control of the syntax.

📚

Learn how Markdown works and dive in using an online editor.

📝

Practice using basic and extended Markdown syntax elements.

💪

Start using Markdown everywhere
for all of your writing.

What's inside.

Detailed descriptions. Clear and concise examples. Beautifully formatted pages.

        {% include image.html file="/assets/images/book-page-1.png" alt="The Markdown Guide book page one" class="img-fluid border rounded" width="90" lazy="yes" %}

        {% include image.html file="/assets/images/book-page-2.png" alt="The Markdown Guide book page two" class="img-fluid border rounded" width="90" lazy="yes" %}

Trusted by thousands of readers.

5 stars on Gumroad

4 stars on Amazon

4 stars on Goodreads

The Markdown Guide is hands-down the best Markdown reference.

  Michael Hartl, Founder of Learn Enough and author of the Ruby on Rails Tutorial

If you're looking for an in-depth guide for more Markdown tips and tricks, I highly recommend the unofficial but authoritative Markdown Guide.

  Justin Duke, Engineering Manager at Stripe and Founder of Buttondown

The Markdown Guide is awesome. I keep it open in a browser tab for reference while working on my guides.

  Rob Reeder, Documentation Specialist, Software Engineering Institute, CMU

If you're working with Markdown, then do yourself a favour and check out The Markdown Guide... It's excellent.

  Matthew Setter, via Twitter

A terrific reference—straightforward and well organized, briskly paced, and featuring a spot-on instructive tone that conveys friendly engagement.

  David Buck, Technical Writer

This book provides the right amount of information to learn Markdown and I highly recommend it!

  Mohamad Kalaaji, via Goodreads

I've found this very simple guide to Markdown syntax very useful in a pinch.

  Morgan Thompson, via Twitter

Well done! This is an incredibly valuable and well-done resource. It does a great job of educating without becoming too overwhelming or too narrowly focused on one application of Markdown.

  nxprefect, via Reddit

100% satisfaction guaranteed.

If you're not completely satisfied with The Markdown Guide, I'll refund your money, no questions asked.

Buy now for $5

About the Author

Matt Cone is a technical writer at Fastly. He has experience creating documentation for organizations like Linode and the U.S. Department of Health and Human Services. Matt's first book, Master Your Mac, was published by No Starch Press. To get in touch with Matt, visit https://www.mattcone.com.

      {% include image.html file="/assets/images/mattcone.jpg" alt="Matt Cone" class="img-fluid border rounded" width="90" lazy="yes" %}


text:
Danilo Correa <danilosilva87@gmail.com>
--FILE--
<?php

declare(strict_types=1);

require 'vendor/autoload.php';

use Respect\Validation\Exceptions\ExtensionException;
use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Validator as v;

try {
    v::extension('png')->check('filename.txt');
} catch (ExtensionException $exception) {
    echo $exception->getMessage() . PHP_EOL;
}

try {
    v::not(v::extension('gif'))->check('filename.gif');
} catch (ExtensionException $exception) {
    echo $exception->getMessage() . PHP_EOL;
}

try {
    v::extension('mp3')->assert('filename.wav');
} catch (NestedValidationException $exception) {
    echo $exception->getFullMessage() . PHP_EOL;
}

try {
    v::not(v::extension('png'))->assert('tests/fixtures/invalid-image.png');
} catch (NestedValidationException $exception) {
    echo $exception->getFullMessage() . PHP_EOL;
}
?>
--EXPECT--
"filename.txt" must have "png" extension
"filename.gif" must not have "gif" extension
- "filename.wav" must have "mp3" extension
- "tests/fixtures/invalid-image.png" must not have "png" extension


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Salix Media | Projects | Qolorizer</title>
    <link rel="icon" type="image/png" href="/images/favicon.png" />
    <link rel="stylesheet" href="scripts/bgrins-spectrum-ed52c1c/spectrum.css" />
    <link rel="stylesheet" href="styles/main.css" />

          OPEN SOURCE PROJECTS

Qolorizer demo

        When you click the  Colorize!
         button, colorized versions of the left-hand images will
        be requested from the server. The normal and recommended
        behavior of the app is to save colorized images in a
        designated directory, so that they don't need to constantly be
        regenerated. However, for purposes of this demo, the
        app is configured to generate new images for each request.

Stored greyscale images

          <form>

                1. Choose a color.

              <input id="colorpicker"/>

                2. Choose a blend mode.

                <input type="radio" name="mode-select" id="mode-normal" value="normal" checked="checked"/>
                Normal

                <input type="radio" name="mode-select" id="mode-multiply" value="multiply"/>
                Multiply

                <input type="radio" name="mode-select" id="mode-screen" value="screen"/>
                Screen

                <input type="radio" name="mode-select" id="mode-overlay" value="overlay"/>
                Overlay

                <input type="radio" name="mode-select" id="mode-darken" value="darken-only"/>
                Darken Only

                <input type="radio" name="mode-select" id="mode-lighten" value="lighten-only"/>
                Lighten Only

                <input type="radio" name="mode-select" id="mode-dodge" value="dodge"/>
                Dodge

                <input type="radio" name="mode-select" id="mode-burn" value="burn"/>
                Burn

                <input type="radio" name="mode-select" id="mode-hardlight" value="hard-light"/>
                Hard Light

                <input type="radio" name="mode-select" id="mode-softlight" value="soft-light"/>
                Soft Light

                <input type="radio" name="mode-select" id="mode-difference" value="difference"/>
                Difference

                <input type="radio" name="mode-select" id="mode-exclusion" value="exclusion"/>
                Exclusion

                <input type="radio" name="mode-select" id="mode-hue" value="hue"/>
                Hue

                <input type="radio" name="mode-select" id="mode-saturation" value="saturation"/>
                Saturation

                <input type="radio" name="mode-select" id="mode-color" value="color"/>
                Color

                <input type="radio" name="mode-select" id="mode-luminosity" value="luminosity"/>
                Luminosity

                  (For a simple color change, Screen, Lighten Only, and Dodge are good choices)

              <input type="button" value="3. Colorize!" id="colorize-button"/>

          </form>

Colorized on demand

        Copyright © 2014 by Salix Media.


text:
package com.javachen.service;

import com.javachen.model.Idea;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface IdeaService {

    List<Idea> getIdeas();

    @Transactional
    Idea addIdea(Idea idea);

    @Transactional
    Idea updateIdea(Idea idea);

    @Transactional
    void deleteIdea(Idea idea);
}


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

001
018
019package org.apache.hadoop.record;
020
021import java.io.InputStreamReader;
022import java.io.InputStream;
023import java.io.IOException;
024import java.io.PushbackReader;
025import java.io.UnsupportedEncodingException;
026
027import org.apache.hadoop.classification.InterfaceAudience;
028import org.apache.hadoop.classification.InterfaceStability;
029
030/**
031 * @deprecated Replaced by <a href="http://hadoop.apache.org/avro/">Avro</a>.
032 */
033@Deprecated
034@InterfaceAudience.Public
035@InterfaceStability.Stable
036public class CsvRecordInput implements RecordInput {
037
038  private PushbackReader stream;
039
040  private class CsvIndex implements Index {
041    @Override
042    public boolean done() {
043      char c = '\0';
044      try {
045        c = (char) stream.read();
046        stream.unread(c);
047      } catch (IOException ex) {
048      }
049      return (c == '}') ? true : false;
050    }
051    @Override
052    public void incr() {}
053  }
054
055  private void throwExceptionOnError(String tag) throws IOException {
056    throw new IOException("Error deserializing "+tag);
057  }
058
059  private String readField(String tag) throws IOException {
060    try {
061      StringBuilder buf = new StringBuilder();
062      while (true) {
063        char c = (char) stream.read();
064        switch (c) {
065        case ',':
066          return buf.toString();
067        case '}':
068        case '\n':
069        case '\r':
070          stream.unread(c);
071          return buf.toString();
072        default:
073          buf.append(c);
074        }
075      }
076    } catch (IOException ex) {
077      throw new IOException("Error reading "+tag);
078    }
079  }
080
081  /** Creates a new instance of CsvRecordInput */
082  public CsvRecordInput(InputStream in) {
083    try {
084      stream = new PushbackReader(new InputStreamReader(in, "UTF-8"));
085    } catch (UnsupportedEncodingException ex) {
086      throw new RuntimeException(ex);
087    }
088  }
089
090  @Override
091  public byte readByte(String tag) throws IOException {
092    return (byte) readLong(tag);
093  }
094
095  @Override
096  public boolean readBool(String tag) throws IOException {
097    String sval = readField(tag);
098    return "T".equals(sval) ? true : false;
099  }
100
101  @Override
102  public int readInt(String tag) throws IOException {
103    return (int) readLong(tag);
104  }
105
106  @Override
107  public long readLong(String tag) throws IOException {
108    String sval = readField(tag);
109    try {
110      long lval = Long.parseLong(sval);
111      return lval;
112    } catch (NumberFormatException ex) {
113      throw new IOException("Error deserializing "+tag);
114    }
115  }
116
117  @Override
118  public float readFloat(String tag) throws IOException {
119    return (float) readDouble(tag);
120  }
121
122  @Override
123  public double readDouble(String tag) throws IOException {
124    String sval = readField(tag);
125    try {
126      double dval = Double.parseDouble(sval);
127      return dval;
128    } catch (NumberFormatException ex) {
129      throw new IOException("Error deserializing "+tag);
130    }
131  }
132
133  @Override
134  public String readString(String tag) throws IOException {
135    String sval = readField(tag);
136    return Utils.fromCSVString(sval);
137  }
138
139  @Override
140  public Buffer readBuffer(String tag) throws IOException {
141    String sval = readField(tag);
142    return Utils.fromCSVBuffer(sval);
143  }
144
145  @Override
146  public void startRecord(String tag) throws IOException {
147    if (tag != null && !tag.isEmpty()) {
148      char c1 = (char) stream.read();
149      char c2 = (char) stream.read();
150      if (c1 != 's' || c2 != '{') {
151        throw new IOException("Error deserializing "+tag);
152      }
153    }
154  }
155
156  @Override
157  public void endRecord(String tag) throws IOException {
158    char c = (char) stream.read();
159    if (tag == null || tag.isEmpty()) {
160      if (c != '\n' && c != '\r') {
161        throw new IOException("Error deserializing record.");
162      } else {
163        return;
164      }
165    }
166
167    if (c != '}') {
168      throw new IOException("Error deserializing "+tag);
169    }
170    c = (char) stream.read();
171    if (c != ',') {
172      stream.unread(c);
173    }
174
175    return;
176  }
177
178  @Override
179  public Index startVector(String tag) throws IOException {
180    char c1 = (char) stream.read();
181    char c2 = (char) stream.read();
182    if (c1 != 'v' || c2 != '{') {
183      throw new IOException("Error deserializing "+tag);
184    }
185    return new CsvIndex();
186  }
187
188  @Override
189  public void endVector(String tag) throws IOException {
190    char c = (char) stream.read();
191    if (c != '}') {
192      throw new IOException("Error deserializing "+tag);
193    }
194    c = (char) stream.read();
195    if (c != ',') {
196      stream.unread(c);
197    }
198    return;
199  }
200
201  @Override
202  public Index startMap(String tag) throws IOException {
203    char c1 = (char) stream.read();
204    char c2 = (char) stream.read();
205    if (c1 != 'm' || c2 != '{') {
206      throw new IOException("Error deserializing "+tag);
207    }
208    return new CsvIndex();
209  }
210
211  @Override
212  public void endMap(String tag) throws IOException {
213    char c = (char) stream.read();
214    if (c != '}') {
215      throw new IOException("Error deserializing "+tag);
216    }
217    c = (char) stream.read();
218    if (c != ',') {
219      stream.unread(c);
220    }
221    return;
222  }
223}


text:
===
fpc
===

Contains Fiber Photometry Camera (FPC) data.

.. toctree::
    :maxdepth: 1

    PROTODESI_FPC


text:
module Apipie
  module Params
    module DSL
      def _apipie_params_dsl_data
        @_apipie_params_dsl_data ||= _apipie_params_dsl_data_init
      end

      def _apipie_params_dsl_data_init
        @_apipie_params_dsl_data = []
      end

      # Describe method's parameter
      #
      # Example:
      #   param :greeting, String, :desc => "arbitrary text", :required => true
      #
      def param(param_name, descriptor_arg = nil, desc_or_options = nil, options = {}, &block) #:doc:
        if desc_or_options.is_a? String
          options = options.merge(:desc => desc_or_options)
        end
        _apipie_params_dsl_data << [param_name,
                                    descriptor_arg,
                                    options,
                                    block]
      end

      # +descriptor+ might be instance of Descriptor::Base or
      # something that has it in :descriptor method
      def array_of(descriptor)
        descriptor = if descriptor.is_a? Descriptor::Base
                       descriptor
                     elsif descriptor.respond_to?(:descriptor)
                       descriptor.descriptor
                     else
                       raise ArgumentError,
                             "descriptor is not a Descriptor::Base or an Object with #descriptor method"
                     end
        Descriptor::Array.new(descriptor, {})
      end
    end

  end
end


text:
using System;
using System.ComponentModel;
using System.Globalization;
using Xunit;

namespace UnitTests.Snippets.TypeConverters
{
    public sealed class TypeConverterSnippet
    {
        public TypeConverterSnippet()
        {
            TypeDescriptor.AddAttributes(typeof(SourceClass), new TypeConverterAttribute(typeof(SourceClassConverter)));
        }

        [Fact]
        public void Converter()
        {
            TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(SourceClass));
            var source = new SourceClass
            {
                FirstName = "First",
                LastName = "Last"
            };
            var target = (TargetClass)typeConverter.ConvertFrom(source);
            Assert.Equal(string.Format("{0} {1}", source.FirstName, source.LastName), target.FullName);
        }

        private class SourceClass
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }

        private sealed class SourceClassConverter : TypeConverter
        {
            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            {
                return sourceType == typeof(SourceClass);
            }

            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
            {
                var concreteValue = (SourceClass)value;
                var result = new TargetClass
                {
                    FullName = string.Format("{0} {1}", concreteValue.FirstName, concreteValue.LastName)
                };
                return result;
            }
        }

        private class TargetClass
        {
            public string FullName { get; set; }
        }
    }
}


text:
CREATE USER 'jboss'@'localhost' IDENTIFIED BY 'jboss';
GRANT ALL PRIVILEGES ON ticket.* TO 'jboss'@'localhost' WITH
GRANT OPTION;

CREATE TABLE seat_type (
id int(10) NOT NULL PRIMARY KEY auto_increment,
description varchar(50) NOT NULL,
price int(10) NOT NULL,
quantity int(10) NOT NULL
) ENGINE=InnoDB;

CREATE TABLE seat (
id int(10) NOT NULL PRIMARY KEY auto_increment,
booked Boolean,
seat_id int(10),
FOREIGN KEY (seat_id) REFERENCES seat_type (id) ON DELETE CASCADE)
ENGINE=InnoDB;


text:
// SampSharp.Streamer
// Copyright 2018 Tim Potze
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using SampSharp.Core.Natives.NativeObjects;

namespace SampSharp.Streamer.World
{
    public partial class DynamicMapIcon
    {
        protected static readonly DynamicMapIconInternal Internal = NativeObjectProxyFactory.CreateInstance<DynamicMapIconInternal>();

        public class DynamicMapIconInternal
        {
            [NativeMethod]
            public virtual int CreateDynamicMapIcon(float x, float y, float z, int type, int color, int worldid,
                int interiorid, int playerid, float streamdistance, int style, int areaid, int priority)
            {
                throw new NativeNotImplementedException();
            }

            [NativeMethod]
            public virtual int DestroyDynamicMapIcon(int iconid)
            {
                throw new NativeNotImplementedException();
            }

            [NativeMethod]
            public virtual bool IsValidDynamicMapIcon(int iconid)
            {
                throw new NativeNotImplementedException();
            }
        }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package WiredCatsControllers;

import WiredCatsEvents.SensorEvents.EventArmAngleChanged;
import WiredCatsEvents.SensorEvents.EventArmLimitReached;
import edu.wpi.first.wpilibj.AnalogChannel;
import edu.wpi.first.wpilibj.Counter;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/**
 *
 * @author Bruce Crane
 */
public class ControllerArm extends WiredCatsController {
    //private DigitalInput ls;
    private Encoder armEncoder;

    private DigitalInput limitSwitch;

    private double armAngle;

    private boolean needsReset;

    Timer timer;

    public ControllerArm(int limit)
    {
        super(limit);
        armEncoder = new Encoder(9,8);
        armAngle = armEncoder.getDistance();
        timer = new Timer();
        timer.start();

        needsReset = true;

        limitSwitch = new DigitalInput(12);

        System.out.println("[WiredCats] Arm Controller initialized.");
    }

    public void run()
    {
        //fireEvent(new EventArmAngleChanged(this, armAngle));
        armEncoder.start();

        while (true)
        {

            //System.out.println("Pot reading: " + arm.getValue());

            double currentArmAngle = armEncoder.getDistance()/100;
//            if (armAngle != currentArmAngle)
//            {
                //System.out.println("arm angle changed. " + currentArmAngle);
                armAngle = currentArmAngle;
                fireEvent(new EventArmAngleChanged(this, armAngle, timer.get()));
//            }

            if (!limitSwitch.get())
            {
                if(needsReset) {
                    armEncoder.reset();
                    needsReset = false;
                }
                fireEvent(new EventArmLimitReached(this));
            }

//            lastLimitSwitchState = limitSwitch.get();

            try {
                Thread.sleep(15);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}


text:
require 'rspec'
require 'mailcheck'

RSpec.configure do |config|
  config.color_enabled = true
  config.formatter     = 'documentation'
end


text:
uint64_t get_timestamp_ms_current(void);
uint64_t get_timestamp_ms_by_diff(uint64_t diff);

#endif      // P7R_TIMING_H_


text:
#include "nau/scene/octreeByMatScene.h"
#include "nau/render/renderManager.h"
#include "nau/material/materialGroup.h"

#include "nau/debug/profile.h"
#include "nau.h"

#include "nau/slogger.h"

using namespace nau::scene;
using namespace nau::geometry;
using namespace nau::render;
using namespace nau::material;

OctreeByMatScene::OctreeByMatScene(void) : IScenePartitioned(),
	m_SceneObjects(),
	m_pGeometry (0),
	m_BoundingBox()
{
	EVENTMANAGER->addListener("SET_POSITION", this);
	EVENTMANAGER->addListener("SET_ROTATION", this);

	m_Type = "OctreeByMatScene";

}

OctreeByMatScene::~OctreeByMatScene(void) {

}

void
OctreeByMatScene::eventReceived(const std::string &sender,
	const std::string &eventType, const std::shared_ptr<IEventData> &evt) {
	vec4 *p = (vec4 *)evt->getData();

	if (eventType == "SET_POSITION") {
		mat4 t;
		t.setIdentity();
		t.translate(p->x, p->y, p->z);
		this->setTransform(t);
	}
	if (eventType == "SET_ROTATION") {
		m_Transform.setIdentity();
		m_Transform.rotate(p->w, p->x, p->y, p->z);
		updateSceneObjectTransforms();
	}
}

mat4 &
OctreeByMatScene::getTransform() {

	return m_Transform;
}

void
OctreeByMatScene::setTransform(nau::math::mat4 &t) {

	m_Transform = t;
	updateSceneObjectTransforms();
}

void
OctreeByMatScene::transform(nau::math::mat4 &t) {

	m_Transform*= t;
	updateSceneObjectTransforms();
}

void
OctreeByMatScene::updateSceneObjectTransforms() {

    for(auto &so: m_SceneObjects)
    {
		so->updateGlobalTransform(m_Transform);
    }

	if (m_pGeometry)
		m_pGeometry->updateOctreeTransform(m_Transform);
}

void
OctreeByMatScene::build (void) {

	if (true == m_Built) {
		return ;
	}

	m_Built = true;
	// First create a list with objects that are static
	std::vector<std::shared_ptr<SceneObject>> staticObjects;

	for (auto &so : m_SceneObjects) {

		if (so->isStatic()) {
			staticObjects.push_back(so);
		}
	}

	// Create Octree's root node
	m_pGeometry = new OctreeByMat;
	m_pGeometry->setName(this->m_Name);

	// Feed the octree with each renderable
	m_pGeometry->build (staticObjects);

	// Erase the scene object afterwards
	std::vector<std::shared_ptr<SceneObject>>::iterator objIter;
	for (objIter = m_SceneObjects.begin(); objIter != m_SceneObjects.end(); ) {

		if ((*objIter)->isStatic()) {
			std::string renderableName = (*objIter)->getRenderable()->getName();
			objIter = m_SceneObjects.erase (objIter);
			RESOURCEMANAGER->removeRenderable(renderableName);
		}
	}
}

IBoundingVolume&
OctreeByMatScene::getBoundingVolume (void) {

	return m_BoundingBox;
}

void
OctreeByMatScene::compile (void) {

	if (true == m_Compiled) {
		return;
	}

	m_Compiled = true;

	if (0 != m_pGeometry) {
		m_pGeometry->_compile();
	}

	for (auto &objIter: m_SceneObjects) {
		std::vector<std::shared_ptr<MaterialGroup>> &matGroups = objIter->getRenderable()->getMaterialGroups();

		for (auto& matGroupsIter: matGroups){
			matGroupsIter->compile();
		}
	}
}

void
OctreeByMatScene::add (std::shared_ptr<SceneObject> &aSceneObject) {

	if (0 == aSceneObject->getType().compare ("OctreeNode")) {
		m_Built = true;
		if (0 == m_pGeometry) {
			m_pGeometry = new OctreeByMat;
		}
		m_pGeometry->_place (aSceneObject);
	} else {
		m_SceneObjects.push_back (aSceneObject);
	}
	aSceneObject->updateGlobalTransform(m_Transform);
	m_BoundingBox.compound (aSceneObject->getBoundingVolume());
}

 void
OctreeByMatScene::findVisibleSceneObjects (std::vector<std::shared_ptr<SceneObject>> *v, Frustum &aFrustum,
				Camera &aCamera, bool conservative) {

	if (0 != m_pGeometry) {
		m_pGeometry->_findVisibleSceneObjects (v, aFrustum, aCamera, conservative);
	}

	/* The objects NOT on the octree */
	for (auto &so:m_SceneObjects) {
		/***MARK***/ /* View Frustum Culling Test */

		int side = aFrustum.isVolumeInside (so->getBoundingVolume(), conservative);

		if (Frustum::OUTSIDE != side) {
			v->push_back (so);
		}
	}
}

 void
OctreeByMatScene::getAllObjects (std::vector<std::shared_ptr<SceneObject>> *v) {

	for (auto &so: m_SceneObjects) {
		v->push_back(so);
	}

	if (0 != m_pGeometry) {
		m_pGeometry->_getAllObjects (v);
	}
}

const std::set<std::string> &
OctreeByMatScene::getMaterialNames() {

	m_MaterialNames.clear();

	for ( auto objIter : m_SceneObjects) {
		objIter->getRenderable()->getMaterialNames(&m_MaterialNames);
	}

	if (0 != m_pGeometry) {
		m_pGeometry->getMaterialNames(&m_MaterialNames);
	}
	return m_MaterialNames;
}

std::shared_ptr<SceneObject> &
OctreeByMatScene::getSceneObject (std::string name) {

	for (auto &so: m_SceneObjects) {
		if (0 == so->getName().compare (name)) {
			return so;
		}
	}
	return m_EmptySOptr;
}

std::shared_ptr<SceneObject> &
OctreeByMatScene::getSceneObject( int index) {

	if (index < 0 || (unsigned int)index >= m_SceneObjects.size())
		return m_EmptySOptr;

	return m_SceneObjects.at(index);
}

void OctreeByMatScene::unitize() {

	unsigned int i;
	nau::math::vec3 vMax, vMin, vCenter;;

	vMax = m_BoundingBox.getMax();
	vMin = m_BoundingBox.getMin();
	vCenter = m_BoundingBox.getCenter();

	m_BoundingBox.set(vec3(-1), vec3(1));

	if (m_SceneObjects.size()) {

		for ( i = 0; i < m_SceneObjects.size(); i++)
			m_SceneObjects[i]->unitize(vCenter, vMin, vMax);

		m_BoundingBox.intersect(m_SceneObjects[0]->getBoundingVolume());
		for (i = 1; i < m_SceneObjects.size(); i++)
			m_BoundingBox.compound(m_SceneObjects[i]->getBoundingVolume());
	}

	// if the scene is in a octree
	if (0 != m_pGeometry) {
		m_pGeometry->unitize(vCenter, vMin, vMax);

	}

}


text:
'use strict';

const mongoose = require('mongoose');

const planetSchema = new mongoose.Schema({
  name: String,
  countries: [{
    name: String,
    cities: [String]
  }]
});

let Planet;
planetSchema.static('getPlanet', (planet) => {
  return new Planet({
    name: planet.name,
    countries: planet.countries
  });
});

mongoose.model('Planet', planetSchema);
Planet = mongoose.model('Planet');

module.exports = Planet;


text:
<?php

namespace OC\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Types\Type;
use OCP\Migration\ISchemaMigration;

/**
 * Add account_terms table for account searching
 */
class Version20170516100103 implements ISchemaMigration {
	public function changeSchema(Schema $schema, array $options) {
		$prefix = $options['tablePrefix'];
		if (!$schema->hasTable("${prefix}account_terms")) {
			$table = $schema->createTable("${prefix}account_terms");

			$table->addColumn('id', Type::BIGINT, [
				'autoincrement' => true,
				'unsigned' => true,
				'notnull' => true,
			]);

			// Foreign key to oc_accounts.id column
			$table->addColumn('account_id', Type::BIGINT, [
				'notnull' => true,
				'unsigned' => true,
			]);

			$table->addColumn('term', Type::STRING, [
				'notnull' => true,
				'length' => 255
			]);

			$table->setPrimaryKey(['id']);
			$table->addIndex(['account_id'], 'account_id_index');
			$table->addIndex(['term'], 'term_index');
		}

		if ($schema->hasTable("${prefix}accounts")) {
			$table = $schema->getTable("${prefix}accounts");
			if (!$table->hasIndex('lower_user_id_index')) {
				$table->addUniqueIndex(['lower_user_id'], 'lower_user_id_index');
			}
			if (!$table->hasIndex('display_name_index')) {
				$table->addIndex(['display_name'], 'display_name_index');
			}
			if (!$table->hasIndex('email_index')) {
				$table->addIndex(['email'], 'email_index');
			}
		}
	}
}


text:
using System;

namespace Microsoft.AspNetCore.SignalR.Configuration
{
    public class TransportOptions
    {
        // The below effectively sets the minimum heartbeat to once per second.
        // if _minimumKeepAlive != 2 seconds, update the ArguementOutOfRanceExceptionMessage below
        private static readonly TimeSpan _minimumKeepAlive = TimeSpan.FromSeconds(2);

        // if _minimumKeepAlivesPerDisconnectTimeout != 3, update the ArguementOutOfRanceExceptionMessage below
        private const int _minimumKeepAlivesPerDisconnectTimeout = 3;

        // if _minimumDisconnectTimeout != 6 seconds, update the ArguementOutOfRanceExceptionMessage below
        private static readonly TimeSpan _minimumDisconnectTimeout = TimeSpan.FromTicks(_minimumKeepAlive.Ticks * _minimumKeepAlivesPerDisconnectTimeout);

        private bool _keepAliveConfigured;
        private TimeSpan? _keepAlive;
        private TimeSpan _disconnectTimeout;

        public TransportOptions()
        {
            EnabledTransports = TransportType.All;
            TransportConnectTimeout = TimeSpan.FromSeconds(5);
            DisconnectTimeout = TimeSpan.FromSeconds(30);
            WebSockets = new WebSocketOptions();
            LongPolling = new LongPollingOptions();
        }

        /// <summary>
        /// Gets or sets the enabled transports.
        /// The default value is <see cref="TransportType.All"/>.
        public TransportType EnabledTransports { get; set; }

        /// <summary>
        /// Gets or sets a <see cref="TimeSpan"/> representing the amount of time a client should allow to connect before falling
        /// back to another transport or failing.
        /// The default value is 5 seconds.
        /// </summary>
        public TimeSpan TransportConnectTimeout { get; set; }

        /// <summary>
        /// Gets or sets a <see cref="TimeSpan"/> representing the amount of time to wait after a connection goes away before raising the disconnect event.
        /// The default value is 30 seconds.
        /// </summary>
        public TimeSpan DisconnectTimeout
        {
            get
            {
                return _disconnectTimeout;
            }
            set
            {
                if (value < _minimumDisconnectTimeout)
                {
                    throw new ArgumentOutOfRangeException("value", Resources.Error_DisconnectTimeoutMustBeAtLeastSixSeconds);
                }

                if (_keepAliveConfigured)
                {
                    throw new InvalidOperationException(Resources.Error_DisconnectTimeoutCannotBeConfiguredAfterKeepAlive);
                }

                _disconnectTimeout = value;
                _keepAlive = TimeSpan.FromTicks(_disconnectTimeout.Ticks / _minimumKeepAlivesPerDisconnectTimeout);
            }
        }

        /// <summary>
        /// Gets or sets a <see cref="TimeSpan"/> representing the amount of time between sending keep alive messages.
        /// If enabled, this value must be at least two seconds. Set to null to disable.
        /// The default value is 10 seconds.
        /// </summary>
        public TimeSpan? KeepAlive
        {
            get
            {
                return _keepAlive;
            }
            set
            {
                if (value < _minimumKeepAlive)
                {
                    throw new ArgumentOutOfRangeException("value", Resources.Error_KeepAliveMustBeGreaterThanTwoSeconds);
                }

                if (value > TimeSpan.FromTicks(_disconnectTimeout.Ticks / _minimumKeepAlivesPerDisconnectTimeout))
                {
                    throw new ArgumentOutOfRangeException("value", Resources.Error_KeepAliveMustBeNoMoreThanAThirdOfTheDisconnectTimeout);
                }

                _keepAlive = value;
                _keepAliveConfigured = true;
            }
        }

        /// <summary>
        /// Gets or sets WebSocket specific configuration.
        /// </summary>
        public WebSocketOptions WebSockets { get; set; }

        /// <summary>
        /// Gets or sets long-polling specific configuration.
        /// </summary>
        /// <returns></returns>
        public LongPollingOptions LongPolling { get; set; }
    }
}


text:
using System;
using System.Globalization;

namespace FlitBit.WebApi
{
  public static class IsoDate
  {
    static readonly string[] DateFormats =
    {
      // most-common javascript formats
      "yyyy-MM-ddTHH:mm:ss.fffZ",
      "yyyy-MM-ddTHH:mm:ss.fffzzz",
      // Basic formats
      "yyyyMMddTHHmmsszzz",
      "yyyyMMddTHHmmsszz",
      "yyyyMMddTHHmmssZ",
      // Extended formats
      "yyyy-MM-ddTHH:mm:sszzz",
      "yyyy-MM-ddTHH:mm:sszz",
      "yyyy-MM-ddTHH:mm:ssZ",
      // All of the above with reduced accuracy
      "yyyyMMddTHHmmzzz",
      "yyyyMMddTHHmmzz",
      "yyyyMMddTHHmmZ",
      "yyyy-MM-ddTHH:mmzzz",
      "yyyy-MM-ddTHH:mmzz",
      "yyyy-MM-ddTHH:mmZ",
      // Accuracy reduced to hours
      "yyyyMMddTHHzzz",
      "yyyyMMddTHHzz",
      "yyyyMMddTHHZ",
      "yyyy-MM-ddTHHzzz",
      "yyyy-MM-ddTHHzz",
      "yyyy-MM-ddTHHZ",
      // Plaino dates
      "yyyyMMddzzz",
      "yyyyMMddzz",
      "yyyyMMddZ",
      "yyyy-MM-ddzzz",
      "yyyy-MM-ddzz",
      "yyyy-MM-ddZ",
      // No timezone indicator
      "yyyyMMdd",
      "yyyy-MM-dd"
    };

    public static bool TryParse(string str, out DateTimeOffset timestamp)
    {
      // from http://stackoverflow.com/questions/3556144/how-to-create-a-net-datetime-from-iso-8601-format
      // modified for DateTimeOffset and Try...
      return DateTimeOffset.TryParseExact(str, DateFormats,
        CultureInfo.InvariantCulture, DateTimeStyles.None, out timestamp);
    }
  }
}


text:
<?php

namespace AmoCRM\Models;

class Account extends AbstractModel
{
    /**
     * Данные по аккаунту
     *
     * Получение информации по аккаунту в котором произведена авторизация:
     * название, оплаченный период, пользователи аккаунта и их права,
     * справочники дополнительных полей контактов и сделок, справочник статусов сделок,
     * справочник типов событий, справочник типов задач и другие параметры аккаунта.
     *
     * @link https://developers.amocrm.ru/rest_api/accounts_current.php
     * @param bool $short Краткий формат, только основные поля
     * @param array $parameters Массив параметров к amoCRM API
     * @return array Ответ amoCRM API
     */
    public function apiCurrent($short = false, $parameters = [])
    {
        $result = $this->getRequest('/private/api/v2/json/accounts/current', $parameters);

        return $short ? $this->getShorted($result['account']) : $result['account'];
    }

    /**
     * Возвращает сведения о пользователе по его логину.
     * Если не указывать логин, вернутся сведения о владельце API ключа.
     *
     * @param null|string $login Логин пользователя
     * @return mixed Данные о пользователе
     */
    public function getUserByLogin($login = null)
    {
        if ($login === null) {
            $login = $this->getParameters()->getAuth('login');
        }

        $login = strtolower($login);
        $result = $this->apiCurrent();

        foreach ($result['users'] as $user) {
            if (strtolower($user['login']) == $login) {
                return $user;
            }
        }

        return false;
    }

    /**
     * Урезание значения возвращаемого методом apiCurrent,
     * оставляет только основные поля такие как 'id', 'name', 'type_id', 'enums'
     *
     * @param array $account Ответ amoCRM API
     * @return mixed Краткий ответ amoCRM API
     */
    private function getShorted($account)
    {
        $keys = array_fill_keys(['id', 'name', 'login'], 1);
        $account['users'] = array_map(function($val) use ($keys) {
            return array_intersect_key($val, $keys);
        }, $account['users']);

        $keys = array_fill_keys(['id', 'name'], 1);
        $account['leads_statuses'] = array_map(function($val) use ($keys) {
            return array_intersect_key($val, $keys);
        }, $account['leads_statuses']);

        $keys = array_fill_keys(['id', 'name'], 1);
        $account['note_types'] = array_map(function($val) use ($keys) {
            return array_intersect_key($val, $keys);
        }, $account['note_types']);

        $keys = array_fill_keys(['id', 'name'], 1);
        $account['task_types'] = array_map(function($val) use ($keys) {
            return array_intersect_key($val, $keys);
        }, $account['task_types']);

        $keys = array_fill_keys(['id', 'name', 'type_id', 'enums'], 1);
        foreach ($account['custom_fields'] AS $type => $fields) {
            $account['custom_fields'][$type] = array_map(function($val) use ($keys) {
                return array_intersect_key($val, $keys);
            }, $fields);
        }

        $keys = array_fill_keys(['id', 'label', 'name'], 1);
        $account['pipelines'] = array_map(function($val) use ($keys) {
            return array_intersect_key($val, $keys);
        }, $account['pipelines']);

        return $account;
    }
}


text:
require 'spec_helper'

describe Protocool do

  let(:protocool) { Protocool }

  context 'Rails 2 development' do
    before do
      Rails.stub!(:env).and_return mock(:environment, development?: true)
    end

    describe '.https' do
      it 'does not use TLS' do
        protocool.https.should == 'http'
      end
    end
  end

  context 'Rails 2 production' do
    before do
      Rails.stub!(:env).and_return mock(:environment, development?: false, test?: false)
    end

    describe '.https' do
      it 'uses TLS' do
        protocool.https.should == 'https'
      end
    end
  end

  context 'if force_ssl is set' do
    before do
      Rails.stub_chain(:application, :config, :force_ssl).and_return true
    end

    describe '.https' do
      it 'uses TLS' do
        protocool.https.should == 'https'
      end
    end

    describe '.protocol' do
      it 'uses TLS' do
        protocool.protocol.should == 'https://'
      end
    end
  end

  context 'if force_ssl is not set' do
    before do
      Rails.stub_chain(:application, :config, :force_ssl).and_return false
    end

    context 'in development mode' do
      before do
        Rails.stub!(:env).and_return mock(:environment, development?: true)
      end

      describe '.https' do
        it 'does not use TLS' do
          protocool.https.should == 'http'
        end
      end

      describe '.protocol' do
        it 'does not use TLS' do
          protocool.protocol.should == 'http://'
        end
      end
    end

    context 'in test mode' do
      before do
        Rails.stub!(:env).and_return mock(:environment, development?: false, test?: true)
      end

      describe '.https' do
        it 'does not use TLS' do
          protocool.https.should == 'http'
        end
      end

      describe '.protocol' do
        it 'does not use TLS' do
          protocool.protocol.should == 'http://'
        end
      end
    end

    context 'in non-dev and non-test mode' do
      before do
        Rails.stub!(:env).and_return mock(:environment, development?: false, test?: false)
      end

      describe '.https' do
        it 'uses TLS' do
          protocool.https.should == 'https'
        end
      end

      describe '.protocol' do
        it 'uses TLS' do
          protocool.protocol.should == 'https://'
        end
      end
    end

    context 'with force_ssl in non-dev and non-test mode but overriding manually' do
      before do
        Rails.stub_chain(:application, :config, :force_ssl).and_return true
        Rails.stub!(:env).and_return mock(:environment, development?: false, test?: false)
        stub_const 'ENV', {'PROTOCOOL_FORCE_INSECURE' => 'true'}
      end

      describe '.https' do
        it 'uses TLS' do
          protocool.https.should == 'http'
        end
      end

      describe '.protocol' do
        it 'uses TLS' do
          protocool.protocol.should == 'http://'
        end
      end
    end

  end
end


text:
import sbt._

object ResolverSettings {

  lazy val resolvers = Seq(
    Resolver.mavenLocal,
    Resolver.sonatypeRepo("releases"),
    Resolver.typesafeRepo("releases"),
    Resolver.typesafeRepo("snapshots"),
    Resolver.sonatypeRepo("snapshots"),
    "Linter" at "http://hairyfotr.github.io/linteRepo/releases",
    "krasserm" at "http://dl.bintray.com/krasserm/maven"
  )
}


text:
<meta charset="UTF-8">
<title>BidirectionalDictionary.Strings.mappingIterator - biomedicus-core</title>
<link rel="stylesheet" href="../../../../style.css">

biomedicus-core / edu.umn.biomedicus.common.dictionary / BidirectionalDictionary / Strings / mappingIterator

mappingIterator

abstract fun mappingIterator(): MappingIterator

Returns a mapping iterator of all the identifiers to strings mapping stored in this object.

Return

newly created mapping iterator


text:
class RecommendListController < ApplicationController
  def recommend
    if params[:q]
      response1 = Amazon::Ecs.item_search(params[:q]+" お土産" ,
                                  :search_index => 'All' ,
                                  :response_group => 'Medium' ,
                                  :country => 'jp',
                                  :ItemPage => '1')
      response2 = Amazon::Ecs.item_search(params[:q]+" お土産" ,
                                  :search_index => 'All' ,
                                  :response_group => 'Medium' ,
                                  :country => 'jp',
                                  :ItemPage => '2')

      @amazon_items = response1.items + response2.items
      puts @amazon_items
    end
  end
end


text:
package org.jkiss.dbeaver.ui.editors.object;

import org.eclipse.jface.resource.ImageDescriptor;
import org.jkiss.dbeaver.model.navigator.DBNDatabaseObject;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.editors.DatabaseEditorInput;

/**
 * ObjectEditorInput
 */
public class ObjectEditorInput extends DatabaseEditorInput<DBNDatabaseObject>
{
    public ObjectEditorInput(DBNDatabaseObject dbmNode)
    {
        super(dbmNode);
    }

    @Override
    public ImageDescriptor getImageDescriptor()
    {
        DBNDatabaseObject node = getNavigatorNode();
//        IEditorDescriptor editorDescriptor = node.getEditorDescriptor();
//        if (editorDescriptor != null) {
//            return editorDescriptor.getImageDescriptor();
//        } else {
            return DBeaverIcons.getImageDescriptor(node.getNodeIconDefault());
//        }
    }

    @Override
    public String getToolTipText()
    {
        return getNavigatorNode().getMeta().getDescription();
    }

}


text:
var mongoose  = require('mongoose');
var BaseModel = require("./base_model");
var Schema    = mongoose.Schema;
var ObjectId  = Schema.ObjectId;
var config    = require('../config');
var _         = require('lodash');

var TopicSchema = new Schema({
  title: { type: String },
  content: { type: String },
  author_id: { type: ObjectId },
  top: { type: Boolean, default: false }, // 置顶帖
  good: {type: Boolean, default: false}, // 精华帖
  lock: {type: Boolean, default: false}, // 被锁定主题
  reply_count: { type: Number, default: 0 },
  visit_count: { type: Number, default: 0 },
  collect_count: { type: Number, default: 0 },
  create_at: { type: Date, default: Date.now },
  update_at: { type: Date, default: Date.now },
  last_reply: { type: ObjectId },
  last_reply_at: { type: Date, default: Date.now },
  content_is_html: { type: Boolean },
  tab: {type: String},
  deleted: {type: Boolean, default: false},
});

TopicSchema.plugin(BaseModel);
TopicSchema.index({create_at: -1});
TopicSchema.index({top: -1, last_reply_at: -1});
TopicSchema.index({author_id: 1, create_at: -1});

TopicSchema.virtual('tabName').get(function () {
  var tab  = this.tab;
  var pair = _.find(config.tabs, function (_pair) {
    return _pair[0] === tab;
  });

  if (pair) {
    return pair[1];
  } else {
    return '';
  }
});

mongoose.model('Topic', TopicSchema);