text:
package org.apache.jmeter.gui;

import java.util.HashMap;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JComponent;

import org.apache.jmeter.testbeans.gui.TestBeanGUI;

/**
 * Provides a way to register and retrieve GUI classes and icons.
 *
 */
public final class GUIFactory {
    /** A Map from String to JMeterGUIComponent of registered GUI classes. */
    private static final Map<String, JMeterGUIComponent> GUI_MAP = new HashMap<>();

    /** A Map from String to ImageIcon of registered icons. */
    private static final Map<String, ImageIcon> ICON_MAP = new HashMap<>();

    /** A Map from String to ImageIcon of registered icons. */
    private static final Map<String, ImageIcon> DISABLED_ICON_MAP = new HashMap<>();

    /**
     * Prevent instantiation since this is a static utility class.
     */
    private GUIFactory() {
    }

    /**
     * Get an icon which has previously been registered for this class object.
     *
     * @param elementClass
     *            the class object which we want to get an icon for
     *
     * @return the associated icon, or null if this class or its superclass has
     *         not been registered
     */
    public static ImageIcon getIcon(Class<?> elementClass) {
        return getIcon(elementClass, true);

    }

    /**
     * Get icon/disabledicon which has previously been registered for this class
     * object.
     *
     * @param elementClass
     *            the class object which we want to get an icon for
     * @param enabled -
     *            is icon enabled
     *
     * @return the associated icon, or null if this class or its superclass has
     *         not been registered
     */
    public static ImageIcon getIcon(Class<?> elementClass, boolean enabled) {
        String key = elementClass.getName();
        ImageIcon icon = (enabled ? ICON_MAP.get(key) : DISABLED_ICON_MAP.get(key));

        if (icon != null) {
            return icon;
        }

        if (elementClass.getSuperclass() != null) {
            return getIcon(elementClass.getSuperclass(), enabled);
        }

        return null;
    }

    /**
     * Get a component instance which has previously been registered for this
     * class object.
     *
     * @param elementClass
     *            the class object which we want to get an instance of
     *
     * @return an instance of the class, or null if this class or its superclass
     *         has not been registered
     */
    public static JComponent getGUI(Class<?> elementClass) {
        // TODO: This method doesn't appear to be used.
        String key = elementClass.getName();
        JComponent gui = (JComponent) GUI_MAP.get(key);

        if (gui != null) {
            return gui;
        }

        if (elementClass.getSuperclass() != null) {
            return getGUI(elementClass.getSuperclass());
        }

        return null;
    }

    /**
     * Register an icon so that it can later be retrieved via
     * {@link #getIcon(Class)}. The key should match the fully-qualified class
     * name for the class used as the parameter when retrieving the icon.
     *
     * @param key
     *            the name which can be used to retrieve this icon later
     * @param icon
     *            the icon to store
     */
    public static void registerIcon(String key, ImageIcon icon) {
        ICON_MAP.put(key, icon);
    }

    /**
     * Register an icon so that it can later be retrieved via
     * {@link #getIcon(Class)}. The key should match the fully-qualified class
     * name for the class used as the parameter when retrieving the icon.
     *
     * @param key
     *            the name which can be used to retrieve this icon later
     * @param icon
     *            the icon to store
     */
    public static void registerDisabledIcon(String key, ImageIcon icon) {
        DISABLED_ICON_MAP.put(key, icon);
    }

    /**
     * Register a GUI class so that it can later be retrieved via
     * {@link #getGUI(Class)}. The key should match the fully-qualified class
     * name for the class used as the parameter when retrieving the GUI.
     *
     * @param key
     *            the name which can be used to retrieve this GUI later
     * @param guiClass
     *            the class object for the GUI component
     * @param testClass
     *            the class of the objects edited by this GUI
     *
     * @throws InstantiationException
     *             if an instance of the GUI class can not be instantiated
     * @throws IllegalAccessException
     *             if access rights do not permit an instance of the GUI class
     *             to be created
     */
    public static void registerGUI(String key, Class<?> guiClass, Class<?> testClass) throws InstantiationException,
            IllegalAccessException {
        // TODO: This method doesn't appear to be used.
        JMeterGUIComponent gui;

        if (guiClass == TestBeanGUI.class) {
            gui = new TestBeanGUI(testClass);
        } else {
            gui = (JMeterGUIComponent) guiClass.newInstance();
        }
        GUI_MAP.put(key, gui);
    }
}


text:
package integration_test

import (
	"encoding/json"
	"net/http"
	"os/exec"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"
	"github.com/onsi/gomega/ghttp"
	"github.com/tedsuo/rata"
	"gopkg.in/yaml.v2"

	"github.com/concourse/atc"
)

var _ = Describe("Fly CLI", func() {
	Describe("get-pipeline", func() {
		var (
			config atc.Config
		)

		BeforeEach(func() {
			config = atc.Config{
				Groups: atc.GroupConfigs{
					{
						Name:      "some-group",
						Jobs:      []string{"job-1", "job-2"},
						Resources: []string{"resource-1", "resource-2"},
					},
					{
						Name:      "some-other-group",
						Jobs:      []string{"job-3", "job-4"},
						Resources: []string{"resource-6", "resource-4"},
					},
				},

				Resources: atc.ResourceConfigs{
					{
						Name: "some-resource",
						Type: "some-type",
						Source: atc.Source{
							"source-config": "some-value",
						},
					},
					{
						Name: "some-other-resource",
						Type: "some-other-type",
						Source: atc.Source{
							"source-config": "some-value",
						},
					},
				},

				ResourceTypes: atc.ResourceTypes{
					{
						Name: "some-resource-type",
						Type: "some-type",
						Source: atc.Source{
							"source-config": "some-value",
						},
					},
					{
						Name: "some-other-resource-type",
						Type: "some-other-type",
						Source: atc.Source{
							"source-config": "some-value",
						},
					},
				},

				Jobs: atc.JobConfigs{
					{
						Name:   "some-job",
						Public: true,
						Serial: true,
					},
					{
						Name: "some-other-job",
					},
				},
			}
		})

		Describe("getting", func() {
			Context("when not specifying a pipeline name", func() {
				It("fails and says you should give a pipeline name", func() {
					flyCmd := exec.Command(flyPath, "-t", targetName, "get-pipeline")

					sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
					Expect(err).NotTo(HaveOccurred())

					<-sess.Exited
					Expect(sess.ExitCode()).To(Equal(1))

					Expect(sess.Err).To(gbytes.Say("error: the required flag `" + osFlag("p", "pipeline") + "' was not specified"))
				})
			})

			Context("when specifying a pipeline name", func() {
				var path string
				BeforeEach(func() {
					var err error
					path, err = atc.Routes.CreatePathForRoute(atc.GetConfig, rata.Params{"pipeline_name": "some-pipeline"})
					Expect(err).NotTo(HaveOccurred())
				})

				Context("when atc returns valid config", func() {
					BeforeEach(func() {
						atcServer.AppendHandlers(
							ghttp.CombineHandlers(
								ghttp.VerifyRequest("GET", path),
								ghttp.RespondWithJSONEncoded(200, atc.ConfigResponse{Config: &config}, http.Header{atc.ConfigVersionHeader: {"42"}}),
							),
						)
					})

					It("prints the config as yaml to stdout", func() {
						flyCmd := exec.Command(flyPath, "-t", targetName, "get-pipeline", "--pipeline", "some-pipeline")

						sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
						Expect(err).NotTo(HaveOccurred())

						<-sess.Exited
						Expect(sess.ExitCode()).To(Equal(0))

						var printedConfig atc.Config
						err = yaml.Unmarshal(sess.Out.Contents(), &printedConfig)
						Expect(err).NotTo(HaveOccurred())

						Expect(printedConfig).To(Equal(config))
					})

					Context("when -j is given", func() {
						It("prints the config as json to stdout", func() {
							flyCmd := exec.Command(flyPath, "-t", targetName, "get-pipeline", "--pipeline", "some-pipeline", "-j")

							sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
							Expect(err).NotTo(HaveOccurred())

							<-sess.Exited
							Expect(sess.ExitCode()).To(Equal(0))

							var printedConfig atc.Config
							err = json.Unmarshal(sess.Out.Contents(), &printedConfig)
							Expect(err).NotTo(HaveOccurred())

							Expect(printedConfig).To(Equal(config))
						})
					})
				})

				Context("when atc returns an error loading config", func() {
					BeforeEach(func() {
						configResponse := atc.ConfigResponse{
							Errors: []string{"invalid-config"},
							RawConfig: atc.RawConfig(`{
								"foo":{"bar": [1, 2, 3]},
								"baz":"quux"
							}`),
						}
						atcServer.AppendHandlers(
							ghttp.CombineHandlers(
								ghttp.VerifyRequest("GET", path),
								ghttp.RespondWithJSONEncoded(200, configResponse, http.Header{atc.ConfigVersionHeader: {"42"}}),
							),
						)
					})

					It("prints raw config as yaml with error", func() {
						flyCmd := exec.Command(flyPath, "-t", targetName, "get-pipeline", "--pipeline", "some-pipeline")

						sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
						Expect(err).NotTo(HaveOccurred())

						<-sess.Exited
						Expect(sess.ExitCode()).To(Equal(1))
						Expect(sess.Err).To(gbytes.Say("error: invalid-config"))
						var printedConfig map[string]interface{}
						err = yaml.Unmarshal(sess.Out.Contents(), &printedConfig)
						Expect(err).NotTo(HaveOccurred())

						Expect(printedConfig).To(Equal(map[string]interface{}{
							"foo": map[interface{}]interface{}{
								"bar": []interface{}{1, 2, 3},
							},
							"baz": "quux",
						},
						))
					})

					Context("when requesting JSON format", func() {
						It("prints raw config as json with error", func() {
							flyCmd := exec.Command(flyPath, "-t", targetName, "get-pipeline", "--pipeline", "some-pipeline", "-j")

							sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
							Expect(err).NotTo(HaveOccurred())

							<-sess.Exited
							Expect(sess.ExitCode()).To(Equal(1))
							Expect(sess.Err).To(gbytes.Say("error: invalid-config"))
							Expect(sess.Out.Contents()).To(MatchJSON(`{
								"foo":{"bar": [1, 2, 3]},
								"baz":"quux"
							}`))
						})
					})
				})

				Context("when atc returns an error loading config but returns an empty raw config", func() {
					BeforeEach(func() {
						configResponse := atc.ConfigResponse{Errors: []string{"invalid-config"}, RawConfig: atc.RawConfig("")}
						atcServer.AppendHandlers(
							ghttp.CombineHandlers(
								ghttp.VerifyRequest("GET", path),
								ghttp.RespondWithJSONEncoded(200, configResponse, http.Header{atc.ConfigVersionHeader: {"42"}}),
							),
						)
					})

					It("does not print the (empty) raw config", func() {
						flyCmd := exec.Command(flyPath, "-t", targetName, "get-pipeline", "--pipeline", "some-pipeline")

						sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
						Expect(err).NotTo(HaveOccurred())

						<-sess.Exited
						Expect(sess.ExitCode()).To(Equal(1))
						Expect(sess.Err).To(gbytes.Say("error: invalid-config"))
						Expect(sess.Out.Contents()).To(HaveLen(0))
					})
				})
			})
		})
	})
})

