text:
namespace Microsoft.AspNetCore.Components.Web.Virtualization;

/// <summary>
/// Represents the result of a <see cref="ItemsProviderDelegate{TItem}"/>.
/// </summary>
/// <typeparam name="TItem">The type of the context for each item in the list.</typeparam>
public readonly struct ItemsProviderResult<TItem>
{
    /// <summary>
    /// The items to provide.
    /// </summary>
    public IEnumerable<TItem> Items { get; }

    /// <summary>
    /// The total item count in the source generating the items provided.
    /// </summary>
    public int TotalItemCount { get; }

    /// <summary>
    /// Instantiates a new <see cref="ItemsProviderResult{TItem}"/> instance.
    /// </summary>
    /// <param name="items">The items to provide.</param>
    /// <param name="totalItemCount">The total item count in the source generating the items provided.</param>
    public ItemsProviderResult(IEnumerable<TItem> items, int totalItemCount)
    {
        Items = items;
        TotalItemCount = totalItemCount;
    }
}


text:
 Log in

        <form name="loginForm" ng-submit="emailLogin()" novalidate>

            <input server-error class="form-control input-lg" type="text" name="email" ng-model="email" placeholder="Email" required autofocus>

Please enter your email

{{errorMessage.email}}

            <input server-error class="form-control input-lg" type="password" name="password" ng-model="password" placeholder="Password" required>

Please enter your password

{{errorMessage.password}}

          <button type="submit" class="btn btn-block btn-success" ng-disabled="loginForm.$invalid">Log in</button>

            Don't have an account yet? Sign up

        </form>

redpajama_set_name: RedPajamaGithub


text:
package com.yahoo.sshd.tools.artifactory;

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

@Test(groups = "unit")
public class TestRepoStripping {
    @DataProvider
    Object[][] repos() {
        return new Object[][] {//
                        {null, null},//
                        {"", RepositoryAndPath.EMPTY_REPOSITORY}, //
                        {"/", RepositoryAndPath.EMPTY_REPOSITORY},//
                        {"/repo", RepositoryAndPath.EMPTY_REPOSITORY}, //
                        {
                                        "/ssh-proxy-test/com/yahoo/sshd/0.0.1-SNAPSHOT/",
                                        new RepositoryAndPath("ssh-proxy-test",
                                                        "com/yahoo/sshd/0.0.1-SNAPSHOT/")}, //
                        {
                                        "ssh-proxy-test/com/yahoo/sshd/0.0.1-SNAPSHOT/",
                                        new RepositoryAndPath("ssh-proxy-test",
                                                        "com/yahoo/sshd/0.0.1-SNAPSHOT/")}, //
                        {"samIAm/com/foo.jar", new RepositoryAndPath("samIAm", "com/foo.jar")}, //
        };
    }

    @Test(dataProvider = "repos")
    public void testRepoStripping(String in, RepositoryAndPath expected) {
        RepositoryAndPath actual = RepositoryAndPath.splitRepositoryAndPath(in);
        Assert.assertEquals(actual, expected);
    }
}


text:
/*
 * Maciej Pacut, 2011
 *
 * package_index.cpp
 *
 * Moduł odpowiadający na zapytania o wersję zainstalowanego lub dostępnego pakietu.
 */

#include "package_index.h"

std::string package_version(const std::string& package_name, const std::string& index_file_path)
{
  std::ifstream index_file(index_file_path.c_str());

  po::options_description index_file_args_desc("Version");
  index_file_args_desc.add_options()
    (
      package_name.c_str(),
      po::value<std::string>(),
      ("specifying version of package " + package_name).c_str()
     );

  po::variables_map index_file_args;

  // trzeci parametr parse_config_file pozawala na występowanie w pliku tłumaczeń opcji niewyspecyfikowanych w opisie parsera
  store(parse_config_file(index_file, index_file_args_desc, true), index_file_args);
  notify(index_file_args);

  if(!index_file_args.count(package_name))
  {
    return "";
  }

  return index_file_args[package_name].as<std::string>();
}


text:
#pragma once
#include <aws/codecommit/CodeCommit_EXPORTS.h>
#include <aws/codecommit/CodeCommitRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace CodeCommit
{
namespace Model
{

  /**
   *
Represents the input of a get commit operation.

   */
  class AWS_CODECOMMIT_API GetCommitRequest : public CodeCommitRequest
  {
  public:
    GetCommitRequest();
    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of the repository to which the commit was made.

     */
    inline const Aws::String& GetRepositoryName() const{ return m_repositoryName; }

    /**
     *
The name of the repository to which the commit was made.

     */
    inline void SetRepositoryName(const Aws::String& value) { m_repositoryNameHasBeenSet = true; m_repositoryName = value; }

    /**
     *
The name of the repository to which the commit was made.

     */
    inline void SetRepositoryName(Aws::String&& value) { m_repositoryNameHasBeenSet = true; m_repositoryName = value; }

    /**
     *
The name of the repository to which the commit was made.

     */
    inline void SetRepositoryName(const char* value) { m_repositoryNameHasBeenSet = true; m_repositoryName.assign(value); }

    /**
     *
The name of the repository to which the commit was made.

     */
    inline GetCommitRequest& WithRepositoryName(const Aws::String& value) { SetRepositoryName(value); return *this;}

    /**
     *
The name of the repository to which the commit was made.

     */
    inline GetCommitRequest& WithRepositoryName(Aws::String&& value) { SetRepositoryName(value); return *this;}

    /**
     *
The name of the repository to which the commit was made.

     */
    inline GetCommitRequest& WithRepositoryName(const char* value) { SetRepositoryName(value); return *this;}

    /**
     *
The commit ID.

     */
    inline const Aws::String& GetCommitId() const{ return m_commitId; }

    /**
     *
The commit ID.

     */
    inline void SetCommitId(const Aws::String& value) { m_commitIdHasBeenSet = true; m_commitId = value; }

    /**
     *
The commit ID.

     */
    inline void SetCommitId(Aws::String&& value) { m_commitIdHasBeenSet = true; m_commitId = value; }

    /**
     *
The commit ID.

     */
    inline void SetCommitId(const char* value) { m_commitIdHasBeenSet = true; m_commitId.assign(value); }

    /**
     *
The commit ID.

     */
    inline GetCommitRequest& WithCommitId(const Aws::String& value) { SetCommitId(value); return *this;}

    /**
     *
The commit ID.

     */
    inline GetCommitRequest& WithCommitId(Aws::String&& value) { SetCommitId(value); return *this;}

    /**
     *
The commit ID.

     */
    inline GetCommitRequest& WithCommitId(const char* value) { SetCommitId(value); return *this;}

  private:
    Aws::String m_repositoryName;
    bool m_repositoryNameHasBeenSet;
    Aws::String m_commitId;
    bool m_commitIdHasBeenSet;
  };

} // namespace Model
} // namespace CodeCommit
} // namespace Aws


text:
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;

namespace Azure.ResourceManager.AgFoodPlatform
{
    /// <summary>
    /// A Class representing an AgFoodPlatformPrivateLinkResource along with the instance operations that can be performed on it.
    /// If you have a <see cref="ResourceIdentifier" /> you can construct an <see cref="AgFoodPlatformPrivateLinkResource" />
    /// from an instance of <see cref="ArmClient" /> using the GetAgFoodPlatformPrivateLinkResource method.
    /// Otherwise you can get one from its parent resource <see cref="FarmBeatResource" /> using the GetAgFoodPlatformPrivateLinkResource method.
    /// </summary>
    public partial class AgFoodPlatformPrivateLinkResource : ArmResource
    {
        /// <summary> Generate the resource identifier of a <see cref="AgFoodPlatformPrivateLinkResource"/> instance. </summary>
        public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string farmBeatsResourceName, string subResourceName)
        {
            var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgFoodPlatform/farmBeats/{farmBeatsResourceName}/privateLinkResources/{subResourceName}";
            return new ResourceIdentifier(resourceId);
        }

        private readonly ClientDiagnostics _agFoodPlatformPrivateLinkResourcePrivateLinkResourcesClientDiagnostics;
        private readonly PrivateLinkResourcesRestOperations _agFoodPlatformPrivateLinkResourcePrivateLinkResourcesRestClient;
        private readonly AgFoodPlatformPrivateLinkResourceData _data;

        /// <summary> Initializes a new instance of the <see cref="AgFoodPlatformPrivateLinkResource"/> class for mocking. </summary>
        protected AgFoodPlatformPrivateLinkResource()
        {
        }

        /// <summary> Initializes a new instance of the <see cref = "AgFoodPlatformPrivateLinkResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="data"> The resource that is the target of operations. </param>
        internal AgFoodPlatformPrivateLinkResource(ArmClient client, AgFoodPlatformPrivateLinkResourceData data) : this(client, data.Id)
        {
            HasData = true;
            _data = data;
        }