redpajama_set_name: RedPajamaGithub


text:
module example {

  import Pool = entitas.Pool;
  import Group = entitas.Group;
  import Entity = entitas.Entity;
  import Matcher = entitas.Matcher;
  import Exception = entitas.Exception;
  import TriggerOnEvent = entitas.TriggerOnEvent;
  import IExecuteSystem = entitas.IExecuteSystem;
  import ISetPool = entitas.ISetPool;
  import Sprite = PIXI.Sprite;

  export class ColorAnimationSystem implements IExecuteSystem, ISetPool {

    protected pool:Pool;
    protected group:Group;

    public execute() {
      var delta = bosco.delta;
      var entities = this.group.getEntities();
      for (var i = 0, l = entities.length; i < l; i++) {
        var e = entities[i];
        var c:ColorAnimationComponent = e.colorAnimation;
        var sprite:Sprite = <Sprite>e.sprite.object;

        if(c.alphaAnimate) {
          sprite.alpha += c.alphaSpeed * delta;

          if(sprite.alpha > c.alphaMax || sprite.alpha < c.alphaMin) {
            if(c.repeat) {
              c.alphaSpeed = -c.alphaSpeed;
            } else {
              c.alphaAnimate = false;
            }
          }
        }
      }
    }

    public setPool(pool:Pool) {
      this.pool = pool;
      this.group = pool.getGroup(Matcher.allOf(Matcher.ColorAnimation, Matcher.Sprite));
    }

  }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>QuorraJS</title>
    <link rel="icon" type="image/x-icon" href="/assets/icons/favicon.ico"/>
    <link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,400italic' rel='stylesheet'
          type='text/css'>
    <link rel="stylesheet" href="/assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="/assets/css/theme.css">
    <link rel="stylesheet" href="/assets/css/color-defaults.min.css">
    <link rel="stylesheet" href="/assets/css/swatch-blue-white.css">
    <link rel="stylesheet" href="/assets/css/swatch-white-blue.css">
    <link rel="stylesheet" href="/assets/css/prism.css">
    <link rel="stylesheet" href="/assets/css/fonts.min.css" media="screen">

            QuorraJS

Blog

                    Community

Github

Slack

Gitter

Twitter

Documentation

Preface

                                        Quickstart

                                        Contribution Guide

Getting started

                                        Installation

                                        Configuration

                                        Request Lifecycle

                                        Routing

                                        Requests & Input

                                        Views & Responses

                                        Controllers

                                        Errors & Logging

                                        Models & ORM

                                        Globals

                                        Middleware

Learning more

                                        Security

                                        Session

                                        Mail

                                        Request Object

                                        Response Object

                                        Service Providers

                                        Body Parser

                                        Query Parser

                                        Cookie Parser

                                        Authentication

                                        Localization

                                        HTTP Method Override

                                        Server Static

                                        Elixir

                                        Miscellaneous

                                        Testing

Quorra CLI

                                        Overview

                        QuorraJS

                            <input type="text" name="search" class="form-control">
                            <button type="submit"></button>

Documentation

Blog

                                Community

Github

Slack

Gitter

Twitter

                            <button class="btn btn-info dropdown-toggle" type="button" aria-haspopup="true"
                                    data-toggle="dropdown">
                                1.0.0

                            </button>

                                        Master

                                        1.0.0

                    <button type="button" class="navbar-toggle collapsed">

                    </button>

Preface

                                                        Quickstart

                                                        Contribution Guide

Getting started

                                                        Installation

                                                        Configuration

                                                        Request Lifecycle

                                                        Routing

                                                        Requests & Input

                                                        Views & Responses

                                                        Controllers

                                                        Errors & Logging

                                                        Models & ORM

                                                        Globals

                                                        Middleware

Learning more

                                                        Security

                                                        Session

                                                        Mail

                                                        Request Object

                                                        Response Object

                                                        Service Providers

                                                        Body Parser

                                                        Query Parser

                                                        Cookie Parser

                                                        Authentication

                                                        Localization

                                                        HTTP Method Override

                                                        Server Static

                                                        Elixir

                                                        Miscellaneous

                                                        Testing

Quorra CLI

                                                        Overview

Controllers

Basic Controllers

Controller Filters

Implicit Controllers

RESTful Resource Controllers

Handling Missing Methods

Basic Controllers

Instead of defining all of your route-level logic in a single routes.js file, you may wish to organize this behavior
using Controllers. Controllers can group related route logic into a single file.

Controllers are typically stored in the app/controllers directory and loaded to the application based on the routes
declared in the routes.js. However, controllers can technically live in any directory or any sub-directory. Route
declarations are dependent on the location of the controller folder on disk. Default namespace for controllers is
controllers. So if you wish to add add controller file in any other path you have to provide namespace
relative to app directory.

Here is an example of a basic controller file:

var BaseController = require('../BaseController');

var UserController = BaseController.extend(function(){

    /**
     * Show the profile for the given user.
     */
    this.ShowProfile = function(req, res, id)
    {
        var user = User.findOne(id);

        res.view('profile/user', {user: user});
    };
});

All controllers should extend the BaseController. The BaseController is also stored in the app/controllers directory,
and may be used as a place to put shared controller logic. The BaseController extends the framework's Controller.
Now, we can route to this controller action like so:

Route.get('user/{id}', 'UserController@showProfile');

If you choose to nest or organize your controller using sub-directories, simply use the fully qualified path to the
controller relative to your app directory when defining the route:

Route.get('foo', 'controllers/Namespace/FooController@method');

You may also specify names on controller routes:

Route.get('foo', {'uses': 'FooController@method', 'as': 'name'});

To generate a URL to a controller action, you may use the URL.action method:

var URL = App.url;
$url = URL.action('FooController@method');

Controller Filters

Filters may be specified on controller routes similar to "regular" routes:

Route.get('profile', {before': 'auth', 'uses': 'UserController@showProfile'});

However, you may also specify filters from within your controller:

var BaseController = require('../BaseController');

var UserController = BaseController.extend(function(){

    this.beforeFilter('auth', {'except': 'getLogin'});

    this.beforeFilter('csrf', {'on': 'post'});

    this.beforeFilter('log', {'only':  ['fooAction', 'barAction']));
});

You may also specify controller filters inline using a Closure:

var BaseController = require('../BaseController');

var UserController = BaseController.extend(function(){

    this.beforeFilter(function(req, res, next){
        //
    });
});

If you would like to use another method on the controller as a filter, you may use @syntax to define the filter:

var BaseController = require('../BaseController');

var UserController = BaseController.extend(function(){

        this.FilterRequests = function(req, res, next){
            //
        };

        this.beforeFilter('@filterRequests');
});

Implicit Controllers

Quorra allows you to easily define a single route to handle every action in a controller. First, define the route using
the Route.controller method:

Route.controller('users', 'UserController');

The controller method accepts two arguments. The first is the base URI the controller handles, while the second is the class name of the controller. Next, just add methods to your controller, prefixed with the HTTP verb they respond to:

var BaseController = require('../BaseController');

var UserController = BaseController.extend(function(){

        this.getIndex = function(req, res, next) {
            //
        }

        this.postProfile = function(req, res, next) {
            //
        }

        this.anyLogin = function(req, res, next) {
            //
        }
});

The index methods will respond to the root URI handled by the controller, which, in this case, is users.

If your controller action contains multiple words, you may access the action using "dash" syntax in the URI. For
example, the following controller action on our UserController would respond to the users/admin-profile URI:

    this.getAdminProfile = function(req, res, next) {}

RESTful Resource Controllers

Resource controllers make it easier to build RESTful controllers around resources. For example, you may wish to create a controller that manages "photos" stored by your application.

To register a resourceful route to the controller:

Route.resource('photo', 'PhotoController');

This single route declaration creates multiple routes to handle a variety of RESTful actions on the photo resource.

Actions Handled By Resource Controller

Verb
Path
Action
Route Name

GET
/resource
index
resource.index

GET
/resource/create
create
resource.create

POST
/resource
store
resource.store

GET
/resource/{resource}
show
resource.show

GET
/resource/{resource}/edit
edit
resource.edit

PUT/PATCH
/resource/{resource}
update
resource.update

DELETE
/resource/{resource}
destroy
resource.destroy

Sometimes you may only need to handle a subset of the resource actions, then you may the subset of actions to handle
on the route:

Route.resource('photo', 'PhotoController', {'only': ['index', 'show']});

Route.resource('photo', 'PhotoController', {'except': ['create', 'store', 'update', 'destroy']});

By default, all resource controller actions have a route name; however, you can override these names by passing a
names object with your options:

Route::resource('photo', 'PhotoController', {'names': {'create': 'photo.build'}});

You can prefix all resource route names with your own prefix by using as attribute:

Route::resource('photo', 'PhotoController', {'as': 'prefix'});

Handling Nested Resource Controllers

To "nest" resource controllers, use "dot" notation in your route declaration:

Route.resource('photos.comments', 'PhotoCommentController');

This route will register a "nested" resource that may be accessed with URLs like the following:

photos/{photoResource}/comments/{commentResource}.

var BaseController = require('../BaseController');

var PhotoCommentController = BaseController.extend(function(){

        this.show = function(req, res, photoId, commentId) {
            //
        }
});

Adding Additional Routes To Resource Controllers

If it becomes necessary for you to add additional routes to a resource controller beyond the default resource routes,
you should define those routes before your call to Route.resource:

Route.get('photos/popular', 'PhotoController@method');
Route.resource('photos', 'PhotoController');

Handling Missing Methods

When using Route.controller, a catch-all method may be defined which will be called when no other matching method is
found on a given controller. The method should be named missingMethod, and receives the method and parameter array for the request:

Defining A Catch-All Method

this.missingMethod = function(parameters)
{
    //
}

Connect with us

QuorraJS 2016 ALL RIGHTS RESERVED


text: This directory containes PipelineRuns and TaskRuns that can be used for one off manual runs.


text:
package org.nfpj.utils;

import java.util.function.Predicate;
import org.nfpj.utils.predicates.TruePredicate;

/**
 *
 * @author njacinto
 */
public interface PageFilterIteratorWithSizeTestFactory extends PageIteratorTestFactory,
        FilterIteratorTestFactory, PageFilterIteratorTestFactory, PageIteratorWithSizeTestFactory {
    PageIterator<Character> get(int fromIndex, int toIndex,
            Predicate<Character> filter, Character ... c);
    IteratorWithSize<Character> getWithSize(int fromIndex, int toIndex,
            Predicate<Character> filter, Character ... c);

    @Override
    default PageIterator<Character> get(Predicate<Character> filter, Character ... c){
        return get(0, (c==null || c.length==0 ? 1 : c.length), filter, c);
    }

    @Override
    default PageIterator<Character> get(int fromIndex, int toIndex, Character ... c){
        return get(fromIndex, toIndex, TruePredicate.INSTANCE, c);
    }

    @Override
    default PageIterator<Character> get(Character ... c){
        return get(0, (c==null || c.length==0 ? 1 : c.length), TruePredicate.INSTANCE, c);
    }

    default IteratorWithSize<Character> getWithSize(Predicate<Character> filter, Character ... c){
        return getWithSize(0, (c==null || c.length==0 ? 1 : c.length), filter, c);
    }

    default IteratorWithSize<Character> getWithSize(int fromIndex, int toIndex, Character ... c){
        return getWithSize(fromIndex, toIndex, TruePredicate.INSTANCE, c);
    }

    default IteratorWithSize<Character> getWithSize(Character ... c){
        return getWithSize(0, (c==null || c.length==0 ? 1 : c.length), TruePredicate.INSTANCE, c);
    }
}


text:
package com.ltdev.math;

/**
 * A class containing various math helper methods.
 * @author Lightning Development Studios
 */
public final class MathHelper
{
    /**
     * Prevents initialization of MathHelper.
     */
    private MathHelper()
    {

    }

    /**
     * Returns the number of bits set in a byte bitfield.
     * @param b A byte bitfield.
     * @return The number of bits set in b.
     */
    public static int numberOfBitsSet(byte b)
    {
        int count = 0;
        for (int i = 0; i < 8; i++)
        {
            if ((b & 1) == 1)
                count++;
            b >>= 1;
        }

        return count;
    }
}


text:
//
// C++ Interface: fileinfo
//
// Description:
//
//
// Author: Lorenzo Bettini <http://www.lorenzobettini.it>, (C) 2005
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef FILEINFO_H
#define FILEINFO_H

#include <parserinfo.h>

/**
Information about the file we are processing

@author Lorenzo Bettini
*/
struct FileInfo : public ParserInfo
{
  std::string input_file_name; // with no path
  std::string output_file_name;
  std::string output_file_extension;

  FileInfo(const std::string &input, const std::string &output);

  ~FileInfo();

};

#endif


text:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.

// +build appengine

package dl

// TODO(adg): refactor this to use the tools/godoc/static template.

const templateHTML = `
{{define "root"}}
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Downloads - The Go Programming Language</title>
        <link type="text/css" rel="stylesheet" href="/lib/godoc/style.css">

The Go Programming Language

<form method="GET" action="/search">

Documents
Packages
The Project
Help
Blog
<input type="search" id="search" name="q" placeholder="Search" aria-label="Search" required><button type="submit"><svg width="24" height="24" viewBox="0 0 24 24"><title>submit search</title><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/><path d="M0 0h24v24H0z" fill="none"/></svg></button>

</form>

Downloads

After downloading a binary release suitable for your system,
please follow the installation instructions.

If you are building from source,
follow the source installation instructions.

See the release history for more
information about Go releases.

{{with .Featured}}

Featured downloads

{{range .}}
{{template "download" .}}
{{end}}
{{end}}

{{with .Stable}}

Stable versions

{{template "releases" .}}
{{end}}

{{with .Unstable}}

Unstable version

{{template "releases" .}}
{{end}}

{{with .Archive}}

Archived versions▹

Archived versions▾

    {{template "releases" .}}

{{end}}

        Except as
        noted,
        the content of this page is licensed under the Creative Commons
        Attribution 3.0 License,

        and code is licensed under a BSD license.

        Terms of Service |
        Privacy Policy

{{end}}

{{define "releases"}}
{{range .}}

{{.Version}} ▹

{{.Version}} ▾

		{{if .Stable}}{{else}}

This is an unstable version of Go. Use with caution.

If you already have Go installed, you can install this version by running:

go get golang.org/x/build/version/{{.Version}}

Then, use the {{.Version}} command instead of the go command to use {{.Version}}.

		{{end}}
		{{template "files" .}}

{{end}}
{{end}}

{{define "files"}}

  File name
  Kind
  OS
  Arch
  Size
  {{/* Use the checksum type of the first file for the column heading. */}}
  {{(index .Files 0).ChecksumType}} Checksum

{{if .SplitPortTable}}
  {{range .Files}}{{if .PrimaryPort}}{{template "file" .}}{{end}}{{end}}

  {{/* TODO(cbro): add a link to an explanatory doc page */}}

Other Ports

  {{range .Files}}{{if not .PrimaryPort}}{{template "file" .}}{{end}}{{end}}
{{else}}
  {{range .Files}}{{template "file" .}}{{end}}
{{end}}

{{end}}

{{define "file"}}

  {{.Filename}}
  {{pretty .Kind}}
  {{.PrettyOS}}
  {{pretty .Arch}}
  {{.PrettySize}}
  <tt>{{.PrettyChecksum}}</tt>

{{end}}

{{define "download"}}

{{.Platform}}

{{with .Requirements}}
{{.}}
{{end}}

  {{.Filename}}
  {{if .Size}}({{.PrettySize}}){{end}}

{{end}}
`


text: from sorting import insert_sorted


text:
Gil
===
[![Build Status](https://travis-ci.org/modalsoul/Gil.svg?branch=master)](https://travis-ci.org/modalsoul/Gil)
[![Hex.pm](https://img.shields.io/hexpm/v/gil.svg)](https://hex.pm/packages/gil)

Gil is a mix custom task for checking exchange rate.

## Installation

* mix.exs
```elixir
def deps do
  [{:gil, "~> 0.0.2"}]
end
```

## Usage

Get USD/EUR rate.

```elixir
> mix gil USD EUR
USD/EUR: 0.8850
```

Set key currency.

* config/config.exs
```elixir
config :gil,
  key_currency: "eur"
```

```elixir
> mix gil USD
EUR/USD: 1.1187
```

Default key currency is USD.

```elixir
> mix gil EUR
USD/EUR: 0.8850
```

## License

Copyright (C) 2015 Masatoshi Imae([@modal_soul](http://twitter.com/modal_soul))

Distributed under the MIT License.


text:
@echo off
echo "starting 34-32"

setlocal EnableDelayedExpansion
set MSSdk=1
CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x86 /release
set DISTUTILS_USE_SDK=1

title 34-32 build
echo "building"
cd "c:\users\Jeff Reback\documents\github\pandas"
C:\python34-32\python.exe setup.py build > build.34-32.log 2>&1

echo "installing"
C:\python34-32\python.exe setup.py bdist --formats=wininst > install.34-32.log 2>&1

echo "testing"
C:\python34-32\scripts\nosetests -A "not slow" build\lib.win32-3.4\pandas > test.34-32.log 2>&1

echo "versions"
cd build\lib.win32-3.4
C:\python34-32\python.exe ../../ci/print_versions.py > ../../versions.34-32.log 2>&1

exit


text:
Fast CORs support for Angular 1.x

```html
<body ng-app="App">
</body>
<script>
angular.module('App', ['ngCors'])
</script>
```


text:
require 'safety_razor/slice/base'

module SafetyRazor

  module Slice

    # Client API for Razor's policy slice.
    #
    # @author Fletcher Nichol <fnichol@nichol.ca>
    #
    class Policy < Base

      def templates
        response = connection.get(slice_path("templates"))
        parse(response)
      end

      private

      def slice_name
        "policy"
      end
    end
  end
end


text: Public website repo for Bananatree Consulting.


text:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *nome;

-(IBAction)clickButtonAction:(id)sender;
@end

@implementation ViewController

- (void)viewDidLoad
{
    NSString *nome;
    nome=@"blabl abla";
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    _nome.text=nome;

    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 20)];
    label2.text=@"feitooooo!";
    [self.view addSubview:label2];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)clickButtonAction:(id)sender{
    NSLog(@"Clicou no maldito botão");
}

-(IBAction)clickButtonAction2:(id)sender{
    NSLog(@"Clicou no maldito botão2 agora vai");
}

@end


text:
'use strict';
const Rect = require('./Rect');
const Position = function( options ) {
    const component = {
        _name : 'position',
        worldX:  options.worldX || 0,
        worldY:  options.worldY || 0,
        isoX:  options.isoX || 0,
        isoY:  options.isoY || 0,
        rect: new Rect(options.isoX, options.isoY, options.width, options.height),
        zIndex: options.zIndex || 0
    };
    return component;
};

module.exports = Position;


text:
var books = new Mongo.Collection('books');

//one before and one after to verify that order doesn't matter
books.attachIndex('isbn', {
    unique: true,
    action: 'rebuild',
    background: false
  }
);

books.attachSchema(new SimpleSchema({
  title: {
    type: String,
    label: 'Title',
    max: 200,
    index: {
      name: 'title',
      type:-1
    }
  },
  author: {
    type: String,
    label: 'Author'
  },
  copies: {
    type: Number,
    label: 'Number of copies',
    min: 0
  },
  lastCheckedOut: {
    type: Date,
    label: 'Last date this book was checked out',
    optional: true
  },
  summary: {
    type: String,
    label: 'Brief summary',
    optional: true,
    max: 1000
  },
  isbn: {
    type: String,
    label: 'ISBN',
    optional: true,
    index: {name: 'isbn'}
  },
  field1: {
    type: String,
    optional: true
  },
  field2: {
    type: String,
    optional: true
  },
  createdAt: {
    type: Date,
    optional: true
  },
  updatedAt: {
    type: Date,
    optional: true
  }
}));

books.attachIndex('title', {
  action: 'rebuild',
  background: false
});

if (Meteor.isServer) {

  Meteor.publish("books", function() {
    return books.find();
  });

  books.allow({
    insert: function() {
      return true;
    },
    update: function() {
      return true;
    },
    remove: function() {
      return true;
    }
  });
} else {
  Meteor.subscribe("books");
}

// Add one unique index outside of C2
if (Meteor.isServer) {
  try {
    books._dropIndex({field1: 1, field2: 1});
  } catch (err) {

  }
  books._ensureIndex({field1: 1, field2: 1}, {unique: true, sparse: true});
}

if (Meteor.isServer) {
  Tinytest.add('Collection2 - Ensure Index', function () {
    // We need to have an access to the getIndexes method of the embedded
    // collection in order to test this feature.
    // var indexes = books._collection._getIndexes();
  });
}

// When unique: true, inserts should fail if another document already has the same value
var uniqueBookId, isbn;
Tinytest.addAsync('Collection2 - Unique - Prep', function (test, next) {
  if (Meteor.isServer) books.remove({});

  isbn = Random.id();
  // Insert isbn
  uniqueBookId = books.insert({
    title: 'Ulysses',
    author: 'James Joyce',
    copies: 1,
    isbn: isbn
  }, function (error, result) {
    test.isFalse(!!error, 'We expected the insert not to trigger an error since isbn is unique');
    test.isTrue(!!result, 'result should be defined');

    var invalidKeys = books.simpleSchema().namedContext().invalidKeys();
    test.equal(invalidKeys.length, 0, 'We should get no invalidKeys back');
    // Insert isbn+'A'
    books.insert({
      title: 'Ulysses',
      author: 'James Joyce',
      copies: 1,
      isbn: isbn + 'A'
    }, function (error, result) {
      test.isFalse(!!error, 'We expected the insert not to trigger an error since isbn is unique');
      test.isTrue(!!result, 'result should be defined');

      var invalidKeys = books.simpleSchema().namedContext().invalidKeys();
      test.equal(invalidKeys.length, 0, 'We should get no invalidKeys back');
      next();
    });
  });
});

Tinytest.addAsync('Collection2 - Unique - Insert Duplicate', function (test, next) {
  books.insert({
    title: 'Ulysses',
    author: 'James Joyce',
    copies: 1,
    isbn: isbn
  }, function (error, result) {
    //console.log('error is', error, 'result is', result);
    test.isTrue(!!error, 'We expected the insert to trigger an error since isbn being inserted is already used');
    //test.equal(error.code, 11000, 'We expected the insert to trigger an E11000 duplicate key error');
    test.equal(error.invalidKeys.length, 1, 'We should get one invalidKey back attached to the Error object');
    test.isFalse(result, 'result should be false');

    var invalidKeys = books.simpleSchema().namedContext().invalidKeys();
    test.equal(invalidKeys.length, 1, 'We should get one invalidKey back');
    var key = invalidKeys[0] || {};

    test.equal(key.name, 'isbn', 'We expected the key "isbn"');
    test.equal(key.type, 'notUnique', 'We expected the type to be "notUnique"');
    next();
  });
});

Tinytest.addAsync('Collection2 - Unique - Insert Duplicate Non-C2 Index', function (test, next) {
  var val = Meteor.isServer ? 'foo' : 'bar';

  // Good insert
  books.insert({
    title: 'Ulysses',
    author: 'James Joyce',
    copies: 1,
    field1: val,
    field2: val
  }, function (error, result) {
    test.isFalse(!!error, 'We expected the insert not to trigger an error since the fields are unique');
    test.isTrue(!!result, 'result should be the new ID');

    var invalidKeys = books.simpleSchema().namedContext().invalidKeys();
    test.equal(invalidKeys.length, 0, 'We should get no invalidKeys back');

    // Bad insert
    books.insert({
      title: 'Ulysses',
      author: 'James Joyce',
      copies: 1,
      field1: val,
      field2: val
    }, function (error, result) {
      test.isTrue(!!error, 'We expected the insert to trigger an error since the fields are not unique');
      test.isFalse(result, 'result should be false');

      var invalidKeys = books.simpleSchema().namedContext().invalidKeys();
      test.equal(invalidKeys.length, 0, 'We should get no invalidKeys back because this is a non-C2 unique index');

      next();
    });
  });
});

Tinytest.addAsync('Collection2 - Unique - Validation Alone', function (test, next) {
  //test validation without actual updating
  var context = books.simpleSchema().namedContext();

  //we don't know whether this would result in a non-unique value or not because
  //we don't know which documents we'd be changing; therefore, no notUnique error
  context.validate({
    $set: {
      isbn: isbn
    }
  }, {
    modifier: true
  });
  var invalidKeys = context.invalidKeys();
  test.equal(invalidKeys.length, 0, 'We should get no invalidKeys back');

  context.validateOne({
    $set: {
      isbn: isbn
    }
  }, 'isbn', {
    modifier: true
  });
  invalidKeys = context.invalidKeys();
  test.equal(invalidKeys.length, 0, 'We should get no invalidKeys back');
  next();
});

Tinytest.addAsync('Collection2 - Unique - Update Self', function (test, next) {
  // When unique: true, updates should not fail when the document being updated has the same value
  books.update(uniqueBookId, {
    $set: {
      isbn: isbn
    }
  }, function (error) {
    test.isFalse(!!error,
      'We expected the update not to trigger an error since isbn is used only by the doc being updated');

    var invalidKeys = books.simpleSchema().namedContext().invalidKeys();
    test.equal(invalidKeys, [], 'We should get no invalidKeys back');
    next();
  });
});

Tinytest.addAsync('Collection2 - Unique - Update Another', function (test, next) {
  // When unique: true, updates should fail if another document already has the same value
  books.update(uniqueBookId, {
    $set: {
      isbn: isbn + 'A'
    }
  }, function (error) {
    test.isTrue(!!error,
      'We expected the update to trigger an error since isbn we want to change to is ' +
      'already used by a different document');
    test.equal(error.invalidKeys.length, 1, 'We should get one invalidKey back attached to the Error object');

    var invalidKeys = books.simpleSchema().namedContext().invalidKeys();
    test.equal(invalidKeys.length, 1, 'We should get one invalidKey back');
    var key = invalidKeys[0] || {};

    test.equal(key.name, 'isbn', 'We expected the key "isbn"');
    test.equal(key.type, 'notUnique', 'We expected the type to be "notUnique"');
    next();
  });
});

var testCollection = new Mongo.Collection('testCollection');
Tinytest.add('Collection2 - Unique - Object Array', function (test) {
  // We need to handle arrays of objects specially because the
  // index key must be 'a.b' if, for example, the schema key is 'a.$.b'.
  // Here we make sure that works.
  var testSchema = new SimpleSchema({
    'a.$.b': {
      type: String,
      index: {
        name: 'ab'
      }
    }
  });

  try {
    testCollection.attachSchema(testSchema);
    testCollection.attachIndex('ab', {unique: true});
  } catch (e) {
    // If we error, that means collection2 tried to set up the index incorrectly,
    // using the wrong index key
  }

  test.instanceOf(testCollection.simpleSchema(), SimpleSchema);
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Runtime;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Sync;
using Umbraco.Cms.Core.Web;

namespace Umbraco.Cms.Infrastructure.HostedServices
{
    /// <summary>
    /// Hosted service implementation for scheduled publishing feature.
    /// </summary>
    /// <remarks>
    /// Runs only on non-replica servers.</remarks>
    public class ScheduledPublishing : RecurringHostedServiceBase
    {
        private readonly IContentService _contentService;
        private readonly ILogger<ScheduledPublishing> _logger;
        private readonly IMainDom _mainDom;
        private readonly IRuntimeState _runtimeState;
        private readonly IServerMessenger _serverMessenger;
        private readonly IServerRoleAccessor _serverRegistrar;
        private readonly IUmbracoContextFactory _umbracoContextFactory;

        /// <summary>
        /// Initializes a new instance of the <see cref="ScheduledPublishing"/> class.
        /// </summary>
        /// <param name="runtimeState">Representation of the state of the Umbraco runtime.</param>
        /// <param name="mainDom">Representation of the main application domain.</param>
        /// <param name="serverRegistrar">Provider of server registrations to the distributed cache.</param>
        /// <param name="contentService">Service for handling content operations.</param>
        /// <param name="umbracoContextFactory">Service for creating and managing Umbraco context.</param>
        /// <param name="logger">The typed logger.</param>
        /// <param name="serverMessenger">Service broadcasting cache notifications to registered servers.</param>
        /// <param name="backofficeSecurityFactory">Creates and manages <see cref="IBackOfficeSecurity"/> instances.</param>
        public ScheduledPublishing(
            IRuntimeState runtimeState,
            IMainDom mainDom,
            IServerRoleAccessor serverRegistrar,
            IContentService contentService,
            IUmbracoContextFactory umbracoContextFactory,
            ILogger<ScheduledPublishing> logger,
            IServerMessenger serverMessenger)
            : base(TimeSpan.FromMinutes(1), DefaultDelay)
        {
            _runtimeState = runtimeState;
            _mainDom = mainDom;
            _serverRegistrar = serverRegistrar;
            _contentService = contentService;
            _umbracoContextFactory = umbracoContextFactory;
            _logger = logger;
            _serverMessenger = serverMessenger;
        }

        public override Task PerformExecuteAsync(object state)
        {
            if (Suspendable.ScheduledPublishing.CanRun == false)
            {
                return Task.CompletedTask;
            }

            switch (_serverRegistrar.CurrentServerRole)
            {
                case ServerRole.Subscriber:
                    _logger.LogDebug("Does not run on subscriber servers.");
                    return Task.CompletedTask;
                case ServerRole.Unknown:
                    _logger.LogDebug("Does not run on servers with unknown role.");
                    return Task.CompletedTask;
            }

            // Ensure we do not run if not main domain, but do NOT lock it
            if (_mainDom.IsMainDom == false)
            {
                _logger.LogDebug("Does not run if not MainDom.");
                return Task.CompletedTask;
            }

            // Do NOT run publishing if not properly running
            if (_runtimeState.Level != RuntimeLevel.Run)
            {
                _logger.LogDebug("Does not run if run level is not Run.");
                return Task.CompletedTask;
            }

            try
            {
                // We don't need an explicit scope here because PerformScheduledPublish creates it's own scope
                // so it's safe as it will create it's own ambient scope.
                // Ensure we run with an UmbracoContext, because this will run in a background task,
                // and developers may be using the UmbracoContext in the event handlers.

                // TODO: or maybe not, CacheRefresherComponent already ensures a context when handling events
                // - UmbracoContext 'current' needs to be refactored and cleaned up
                // - batched messenger should not depend on a current HttpContext
                //    but then what should be its "scope"? could we attach it to scopes?
                // - and we should definitively *not* have to flush it here (should be auto)

                using UmbracoContextReference contextReference = _umbracoContextFactory.EnsureUmbracoContext();
                try
                {
                    // Run
                    IEnumerable<PublishResult> result = _contentService.PerformScheduledPublish(DateTime.Now);
                    foreach (IGrouping<PublishResultType, PublishResult> grouped in result.GroupBy(x => x.Result))
                    {
                        _logger.LogInformation(
                            "Scheduled publishing result: '{StatusCount}' items with status {Status}",
                            grouped.Count(),
                            grouped.Key);
                    }
                }
                finally
                {
                    // If running on a temp context, we have to flush the messenger
                    if (contextReference.IsRoot)
                    {
                        _serverMessenger.SendMessages();
                    }
                }
            }
            catch (Exception ex)
            {
                // important to catch *everything* to ensure the task repeats
                _logger.LogError(ex, "Failed.");
            }

            return Task.CompletedTask;
        }
    }
}


text:
let Entity = require('./Entity');

class Dog extends Entity{
    constructor(name) {
        super(name);
    }

    saySomething() {
        return `${super.name} barks!`;
    }
}

module.exports = Dog;


text:
package genetic_algorithm

import (
	log "github.com/cihub/seelog"
	"sort"
)

type OptimizerBase struct {
	OptimizerBaseVirtualMInterface

	initializer InitializerInterface
	weeder      WeederInterface
	selector    SelectorInterface
	crossover   CrossoverInterface
	mutator     MutatorInterface

	costFunction          CostFunction
	statisticsConstructor StatisticsConstructor
	statisticsOptions     StatisticsOptionsInterface
	stopCriterion         StopCriterionInterface

	popSize   int
	chromSize int

	population Chromosomes
	statistics StatisticsInterface
}

// MutatorBase's virtual methods
type OptimizerBaseVirtualMInterface interface {
	optimizeInner()
	check()
}

func NewOptimizerBase(virtual OptimizerBaseVirtualMInterface) *OptimizerBase {
	optimizer := new(OptimizerBase)

	optimizer.OptimizerBaseVirtualMInterface = virtual
	optimizer.statisticsConstructor = NewStatisticsDefault
	optimizer.statisticsOptions = NewStatisticsDefaultOptions()

	return optimizer
}

func (optimizer *OptimizerBase) Initializer(initializer InitializerInterface) *OptimizerBase {
	optimizer.initializer = initializer
	return optimizer
}
func (optimizer *OptimizerBase) Selector(selector SelectorInterface) *OptimizerBase {
	optimizer.selector = selector
	return optimizer
}
func (optimizer *OptimizerBase) Crossover(crossover CrossoverInterface) *OptimizerBase {
	optimizer.crossover = crossover
	return optimizer
}
func (optimizer *OptimizerBase) Mutator(mutator MutatorInterface) *OptimizerBase {
	optimizer.mutator = mutator
	return optimizer
}
func (optimizer *OptimizerBase) CostFunction(cost CostFunction) *OptimizerBase {
	optimizer.costFunction = cost
	return optimizer
}
func (optimizer *OptimizerBase) StopCriterion(stopCriterion StopCriterionInterface) *OptimizerBase {
	optimizer.stopCriterion = stopCriterion
	return optimizer
}
func (optimizer *OptimizerBase) StatisticsConstructor(constr StatisticsConstructor) *OptimizerBase {
	optimizer.statisticsConstructor = constr
	return optimizer
}
func (optimizer *OptimizerBase) StatisticsOptions(statisticsOptions StatisticsOptionsInterface) *OptimizerBase {
	optimizer.statisticsOptions = statisticsOptions
	return optimizer
}
func (optimizer *OptimizerBase) PopSize(popSize int) *OptimizerBase {
	optimizer.popSize = popSize
	return optimizer
}
func (optimizer *OptimizerBase) ChromSize(chromSize int) *OptimizerBase {
	optimizer.chromSize = chromSize
	return optimizer
}
func (optimizer *OptimizerBase) check() {
	if optimizer.initializer == nil {
		panic("Initializer must be set")
	}
	if optimizer.selector == nil {
		panic("Selector must be set")
	}
	if optimizer.crossover == nil {
		panic("Crossover must be set")
	}
	if optimizer.mutator == nil {
		panic("Mutator must be set")
	}
	if optimizer.costFunction == nil {
		panic("CostFunction must be set")
	}
	if optimizer.stopCriterion == nil {
		panic("StopCriterion must be set")
	}
	if optimizer.statisticsConstructor == nil {
		panic("StatisticsConstructor must be set")
	}
	if optimizer.statisticsOptions == nil {
		panic("StatisticsOptions must be set")
	}
	if optimizer.popSize <= 0 {
		panic("PopSize must be positive value")
	}
	if optimizer.chromSize <= 0 {
		panic("ChromSize must be positive value")
	}

	optimizer.OptimizerBaseVirtualMInterface.check()
}

func (optimizer *OptimizerBase) Optimize() (ChromosomeInterface, StatisticsDataInterface) {
	optimizer.check()
	optimizer.stopCriterion.Setup(optimizer.statisticsOptions)

	optimizer.statistics = optimizer.statisticsConstructor(optimizer.statisticsOptions)
	optimizer.statistics.Start()

	optimizer.initPopulation()

	iter := 0
	for {
		log.Infof("GENERATION %d", iter)

		optimizer.sort()
		optimizer.statistics.OnGeneration(optimizer.population)

		if optimizer.stopCriterion.ShouldStop(optimizer.statistics.Data()) {
			break
		}

		optimizer.OptimizerBaseVirtualMInterface.optimizeInner()

		iter++
	}

	optimizer.statistics.End()

	return optimizer.population[0], optimizer.statistics.Data()
}
func (optimizer *OptimizerBase) initPopulation() {
	optimizer.statistics.Start("init")
	defer optimizer.statistics.End()

	optimizer.population = optimizer.initializer.Init(optimizer.popSize, optimizer.chromSize)
	if len(optimizer.population) == 0 {
		panic("Init population is empty")
	}
}
func (optimizer *OptimizerBase) sort() {
	optimizer.statistics.Start("cost")
	defer optimizer.statistics.End()

	optimizer.population.SetCost(optimizer.costFunction)
	sort.Sort(optimizer.population)

	log.Infof("Best: %v", optimizer.population[0])
	log.Debugf("Population:\n%v\n", optimizer.population)
}

func (optimizer *OptimizerBase) SetupStatisticsOptions() StatisticsOptionsInterface {
	return optimizer.statisticsOptions
}


text:
package org.elasticsearch.action.support;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.tasks.TaskManager;

import java.util.concurrent.atomic.AtomicInteger;

public abstract class TransportAction<Request extends ActionRequest, Response extends ActionResponse> {

    public final String actionName;
    private final ActionFilter[] filters;
    protected final TaskManager taskManager;
    /**
     * @deprecated declare your own logger.
     */
    @Deprecated
    protected Logger logger = LogManager.getLogger(getClass());

    protected TransportAction(String actionName, ActionFilters actionFilters, TaskManager taskManager) {
        this.actionName = actionName;
        this.filters = actionFilters.filters();
        this.taskManager = taskManager;
    }

    /**
     * Use this method when the transport action should continue to run in the context of the current task
     */
    public final void execute(Task task, Request request, ActionListener<Response> listener) {
        ActionRequestValidationException validationException = request.validate();
        if (validationException != null) {
            listener.onFailure(validationException);
            return;
        }

        if (task != null && request.getShouldStoreResult()) {
            listener = new TaskResultStoringActionListener<>(taskManager, task, listener);
        }

        RequestFilterChain<Request, Response> requestFilterChain = new RequestFilterChain<>(this, logger);
        requestFilterChain.proceed(task, actionName, request, listener);
    }

    protected abstract void doExecute(Task task, Request request, ActionListener<Response> listener);

    private static class RequestFilterChain<Request extends ActionRequest, Response extends ActionResponse>
        implements
            ActionFilterChain<Request, Response> {

        private final TransportAction<Request, Response> action;
        private final AtomicInteger index = new AtomicInteger();
        private final Logger logger;

        private RequestFilterChain(TransportAction<Request, Response> action, Logger logger) {
            this.action = action;
            this.logger = logger;
        }

        @Override
        public void proceed(Task task, String actionName, Request request, ActionListener<Response> listener) {
            int i = index.getAndIncrement();
            try {
                if (i < this.action.filters.length) {
                    this.action.filters[i].apply(task, actionName, request, listener, this);
                } else if (i == this.action.filters.length) {
                    this.action.doExecute(task, request, listener);
                } else {
                    listener.onFailure(new IllegalStateException("proceed was called too many times"));
                }
            } catch (Exception e) {
                logger.trace("Error during transport action execution.", e);
                listener.onFailure(e);
            }
        }

    }

    /**
     * Wrapper for an action listener that stores the result at the end of the execution
     */
    private static class TaskResultStoringActionListener<Response extends ActionResponse> implements ActionListener<Response> {
        private final ActionListener<Response> delegate;
        private final Task task;
        private final TaskManager taskManager;

        private TaskResultStoringActionListener(TaskManager taskManager, Task task, ActionListener<Response> delegate) {
            this.taskManager = taskManager;
            this.task = task;
            this.delegate = delegate;
        }

        @Override
        public void onResponse(Response response) {
            try {
                taskManager.storeResult(task, response, delegate);
            } catch (Exception e) {
                delegate.onFailure(e);
            }
        }

        @Override
        public void onFailure(Exception e) {
            try {
                taskManager.storeResult(task, e, delegate);
            } catch (Exception inner) {
                inner.addSuppressed(e);
                delegate.onFailure(inner);
            }
        }
    }
}


text:
package com.cardshifter.api.both;

import com.cardshifter.api.messages.Message;

/**
 * Request to invite a player to start a new game.
 */
public class InviteRequest extends Message {

	private int id;
	private String name;
	private String gameType;

	/** Constructor. (no params) */
	public InviteRequest() {
		this(0, "", "");
	}
	/**
	 * Constructor.
	 * @param id  The Id of this invite request
	 * @param name  The name of the player being invited
	 * @param gameType  The game type of this invite request
	 */
	public InviteRequest(int id, String name, String gameType) {
		super("inviteRequest");
		this.id = id;
		this.name = name;
		this.gameType = gameType;
	}
	/** @return  The Id of this invite request */
	public int getId() {
		return id;
	}
	/** @return  The name of the player being invited */
	public String getName() {
		return name;
	}
	/** @return  The game type of this invite request */
	public String getGameType() {
		return gameType;
	}

}


text:
卡劵类型

										<input type="search" placeholder="名称" data-ng-keyup="getCouponCategoryList()" ng-model="queryParam.keyword" class="form-control" aria-controls="dt_basic">

                                        <select ug-select2 style="width: 250px;" ng-change="getCouponCategoryList()" ng-model="queryParam.categoryType" name="categoryType">
                                            <option value="">--请选择--</option>
                                            <option value="1">卡</option>
                                            <option value="2">劵</option>
                                        </select>

								<button class="btn btn-primary" type="button" data-ng-click="open()">

									新增
								</button>

                                    类别类型
                                    类别名称
									操作

 0" ng-mouseenter="show=true" ng-mouseleave="show=false">

                                        卡
                                        消费券

                                             |

暂无消息数据

								<ug-pagination page-info="pageInfoSetting" ></ug-pagination>


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

<title>Running Examples</title>

Running Examples with latest snapshot

JBehave was developed as behaviour and example driven.  As such the examples are
an integral part of the build, verifying the correctness of the behaviour.  They
are not released as artifacts, but they can be run easily browsed
or checked out from source control:

To build core modules and run examples with Maven:

The 'examples' profile instructs Maven to build the releasable modules and to verify their
behaviour by running the examples afterwards.

Running Examples against a fixed version

In some cases, it may be necessary to run the examples against a known version of JBehave.

Note that running the examples in 'standalone' mode requires the JBehave parent POM to be present, as it
contains the information about the development setup of the project, e.g. the compiler, the layout of the source, etc.

To ensure JBehave parent POM is available, two approaches are possible.  One is to check out project source as above and install the parent POM:

The other approach is to fetch the parent POM from the snapshots remote repository.  For this, you need to add the
following profile to your $HOME/.m2/settings.xml

and run with additional profile

As with any Maven artifact that is not expected to change,
the build or retrieval is only required once, as it will be cached in the local repository.
So, once you've built the JBehave parent POM from source or retrieved it from the snapshots
repository, you don't need to do it again, unless you think it needs to be updated.

Running Examples via Ant

While the basic infrastructure of the build is Maven-based, the examples also show how to run stories via Ant.
The trader example has an Ant build.xml which shows its use.  Note that it requires the
Maven Ant Tasks jar to be present in the $ANT_HOME/lib directory
in order to retrieve the dependency information from the Maven POM.


text:
FROM node:latest

WORKDIR /opt

COPY package.json ./

RUN npm install

ENV PATH /opt/node_modules/mocha/bin:$PATH

VOLUME ["/opt/app"]

ENTRYPOINT ["npm", "test"]


text:
package org.apereo.cas.adaptors.jdbc;

import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.authentication.HandlerResult;
import org.apereo.cas.authentication.PreventedException;
import org.apereo.cas.authentication.UsernamePasswordCredential;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;

import javax.security.auth.login.AccountNotFoundException;
import javax.security.auth.login.FailedLoginException;
import java.security.GeneralSecurityException;

/**
 * Class that if provided a query that returns a password (parameter of query
 * must be username) will compare that password to a translated version of the
 * password provided by the user. If they match, then authentication succeeds.
 * Default password translator is plaintext translator.
 *
 * @author Scott Battaglia
 * @author Dmitriy Kopylenko
 * @author Marvin S. Addison
 *
 * @since 3.0.0
 */
public class QueryDatabaseAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler {

    private String sql;

    @Override
    protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential, final String originalPassword)
            throws GeneralSecurityException, PreventedException {

        if (StringUtils.isBlank(this.sql) || getJdbcTemplate() == null) {
            throw new GeneralSecurityException("Authentication handler is not configured correctly. "
                + "No SQL statement or JDBC template is found.");
        }

        final String username = credential.getUsername();
        final String password = credential.getPassword();

        try {
            final String dbPassword = getJdbcTemplate().queryForObject(this.sql, String.class, username);

            if ((StringUtils.isNotBlank(originalPassword) && !this.matches(originalPassword, dbPassword))
                  || (StringUtils.isBlank(originalPassword) && !StringUtils.equals(password, dbPassword))) {
                throw new FailedLoginException("Password does not match value on record.");
            }
        } catch (final IncorrectResultSizeDataAccessException e) {
            if (e.getActualSize() == 0) {
                throw new AccountNotFoundException(username + " not found with SQL query");
            }
            throw new FailedLoginException("Multiple records found for " + username);
        } catch (final DataAccessException e) {
            throw new PreventedException("SQL exception while executing query for " + username, e);
        }

        return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null);
    }

    @Override
    protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
                throws GeneralSecurityException, PreventedException {
        return authenticateUsernamePasswordInternal(credential, null);
    }

    public void setSql(final String sql) {
        this.sql = sql;
    }
}


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model and pass it using module.exports
module.exports = mongoose.model('Company', new Schema({
    name: String,
    currentRating : String
}));


text:
import * as fs from 'fs';
import * as path from 'path';
import * as shx from 'shelljs';

shx.cd(path.join(process.env['TEST_SRCDIR'] !, 'angular', 'packages', 'common', 'npm_package'));

describe('@angular/common ng_package', () => {
  describe('should have the locales files', () => {
    it('/locales', () => {
      const files = shx.ls('locales').stdout.split('\n');
      expect(files.some(n => n.endsWith('.d.ts'))).toBe(true, `.d.ts files don't exist`);
      expect(files.some(n => n.endsWith('.js'))).toBe(true, `.js files don't exist`);
    });
    it('/locales/extra', () => {
      const files = shx.ls('locales/extra').stdout.split('\n');
      expect(files.some(n => n.endsWith('.d.ts'))).toBe(true, `.d.ts files don't exist`);
      expect(files.some(n => n.endsWith('.js'))).toBe(true, `.js files don't exist`);
    });
    // regression test for https://github.com/angular/angular/issues/23217
    // Note, we don't have an e2e test that covers this
    it('doesn\'t pass require in a way that breaks webpack static analysis',
       () => { expect(shx.cat('locales/fr.js')).not.toContain('factory(require, exports)'); });
  });

  it('should have right bundle files', () => {
    expect(shx.ls('-R', 'bundles').stdout.split('\n').filter(n => !!n).sort()).toEqual([
      'common-http-testing.umd.js',
      'common-http-testing.umd.js.map',
      'common-http-testing.umd.min.js',
      'common-http-testing.umd.min.js.map',
      'common-http.umd.js',
      'common-http.umd.js.map',
      'common-http.umd.min.js',
      'common-http.umd.min.js.map',
      'common-testing.umd.js',
      'common-testing.umd.js.map',
      'common-testing.umd.min.js',
      'common-testing.umd.min.js.map',
      'common.umd.js',
      'common.umd.js.map',
      'common.umd.min.js',
      'common.umd.min.js.map',
    ]);
  });

  it('should reference core using global symbol in umd',
     () => { expect(shx.cat('bundles/common.umd.js')).toContain('global.ng.core'); });

  it('should have right fesm files', () => {
    const expected = [
      'common.js',
      'common.js.map',
      'http',
      'http.js',
      'http.js.map',
      'http/testing.js',
      'http/testing.js.map',
      'testing.js',
      'testing.js.map',
    ];
    expect(shx.ls('-R', 'fesm5').stdout.split('\n').filter(n => !!n).sort()).toEqual(expected);
    expect(shx.ls('-R', 'fesm2015').stdout.split('\n').filter(n => !!n).sort()).toEqual(expected);
  });

  describe('should have module resolution properties in the package.json file for', () => {
    // https://github.com/angular/common-builds/blob/master/package.json
    it('/', () => {
      const actual = JSON.parse(fs.readFileSync('package.json', {encoding: 'utf-8'}));
      expect(actual['main']).toEqual('./bundles/common.umd.js');
    });
    // https://github.com/angular/common-builds/blob/master/http/package.json
    it('/http', () => {
      const actual = JSON.parse(fs.readFileSync('http/package.json', {encoding: 'utf-8'}));
      expect(actual['main']).toEqual('../bundles/common-http.umd.js');
      expect(actual['es2015']).toEqual('../fesm2015/http.js');
      expect(actual['module']).toEqual('../fesm5/http.js');
      expect(actual['typings']).toEqual('./http.d.ts');
    });
    // https://github.com/angular/common-builds/blob/master/testing/package.json
    it('/testing', () => {
      const actual = JSON.parse(fs.readFileSync('testing/package.json', {encoding: 'utf-8'}));
      expect(actual['main']).toEqual('../bundles/common-testing.umd.js');
    });
    // https://github.com/angular/common-builds/blob/master/http/testing/package.json
    it('/http/testing', () => {
      const actual = JSON.parse(fs.readFileSync('http/testing/package.json', {encoding: 'utf-8'}));
      expect(actual['main']).toEqual('../../bundles/common-http-testing.umd.js');
      expect(actual['es2015']).toEqual('../../fesm2015/http/testing.js');
      expect(actual['module']).toEqual('../../fesm5/http/testing.js');
      expect(actual['typings']).toEqual('./testing.d.ts');
    });
  });
});


text:
export class Property {
   key: string;
   secret: string;
   val: string;

   constructor(prop: any) {
      this.key = prop.key;
      this.secret = prop.secret;
      this.val = prop.val;

   }

   static compareProperties(a:Property, b:Property) {
      return a.key.localeCompare(b.key);
   }

}


text:
<?php
// NOTE: This example uses the next generation Twilio helper library - for more
// information on how to download and install this version, visit
// https://www.twilio.com/docs/libraries/php
require_once('/path/to/twilio-php/Rest/Client.php');

use Twilio\Rest\Client;

// Your Account SID and Auth Token from https://www.twilio.com/console
$accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$authToken = "your_auth_token";

$serviceSid = "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

// Initialize the client
$client = new Client($accountSid, $authToken);

// Create a user
$bindings = $client
    ->notify->services($serviceSid)
    ->users('User0001')->bindings->read();

echo $bindings[0]->sid;


text:
module Api
  class ContactsController < ApplicationController
    #before_filter :require_login
    #skip_before_filter :require_login, only: [:new, :create, :verify]
    before_filter :restrict_access, :verify_user
    respond_to :html, :json

    # GET /contacts(.:format)
    def index
      respond_to do |format|
        format.json do
          render :json => current_user.contacts.to_json
        end
      end
    end

    # GET /contacts/:id(.:format)
    def show
      respond_to do |format|
        format.json do
          render :json => contacts.find(params[:id]).to_json
        end
      end
    end

    # GET /user(.:format)
    def show
      respond_to do |format|
        format.json do
          render :json => current_user.to_json
        end
      end
    end

    # POST /contacts/(.:format)
    def create
      @contact = current_user.contacts.build(params)

      respond_to do |format|
        if @contact.save
          format.json { render :json => params }
        else
          format.json { render :json => {:errors => @contact.errors.full_messages } }
        end
      end
    end

    # GET /api/contacts/:id/phone(.:format)
    def phone
      contact = current_user.contacts.find(params[:id])
      respond_to do |format|
        format.json do
          render :json => contact.phone
        end
      end
    end

    def destroy
    end

    protected

    def verify_user
      token = request.headers['Authorization']
      application = Stormpath::Rails::Client.application
      verify_token = Stormpath::Oauth::VerifyAccessToken.new(application).verify(token)
      user_href = verify_token.account["href"]
      @account = application.accounts.get user_href
      @current_user = User.find_by username: @account.properties["username"]
    end

    def restrict_access
      secret_token = request.headers['X-3scale-proxy-secret-token']
      if secret_token != ENV['SHARED_PROXY_SECRET']
        respond_to do |format|
          format.html
          format.json { render :json => { :outcome => 'Access Denied'} }
        end
        return false
      end
    end

    private
    def contact_params
      params.require(:contact).permit(:format,:name,:email,:phone) if params[:contact]
    end
  end
end


text:
var base_filter_buffer = require('../lib/base_filter_buffer'),
  util = require('util'),
  logger = require('log4node');

function FilterMultiline() {
  base_filter_buffer.BaseFilterBuffer.call(this);
  this.mergeConfig({
    name: 'Multiline',
    required_params: ['start_line_regex'],
    optional_params: ['max_delay', 'regex_flags'],
    default_values: {
      max_delay: 50,
    },
    start_hook: this.start,
  });
}

util.inherits(FilterMultiline, base_filter_buffer.BaseFilterBuffer);

FilterMultiline.prototype.start = function(callback) {
  this.start_line_regex = new RegExp(this.start_line_regex, this.regex_flags);
  logger.info('Initialized multiline filter with start_line_regex: ' + this.start_line_regex + ', flags: ' + (this.regex_flags || ''));
  this.setInterval(this.max_delay);
  callback();
};

FilterMultiline.prototype.process = function(data) {
  var key = this.computeKey(data);
  if (data.message.match(this.start_line_regex)) {
    this.sendIfNeeded(key);
  }
  this.store(key, data);
};

exports.create = function() {
  return new FilterMultiline();
};


text:
Package.describe({
  summary: "An angular directive for the fullcalendar jquery plugin."
});

function packageExists(pkgname) {
  var fs = Npm.require('fs');
  var path = Npm.require('path');
  var pkgpath = path.join('packages', pkgname);
  return fs.existsSync(pkgpath);
}

Package.on_use(function (api) {
  api.use('bower', 'client');

  if (packageExists('angularite')) {
    api.use('angularite', 'client');
  } else if (packageExists('ngMeteor')) {
    api.use('ngMeteor', 'client');
  }

  // Install bower components.
  api.add_files('smart.json', 'client');

  // Client files.
  api.add_files('init.js', 'client');

  api.add_files('.meteor/local/bower/moment/moment.js', 'client');
  api.add_files('.meteor/local/bower/fullcalendar/dist/fullcalendar.js', 'client');
  api.add_files('.meteor/local/bower/fullcalendar/dist/fullcalendar.css', 'client');
});


text:
<raid>
	 <!--Announcements-->
	<announce delay="1000" type="event" message="Even more sizzling in the Ankrahmun Dipthrah tombs." />
	<announce delay="20000" type="event" message="Poison overflow in the Ankrahmun Dipthrah tombs!" />

	 <!--Single Spawns-->
	 <areaspawn delay="20000" fromx="33129" fromy="32569" fromz="7" tox="33156" toy="32598" toz="7">
	    <monster name="Cobra" amount="15" />
	 </areaspawn>
</raid>


text:
title: "Painting: Variance Number 5"
header:
  image: /assets/images/content/header_variance5.png
  teaser: "/assets/images/content/teaser/t_v5.png"
categories:
  - Painting
tags:
  - painting
  - variance
  - fantasy man
  - process
  - sketches
  - lineart
  - composition
---

Each time I look at this picture I get the sense of – dryness –. Certain amount of ugliness. There's enough vibrancy to ensure this picture will gather the attention of those that enjoy neon colour schemes, but it is subdued by the dull background – pale mauve, gray periwinkle and a midnight blue: light enough to share the same space with the mauve and periwinkle.

This is also my first definite picture to incorporate only CMYK values. They were selected from the Pantone +CMYK library. It worked pretty well. This was the palette I worked with:

The only colour I didn't use was the light green.
I proofed the image, and only the green in the man's cloak dulls a tad; the green was mixed too much with the blue while painting, so the green, which is greenish-blue, does not properly come out when switched to CMYK. The rest of the colours keep consistent.
The initial concept came from a sketch I drew in an old sketch book of mine, back in 2014. I probably sketched it in one of my art classes and I was going to eventually plan it out as an image but I never did. The character is Wolfe, a shape shifter. Two years later, and here is a much nicer rendition of the original. I do not have this sketch book with me currently so no scan of the original is available.
A black and white creation of the image might be done.


text:
#ifndef TABU_HH
#define TABU_HH

// generic tabu engine
// variants are: tabu, tabu_gain, tabu_ns_omp, tabu_ns_mpi

#include <limits>
#include <iostream>
#include <algorithm>

#include "neighborhood_oper.hh"
#include "move_reduction.hh"
#include "meta_gen.hh"
#include "dummy_oper.hh"
#include <time.h>

namespace metl {

// this is an internal class used by tabu algorithms
template<class prob_t, class _move, class _tabu_list>
class tabu_kernel : public move_reduction<prob_t, _move> {
  typedef move_reduction<prob_t, _move> base;
public:

  tabu_kernel(const typename prob_t::sol_t& sol,
	      _move& best_move,
	      const typename prob_t::eval_t& current_eval,
	      const typename prob_t::eval_t& best_eval,
	      const _tabu_list& tabu_list,
	      const unsigned& cycle,
	      bool using_mpi=false)
    : move_reduction<prob_t, _move>(best_move, using_mpi),

      s(sol),
      ce(current_eval),
      be(best_eval),
      _tl(tabu_list),
      _cycle(cycle)
  {}

  // tabu kernel. Called from the neighborhood evaluation (defined by user)
  // compute move evaluation
  inline bool operator()(const _move m) {
    operator()(m,m.internal_cost(s));
    return false;  // always return false because move not directly applied
  }

  // evaluation is available. This is called either from previous version or
  //    from tabu_gain because the gain structure already has the cost of the
  //    move pre-computed
  inline bool operator()(const _move m, const typename prob_t::eval_t& e) {
    if ((e<base::thread_cost()) && (!_tl.is_tabu(m, s, _cycle) || (e+ce < be))) {
      base::update_thread_move_and_cost(m,e);
    }
    return false;  // always return false because move not directly applied
  }

private:
  const typename prob_t::sol_t& s;
  const typename prob_t::eval_t& ce;
  const typename prob_t::eval_t& be;

  const _tabu_list& _tl;
  const unsigned& _cycle;
};

// this is a generic implementation of the tabu algorithm
// this is not usable directly. Use one of its derived class.
template <class prob_t,
	  class _move,
	  class _neighborhood,
	  class _tabu_list,
	  class generator_type=no_generator<prob_t> >
struct tabu_base: public meta_gen<prob_t, generator_type> {

  void set_tenur_out(unsigned tabu_tenur) {
    // tabu tenur
    tenur_out=tabu_tenur;
  }

  void set_tenur_in(unsigned tabu_tenur) {
    // tabu tenur
    tenur_in=tabu_tenur;
  }

  void set_tenur(unsigned tabu_tenur) {
    // tabu tenur
    tenur_out=tenur_out=tabu_tenur;
  }

  void set_n_iter(unsigned n_iter) {
    // number of iteration of tabu search
    _n_iter = n_iter;
  }

  void set_return_current(float _p) {
    // probability of returning with current solution rather than the
    // best solution if the algorithm could not improve the best
    // solution
    return_current = _p;
  }

#ifdef XLC_WORKAROUND
  // IBM XLC does not let the derived classes to access the protected member.
  // this is stupid and I could not find out why.
public:
#else
protected:
#endif

#ifndef XLC_WORKAROUND
  using meta_gen<prob_t, generator_type>::operator();
#endif

  using meta_gen<prob_t, generator_type>::generator;

  tabu_base(unsigned tabu_tenur=8, unsigned n_iter=200, float r_current=0)
    : tenur_in(tabu_tenur),
      tenur_out(tabu_tenur),
      _n_iter(n_iter),
      return_current(r_current)
  {}

  virtual ~tabu_base() {}

  template <class _nh_eval, class _gain_t, class PE, class RNG>
  typename prob_t::soleval_t operator()(const typename prob_t::soleval_t& se_in,
					_nh_eval& nh_eval, _gain_t& gain,
					PE& periodic_exchange, RNG& srng,
					bool mpi=false) const {

    typename prob_t::soleval_t se(se_in);

    CHECK_EVAL(se);

    _move next_move;  // best non tabu move or aspirated
    _tabu_list tl;

    typename prob_t::soleval_t best=se;
    unsigned cycle=1; // need to start at 1 because tabu list is filled with 0s. (every moves are tabu if cycle=0)

    typedef tabu_kernel<prob_t, _move, _tabu_list> tabu_k_t;

    tabu_k_t tabu_k(se.first, next_move, se.second, best.second, tl, cycle, mpi);

    const typename prob_t::eval_t optimum = prob_t::instance().optimum();

    while(cycle<=_n_iter) {
      nh_eval(tabu_k, se.first);
      tabu_k.reduce();

      if (tabu_k.cost() == std::numeric_limits<typename prob_t::eval_t>::max())
	{
	  std::cerr << "No move left. (tabu tenur probably too high)"<< std::endl;
	  abort();
	}

      gain.update_before(next_move, se.first);
      //********* APPLY SELECTED MOVE
      next_move(se.first);           // apply the move to sol
      //*********
      // one of the two update functions usually does nothing and will
      // be optimised away.
      gain.update_after(next_move, se.first);

      // make the move tabu
      tl.make_tabu(next_move, se.first, cycle,
		   srng(9*tenur_in/10, 11*tenur_in/10),
		   srng(9*tenur_out/10, 11*tenur_out/10));

      se.second += tabu_k.cost();

      if (se.second < best.second) {
	// save new best solution
	best = se;
#ifdef TABU_TRACE
	std::cout <<
#ifdef USE_MPI
	  MPI::COMM_WORLD.Get_rank() << " " <<
#else
	  "0 "<<
#endif
	  cycle << " xxxx "<< se.second << std::endl;
#endif
	if (se.second <= optimum) break;
      }

      if (periodic_exchange(se)) {
	gain.init(se.first);
      }

      tabu_k.reset();
      ++cycle;
    }

    if ((se_in.second > best.second) || (srng()>return_current)) {
      se = best;
    }

    CHECK_EVAL(se);

    return se;
  }

protected:
  unsigned tenur_in, tenur_out;
  unsigned _n_iter;
private:
  float return_current;
};

// this is a basic version
template<class prob_t,
	 class _move,
	 class _neighborhood,
	 class _tabu_list,
	 class generator_type=no_generator<prob_t> >
class tabu : public tabu_base<prob_t, _move, _neighborhood, _tabu_list, generator_type> {

  typedef tabu_base<prob_t, _move, _neighborhood, _tabu_list, generator_type> base;

public:
    using base::operator();
    using base::generator;

  tabu(unsigned tabu_tenur=8, unsigned n_iter=1000)
    : base(tabu_tenur, n_iter)
  {}
  const std::string name() const { return "Tabu Search, base version"; }

  typename prob_t::soleval_t operator()(const typename prob_t::soleval_t& se) {
    dummy_op dummy;
    return operator()(se, dummy);
  }

protected:
  template <class PE>
  typename prob_t::soleval_t operator()(const typename prob_t::soleval_t& se, PE& periodic_exchange) {
    _neighborhood n;
    basic_nh_eval<_neighborhood, _move, typename prob_t::sol_t> nh_eval(n);
    dummy_op dummy;

    return base::operator()(se, nh_eval, dummy, periodic_exchange, rng);
  }
};

// this version uses OpenMP for parallel neighborhood evaluation
template<class prob_t,
	 class _move,
	 class _neighborhood,
	 class _tabu_list,
	 class generator_type=no_generator<prob_t> >
class tabu_ns_omp : public tabu_base<prob_t, _move,_neighborhood, _tabu_list, generator_type> {

  typedef tabu_base<prob_t, _move, _neighborhood, _tabu_list, generator_type> base;

public:
   using base::operator();
   using base::generator;

  tabu_ns_omp(unsigned tabu_tenur=8, unsigned n_iter=1000)
    : base(tabu_tenur, n_iter)
  {}

  const std::string name() const { return "Parallel tabu search based on neighborhood separation using OpenMP"; }

  typename prob_t::soleval_t operator()(const typename prob_t::soleval_t& se) {
    dummy_op dummy;
    return operator()(se, dummy);
  }

protected:
  template<class PE>
  typename prob_t::soleval_t operator()(const typename prob_t::soleval_t& se, PE& periodic_exchange) {
    _neighborhood n;
    ns_nh_omp<_neighborhood, _move, typename prob_t::sol_t> nh_eval(n);
    dummy_op dummy;
    sync_rng srng(time(0));

    return base::operator()(se, nh_eval, dummy, periodic_exchange, srng);
  }
};

#ifdef USE_MPI

// this version use MPI to seperate neighborhood evaluation
template<class prob_t,
	 class _move,
	 class _neighborhood,
	 class _tabu_list,
	 class generator_type=no_generator<prob_t> >
class tabu_ns_mpi : public tabu_base<prob_t, _move, _neighborhood, _tabu_list, generator_type> {

  typedef tabu_base<prob_t, _move, _neighborhood, _tabu_list, generator_type> base;

public:
   using base::operator();
   using base::generator;

  tabu_ns_mpi(unsigned tabu_tenur=8, unsigned n_iter=1000)
    : base(tabu_tenur, n_iter)
  {}

  typename prob_t::soleval_t operator()(const typename prob_t::soleval_t& se) {
    dummy_op dummy;
    return operator()(se, dummy);
  }

  const std::string name() const { return "Parallel tabu search based on neighborhood separation using MPI"; }

protected:
  template<class PE>
  typename prob_t::soleval_t operator()(const typename prob_t::soleval_t& se_in, PE& periodic_exchange) {
    typename prob_t::soleval_t se(se_in);
    sol_reducter<prob_t>::Allreduce(se);

    _neighborhood n;
    ns_nh_mpi<_neighborhood, _move, typename prob_t::sol_t> nh_eval(n);
    dummy_op dummy;
    sync_rng srng(time(0));

    return base::operator()(se, nh_eval, dummy, periodic_exchange, srng,true);
  }
};
#endif

// this version uses a gain structure to accelerate the computation of the next move
template<class prob_t,
	 class _move,
	 class _gain_struct_t,
	 class _tabu_list,
	 class generator_type=no_generator<prob_t> >
class tabu_gain : public tabu_base<prob_t, _move, dummy_neighborhood<prob_t>, _tabu_list,generator_type> {
  typedef tabu_base<prob_t, _move, dummy_neighborhood<prob_t>, _tabu_list, generator_type> base;

public:
   using base::operator();
   using base::generator;

  tabu_gain(unsigned tabu_tenur=8, unsigned n_iter=1000)
    : base(tabu_tenur, n_iter)
  {}

  typename prob_t::soleval_t operator()(const typename prob_t::soleval_t& se) {
    dummy_op dummy;
    return operator()(se, dummy);
  }

  const std::string name() const { return "Tabu Search using a gain structure"; }

#ifdef XLC_WORKAROUND
  // IBM XLC does not let the derived classes to access the protected member.
  // this is stupid and I could not find out why.
public:
#else
protected:
#endif

  template <class PE>
  typename prob_t::soleval_t operator()(const typename prob_t::soleval_t& se, PE& periodic_exchange) {

    _gain_struct_t _gain;
    _gain.init(se.first);
    gain_nh_eval<_gain_struct_t, _move, typename prob_t::sol_t> nh_eval(_gain);

    return base::operator()(se, nh_eval, _gain, periodic_exchange, rng);
  }
};

}

#endif


text:
<?php

namespace Oro\Bundle\FormBundle\Tests\Unit\Fixtures\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 */
class Contact
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="ContactEmail", mappedBy="owner", cascade={"all"}, orphanRemoval=true)
     */
    protected $emails;
}


text:
<?php

namespace Molajo\Fieldhandler\Constraint;

use CommonApi\Fieldhandler\ConstraintInterface;

/**
 * Length Constraint
 *
 * @package    Molajo
 * @copyright  2014-2015 Amy Stephen. All rights reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @since      1.0.0
 */
class Length extends AbstractConstraintTests implements ConstraintInterface
{
    /**
     * Message Code
     *
     * @var    integer
     * @since  1.0.0
     */
    protected $message_code = 8000;

    /**
     * Validate
     *
     * @return  boolean
     * @since   1.0.0
     */
    protected function validation()
    {
        $minimum = $this->getOption('minimum_length', 0);
        $maximum = $this->getOption('maximum_length', 999999999999);

        $string_length = strlen(trim($this->field_value));

        if ($string_length >= $minimum
            && $string_length <= $maximum
        ) {
            return true;
        }

        return false;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessLib.Mocking
{
    public class Product
    {
        public float ListPrice { get; set; }

        public float GetPrice(Customer customer)
        {
            if (customer.IsGold)
                return ListPrice * 0.7f;

            return ListPrice;
        }
    }

    public class Customer
    {
        public bool IsGold { get; set; }
    }
}


text:
Twitter LazyBird Plugin v0.9.9
=====

A Google Chrome extension that is based heavily off of the Twitter Reporter Plugin v0.1:
https://github.com/twitterdev/chrome-reporter-plugin

If you would like to download the packed extension, simply download the file,
"Twitter-LazyBird.crx"


text:
permalink: /
title: "About me"
excerpt: "About me"
author_profile: true
redirect_from:
  - /about/
  - /about.html
---

<img class="img-responsive" style="float: left; margin: 0px 20px 20px 0px;" src="/images/profile.jpg" width="280">I am an Assistant Professor in the Kenneth C. Griffin Department of Economics at the University of Chicago. I work mainly on topics in labor, human capital, discrimination, and crime.

If you'd like to contact me, you can email ekrose at uchicago.edu. You can find a relatively current version of my CV [here](/files/ekr_cv.pdf). I'm on Google Scholar [here](https://scholar.google.com/citations?user=dMs-BJUAAAAJ). I have a largely neglected Twitter account [here](https://twitter.com/evankrose).

You can listen to me talk about some of my work on the Microsoft Research podcast [here](https://www.microsoft.com/en-us/research/podcast/econ1-using-microeconomics-to-solve-mass-incarceration-featuring-hunt-allcott-and-evan-rose/) and on InequaliTalks [here](https://inequalitalks.fireside.fm/21).

**Office hours by appointment** (email me).


text:
/*[clinic input]
preserve
[clinic start generated code]*/

PyDoc_STRVAR(curses_window_addch__doc__,
"addch([y, x,] ch, [attr])\n"
"Paint character ch at (y, x) with attributes attr.\n"
"\n"
"  y\n"
"    Y-coordinate.\n"
"  x\n"
"    X-coordinate.\n"
"  ch\n"
"    Character to add.\n"
"  attr\n"
"    Attributes for the character.\n"
"\n"
"Paint character ch at (y, x) with attributes attr,\n"
"overwriting any character previously painted at that location.\n"
"By default, the character position and attributes are the\n"
"current settings for the window object.");

#define CURSES_WINDOW_ADDCH_METHODDEF    \
    {"addch", (PyCFunction)curses_window_addch, METH_VARARGS, curses_window_addch__doc__},

static PyObject *
curses_window_addch_impl(PyCursesWindowObject *self, int group_left_1, int y,
                         int x, PyObject *ch, int group_right_1, long attr);

static PyObject *
curses_window_addch(PyCursesWindowObject *self, PyObject *args)
{
    PyObject *return_value = NULL;
    int group_left_1 = 0;
    int y = 0;
    int x = 0;
    PyObject *ch;
    int group_right_1 = 0;
    long attr = 0;

    switch (PyTuple_GET_SIZE(args)) {
        case 1:
            if (!PyArg_ParseTuple(args, "O:addch", &ch))
                goto exit;
            break;
        case 2:
            if (!PyArg_ParseTuple(args, "Ol:addch", &ch, &attr))
                goto exit;
            group_right_1 = 1;
            break;
        case 3:
            if (!PyArg_ParseTuple(args, "iiO:addch", &y, &x, &ch))
                goto exit;
            group_left_1 = 1;
            break;
        case 4:
            if (!PyArg_ParseTuple(args, "iiOl:addch", &y, &x, &ch, &attr))
                goto exit;
            group_right_1 = 1;
            group_left_1 = 1;
            break;
        default:
            PyErr_SetString(PyExc_TypeError, "curses.window.addch requires 1 to 4 arguments");
            goto exit;
    }
    return_value = curses_window_addch_impl(self, group_left_1, y, x, ch, group_right_1, attr);

exit:
    return return_value;
}
/*[clinic end generated code: output=982b1e709577f3ec input=a9049054013a1b77]*/


text:
package net.ensode.javaee8book.entityrelationship.namedbean;

import javax.annotation.Resource;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import net.ensode.javaee8book.entityrelationship.entity.Customer;
import net.ensode.javaee8book.entityrelationship.entity.LoginInfo;

@Named
@RequestScoped
public class OneToOneRelationshipDemoBean {

    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    private UserTransaction userTransaction;

    public String updateDatabase() {
        String retVal = "confirmation";
        Customer customer;
        LoginInfo loginInfo = new LoginInfo();

        loginInfo.setLoginInfoId(1L);
        loginInfo.setLoginName("charlesj");
        loginInfo.setPassword("iwonttellyou");

        try {
            userTransaction.begin();

            customer = entityManager.find(Customer.class, 4L);
            loginInfo.setCustomer(customer);

            entityManager.persist(loginInfo);

            userTransaction.commit();

        } catch (NotSupportedException |
                SystemException |
                SecurityException |
                IllegalStateException |
                RollbackException |
                HeuristicMixedException |
                HeuristicRollbackException e) {
            retVal = "error";
            e.printStackTrace();
        }

        return retVal;
    }
}


text:
package com.heaven7.databinding.demo.bean;

/**
 * Created by heaven7 on 2016/3/23.
 */
public class Person {

    protected String nickname ;
    protected String username ;

    public String getNickname(){
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

}


text:
/*
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.

Formally the function should:
    Return true if there exists i, j, k
    such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.

Your algorithm should run in O(n) time complexity and O(1) space complexity.

Examples:
Given [1, 2, 3, 4, 5],
return true.

Given [5, 4, 3, 2, 1],
return false.
*/

'use strict'

/**
 * @param {number[]} nums
 * @return {boolean}
 */
const increasingTriplet = function(nums) {
  let first = Infinity
  let second = Infinity

  for (let i = 0; i < nums.length; ++i) {
    const n = nums[i]
    if (n <= first) {
      first = n
    }
    else if (n <= second) {
      second = n
    }
    else {
      return true
    }
  }

  return false
}