        /// <summary> Initializes a new instance of the <see cref="AgFoodPlatformPrivateLinkResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="id"> The identifier of the resource that is the target of operations. </param>
        internal AgFoodPlatformPrivateLinkResource(ArmClient client, ResourceIdentifier id) : base(client, id)
        {
            _agFoodPlatformPrivateLinkResourcePrivateLinkResourcesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.AgFoodPlatform", ResourceType.Namespace, Diagnostics);
            TryGetApiVersion(ResourceType, out string agFoodPlatformPrivateLinkResourcePrivateLinkResourcesApiVersion);
            _agFoodPlatformPrivateLinkResourcePrivateLinkResourcesRestClient = new PrivateLinkResourcesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, agFoodPlatformPrivateLinkResourcePrivateLinkResourcesApiVersion);
#if DEBUG
			ValidateResourceId(Id);
#endif
        }

        /// <summary> Gets the resource type for the operations. </summary>
        public static readonly ResourceType ResourceType = "Microsoft.AgFoodPlatform/farmBeats/privateLinkResources";

        /// <summary> Gets whether or not the current instance has data. </summary>
        public virtual bool HasData { get; }

        /// <summary> Gets the data representing this Feature. </summary>
        /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
        public virtual AgFoodPlatformPrivateLinkResourceData Data
        {
            get
            {
                if (!HasData)
                    throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
                return _data;
            }
        }

        internal static void ValidateResourceId(ResourceIdentifier id)
        {
            if (id.ResourceType != ResourceType)
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
        }

        /// <summary>
        /// Get Private link resource object.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgFoodPlatform/farmBeats/{farmBeatsResourceName}/privateLinkResources/{subResourceName}
        /// Operation Id: PrivateLinkResources_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<AgFoodPlatformPrivateLinkResource>> GetAsync(CancellationToken cancellationToken = default)
        {
            using var scope = _agFoodPlatformPrivateLinkResourcePrivateLinkResourcesClientDiagnostics.CreateScope("AgFoodPlatformPrivateLinkResource.Get");
            scope.Start();
            try
            {
                var response = await _agFoodPlatformPrivateLinkResourcePrivateLinkResourcesRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new AgFoodPlatformPrivateLinkResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Get Private link resource object.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgFoodPlatform/farmBeats/{farmBeatsResourceName}/privateLinkResources/{subResourceName}
        /// Operation Id: PrivateLinkResources_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<AgFoodPlatformPrivateLinkResource> Get(CancellationToken cancellationToken = default)
        {
            using var scope = _agFoodPlatformPrivateLinkResourcePrivateLinkResourcesClientDiagnostics.CreateScope("AgFoodPlatformPrivateLinkResource.Get");
            scope.Start();
            try
            {
                var response = _agFoodPlatformPrivateLinkResourcePrivateLinkResourcesRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new AgFoodPlatformPrivateLinkResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
    }
}


text:
<?php

namespace atomar\hook;

use atomar\core\Logger;

class Uninstall implements Hook {

    /**
     * Hooks may receive optional params
     * @param $params mixed
     */
    function __construct($params = null) {

    }

    /**
     * Executed just before the hook implementation is ran
     * @param $extension mixed The extension in which the hook implementation is running.
     * @return bool true if the hook execution can proceed otherwise false
     */
    public function preProcess($extension) {
        return $extension->is_enabled != 1;
    }

    /**
     * Executes the hook with the result of the hooked.
     * @param $params mixed The params returned (if any) from the hook implementation.
     * @param $ext_path string The path to the extension's directory
     * @param $ext_namespace string The namespace of the extension
     * @param $ext mixed The extension in which the hook implementation is running.
     * @param $state mixed The last returned state of the hook. If you want to maintain state you should modify and return this.
     * @return mixed The hook state.
     */
    public function process($params, $ext_path, $ext_namespace, $ext, $state) {
        if ($params) {
            $ext->installed_version = '';
            store($ext);
        } else {
            Logger::log_error('Failed to uninstall extension ' . $ext->slug);
        }
        return $state;
    }

    /**
     * Executed after the hook implementations have finished executing.
     * @param $state mixed The final state of the hook.
     * @return mixed
     */
    public function postProcess($state) {
        return $state;
    }

    /**
     * Returns an array of parameters that will be passed to the hook receiver
     * @return array
     */
    public function params()
    {
        return null;
    }
}


text:
Networking Lounge

A key element of the Swiss Cyber Storm is the information
						exchange among IT Security Enthusiasts. To give more room for
						after-talk-discussions, networking and even experimenting, we will
						introduce the Networking Lounge as a core part of the event for
						the first time.

The Networking Lounge is a central meeting place with free
						WIFI, computer accessories, equipped with black boards,
						movable walls, but also with couches, catering and a bar for
						refreshment. It aims to offer the perfect place to meet, discuss,
						experiment and socialize.

Instead of running the Swiss Cyber Storm Challenges on this
						day, the participants of the SCS Challenges 2017 will use the
						Networking Lounge as their training and playing ground, solving
						challenges and presenting small tasks. If you want to see them solving
						such challenges or want to get more information about the SCS challenges please let us know or just contact them yourself.

Our partners and sponsors are integrated in Networking
						Lounge. The Networking Lounge is the perfect place to approach
						these IT professionals with affiliation to industry, government
						and university.

The Networking Lounge is the place to stay in between the talks. It offers food and drinks. This is the place were we hope to meet on the party after the conference.

Conference Speakers

        	{% include speakers-announce.html %}

            {% for article in site.data.confPage %}

{{ article.title }}

		{% for para in article.paragraph %}
		{% if para.raw != null %}
		  {{ para.raw }}
                {% endif %}
		{% if para.text != null %}

{{ para.text }}

                {% endif %}
		{% if para.include != null %}
		  {% include {{para.include}} %}
                {% endif %}
		{% if para.image != null %}

                {% endif %}
                {% endfor %}

            {% endfor %}

               {% include sponsors.md %}


text:
//
//  GPSegment.h
//  礼物说
//
//  Created by heew on 15/1/18.
//  Copyright (c) 2014年 giftTalk All rights reserved.
//

#import <UIKit/UIKit.h>
@class GPSearchGift;

@interface GPSegment : UIView

@property (nonatomic, strong) GPSearchGift *gift; /**礼物模型 */
+ (instancetype)segment;
- (void)descButtonAddTarget:(id) target selector:(SEL)action forContrlEvents:(UIControlEvents)controlEvents;
- (void)commentButtonAddTarget:(id) target selector:(SEL)action forContrlEvents:(UIControlEvents)controlEvents;
@end


text:
layout: post
title: Learn linux 2 - Services and demons
category: posts
---

## What to learn in this chapter
How to handle services, server software and daemons.

### Daemons
Systems often start daemons at boot time and serve the function of responding to network requests, hardware activity, or other programs by performing some task. Daemons can also configure hardware (like udevd on some GNU/Linux systems), run scheduled tasks (like [cron](http://en.wikipedia.org/wiki/Cron)), and perform a variety of other tasks.

Later on I want you to try installing an [apache](http://en.wikipedia.org/wiki/Apache_HTTP_Server) server which is a webserver.
Since there really is no output of that program that is interesting for you to see the only relevant thing to do is to run it as a daemon and let the system run it in the backgrund without disturbing you and fill your terminal with rubbish.

*(apache is a software which is designed for unix/linux and therefor is included in the apt-get library)*

Almost all server software does run as a daemon because its purpose is to serve/process in the backgrund to all the users/clients.

Also software that is supposed to run as a daemon ends often with 'd', for example a FTP-server in linux is called ftpd. The SSH daemon is sshd,

**Examples of software to run as daemon:**

- [Teamspeak server](http://teamspeak.com/?page=downloads)
- FTP server
- SSH Server ([OpenSSH](http://en.wikipedia.org/wiki/OpenSSH))

All of these can you find in the linux library with 'apt-get'

## Tools

- [Screen](http://www.gnu.org/software/screen/) (Runs multiple virtual terminals)

## Installing on other computer
If you dont want to run the linux distribution and want to runt it on another PC you can easily make a bootable USB with the ISO file.

I use [imgburn](http://www.imgburn.com/index.php?act=Download) to burn to a CD

And [Pen drive linux usb](http://www.pendrivelinux.com) for bootable USB


text:
import * as b from '../node_modules/bobril/index';

export let page = b.createComponent({
    render(ctx: b.IBobrilCtx, me: b.IBobrilNode, oldMe?: b.IBobrilCacheNode): void {
        me.children = [
            { tag: 'h1', children: '<%= app_name %>' }
        ];
    }
});


text:
package talecraft.client.gui.qad;

import java.util.List;

import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;

import talecraft.client.gui.vcui.VCUIRenderer;

public class QADDropdownBox extends QADRectangularComponent {

	private boolean isVisible = true;
	private boolean isFocused = false;

	private boolean fieldbox_visible = true;
	private int fieldbox_width = 100;
	private int fieldbox_height = 20;
	private int fieldbox_x = 0;
	private int fieldbox_y = 0;
	private String fieldbox_text = "";

	private boolean dropbox_visible = false;
	private int dropbox_width = 100;
	private int dropbox_height = 22;
	private int dropbox_x = 0;
	private int dropbox_y = 20;

	private int dropbox_scroll = 0;

	private int dropbox_rowcount = 7;
	private int dropbox_rowheight = 20;
	// private int dropbox_highlight = -1;
	private ListModel dropbox_model = null;
	private String dropbox_filterstr = "";
	private ListModelItem dropbox_selected = null;

	private int color = 0x7F101010;

	public QADDropdownBox(ListModel model, ListModelItem selectedItem) {
		this.dropbox_model = model;
		setSelected(selectedItem);
	}

	public QADDropdownBox(ListModel model) {
		this(model, (ListModelItem)null);
	}

	public void setSelected(ListModelItem item){
		if(dropbox_model != null && dropbox_model.hasItems()) {
			if(item != null && dropbox_model.getItems().contains(item)) {
				this.fieldbox_text = item.getText();
				this.dropbox_selected = item;
				this.dropbox_model.onSelection(item);
			} else {
				ListModelItem itm = dropbox_model.getItems().get(0);
				this.fieldbox_text = itm.getText();
				this.dropbox_selected = itm;
			}
		}
	}

	@Override
	public void handleMouseInput() {
		int amount = Mouse.getEventDWheel()/120;
		if(amount < 0){
			dropbox_scroll += amount;
			if(dropbox_scroll < 0) dropbox_scroll = 0;
		} else if(amount > 0){
			dropbox_scroll += amount;
			if(dropbox_scroll > dropbox_model.getFilteredItems().size() - dropbox_rowcount) dropbox_scroll = dropbox_model.getFilteredItems().size() - dropbox_rowcount < 0 ? 0 : dropbox_model.getFilteredItems().size() - dropbox_rowcount;
		}
	}

	@Override
	public int getWidth() {
		return this.fieldbox_width;
	}

	@Override
	public int getHeight() {
		return this.fieldbox_height;
	}

	@Override
	public void setWidth(int newWidth) {
		setSize(newWidth, fieldbox_height);
	}

	public void setColor(int color){
		this.color = color;
	}

	@Override
	public void setHeight(int newHeight) {
		setSize(fieldbox_width, newHeight);
	}

	@Override
	public void setSize(int newWidth, int newHeight) {
		this.fieldbox_width = newWidth;
		this.fieldbox_height = newHeight;
		reFocus();
	}

	@Override
	public boolean canResize() {
		return true;
	}

	@Override
	public QADEnumComponentClass getComponentClass() {
		return QADEnumComponentClass.INPUT;
	}

	@Override
	public int getX() {
		return this.fieldbox_x;
	}

	@Override
	public int getY() {
		return this.fieldbox_y;
	}

	@Override
	public void setX(int x) {
		setPosition(x, fieldbox_y);
	}

	@Override
	public void setY(int y) {
		setPosition(fieldbox_x, y);
	}

	@Override
	public void setPosition(int x, int y) {
		this.fieldbox_x = x;
		this.fieldbox_y = y;
		reFocus();
	}

	@Override
	public void postDraw(int localMouseX, int localMouseY, float partialTicks, VCUIRenderer renderer){
		if(!(dropbox_visible && dropbox_model != null))return;
		if(!isVisible)
			return;

		renderer.drawRectangle(0, 0, renderer.getWidth(), renderer.getHeight(), 0xaa000000);
		boolean hover = isPointInside(localMouseX+getX(), localMouseY+getY());

		if(fieldbox_visible) {
			int color = -1;
			int hoverState = hover ? 1 : 0;

			if(isFocused)
				hoverState++;

			switch(hoverState) {
			case 0: color = this.color; break;
			case 1: color = 0xFF505030; break;
			case 2: color = 0xFF707030; break;
			default:color = 0xFF101010;break;
//				case 0: color = 0x7F101010; break;
//				case 1: color = 0xFF505030; break;
//				case 2: color = 0xFF707030; break;
//				default:color = 0xFF101010;break;
			}

			renderer.drawRectangle    (this.fieldbox_x, this.fieldbox_y, this.fieldbox_x+this.fieldbox_width, this.fieldbox_y+this.fieldbox_height, 0xFF000000);
			renderer.drawLineRectangle(this.fieldbox_x, this.fieldbox_y, this.fieldbox_x+this.fieldbox_width, this.fieldbox_y+this.fieldbox_height, color);

			renderer.pushScissor(this.fieldbox_x+1, this.fieldbox_y+1, this.fieldbox_width-2, this.fieldbox_height-2);

			int textColor = -1;
			String text = "";
			boolean cursor = true;

			if(isFocused) {
				text = dropbox_filterstr;

				if(dropbox_filterstr.isEmpty()) {
					text = fieldbox_text;
					textColor = 0x7F505050;
					cursor = false;
				}
			} else {
				text = fieldbox_text;
				cursor = false;
			}

			int strp = renderer.drawString(text, this.fieldbox_x+4, this.fieldbox_y+6, textColor, !cursor);

			if(isFocused) {
				if(!cursor) {
					strp = this.fieldbox_x+4;
				}

				// draw text cursor if focused
				renderer.drawRectangle(
						strp+0, this.fieldbox_y+14,
						strp+5, this.fieldbox_y+15,
						(System.currentTimeMillis()%1000) < 700 ? 0 : 0xFFFFFFFF
				);
			}

			renderer.popScissor();
		}

			renderer.drawRectangle(dropbox_x, dropbox_y, dropbox_x+dropbox_width, dropbox_y+dropbox_height, 0x7F000000);

			List<ListModelItem> items = dropbox_model.getFilteredItems();
			if(items != null) {
				int rows = Math.min(items.size(), this.dropbox_rowcount + this.dropbox_scroll);
				boolean hasIcons = dropbox_model.hasIcons();

				// hover highlight
				int hoverlight = hover?mouseToItemIndex(localMouseY+getY()):-1;
				// this.dropbox_highlight = hoverlight;

				// list render
				int yOffset = 0;
				int xOffset = hasIcons?(20+4):4;

				boolean light = false;
				for(int i = dropbox_scroll; i < rows; i++) {
					yOffset = (i * dropbox_rowheight) - (this.dropbox_scroll*dropbox_rowheight);
					light = i == hoverlight;

					ListModelItem item = items.get(i);

					int x = dropbox_x;
					int y = dropbox_y+yOffset;
					renderer.drawLineRectangle(x, y, x+dropbox_width, y+dropbox_rowheight, 0xFFFFFFFF);
					renderer.drawString(item.getText(), x+xOffset, y+6, light?0xFFfff266:0xFFFFFFFF, false);

					if(hasIcons) {
						int icox = x;
						int icoy = y;
						renderer.offset(icox, icoy);
						dropbox_model.drawIcon(renderer, partialTicks, light, item);
						renderer.offset(-icox, -icoy);
					}
				}
			}
	}

	@Override
	public void draw(int localMouseX, int localMouseY, float partialTicks, VCUIRenderer renderer) {
		if(dropbox_visible && dropbox_model != null)return;
		if(!isVisible)
			return;

		boolean hover = isPointInside(localMouseX+getX(), localMouseY+getY());

		if(fieldbox_visible) {
			int color = -1;
			int hoverState = hover ? 1 : 0;

			if(isFocused)
				hoverState++;

			switch(hoverState) {
			case 0: color = this.color; break;
			case 1: color = 0xFF505030; break;
			case 2: color = 0xFF707030; break;
			default:color = 0xFF101010;break;
//				case 0: color = 0x7F101010; break;
//				case 1: color = 0xFF505030; break;
//				case 2: color = 0xFF707030; break;
//				default:color = 0xFF101010;break;
			}

			renderer.drawRectangle    (this.fieldbox_x, this.fieldbox_y, this.fieldbox_x+this.fieldbox_width, this.fieldbox_y+this.fieldbox_height, 0xFF000000);
			renderer.drawLineRectangle(this.fieldbox_x, this.fieldbox_y, this.fieldbox_x+this.fieldbox_width, this.fieldbox_y+this.fieldbox_height, color);

			renderer.pushScissor(this.fieldbox_x+1, this.fieldbox_y+1, this.fieldbox_width-2, this.fieldbox_height-2);

			int textColor = -1;
			String text = "";
			boolean cursor = true;

			if(isFocused) {
				text = dropbox_filterstr;

				if(dropbox_filterstr.isEmpty()) {
					text = fieldbox_text;
					textColor = 0x7F505050;
					cursor = false;
				}
			} else {
				text = fieldbox_text;
				cursor = false;
			}

			int strp = renderer.drawString(text, this.fieldbox_x+4, this.fieldbox_y+6, textColor, !cursor);

			if(isFocused) {
				if(!cursor) {
					strp = this.fieldbox_x+4;
				}

				// draw text cursor if focused
				renderer.drawRectangle(
						strp+0, this.fieldbox_y+14,
						strp+5, this.fieldbox_y+15,
						(System.currentTimeMillis()%1000) < 700 ? 0 : 0xFFFFFFFF
				);
			}

			renderer.popScissor();
		}

	}

	@Override
	public boolean focusInput() {
		return dropbox_visible && dropbox_model != null;
	}

	@Override
	public void onMouseClicked(int localMouseX, int localMouseY, int mouseButton) {
	}

	@Override
	public void onMouseReleased(int localMouseX, int localMouseY, int state) {
		boolean inside = isPointInside(localMouseX+getX(), localMouseY+getY());
		boolean preFocus = isFocused;

		if(inside) {
			setFocused(true);
		} else {
			setFocused(false);
		}

		if(preFocus != isFocused) {
			if(dropbox_model != null) {
				dropbox_model.applyFilter(dropbox_filterstr);
				recalculateDropbox();
			}
			dropbox_filterstr = "";
		}

		if(isFocused && inside && dropbox_model != null) {
			List<ListModelItem> items = dropbox_model.getFilteredItems();
			if(items != null) {
				int hoverlight = mouseToItemIndex(localMouseY+getY());
				// this.dropbox_highlight = hoverlight;

				if(hoverlight != -1 && hoverlight < items.size()) {
					ListModelItem item = items.get(hoverlight);
					fieldbox_text = item.getText();
					dropbox_selected = item;
					dropbox_model.onSelection(item);
					setFocused(false);
				}
			}
		}
	}

	@Override
	public void onMouseClickMove(int localMouseX, int localMouseY, int clickedMouseButton, long timeSinceLastClick) {

	}

	@Override
	public void onKeyTyped(char typedChar, int typedCode) {
		if(isFocused) {

			if(typedCode == Keyboard.KEY_TAB) {
				// autocompletion?
				// Not necessary; see below.
				return;
			}

			if(typedCode == Keyboard.KEY_RETURN) {
				if(dropbox_model != null) {
					List<ListModelItem> items = dropbox_model.getFilteredItems();
					if(items.size() > 0) {
						int hl = 0; // XXX: dropbox_highlight? No.
						ListModelItem item = items.get(hl);
						fieldbox_text = item.getText();
						dropbox_selected = item;
						dropbox_model.onSelection(item);
						setFocused(false);
					}
				}

				return;
			}

			if(typedCode == Keyboard.KEY_BACK) {
				int len = dropbox_filterstr.length();
				if(len > 0) {
					dropbox_filterstr = dropbox_filterstr.substring(0,len-1);

					if(dropbox_model!=null) {
						dropbox_model.applyFilter(dropbox_filterstr);
						recalculateDropbox();
					}
				}

				return;
			}

			if(Character.isJavaIdentifierPart(typedChar) || Character.isWhitespace(typedChar)) {
				dropbox_filterstr += typedChar;

				if(dropbox_model!=null) {
					dropbox_model.applyFilter(dropbox_filterstr);
					recalculateDropbox();
					if(dropbox_model.getFilteredItems().size() > 0) {
						// dropbox_highlight = 0;
					}
				}
			}

		}
	}

	@Override
	public void onTickUpdate() {
	}

	@Override
	public boolean isPointInside(int mouseX, int mouseY) {
		boolean inside =
				mouseX >= this.fieldbox_x &&
				mouseY >= this.fieldbox_y &&
				mouseX <= this.fieldbox_x + this.fieldbox_width &&
				mouseY <= (dropbox_visible?(this.dropbox_y+this.dropbox_height):(this.fieldbox_y+this.fieldbox_height));
		return inside;
	}

	public int mouseToItemIndex(int mouseY) {
		if(mouseY < dropbox_y) {
			return -1;
		}
		if(mouseY >= dropbox_y+dropbox_height) {
			return -1;
		}

		mouseY -= dropbox_y;
		// mouseY -= dropbox_rowheight;

		return (mouseY/dropbox_rowheight) +  + dropbox_scroll;
	}

	@Override
	public boolean transferFocus() {
		return false;
	}

	@Override
	public boolean isFocused() {
		return isFocused;
	}

	@Override
	public void removeFocus() {
		isFocused = false;

	}

	private void reFocus() {
		boolean f = isFocused;
		setFocused(false);
		setFocused(f);
	}

	private void setFocused(boolean b) {
		if(isFocused == b) {
			// nothing to do
			return;
		}

		// Change focus...
		this.isFocused = b;

		recalculateDropbox();
	}

	private void recalculateDropbox() {
		this.dropbox_visible = false;
		if(!isFocused) {
			// dont continue if not focused!
			return;
		}

		this.dropbox_x = this.fieldbox_x;
		this.dropbox_y = this.fieldbox_y + this.fieldbox_height + 3;

		if(this.dropbox_model == null) {
			// no model!
			return;
		}

		if(!this.dropbox_model.hasItems()) {
			// empty model!
			return;
		}

		this.dropbox_scroll = 0;
		if(dropbox_filterstr != null && !dropbox_filterstr.trim().isEmpty())
			dropbox_model.applyFilter(dropbox_filterstr);

		final List<ListModelItem> items = this.dropbox_model.getFilteredItems();
		if(items == null) {
			return;
		}
		int itemCount = items.size();
		int itemHeight = dropbox_rowheight;

		int rows = Math.min(itemCount, this.dropbox_rowcount);

		this.dropbox_width = fieldbox_width;
		this.dropbox_height = rows * itemHeight;

		this.dropbox_visible = true;
	}

	/**
	 * @return The selected item, or null.
	 **/
	public final ListModelItem getSelected() {
		return dropbox_selected;
	}

	public static interface ListModel {
		/** Called when a item is selected. **/
		public void onSelection(ListModelItem selected);

		/** This should return true if getItemCount() > 0. **/
		public boolean hasItems();
		/** This should return the amount of items. **/
		public int getItemCount();
		/** This should return a full list of items. **/
		public List<ListModelItem> getItems();

		/** This should use the given string to filter the list of items. **/
		public void applyFilter(String filterString);
		/** This should return the filtered list (see applyFilter) of items. **/
		public List<ListModelItem> getFilteredItems();

		/** let this return true if drawIcon is implemented. **/
		public boolean hasIcons();
		/** implement this to draw icons (origin is at list item!). **/
		public void drawIcon(VCUIRenderer renderer, float partialTicks, boolean light, ListModelItem item);
	}

	// The interface for list items. Pretty simple, isnt it?
	public static interface ListModelItem {
		String getText();
	}

	// A basic implementation for ListModelItem.
	public static class StringItem implements ListModelItem {
		private final String text;

		public StringItem(final String text) {
			this.text = text;
		}

		@Override
		public final String getText() {
			return text;
		}
	}

}


text:
#include "elm/ts/learninglayer_assertions.h"

#include "gtest/gtest.h"

#include "elm/core/exception.h"
#include "elm/core/layerconfig.h"
#include "elm/layers/layers_interim/base_LearningLayer.h"

using namespace std;
using namespace elm;

/** class for deriving from base Layer for test purposes
  */
class DummyChildLearningLayer : public base_LearningLayer
{
public:
    void Clear() {}

    void Reconfigure(const LayerConfig &config) {}

    virtual void InputNames(const LayerInputNames &io) {}

    virtual void OutputNames(const LayerOutputNames &io) {}

    void Activate(const Signal &signal) {}

    void Response(Signal &signal) {}

    void Learn() {}

    void Learn(const cv::Mat1f& features, const cv::Mat1f &labels) {}

    DummyChildLearningLayer() {}
};

TEST(LearningLayerAssertionsNoReqIONamesTest, EmptyIONames)
{
    shared_ptr<base_Layer> to_ptr(new DummyChildLearningLayer());
    EXPECT_NO_THROW(to_ptr->IONames(LayerIONames()));
}

const string NAME_IN        = "i";
const string NAME_OUT       = "o";
const string NAME_OPT_OUT   = "oo";

class DummyChildLearningLayerWithReqIONames : public DummyChildLearningLayer
{
public:
    // I/O Names
    static const string KEY_INPUT_IN;
    static const string KEY_OUTPUT_OUT;
    static const string KEY_OUTPUT_OPT_OUT;

    virtual void InputNames(const LayerInputNames &io) {

        name_in_    = io.Input(KEY_INPUT_IN);
    }

    virtual void OutputNames(const LayerOutputNames &io) {

        name_out_   = io.Output(KEY_OUTPUT_OUT);
        name_opt_out_ = io.OutputOpt(KEY_OUTPUT_OPT_OUT);
    }

    DummyChildLearningLayerWithReqIONames() : DummyChildLearningLayer() {}

    // members
    string name_in_;
    string name_out_;
    OptS name_opt_out_;
};
const string DummyChildLearningLayerWithReqIONames::KEY_INPUT_IN        = "in";
const string DummyChildLearningLayerWithReqIONames::KEY_OUTPUT_OUT      = "out";
const string DummyChildLearningLayerWithReqIONames::KEY_OUTPUT_OPT_OUT  = "optout";

#include <boost/assign/list_of.hpp>
template <>
elm::MapIONames LayerAttr_<DummyChildLearningLayerWithReqIONames>::io_pairs = boost::assign::map_list_of
        ELM_ADD_INPUT_PAIR(DummyChildLearningLayerWithReqIONames::KEY_INPUT_IN)
        ELM_ADD_OUTPUT_PAIR(DummyChildLearningLayerWithReqIONames::KEY_OUTPUT_OUT)
        ;

ELM_INSTANTIATE_LEARNING_LAYER_TYPED_TEST_CASE_P(DummyChildLearningLayerWithReqIONames);

TEST(LearningLayerAssertionsReqIONamesTest, EmptyIONames)
{
    shared_ptr<base_LearningLayer> to_ptr(new DummyChildLearningLayerWithReqIONames());
    EXPECT_THROW(to_ptr->IONames(LayerIONames()), ExceptionKeyError);
}


text:
package controlP5;

/**
 * controlP5 is a processing gui library.
 *
 *  2007-2010 by Andreas Schlegel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307 USA
 *
 * @author 		Andreas Schlegel (http://www.sojamo.de)
 * @modified	10/05/2010
 * @version		0.5.4
 *
 */

import java.util.ArrayList;
import java.util.Hashtable;
import processing.core.PApplet;

/**
 *
 * @deprecated use RadioButton or CheckBox instead
 *  ControlP5
 *  Bang
 *  Button
 *  Knob
 *  Numberbox
 *  Radio
 *  Slider
 *  Tab
 *  Textfield
 *  Toggle
 *
 * @example ControlP5radio
 * @nosuperclasses Controller
 *  Controller
 */
public class Radio extends Controller {

	ArrayList<RadioToggle> _myRadioButtons;

	private int myLineSpacing = 14;

	int labelOffsetX = 14;

	int labelOffsetY = 2;

	CVector3f _myMousePosition = new CVector3f();

	RadioToggle _myCurrentRadioButton;

	int _myRadioButtonWidth = 10;

	int _myRadioButtonHeight = 10;

	boolean isSetupLocked = false;

	int _myHeight;

	int _myWidth;

	public int defaultValue = -1;

	boolean isDeactivateAll = false;
	/**
	 *
	 * @param theControlP5
	 *            ControlP5
	 * @param theParent
	 *            ControllerGroup
	 * @param theName
	 *            String
	 * @param theX
	 *            float
	 * @param theY
	 *            float
	 */
	public Radio(
	        ControlP5 theControlP5,
	        ControllerGroup theParent,
	        String theName,
	        float theX,
	        float theY) {
		super(theControlP5, theParent, theName, theX, theY, 30, 30);
		_myRadioButtons = new ArrayList<RadioToggle>();
	}

	public Radio(
	        ControlP5 theControlP5,
	        ControllerGroup theParent,
	        String theName,
	        float theX,
	        float theY,
	        int theWidth,
	        int theHeight,
	        int theLineSpacing) {
		super(theControlP5, theParent, theName, theX, theY, 30, 30);
		_myRadioButtons = new ArrayList<RadioToggle>();
		myLineSpacing = theLineSpacing;
		_myRadioButtonWidth = theWidth;
		_myRadioButtonHeight = theHeight;
		labelOffsetX = _myRadioButtonWidth + 4;
	}

	/**
	 * @deprecated
	 *
	 * @param theLabel
	 *            String
	 * @param theValue
	 *            int
	 * @return RadioButton
	 */
	public RadioToggle add(
	        final String theLabel,
	        final int theValue) {
		return addItem(theLabel, theValue);
	}

	/**
	 * add a new radio button item.
	 *
	 * @param theLabel
	 *            String
	 * @param theValue
	 *            int
	 */
	public RadioToggle addItem(
	        final String theLabel,
	        final int theValue) {
		RadioToggle myRadioButton = new RadioToggle(0, _myRadioButtons.size() * myLineSpacing, theLabel, theValue);
		_myRadioButtons.add(myRadioButton);
		getDimensions();
		if (_myRadioButtons.size() == 1 && isDeactivateAll==false) {
			activate(myRadioButton.name());
		}
		return myRadioButton;
	}

	public void removeItem(
	        String theName) {
		for (int i = _myRadioButtons.size() - 1; i >= 0; i--) {
			if (((RadioToggle) _myRadioButtons.get(i)).name().equals(theName)) {
				_myRadioButtons.remove(i);
				for (int j = i; j < _myRadioButtons.size(); j++) {
					((RadioToggle) _myRadioButtons.get(j))._myY -= myLineSpacing;
				}
				return;
			}
		}
	}

	private void getDimensions() {
		int myWidth = 0;
		for (int i = 0; i < _myRadioButtons.size(); i++) {
			int myRadioButtonWidth = ((RadioToggle) _myRadioButtons.get(i)).label.width() + labelOffsetX;
			myWidth = (myRadioButtonWidth > myWidth) ? myRadioButtonWidth : myWidth;
		}
		width = myWidth;
		height = _myRadioButtons.size() * myLineSpacing;
	}

	/**
	 *
	 * @param theApplet
	 *            PApplet
	 */
	public void draw(
	        PApplet theApplet) {
		theApplet.pushMatrix();
		theApplet.translate(position.x(), position.y());
		for (int i = 0; i < _myRadioButtons.size(); i++) {
			((RadioToggle) _myRadioButtons.get(i)).updateInternalEvents(theApplet);
			((RadioToggle) _myRadioButtons.get(i)).draw(theApplet);
		}
		theApplet.popMatrix();
	}

	/**
	 * set the default value of a Radio controller, in case no radio button is
	 * selected.
	 *
	 * @param theValue
	 */
	public void setDefaultValue(int theValue) {
		defaultValue = theValue;
	}

	/**
	 *
	 * @param theValue
	 *            float
	 */
	public void setValue(
	        float theValue) {
		for (int i = 0; i < _myRadioButtons.size(); i++) {
			RadioToggle myRadioButton = ((RadioToggle) _myRadioButtons.get(i));
			if (myRadioButton.value == theValue) {
				myRadioButton.activate();
				current(myRadioButton);
			} else {
				myRadioButton.deactivate();
			}
		}
		_myValue = theValue;
		broadcast(FLOAT);
	}

	public void update() {
		setValue(_myValue);
	}

	/**
	 * set current radio button.
	 *
	 * @param theRadioButton
	 *            RadioButton
	 */
	public void current(
	        RadioToggle theRadioButton) {
		_myCurrentRadioButton = theRadioButton;
	}

	/**
	 * get current radio button.
	 *
	 * @return RadioButton
	 */
	public RadioToggle current() {
		return _myCurrentRadioButton;
	}

	/**
	 * activate a radio button by name.
	 *
	 * @param theRadioButtonLabel
	 *            String
	 */
	public void activate(
	        String theRadioButtonName) {
		for (int i = 0; i < _myRadioButtons.size(); i++) {
			RadioToggle myRadioButton = ((RadioToggle) _myRadioButtons.get(i));
			if (theRadioButtonName.equals(myRadioButton.name())) {
				setValue(myRadioButton.value);
				return;
			}
		}
	}

	/**
	 * deactivate a RadioButton and set the value of the radio controller to
	 * the default value.
	 *
	 * @param theRadioButtonName
	 */
	public void deactivate(String theRadioButtonName) {
		for (int i = 0; i < _myRadioButtons.size(); i++) {
			RadioToggle myRadioButton = ((RadioToggle) _myRadioButtons.get(i));
			if (theRadioButtonName.equals(myRadioButton.name())) {
				myRadioButton.deactivate();
				current(null);
				setValue(defaultValue);
				return;
			}
		}
	}

	public void deactivateAll() {
		for (int i = 0; i < _myRadioButtons.size(); i++) {
			RadioToggle myRadioButton = ((RadioToggle) _myRadioButtons.get(i));
			myRadioButton.deactivate();
		}
		current(null);
		setValue(defaultValue);
		isDeactivateAll = true;
	}

	public void setColorBackground(int theColor) {
		color.colorBackground = theColor;
	}

	public void setColorForeground(int theColor) {
		color.colorForeground = theColor;
	}

	public void setColorLabel(int theColor) {
		color.colorCaptionLabel = theColor;
		for (int i = 0; i < _myRadioButtons.size(); i++) {
			RadioToggle myRadioButton = ((RadioToggle) _myRadioButtons.get(i));
			myRadioButton.label.set(myRadioButton.label.toString(), color.colorCaptionLabel);
		}
	}

	public void setColorActive(int theColor) {
		color.colorActive = theColor;
	}

	/**
	 *
	 * @param theElement
	 *            ControlP5XMLElement
	 */
	public void addToXMLElement(
	        ControlP5XMLElement theElement) {
		theElement.setAttribute("type", "radio");
		for (int i = 0; i < _myRadioButtons.size(); i++) {
			theElement.addChild(((RadioToggle) _myRadioButtons.get(i)).getAsXML());
		}
	}

	class RadioToggle {

		int _myX, _myY;

		Label label;

		int value;

		int _myId = -1;

		boolean isActive;

		RadioToggle(
		        final int theX,
		        final int theY,
		        final String theLabel,
		        final int theValue) {
			_myX = theX;
			_myY = theY;
			label = new Label(theLabel);
			label.setColor(color.colorCaptionLabel);
			value = theValue;
		}

		public String name() {
			return label.toString();
		}

		public int id() {
			return _myId;
		}

		public void setId(
		        int theId) {
			_myId = theId;
		}

		protected void deactivate() {
			isActive = false;
		}

		protected void activate() {
			isActive = true;
		}

		/**
		 * @see ControllerInterfalce.updateInternalEvents
		 */
		public void updateInternalEvents(
		        PApplet theApplet) {
			if (getIsInside()) {
				if (insideRadioButton()) {
					if (isMousePressed && current() != this) {
						setValue(value);
					}
				}
			}
		}

		/**
		 *
		 * @param theApplet
		 *            PApplet
		 */
		public void draw(
		        PApplet theApplet) {
			theApplet.noStroke();
			if (isActive) {
				theApplet.fill(color.colorActive);
			} else {
				theApplet.fill(color.colorForeground);
			}
			if (getIsInside()) {
				if (insideRadioButton()) {
					theApplet.fill(color.colorActive);
				}
			}
			theApplet.pushMatrix();
			theApplet.translate(_myX, _myY);
			theApplet.rect(0, 0, _myRadioButtonWidth, _myRadioButtonHeight);
			label.draw(theApplet, labelOffsetX, labelOffsetY);
			theApplet.popMatrix();
		}

		private boolean insideRadioButton() {
			return (_myControlWindow.mouseX > position.x() + _myParent.absolutePosition().x() + _myX
			        && _myControlWindow.mouseX < position.x() + _myParent.absolutePosition().x() + _myX
			                + _myRadioButtonWidth
			        && _myControlWindow.mouseY > position.y() + _myParent.absolutePosition().y() + _myY && _myControlWindow.mouseY < position
			        .y()
			        + _myParent.absolutePosition().y() + _myY + _myRadioButtonHeight);
		}

		protected ControlP5XMLElement getAsXML() {
			ControlP5XMLElement myXMLElement = new ControlP5XMLElement(new Hashtable(), true, false);
			myXMLElement.setName("radiobutton");
			myXMLElement.setAttribute("type", "radiobutton");
			myXMLElement.setAttribute("name", label.toString());
			myXMLElement.setAttribute("label", label.toString());
			myXMLElement.setAttribute("id", new Integer(id()));
			myXMLElement.setAttribute("value", new Float(value));
			myXMLElement.setAttribute("state", new Integer((isActive ? 1 : 0)));
			return myXMLElement;
		}

	}

}


text:
(function() { "use strict";

var Fs = require("fs");
var Util = require("../modules/util");
var World = require("../modules/world");

function Replayer(recordFile)
{
    this.recordFile = recordFile;
}

Replayer.prototype = {
    constructor: Replayer,
};

Replayer.prototype.run = function(resultFile)
{
    var world = new World(false);
    world.start();

    // run by frame
    Util.readLines(this.recordFile, function(line){

        // completed
        if (!line && resultFile) {
            var result = {};
            result.unitBaseId = world.unitBaseId;
            result.frame = world.frame;
            result.seed = world.seed;
            result.units = [];
            world.dumpUnits(result.units);
            result.unitsToAdd = [];
            world.dumpUnitsToAdd(result.unitsToAdd);
            result.players = [];
            world.dumpPlayers(result.players);
            Fs.writeFile(resultFile, JSON.stringify(result));
            Util.logDebug("replay finished");
            return;
        }

        // parse line
        var frame = line.match(/^\d+/)[0];
        while (world.frame < Number(frame) - 1) {
            world.updateFrameLogic();
        }
        var commanders = JSON.parse(line.substr(frame.length + 1));
        for (var i in commanders) {
            var commander = commanders[i];
            Util.logDebug("frame=" + world.frame + " cmd=" + commander.cmd);
            world.commander.push(world.frame, commander);
        }
    });
};

module.exports = Replayer;

})();


text:
package org.apache.camel.reifier;

import org.apache.camel.Expression;
import org.apache.camel.Processor;
import org.apache.camel.Route;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.model.SetHeaderDefinition;
import org.apache.camel.processor.SetHeaderProcessor;
import org.apache.camel.util.ObjectHelper;

public class SetHeaderReifier extends ExpressionReifier<SetHeaderDefinition> {

    public SetHeaderReifier(Route route, ProcessorDefinition<?> definition) {
        super(route, (SetHeaderDefinition) definition);
    }

    @Override
    public Processor createProcessor() throws Exception {
        ObjectHelper.notNull(definition.getName(), "headerName");
        Expression expr = createExpression(definition.getExpression());
        Expression nameExpr = camelContext.resolveLanguage("simple").createExpression(parseString(definition.getName()));
        nameExpr.init(camelContext);
        return new SetHeaderProcessor(nameExpr, expr);
    }
}


text:
package com.wanghuan.accountconfiguration.view.objectviews;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.view.View;

import com.wanghuan.accountconfiguration.view.ACStatus;

/**
 * Created by h1 on 16/3/29 15:34.
 * email: h18501667737@gmail.com
 */
public class SexBoyObject extends ObjectPointBase {

    private float radius = SEX_ITEM_DEFAULT_RADIUS;

    private PointF center = new PointF();

    public PointF getCenter() {
        return center;
    }

    public float getRadius() {
        return radius;
    }

    public SexBoyObject(Context context) {
        super(context);
    }

    public Paint getDotWhitePaint(){
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        return paint;
    }

    @Override
    public void drawEnter(final View view) {
        super.drawMove(view);
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0,1);
        valueAnimator.setDuration(1000);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                center = calculate(sexBoy_point1, sexBoy_point2, value);
                view.postInvalidate();
                ACStatus.animating = value != 1;
                ACStatus.sex1 = value == 1;
            }
        });
        valueAnimator.start();
    }

    @Override
    public void drawMove(final View view) {
        super.drawMove(view);
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0,1);
        valueAnimator.setDuration(1000);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                center = calculate(sexBoy_point2, sexBoy_point3, value);
                view.postInvalidate();
                ACStatus.animating = value != 1;
            }
        });
        valueAnimator.start();
    }

    @Override
    public void drawExit(final View view) {
        super.drawMove(view);
    }

}


text:
.. _advanced-features:

Advanced features
=================

In the examples below, these models are being used::

    from django.db import models
    from polymorphic.models import PolymorphicModel

    class ModelA(PolymorphicModel):
        field1 = models.CharField(max_length=10)

    class ModelB(ModelA):
        field2 = models.CharField(max_length=10)

    class ModelC(ModelB):
        field3 = models.CharField(max_length=10)

Filtering for classes (equivalent to python's isinstance() ):
-------------------------------------------------------------

>>> ModelA.objects.instance_of(ModelB)
.
[ <ModelB: id 2, field1 (CharField), field2 (CharField)>,
  <ModelC: id 3, field1 (CharField), field2 (CharField), field3 (CharField)> ]

In general, including or excluding parts of the inheritance tree::

    ModelA.objects.instance_of(ModelB [, ModelC ...])
    ModelA.objects.not_instance_of(ModelB [, ModelC ...])

You can also use this feature in Q-objects (with the same result as above):

>>> ModelA.objects.filter( Q(instance_of=ModelB) )

Polymorphic filtering (for fields in inherited classes)
-------------------------------------------------------

For example, cherrypicking objects from multiple derived classes
anywhere in the inheritance tree, using Q objects (with the
syntax: ``exact model name + three _ + field name``):

>>> ModelA.objects.filter(  Q(ModelB___field2 = 'B2') | Q(ModelC___field3 = 'C3')  )
.
[ <ModelB: id 2, field1 (CharField), field2 (CharField)>,
  <ModelC: id 3, field1 (CharField), field2 (CharField), field3 (CharField)> ]

Combining Querysets
-------------------

Querysets could now be regarded as object containers that allow the
aggregation of different object types, very similar to python
lists - as long as the objects are accessed through the manager of
a common base class:

>>> Base.objects.instance_of(ModelX) | Base.objects.instance_of(ModelY)
.
[ <ModelX: id 1, field_x (CharField)>,
  <ModelY: id 2, field_y (CharField)> ]

ManyToManyField, ForeignKey, OneToOneField
------------------------------------------

Relationship fields referring to polymorphic models work as
expected: like polymorphic querysets they now always return the
referred objects with the same type/class these were created and
saved as.

E.g., if in your model you define::

    field1 = OneToOneField(ModelA)

then field1 may now also refer to objects of type ``ModelB`` or ``ModelC``.

A ManyToManyField example::

    # The model holding the relation may be any kind of model, polymorphic or not
    class RelatingModel(models.Model):
        many2many = models.ManyToManyField('ModelA')  # ManyToMany relation to a polymorphic model

    >>> o=RelatingModel.objects.create()
    >>> o.many2many.add(ModelA.objects.get(id=1))
    >>> o.many2many.add(ModelB.objects.get(id=2))
    >>> o.many2many.add(ModelC.objects.get(id=3))

    >>> o.many2many.all()
    [ <ModelA: id 1, field1 (CharField)>,
      <ModelB: id 2, field1 (CharField), field2 (CharField)>,
      <ModelC: id 3, field1 (CharField), field2 (CharField), field3 (CharField)> ]

Copying Polymorphic objects
---------------------------

When creating a copy of a polymorphic object, both the
``.id`` and the ``.pk`` of the object need to be set
to ``None`` before saving so that both the base table
and the derived table will be updated to the new object::

    >>> o = ModelB.objects.first()
    >>> o.field1 = 'new val' # leave field2 unchanged
    >>> o.pk = None
    >>> o.id = None
    >>> o.save()

Using Third Party Models (without modifying them)
-------------------------------------------------

Third party models can be used as polymorphic models without
restrictions by subclassing them. E.g. using a third party
model as the root of a polymorphic inheritance tree::

    from thirdparty import ThirdPartyModel

    class MyThirdPartyBaseModel(PolymorphicModel, ThirdPartyModel):
        pass    # or add fields

Or instead integrating the third party model anywhere into an
existing polymorphic inheritance tree::

    class MyBaseModel(SomePolymorphicModel):
        my_field = models.CharField(max_length=10)

    class MyModelWithThirdParty(MyBaseModel, ThirdPartyModel):
        pass    # or add fields

Non-Polymorphic Queries
-----------------------

If you insert ``.non_polymorphic()`` anywhere into the query chain, then
django_polymorphic will simply leave out the final step of retrieving the
real objects, and the manager/queryset will return objects of the type of
the base class you used for the query, like vanilla Django would
(``ModelA`` in this example).

>>> qs=ModelA.objects.non_polymorphic().all()
>>> qs
[ <ModelA: id 1, field1 (CharField)>,
  <ModelA: id 2, field1 (CharField)>,
  <ModelA: id 3, field1 (CharField)> ]

There are no other changes in the behaviour of the queryset. For example,
enhancements for ``filter()`` or ``instance_of()`` etc. still work as expected.
If you do the final step yourself, you get the usual polymorphic result:

>>> ModelA.objects.get_real_instances(qs)
[ <ModelA: id 1, field1 (CharField)>,
  <ModelB: id 2, field1 (CharField), field2 (CharField)>,
  <ModelC: id 3, field1 (CharField), field2 (CharField), field3 (CharField)> ]

About Queryset Methods
----------------------

*   ``annotate()`` and ``aggregate()`` work just as usual, with the
    addition that the ``ModelX___field`` syntax can be used for the
    keyword arguments (but not for the non-keyword arguments).

*   ``order_by()`` similarly supports the ``ModelX___field`` syntax
    for specifying ordering through a field in a submodel.

*   ``distinct()`` works as expected. It only regards the fields of
    the base class, but this should never make a difference.

*   ``select_related()`` works just as usual, but it can not (yet) be used
    to select relations in inherited models
    (like ``ModelA.objects.select_related('ModelC___fieldxy')`` )

*   ``extra()`` works as expected (it returns polymorphic results) but
    currently has one restriction: The resulting objects are required to have
    a unique primary key within the result set - otherwise an error is thrown
    (this case could be made to work, however it may be mostly unneeded)..
    The keyword-argument "polymorphic" is no longer supported.
    You can get back the old non-polymorphic behaviour
    by using ``ModelA.objects.non_polymorphic().extra(...)``.

*   ``get_real_instances()`` allows you to turn a
    queryset or list  of base model objects efficiently into the real objects.
    For example, you could do ``base_objects_queryset=ModelA.extra(...).non_polymorphic()``
    and then call ``real_objects=base_objects_queryset.get_real_instances()``. Or alternatively
    .``real_objects=ModelA.objects.get_real_instances(base_objects_queryset_or_object_list)``

*   ``values()`` & ``values_list()`` currently do not return polymorphic
    results. This may change in the future however. If you want to use these
    methods now, it's best if you use ``Model.base_objects.values...`` as
    this is guaranteed to not change.

*   ``defer()`` and ``only()`` work as expected. On Django 1.5+ they support
    the ``ModelX___field`` syntax, but on Django 1.4 it is only possible to
    pass fields on the base model into these methods.

Using enhanced Q-objects in any Places
--------------------------------------

The queryset enhancements (e.g. ``instance_of``) only work as arguments
to the member functions of a polymorphic queryset.  Occasionally it may
be useful to be able to use Q objects with these enhancements in other places.
As Django doesn't understand these enhanced Q objects, you need to
transform them manually into normal Q objects before you can feed them
to a Django queryset or function::

    normal_q_object = ModelA.translate_polymorphic_Q_object( Q(instance_of=Model2B) )

This function cannot be used at model creation time however (in models.py),
as it may need to access the ContentTypes database table.

Nicely Displaying Polymorphic Querysets
---------------------------------------

In order to get the output as seen in all examples here, you need to use the
:class:`~polymorphic.showfields.ShowFieldType` class mixin::

    from polymorphic.models import PolymorphicModel
    from polymorphic.showfields import ShowFieldType

    class ModelA(ShowFieldType, PolymorphicModel):
        field1 = models.CharField(max_length=10)

You may also use :class:`~polymorphic.showfields.ShowFieldContent`
or :class:`~polymorphic.showfields.ShowFieldTypeAndContent` to display
additional information when printing querysets (or converting them to text).

When showing field contents, they will be truncated to 20 characters. You can
modify this behaviour by setting a class variable in your model like this::

    class ModelA(ShowFieldType, PolymorphicModel):
        polymorphic_showfield_max_field_width = 20
        ...

Similarly, pre-V1.0 output formatting can be re-estated by using
``polymorphic_showfield_old_format = True``.

.. _restrictions:

Restrictions & Caveats
----------------------

*   Database Performance regarding concrete Model inheritance in general.
    Please see the :ref:`performance`.

*   Queryset methods ``values()``, ``values_list()``, and ``select_related()``
    are not yet fully supported (see above). ``extra()`` has one restriction:
    the resulting objects are required to have a unique primary key within
    the result set.

*   Diamond shaped inheritance: There seems to be a general problem
    with diamond shaped multiple model inheritance with Django models
    (tested with V1.1 - V1.3).
    An example is here: http://code.djangoproject.com/ticket/10808.
    This problem is aggravated when trying to enhance models.Model
    by subclassing it instead of modifying Django core (as we do here
    with PolymorphicModel).

*   The enhanced filter-definitions/Q-objects only work as arguments
    for the methods of the polymorphic querysets. Please see above
    for ``translate_polymorphic_Q_object``.

*   When using the ``dumpdata`` management command on polymorphic tables
    (or any table that has a reference to
    :class:`~django.contrib.contenttypes.models.ContentType`),
    include the ``--natural`` flag in the arguments.

.. old links:
    - http://code.djangoproject.com/wiki/ModelInheritance
    - http://lazypython.blogspot.com/2009/02/second-look-at-inheritance-and.html
    - http://www.djangosnippets.org/snippets/1031/
    - http://www.djangosnippets.org/snippets/1034/
    - http://groups.google.com/group/django-developers/browse_frm/thread/7d40ad373ebfa912/a20fabc661b7035d?lnk=gst&q=model+inheritance+CORBA#a20fabc661b7035d
    - http://groups.google.com/group/django-developers/browse_thread/thread/9bc2aaec0796f4e0/0b92971ffc0aa6f8?lnk=gst&q=inheritance#0b92971ffc0aa6f8
    - http://groups.google.com/group/django-developers/browse_thread/thread/3947c594100c4adb/d8c0af3dacad412d?lnk=gst&q=inheritance#d8c0af3dacad412d
    - http://groups.google.com/group/django-users/browse_thread/thread/52f72cffebb705e/b76c9d8c89a5574f
    - http://peterbraden.co.uk/article/django-inheritance
    - http://www.hopelessgeek.com/2009/11/25/a-hack-for-multi-table-inheritance-in-django
    - http://stackoverflow.com/questions/929029/how-do-i-access-the-child-classes-of-an-object-in-django-without-knowing-the-name/929982#929982
    - http://stackoverflow.com/questions/1581024/django-inheritance-how-to-have-one-method-for-all-subclasses
    - http://groups.google.com/group/django-users/browse_thread/thread/cbdaf2273781ccab/e676a537d735d9ef?lnk=gst&q=polymorphic#e676a537d735d9ef
    - http://groups.google.com/group/django-users/browse_thread/thread/52f72cffebb705e/bc18c18b2e83881e?lnk=gst&q=model+inheritance#bc18c18b2e83881e
    - http://code.djangoproject.com/ticket/10808
    - http://code.djangoproject.com/ticket/7270


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 市町村区API
 * @author koji.fukami
 *
 */
require APPPATH . '/controllers/CRU_Master.php';

class SelHistories extends CRU_Master {

    /**
     * construct
     */
    public function __construct()
    {
        parent::__construct('Sel_histories_model');
    }

    protected function getParameterId(){
        $id = $this->input->get('sel_history_id');
        if( !is_numeric($id) ){
            throw new Exception("sel_history_idが数値ではありません。",REST_ER_PARAM_FORMAT);
        }
        return $id;
    }

    /**
     * Check valid the data
     * @param bool $postData
     * @return mixed
     */
    protected  function checkValidations($postData = false)
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->helper('enjin_helper');
        $this->form_validation->set_data($postData);

        $this->form_validation->set_rules('job_vote_id', '', 'trim|required');
        $this->form_validation->set_message('required', '%s is required');

        $this->form_validation->set_rules('start_date', '', 'trim|valid_date_check');
        $this->form_validation->set_message('valid_date_check', '%s should be in "YYYYMMDD" Format');
        $this->form_validation->set_rules('end_date', '', 'trim|valid_date_check');
        $this->form_validation->set_message('valid_date_check', '%s should be in "YYYYMMDD" Format');

        $this->form_validation->set_rules('influx_propriety', '', 'trim|integer');
        $this->form_validation->set_message('integer', '%s is integer');
        $this->form_validation->set_rules('candidate_propriety', '', 'trim|integer');
        $this->form_validation->set_message('integer', '%s is integer');
        $this->form_validation->set_rules('last_modified_type', '', 'trim|integer');
        $this->form_validation->set_message('integer', '%s is integer');

        return $this->form_validation->run();
    }

    protected function prepareInsertData()
    {
        $post = $this->input->post();
        if(isset($post['job_vote_id'])) {
            $jobVoteId = $post['job_vote_id'];
        }else{
            throw new Exception("job_vote_id is required。",REST_ER_PARAM_FORMAT);
        }

        // get candidateId
        $canCandidateId = $this->getCanCandidateId();

        $recCompanyId = $this->getRecCompanyIdFromSession();

        //check jobvote_id: status and rec_company_id
        $this->load->model('Jobvotes_model', 'jobvotes');
        $jobvotes = $this->jobvotes->getRecCompanyIdByVoteJobId($jobVoteId, $recCompanyId);
        if( empty($jobvotes)) {
            throw new Exception("This jobvotes is not available。",REST_ER_PAGE_NOTFOUND);
        }

        //check candidate_id:status and rec_company_id
        $this->load->model('Cancandidates_model', 'canCandidates');
        $canCandidates = $this->canCandidates->checkRecCompanyId($canCandidateId, $recCompanyId);
        if( empty($canCandidates)) {
            throw new Exception("This canCandidates is not available。",REST_ER_PAGE_NOTFOUND);
        }

        //check screening_stage_id:status and rec_company_id
        $this->load->model('Screening_stages_model',"stages");
        $screeningStage = $this->stages->getScreeningStageId($recCompanyId);

        if(empty($screeningStage)) {
            throw new Exception("This ScreeningStages is not available。",REST_ER_PAGE_NOTFOUND);
        }

        //check duplicate job_vote_id and can_candidate_id
        $this->load->model('Sel_histories_model',"selHistory");
        if($this->selHistory->checkUnique($jobVoteId, $canCandidateId)) {
            throw new Exception('Duplicate data', REST_ER_PAGE_NOTFOUND);
        }
        $data = array(
            'can_candidate_id' => $canCandidateId,
            'screening_stage_id' => isset($screeningStage['id'])?$screeningStage['id']:'',
            'job_vote_id' => isset($post['job_vote_id'])?$post['job_vote_id']:'',
            'select_status_id' => 0,
            'select_option_id' => isset($post['select_option_id'])?$post['select_option_id']:'',
            'comment' => isset($post['comment'])?$post['comment']:'',
            'start_date' => isset($post['start_date'])?$post['start_date']:'',
            'end_date' => isset($post['end_date'])?$post['end_date']:'',
            'influx_propriety' => 2,
            'candidate_propriety' => 2,
            'last_modified_type' => 0,
            'rec_recruiter_id' => isset($post['rec_recruiter_id'])?$post['rec_recruiter_id']:'',

        );

        return $data;
    }

}


text:
@class NodeWrapper;

@protocol NodeSearchDelegate

-(void)nodeSearchDelegateDone;
-(void)nodeSelected:(NodeWrapper*)node;
-(void)selectNodeByHostLookup:(NSString*)host;
-(void)selectYouAreHereNode;

@end

@interface NodeSearchViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (weak, nonatomic) id delegate;
@property (nonatomic, copy) NSArray* allItems;
@property (strong, nonatomic) UITableView* tableView;

@end


text:
using UnityEngine;

/// <summary>
/// This script can be used to anchor an object to the side or corner of the screen, panel, or a widget.
/// </summary>

[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/Anchor")]
public class UIAnchor : MonoBehaviour
{
	public enum Side
	{
		BottomLeft,
		Left,
		TopLeft,
		Top,
		TopRight,
		Right,
		BottomRight,
		Bottom,
		Center,
	}

	/// <summary>
	/// Camera used to determine the anchor bounds. Set automatically if none was specified.
	/// </summary>

	public Camera uiCamera = null;

	/// <summary>
	/// Object used to determine the container's bounds. Overwrites the camera-based anchoring if the value was specified.
	/// </summary>

	public GameObject container = null;

	/// <summary>
	/// Side or corner to anchor to.
	/// </summary>

	public Side side = Side.Center;

	/// <summary>
	/// If set to 'true', UIAnchor will execute once, then will be disabled.
	/// Screen size changes will still cause the anchor to update itself, even if it's disabled.
	/// </summary>

	public bool runOnlyOnce = true;

	/// <summary>
	/// Relative offset value, if any. For example "0.25" with 'side' set to Left, means 25% from the left side.
	/// </summary>

	public Vector2 relativeOffset = Vector2.zero;

	/// <summary>
	/// Pixel offset value if any. For example "10" in x will move the widget 10 pixels to the right
	/// while "-10" in x is 10 pixels to the left based on the pixel values set in UIRoot.
	/// </summary>

	public Vector2 pixelOffset = Vector2.zero;

	// Deprecated legacy functionality
	[HideInInspector][SerializeField] UIWidget widgetContainer;

	Transform mTrans;
	Animation mAnim;
	Rect mRect = new Rect();
	UIRoot mRoot;
	bool mStarted = false;

	void OnEnable ()
	{
		mTrans = transform;
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
		mAnim = animation;
#else
		mAnim = GetComponent<Animation>();
#endif
		UICamera.onScreenResize += ScreenSizeChanged;
	}

	void OnDisable () { UICamera.onScreenResize -= ScreenSizeChanged; }

	void ScreenSizeChanged () { if (mStarted && runOnlyOnce) Update(); }

	/// <summary>
	/// Automatically find the camera responsible for drawing the widgets under this object.
	/// </summary>

	void Start ()
	{
		if (container == null && widgetContainer != null)
		{
			container = widgetContainer.gameObject;
			widgetContainer = null;
#if UNITY_EDITOR
			NGUITools.SetDirty(this);
#endif
		}

		mRoot = NGUITools.FindInParents<UIRoot>(gameObject);
		if (uiCamera == null) uiCamera = NGUITools.FindCameraForLayer(gameObject.layer);

		Update();

		mStarted = true;
	}

	/// <summary>
	/// Anchor the object to the appropriate point.
	/// </summary>

	void Update ()
	{
		if (mAnim != null && mAnim.enabled && mAnim.isPlaying) return;

		bool useCamera = false;

		UIWidget wc = (container == null) ? null : container.GetComponent<UIWidget>();
		UIPanel pc = (container == null && wc == null) ? null : container.GetComponent<UIPanel>();

		if (wc != null)
		{
			Bounds b = wc.CalculateBounds(container.transform.parent);

			mRect.x = b.min.x;
			mRect.y = b.min.y;

			mRect.width = b.size.x;
			mRect.height = b.size.y;
		}
		else if (pc != null)
		{
			if (pc.clipping == UIDrawCall.Clipping.None)
			{
				// Panel has no clipping -- just use the screen's dimensions
				float ratio = (mRoot != null) ? (float)mRoot.activeHeight / Screen.height * 0.5f : 0.5f;
				mRect.xMin = -Screen.width * ratio;
				mRect.yMin = -Screen.height * ratio;
				mRect.xMax = -mRect.xMin;
				mRect.yMax = -mRect.yMin;
			}
			else
			{
				// Panel has clipping -- use it as the mRect
				Vector4 pos = pc.finalClipRegion;
				mRect.x = pos.x - (pos.z * 0.5f);
				mRect.y = pos.y - (pos.w * 0.5f);
				mRect.width = pos.z;
				mRect.height = pos.w;
			}
		}
		else if (container != null)
		{
			Transform root = container.transform.parent;
			Bounds b = (root != null) ? NGUIMath.CalculateRelativeWidgetBounds(root, container.transform) :
				NGUIMath.CalculateRelativeWidgetBounds(container.transform);

			mRect.x = b.min.x;
			mRect.y = b.min.y;

			mRect.width = b.size.x;
			mRect.height = b.size.y;
		}
		else if (uiCamera != null)
		{
			useCamera = true;
			mRect = uiCamera.pixelRect;
		}
		else return;

		float cx = (mRect.xMin + mRect.xMax) * 0.5f;
		float cy = (mRect.yMin + mRect.yMax) * 0.5f;
		Vector3 v = new Vector3(cx, cy, 0f);

		if (side != Side.Center)
		{
			if (side == Side.Right || side == Side.TopRight || side == Side.BottomRight) v.x = mRect.xMax;
			else if (side == Side.Top || side == Side.Center || side == Side.Bottom) v.x = cx;
			else v.x = mRect.xMin;

			if (side == Side.Top || side == Side.TopRight || side == Side.TopLeft) v.y = mRect.yMax;
			else if (side == Side.Left || side == Side.Center || side == Side.Right) v.y = cy;
			else v.y = mRect.yMin;
		}

		float width = mRect.width;
		float height = mRect.height;

		v.x += pixelOffset.x + relativeOffset.x * width;
		v.y += pixelOffset.y + relativeOffset.y * height;

		if (useCamera)
		{
			if (uiCamera.orthographic)
			{
				v.x = Mathf.Round(v.x);
				v.y = Mathf.Round(v.y);
			}

			v.z = uiCamera.WorldToScreenPoint(mTrans.position).z;
			v = uiCamera.ScreenToWorldPoint(v);
		}
		else
		{
			v.x = Mathf.Round(v.x);
			v.y = Mathf.Round(v.y);

			if (pc != null)
			{
				v = pc.cachedTransform.TransformPoint(v);
			}
			else if (container != null)
			{
				Transform t = container.transform.parent;
				if (t != null) v = t.TransformPoint(v);
			}
			v.z = mTrans.position.z;
		}

		// Wrapped in an 'if' so the scene doesn't get marked as 'edited' every frame
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
		if (useCamera && uiCamera.isOrthoGraphic && mTrans.parent != null)
#else
		if (useCamera && uiCamera.orthographic && mTrans.parent != null)
#endif
		{
			v = mTrans.parent.InverseTransformPoint(v);
			v.x = Mathf.RoundToInt(v.x);
			v.y = Mathf.RoundToInt(v.y);
			if (mTrans.localPosition != v) mTrans.localPosition = v;
		}
		else if (mTrans.position != v) mTrans.position = v;
		if (runOnlyOnce && Application.isPlaying) enabled = false;
	}
}


text:
package filesystem

import (
	"errors"
	"io/ioutil"
	"os"
)

// RemoveDirContents deletes the contents of a directory including
// all files and directories.
func RemoveDirContents(path string) error {
	src, err := os.Stat(path)
	if err != nil {
		return err
	}
	if !src.IsDir() {
		return errors.New("Path is not a directory")
	}

	fileList, err := ioutil.ReadDir(path)
	if err != nil {
		return err
	}

	for _, file := range fileList {
		if file.Name()[0] == '.' {
			continue
		}

		os.Remove(path + "/" + file.Name())
	}

	return nil
}


text:
var extensionId = "enfkhcelefdadlmkffamgdlgplcionje";

// The id of an app we're using for install tests.
var appId = "iladmdjkfniedhfhcfoefgojhgaiaccc";

var assertEq = chrome.test.assertEq;
var assertFalse = chrome.test.assertFalse;
var assertNoLastError = chrome.test.assertNoLastError;
var assertTrue = chrome.test.assertTrue;
var callbackFail = chrome.test.callbackFail;
var callbackPass = chrome.test.callbackPass;
var listenOnce = chrome.test.listenOnce;
var runTests = chrome.test.runTests;
var succeed = chrome.test.succeed;

// Calls |callback| with true/false indicating whether an item with the |id|
// is installed.
function checkItemInstalled(id, callback) {
  chrome.management.getAll(function(extensions) {
    callback(extensions.some(function(ext) {
      return ext.id == id;
    }));
  });
}

// Calls |callback| with true/false indicating whether an item with an id of
// extensionId is installed.
function checkInstalled(callback) {
  checkItemInstalled(extensionId, callback);
}

var cachedIcon = null;
var img = null;

// This returns the base64-encoded content of the extension's image.
function getIconData(callback) {
  if (cachedIcon) {
    callback(cachedIcon);
    return;
  }
  var canvas = document.createElement("canvas");
  canvas.style.display = "none";
  canvas.width = 128;
  canvas.height = 128;
  img = new Image();
  img.onload = function() {
    console.log('img.onload called');
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var tmp = canvas.toDataURL();
    // Strip the data url prefix to just get the base64-encoded bytes.
    cachedIcon = tmp.slice(tmp.search(",")+1);
    callback(cachedIcon);
  };
  img.src = "extension/icon.png";
}

// This returns the string contents of the extension's manifest file.
function getManifest(alternativePath) {
  // Do a synchronous XHR to get the manifest.
  var xhr = new XMLHttpRequest();
  xhr.open("GET",
           alternativePath ? alternativePath : "extension/manifest.json",
           false);
  xhr.send(null);
  return xhr.responseText;
}

// Installs the extension with the given |installOptions|, calls
// |whileInstalled| and then uninstalls the extension.
function installAndCleanUp(installOptions, whileInstalled) {
  // Begin installing.
  chrome.webstorePrivate.beginInstallWithManifest3(
      installOptions,
      callbackPass(function(result) {
        assertNoLastError();
        assertEq("", result);

        // Now complete the installation.
        chrome.webstorePrivate.completeInstall(
            extensionId,
            callbackPass(function(result) {
              assertNoLastError();
              assertEq(undefined, result);

              whileInstalled();

              chrome.management.uninstall(extensionId, {}, callbackPass());
            }));
      }));
}


text:
$(function () {

    module("bootstrap-buttons")

      test("should be defined on jquery object", function () {
        ok($(document.body).button, 'tabs method is defined')
      })

      test("should return element", function () {
        ok($(document.body).button()[0] == document.body, 'document.body returned')
      })

      test("should return set state to loading", function () {
        var btn = $('<button class="btn" data-loading-text="fat">mdo</button>')
        equals(btn.html(), 'mdo', 'btn text equals mdo')
        btn.button('loading')
        equals(btn.html(), 'fat', 'btn text equals fat')
        stop()
        setTimeout(function() {
          start()
          ok(btn.attr('disabled'), 'btn is disabled')
          ok(btn.hasClass('disabled'), 'btn has disabled class')
        }, 0)
      })

      test("should return reset state", function () {
        var btn = $('<button class="btn" data-loading-text="fat">mdo</button>')
        equals(btn.html(), 'mdo', 'btn text equals mdo')
        btn.button('loading')
        equals(btn.html(), 'fat', 'btn text equals fat')
        stop()
        setTimeout(function() {
          start()
          ok(btn.attr('disabled'), 'btn is disabled')
          ok(btn.hasClass('disabled'), 'btn is disabled')
        }, 0)
        btn.button('reset')
        equals(btn.html(), 'mdo', 'btn text equals mdo')
        ok(!btn.attr('disabled'), 'btn is not disabled')
        ok(!btn.hasClass('disabled'), 'btn does not have disabled class')
      })

      test("should toggle active", function () {
        var btn = $('<button class="btn" data-loading-text="fat">mdo</button>')
        ok(!btn.hasClass('active'), 'btn does not have active class')
        btn.button('toggle')
        ok(btn.hasClass('active'), 'btn has class active')
      })

})


text:
package org.skfiy.typhon.spi.sign;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.skfiy.typhon.AbstractComponent;
import org.skfiy.typhon.dobj.ItemDobj;
import org.skfiy.typhon.domain.Normal;
import org.skfiy.typhon.domain.Player;
import org.skfiy.typhon.packet.Packet;
import org.skfiy.typhon.packet.PacketError;
import org.skfiy.typhon.packet.SingleValue;
import org.skfiy.typhon.session.BagUtils;
import org.skfiy.typhon.session.SessionUtils;
import org.skfiy.typhon.spi.ConfigurationLoader;
import org.skfiy.typhon.spi.ItemProvider;
import org.skfiy.typhon.spi.ServerSettingKeys;
import org.skfiy.typhon.util.ComponentUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Singleton
public class SignProvider extends AbstractComponent {
    @Inject
    private ItemProvider itemProvider;
    @Inject
    private ConfigurationLoader configurationLoader;

    private JSONArray arrayCount;

    //Map<Integer(年),Map<Integer(月),Map<Integer(日),Sign>>>
    public static Map<Integer, Map<Integer, Map<Integer, Sign>>> signies = new HashMap<>();

    @Override
    protected void doDestroy() {

    }

    @Override
    protected void doInit() {
        JSONObject obj = JSON.parseObject(ComponentUtils.readDataFile("month_sign.json"));

        for (Entry<String, Object> entry : obj.entrySet()) {

            JSONObject array = obj.getJSONObject(entry.getKey());
            Map<Integer, Map<Integer, Sign>> asign = new HashMap<>();

            for (Entry<String, Object> entries : array.entrySet()) {

                JSONArray arraies = array.getJSONArray(entries.getKey());
                Map<Integer, Sign> bsign = new HashMap<>();

                for (int i = 0; i < arraies.size(); i++) {

                    Sign sign = new Sign();
                    sign = JSON.toJavaObject(arraies.getJSONObject(i), Sign.class);
                    bsign.put(i, sign);
                }
                asign.put(Integer.valueOf(entries.getKey()), bsign);
            }
            signies.put(Integer.valueOf(entry.getKey()), asign);
        }

        arrayCount = JSON.parseArray(ComponentUtils.readDataFile("sign_cost.json"));
    }

    @Override
    protected void doReload() {

    }

    public void sign(SingleValue packet) {
        Player player = SessionUtils.getPlayer();
        Normal normal = player.getNormal();
        //签到次数packet.getval();
        int size = normal.getSigns().size();
        //领取物品的倍数 &&也代表领取次数
        Calendar calendar = Calendar.getInstance();
        int count = 1;
        Map<Integer, Sign> signa = inster(size, calendar, player);
        if (signa == null) {
            PacketError error = PacketError.createResult(packet, PacketError.Condition.conflict);
            error.setText("Time since I can't sign in");
            player.getSession().write(error);
            return;
        }

        int day = calendar.get(Calendar.DAY_OF_MONTH);

        //获取当前签到的Sign
        Sign sign = signa.get(size);
        if (sign.getVipLevel() <= normal.getVipLevel()) {
            count = 2;
        }

        ItemDobj item = itemProvider.getItem(sign.getPrize());
        BagUtils.intoItem(item, sign.getCount() * count);

        SignDraw signdraw = new SignDraw(count, day, normal.getVipLevel());
        normal.addSigns(signdraw);
        player.getSession().write(Packet.createResult(packet));
    }

    public void signAgain(SingleValue packet) {
        Player player = SessionUtils.getPlayer();

        Normal normal = player.getNormal();
        Calendar calendar = Calendar.getInstance();

        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //领取某天补签第二份奖励
        int oneDay = (int) packet.getVal() - 1;

        Sign sign = new Sign();
        int count = 1;

        Map<Integer, Sign> signa = new HashMap<Integer, Sign>();
        //size+1代表签到的数据size
        signa = inster(oneDay, calendar, player);
        if (signa == null) {
            PacketError error = PacketError.createResult(packet, PacketError.Condition.conflict);
            error.setText("No data cannot be retroactive and be rewarded Sign");
            player.getSession().write(error);
            return;
        }
        if (oneDay + 1 > normal.getSigns().size()) {
            //获取当前签到的Sign
            sign = signa.get(oneDay);
            if (sign.getVipLevel() <= normal.getVipLevel()) {
                count = 2;
            }
            SignDraw signdraw = new SignDraw(count, day, normal.getVipLevel());
            normal.addSigns(signdraw);
            //增加补签次数
            int signed = player.getNormal().getSigned();
            //扣去补签的钱
            int cost = arrayCount.getInteger(signed);
            JSONObject object = new JSONObject();
            object.put("place", "SignAgain");
            object.put("signAgainCounts", signed);
            object.put("signAgainItems", sign.getPrize());
            SessionUtils.decrementDiamond(cost, object.toString());
            player.getNormal().setSigned(signed + 1);

        } else {
            SignDraw signDraw = normal.getSigns().get(oneDay);
            //size代表list中的数据索引 从0开始
            if (signDraw.getDrawTime() != day || signDraw.getCount() == 2
                    || signDraw.getLastVip() >= normal.getVipLevel()) {
                PacketError error =
                        PacketError.createResult(packet, PacketError.Condition.conflict);
                error.setText("No again signed number");
                player.getSession().write(error);
                return;
            } else {
                sign = signa.get(oneDay);
                signDraw.setCount(count + 1);
                signDraw.setDrawTime(day);
                signDraw.setLastVip(normal.getVipLevel());
            }
        }
        ItemDobj item = itemProvider.getItem(sign.getPrize());
        BagUtils.intoItem(item, sign.getCount() * count);
        player.getSession().write(Packet.createResult(packet));
    }

    private Map<Integer, Sign> inster(int size, Calendar calendar,Player player) {

        Calendar serverCalendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        serverCalendar.setTimeInMillis(player.getRole().getCreationTime());
        //对开服时间进行特殊判断
        if (year == serverCalendar.get(Calendar.YEAR)
                && month == serverCalendar.get(Calendar.MONTH)
                && size + serverCalendar.get(Calendar.DAY_OF_MONTH) > day) {

            return null;
        } else {
            if (size > day) {
                return null;
            }
        }
        Map<Integer, Map<Integer, Sign>> signss = signies.get(year);
        Map<Integer, Sign> map = signss.get(month + 1);
        return map;
    }
}


text:
import unittest

import requests.exceptions
import tests.command_download

from onlinejudge.type import SampleParseError

class DownloadInvalidTest(unittest.TestCase):
    def snippet_call_download_raises(self, *args, **kwargs):
        tests.command_download.snippet_call_download_raises(self, *args, **kwargs)

    def snippet_call_download_twice(self, *args, **kwargs):
        tests.command_download.snippet_call_download_twice(self, *args, **kwargs)

    def test_call_download_invalid(self):
        self.snippet_call_download_raises(requests.exceptions.InvalidURL, 'https://not_exist_contest.jp/tasks/001_a')

    def test_call_download_no_sample_found(self):
        self.snippet_call_download_raises(SampleParseError, 'https://atcoder.jp/contests/tenka1-2013-quala/tasks/tenka1_2013_qualA_a')
        self.snippet_call_download_raises(SampleParseError, 'https://open.kattis.com/problems/hello')

    def test_call_download_twice(self):
        self.snippet_call_download_twice('https://atcoder.jp/contests/abc114/tasks/abc114_c', 'https://atcoder.jp/contests/abc003/tasks/abc003_4', [
            {
                "input": "575\n",
                "output": "4\n"
            },
            {
                "input": "3600\n",
                "output": "13\n"
            },
            {
                "input": "999999999\n",
                "output": "26484\n"
            },
        ], type='json')


text:
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title>
  <meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% else %}{{ site.description }}{% endif %}">

  <!-- site icon -->
  <link rel="bookmark" type="image/x-icon" href="{{site.baseurl}}/assets/img/favicon.ico" />
  <link rel="shortcut icon" href="{{site.baseurl}}/assets/img/favicon.ico">

  <!-- evil icon -->
  <link rel="stylesheet" href="{{" /assets/evil-icons.min.css " | prepend:site.baseurl }}">
  <script src="{{" /assets/evil-icons.min.js " | prepend:site.baseurl }}"></script>

  <!-- todo: include this into main.css -->

  <link rel="stylesheet" href="{{ " /css/main.css " | prepend: site.baseurl }}">
  <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
  <link rel="alternate" type="application/rss+xml" title="{{ site.title }}" href="{{ " /feed.xml
    " | prepend: site.baseurl | prepend: site.url }}">
</head>