text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.ewcms</groupId>
	<artifactId>rmyy</artifactId>
	<version>1.0.0</version>
	<packaging>pom</packaging>

	<url>https://github.com/ewcmsfree/rmyy</url>
	<organization>
		<name>rmyy</name>
		<url>https://github.com/ewcmsfree</url>
	</organization>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-site-plugin</artifactId>
				<version>3.5</version>
				<configuration>
					<locales>zh_CN</locales>
					<outputEncoding>UTF-8</outputEncoding>
					<inputEncoding>UTF-8</inputEncoding>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<repositories>
		<repository>
			<id>alimaven</id>
			<name>aliyun maven</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
		</repository>
		<repository>
			<id>apache-repo</id>
			<name>Apache Repository</name>
			<url>https://repository.apache.org/content/groups/public/</url>
		</repository>
		<repository>
			<id>java-repo</id>
			<name>Java Repository</name>
			<url>http://download.java.net/maven/2/</url>
		</repository>
		<repository>
			<id>springsource-repo</id>
			<name>SpringSource Repository</name>
			<url>http://repo.spring.io/release/</url>
		</repository>
		<repository>
			<id>springsource-repo-snapshot</id>
			<name>SpringSource Repository Snapshot</name>
			<url>http://repo.spring.io/snapshot/</url>
		</repository>
		<repository>
			<id>jboss-repo-release</id>
			<name>Jboss Repository</name>
			<url>https://repository.jboss.org/nexus/content/repositories/releases/</url>
		</repository>
		<repository>
			<id>central</id>
			<name>Maven Repository Switchboard</name>
			<layout>default</layout>
			<url>http://repo.maven.apache.org/maven2/</url>
		</repository>
		<repository>
			<id>maven-repo1</id>
			<name>maven-repo1</name>
			<layout>default</layout>
			<url>http://repo1.maven.org/maven2/</url>
		</repository>
		<repository>
			<id>sourceforge-releases</id>
			<name>Sourceforge Releases</name>
			<url>https://oss.sonatype.org/content/repositories/sourceforge-releases/</url>
		</repository>
		<repository>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
			<id>bintray-dnault-maven</id>
			<name>bintray</name>
			<url>http://dl.bintray.com/dnault/maven</url>
		</repository>
		<repository>
			<id>jitpack.io</id>
			<url>https://jitpack.io</url>
		</repository>
		<repository>
			<id>oss-snapshots</id>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
			<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
		</repository>
	</repositories>

	<pluginRepositories>
		<pluginRepository>
			<id>alimaven</id>
			<name>aliyun maven</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
		</pluginRepository>
		<pluginRepository>
			<id>maven2-repo</id>
			<name>Maven2 Repository</name>
			<url>http://repo1.maven.org/maven2/</url>
		</pluginRepository>
		<pluginRepository>
			<id>Codehaus repository</id>
			<url>http://repository.codehaus.org/</url>
		</pluginRepository>
		<!-- <pluginRepository> <id>maven-db-plugin-repo</id> <name>maven db plugin
			repository</name> <url>http://maven-db-plugin.googlecode.com/svn/maven/repo/</url>
			<layout>default</layout> </pluginRepository> -->
	</pluginRepositories>

	<!-- 开发人员信息 -->
	<developers>
		<developer>
			<name>wu_zhijun</name>
			<email>wu_zhijun@msn.com</email>
			<url>https://github.com/ewcmsfree</url>
			<roles>
				<role>software engineer</role>
			</roles>
			<timezone>8</timezone>
		</developer>
		<developer>
			<name>zhou_dongchu</name>
			<email>zhoudcrobin@qq.com</email>
			<url>https://github.com/ewcmsfree</url>
			<roles>
				<role>software engineer</role>
			</roles>
			<timezone>8</timezone>
		</developer>
	</developers>

	<!-- 许可证 -->
	<licenses>
		<license>
			<name>Apache License, Version 2.0</name>
			<url>http://www.apache.org/license/LICENSE-2.0</url>
		</license>
	</licenses>

	<!-- 持续集成信息 -->
	<ciManagement>
		<system>continuum</system>
		<url>https://travis-ci.org/ewcmsfree/rmyy</url>
		<notifiers>
			<notifier>
				<type>mail</type>
				<sendOnError>true</sendOnError>
				<sendOnFailure>true</sendOnFailure>
				<sendOnSuccess>true</sendOnSuccess>
				<sendOnWarning>false</sendOnWarning>
				<configuration>
					<address>wu_zhijun@msn.com</address>
				</configuration>
			</notifier>
		</notifiers>
	</ciManagement>

	<!-- 问题反馈信息 -->
	<issueManagement>
		<system>Github</system>
		<url>https://github.com/ewcmsfree/rmyy/issues</url>
	</issueManagement>

	<!-- 分发管理 -->
	<distributionManagement>
		<!-- mvn site:deploy 部署位置 -->
		<site>
			<id>local</id>
			<name>filesystem</name>
			<!-- 修改到磁盘的相应位置 -->
			<url>file:E:\target\site</url>
		</site>
	</distributionManagement>

	<!-- 版本控制信息 -->
	<scm>
		<url>https://github.com/ewcmsfree/rmyy/</url>
		<connection>scm:git:git://github.com/ewcmsfree/rmyy.git</connection>
		<developerConnection>scm:git:ssh://git@github.com:ewcmsfree/rmyy.git</developerConnection>
	</scm>

</project>


text:
namespace chromeos {

class MockNetworkLibrary;

// Base class for Chromium OS tests wanting to bring up a browser in the
// browser test process and provide MockNetworkLibrary with preset behaviors.
class CrosInProcessBrowserTest : public InProcessBrowserTest {
 public:
  CrosInProcessBrowserTest();
  virtual ~CrosInProcessBrowserTest();

  // InProcessBrowserTest overrides:
  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE;
  virtual void TearDownInProcessBrowserTestFixture() OVERRIDE;

 private:
  // Sets up basic mocks that are used by status area items.
  void InitStatusAreaMocks();

  // Sets up corresponding expectations for basic mocks that
  // are used by status area items.
  // Make sure that InitStatusAreaMocks was called before.
  // They are all configured with RetiresOnSaturation().
  // Once such expectation is used it won't block expectations you've defined.
  void SetStatusAreaMocksExpectations();

  // Destroyed by NetworkLibrary::Shutdown().
  MockNetworkLibrary* mock_network_library_;

  // Stuff used for mock_network_library_.
  WifiNetworkVector wifi_networks_;
  WimaxNetworkVector wimax_networks_;
  CellularNetworkVector cellular_networks_;
  VirtualNetworkVector virtual_networks_;
  std::string empty_string_;

  DISALLOW_COPY_AND_ASSIGN(CrosInProcessBrowserTest);
};

}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_CROS_CROS_IN_PROCESS_BROWSER_TEST_H_

redpajama_set_name: RedPajamaGithub


text:
package com.google.cloud.speech.v2.samples;

// [START speech_v2_generated_Speech_ListPhraseSets_String_sync]
import com.google.cloud.speech.v2.LocationName;
import com.google.cloud.speech.v2.PhraseSet;
import com.google.cloud.speech.v2.SpeechClient;

public class SyncListPhraseSetsString {

  public static void main(String[] args) throws Exception {
    syncListPhraseSetsString();
  }

  public static void syncListPhraseSetsString() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (SpeechClient speechClient = SpeechClient.create()) {
      String parent = LocationName.of("[PROJECT]", "[LOCATION]").toString();
      for (PhraseSet element : speechClient.listPhraseSets(parent).iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}
// [END speech_v2_generated_Speech_ListPhraseSets_String_sync]


text:
static LIST_HEAD DispatchpDeferredQueue;

extern unsigned char g_pfnVectors, _sheap, _eheap;
static unsigned int DispatchpHeapLock;

static void DispatchpLockHeap(void *Arg) {
    (void) Arg;

    DispatchpHeapLock = DispatchEnterSystem();
}

static void DispatchpUnlockHeap(void *Arg) {
    (void) Arg;

    DispatchLeaveSystem(DispatchpHeapLock);
}

static const heap_locking_callbacks_t DispatchpHeapLocks = {
    .lock = DispatchpLockHeap,
    .unlock = DispatchpUnlockHeap
};

void DispatchInit(void) {
    SCB->VTOR = (unsigned int) &g_pfnVectors;

    heap_seed(&_sheap, &_eheap - &_sheap);
    heap_initialize_locking(&DispatchpHeapLocks, NULL);

    // Configure PendSV to lowest priority
    NVIC_SetPriority(PendSV_IRQn, DISPATCH_PENDSV_PRIORITY);
    ListInit(&DispatchpDeferredQueue);
}

void DispatchDefer(DISPATCH_DEFERRED_PROC *Proc) {
    unsigned int Interrupts = DispatchDisableInterrupts();

    ListAppend(&DispatchpDeferredQueue, &Proc->Head);

    DispatchEnableInterrupts(Interrupts);

    SCB->ICSR = SCB_ICSR_PENDSVSET_Msk;
    __DMB();
}

void DispatchAbandon(DISPATCH_DEFERRED_PROC *Proc) {
    unsigned int Interrupts = DispatchDisableInterrupts();

    ListRemove(&Proc->Head);

    DispatchEnableInterrupts(Interrupts);
}

void PendSV_Handler(void) {
    while(1) {
        __disable_irq();

        if(ListEmpty(&DispatchpDeferredQueue)) {
            __enable_irq();

            break;
        }

        LIST_HEAD *Entry = ListTakeFirst(&DispatchpDeferredQueue);

        __enable_irq();

        DISPATCH_DEFERRED_PROC *Proc = LIST_DATA(Entry, DISPATCH_DEFERRED_PROC, Head);
        Proc->Handler(Proc);
    }
}


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

namespace Secure_Camera_Capture_Client
{
    class JsonObject
    {
        public string id { get; set; }
        public string date_created { get; set; }
        public string method { get; set; }
        public List<Year> year { get; set; }

        public JsonObject ()
        {
            year = new List<Year>();
        }

        public class Image
        {
            public Image(Int16 minute, string file_name, string date_taken, Int16 method)
            {
                this.minute = minute;
                this.file_name = file_name;
                this.date_taken = date_taken;
                this.method = method;
            }
            public Int16 minute { get; set; }
            public string file_name { get; set; }
            public string date_taken { get; set; }
            public Int16 method { get; set; }
        }

        public class Hour
        {
            public Hour(Int16 hour)
            {
                this.hour = hour;
                this.images = new List<Image>();
            }
            //This is the hour in the day, 0-23
            public Int16 hour { get; set; }
            public IList<Image> images { get; set; }
        }

        public class Day
        {
            public Day(Int16 day_name)
            {
                this.day_name = day_name;
                this.hours = new List<Hour>();
            }
            //This is the number of the day in the month 1-31ish
            public Int16 day_name { get; set; }
            public IList<Hour> hours { get; set; }
        }

        public class Month
        {
            public Month(Int16 month_name)
            {
                this.month_name = month_name;
                this.days = new List<Day>();
            }
            //This is 1-12 January-December Respective
            public Int16 month_name { get; set; }
            public IList<Day> days { get; set; }

        }

        public class Year
        {
            public Year(Int32 year_name)
            {
                this.year_name = year_name;
                this.months = new List<Month>();
            }

            //Int value of the year such as 2016
            public Int32 year_name { get; set; }
            public IList<Month> months { get; set; }
        }
    }
}


text:
     @foreach($tags as $category_type => $category)

{{ ucfirst($category_type) }}  :

                  @foreach($category->take(10) as $tag)

Request::input('type'),'tag' => $tag->image]) }}" class="size16">
                    {{ ucfirst($tag->name) }}

                  @endforeach

'tags']) }}" class="size16">{{ trans('sovpal.more') }}...

              @if($category_type == 'brands')
                    @include('layout.last.items')
              @endif
              @if($category_type == 'types')
                    @include('layout.last.items')
              @endif
              @if($category_type == 'categories')
                    @include('layout.last.items')
              @endif
              @if($category_type == 'room')
                    @include('layout.last.items')
              @endif

     @endforeach


text:
#ifndef _SECURITY_AUDIT_AUDIT_IOCTL_H_
#define	_SECURITY_AUDIT_AUDIT_IOCTL_H_

#define	AUDITPIPE_IOBASE	'A'
#define	AUDITSDEV_IOBASE	'S'

/*
 * Data structures used for complex ioctl arguments.  Do not change existing
 * structures, add new revised ones to be used by new ioctls, and keep the
 * old structures and ioctls for backwards compatibility.
 */
struct auditpipe_ioctl_preselect {
	au_id_t		aip_auid;
	au_mask_t	aip_mask;
};

/*
 * Possible modes of operation for audit pipe preselection.
 */
#define	AUDITPIPE_PRESELECT_MODE_TRAIL	1	/* Global audit trail. */
#define	AUDITPIPE_PRESELECT_MODE_LOCAL	2	/* Local audit trail. */

/*
 * Ioctls to read and control the behavior of individual audit pipe devices.
 */
#define	AUDITPIPE_GET_QLEN		_IOR(AUDITPIPE_IOBASE, 1, u_int)
#define	AUDITPIPE_GET_QLIMIT		_IOR(AUDITPIPE_IOBASE, 2, u_int)
#define	AUDITPIPE_SET_QLIMIT		_IOW(AUDITPIPE_IOBASE, 3, u_int)
#define	AUDITPIPE_GET_QLIMIT_MIN	_IOR(AUDITPIPE_IOBASE, 4, u_int)
#define	AUDITPIPE_GET_QLIMIT_MAX	_IOR(AUDITPIPE_IOBASE, 5, u_int)
#define	AUDITPIPE_GET_PRESELECT_FLAGS	_IOR(AUDITPIPE_IOBASE, 6, au_mask_t)
#define	AUDITPIPE_SET_PRESELECT_FLAGS	_IOW(AUDITPIPE_IOBASE, 7, au_mask_t)
#define	AUDITPIPE_GET_PRESELECT_NAFLAGS	_IOR(AUDITPIPE_IOBASE, 8, au_mask_t)
#define	AUDITPIPE_SET_PRESELECT_NAFLAGS	_IOW(AUDITPIPE_IOBASE, 9, au_mask_t)
#define	AUDITPIPE_GET_PRESELECT_AUID	_IOR(AUDITPIPE_IOBASE, 10,	\
					    struct auditpipe_ioctl_preselect)
#define	AUDITPIPE_SET_PRESELECT_AUID	_IOW(AUDITPIPE_IOBASE, 11,	\
					    struct auditpipe_ioctl_preselect)
#define	AUDITPIPE_DELETE_PRESELECT_AUID	_IOW(AUDITPIPE_IOBASE, 12, au_id_t)
#define	AUDITPIPE_FLUSH_PRESELECT_AUID	_IO(AUDITPIPE_IOBASE, 13)
#define	AUDITPIPE_GET_PRESELECT_MODE	_IOR(AUDITPIPE_IOBASE, 14, int)
#define	AUDITPIPE_SET_PRESELECT_MODE	_IOW(AUDITPIPE_IOBASE, 15, int)
#define	AUDITPIPE_FLUSH			_IO(AUDITPIPE_IOBASE, 16)
#define	AUDITPIPE_GET_MAXAUDITDATA	_IOR(AUDITPIPE_IOBASE, 17, u_int)

/*
 * Ioctls to retrieve audit pipe statistics.
 */
#define	AUDITPIPE_GET_INSERTS		_IOR(AUDITPIPE_IOBASE, 100, u_int64_t)
#define	AUDITPIPE_GET_READS		_IOR(AUDITPIPE_IOBASE, 101, u_int64_t)
#define	AUDITPIPE_GET_DROPS		_IOR(AUDITPIPE_IOBASE, 102, u_int64_t)
#define	AUDITPIPE_GET_TRUNCATES		_IOR(AUDITPIPE_IOBASE, 103, u_int64_t)

/*
 * Ioctls for the audit session device.
 */
#define	AUDITSDEV_GET_QLEN		_IOR(AUDITSDEV_IOBASE, 1, u_int)
#define	AUDITSDEV_GET_QLIMIT		_IOR(AUDITSDEV_IOBASE, 2, u_int)
#define	AUDITSDEV_SET_QLIMIT		_IOW(AUDITSDEV_IOBASE, 3, u_int)
#define	AUDITSDEV_GET_QLIMIT_MIN	_IOR(AUDITSDEV_IOBASE, 4, u_int)
#define	AUDITSDEV_GET_QLIMIT_MAX	_IOR(AUDITSDEV_IOBASE, 5, u_int)
#define	AUDITSDEV_FLUSH			_IO(AUDITSDEV_IOBASE, 6)
#define	AUDITSDEV_GET_MAXDATA		_IOR(AUDITSDEV_IOBASE, 7, u_int)

/*
 * Ioctls to retrieve and set the ALLSESSIONS flag in the audit session device.
 */
#define	AUDITSDEV_GET_ALLSESSIONS	_IOR(AUDITSDEV_IOBASE, 100, u_int)
#define	AUDITSDEV_SET_ALLSESSIONS	_IOW(AUDITSDEV_IOBASE, 101, u_int)

/*
 * Ioctls to retrieve audit sessions device statistics.
 */
#define	AUDITSDEV_GET_INSERTS		_IOR(AUDITSDEV_IOBASE, 200, u_int64_t)
#define	AUDITSDEV_GET_READS		_IOR(AUDITSDEV_IOBASE, 201, u_int64_t)
#define	AUDITSDEV_GET_DROPS		_IOR(AUDITSDEV_IOBASE, 202, u_int64_t)

#endif /* _SECURITY_AUDIT_AUDIT_IOCTL_H_ */


text:
<input type="hidden" name="attr_attack_formula">

  <input type="hidden" name="attr_roll_toggle_var" value="{{vs_ac=1}} @{roll_info} {{roll1=[[@{preroll}d20cs>@{crit_range}@{postroll} + @{attack_formula}]]}} @{roll_setting}cs>@{crit_range}@{d20_mod} + @{attack_formula}]]}} {{targetAC=@{attacks_vs_target_ac}}} {{targetName=@{attacks_vs_target_name}}}">
  <input type="checkbox" name="attr_roll_toggle" value="@{roll_toggle_var}" class="attack-toggle">

{{'ATTACK' | translate}}.

    <input type="checkbox" name="attr_proficiency" checked>

{{'PROF' | translate}}

      <select name="attr_attack_ability">
        <option value="0">—</option>
        <option value="@{finesse_mod}">Finesse</option>
        <option value="@{strength_mod}">Str</option>
        <option value="@{dexterity_mod}">Dex</option>
        <option value="@{constitution_mod}">Con</option>
        <option value="@{intelligence_mod}">Int</option>
        <option value="@{wisdom_mod}">Wis</option>
        <option value="@{charisma_mod}">Cha</option>
      </select>

      <select name="attr_attack_ability">
        <option value="0">—</option>
        <option value="@{finesse_mod}">Finesse</option>
        <option value="@{strength_mod}">Str</option>
        <option value="@{dexterity_mod}">Ges</option>
        <option value="@{constitution_mod}">Kon</option>
        <option value="@{intelligence_mod}">Int</option>
        <option value="@{wisdom_mod}">Wei</option>
        <option value="@{charisma_mod}">Cha</option>
      </select>

      <select name="attr_attack_ability">
        <option value="0">—</option>
        <option value="@{finesse_mod}">Finesse</option>
        <option value="@{strength_mod}">For</option>
        <option value="@{dexterity_mod}">Dex</option>
        <option value="@{constitution_mod}">Con</option>
        <option value="@{intelligence_mod}">Int</option>
        <option value="@{wisdom_mod}">Sag</option>
        <option value="@{charisma_mod}">Cha</option>
      </select>

      <select name="attr_attack_ability">
        <option value="0">—</option>
        <option value="@{finesse_mod}">Фехтовальное</option>
        <option value="@{strength_mod}">Сил</option>
        <option value="@{dexterity_mod}">Лов</option>
        <option value="@{constitution_mod}">Тел</option>
        <option value="@{intelligence_mod}">Инт</option>
        <option value="@{wisdom_mod}">Муд</option>
        <option value="@{charisma_mod}">Хар</option>
      </select>

+

    <input type="number" name="attr_attack_bonus" class="center" value="0">

    <input type="number" name="attr_crit_range" class="center" value="20" step="1" min="1" max="20">

{{'CRIT_RANGE' | translate}}


text:
[Video]()
![alt text](./readme-imgs/paycheck-fullscreen.png "app screenshot")

Inspired by [Spotify's engineering culture](https://labs.spotify.com/2014/03/27/spotify-engineering-culture-part-1/)
and the description of Alphabet's Moonshot factory workflow and goals as seen in this [interview](http://www.wsj.com/video/astro-teller-on-moonshots-for-alphabet-x/CDC0A79C-CF6B-4FC8-9CF8-5C6A29C55551.html).
The desired effect being the ability to deploy resources ( people ) where they are needed the most at that point in time.

## Public - Projects
Projects open for contributions to the general public, reigstered users or not. Open to any sort of problems, DSA homework or the Ultimate Question of Life, the Universe, and Everything.

## Private - Organizations
The private section is structured around organizations. Organizations contain their private set of projects and users, differentiated by their role within the organization and also within each separate project, e.g. a manager of a certain project can also be assigned as a
contributor in a separate one.

## Architecture
- app.js: composing the application
  - routers: depend on controllers, each routers use depends on its own controller(s)
  - controllers: depend on one or more data objects to work with data
  - data: depend on models for accessing db collections
  - models: provide direct access to the data

## Notable dependencies
  - Socket.io: chat/ messaging
  - Passport: facebook/ local authentication
  - Validate.js: validation and sanitization
  - Crypto-js: client hashing
  - Winston: logging


text:
TODO: Write a project description

## Timeline

1. 28th october: finalise the functionalities, database design, preping up
2. 4th november: finish templates - master css, html, bootstrap layouts.
3. 11th November: database implementation, implementing the primary function of app
4. 18th November: secondary functionality, user signup.
5. 21st november: finishing and touch ups

## Technologies

html, css, jquery, ruby on rails, php, mysql, bootstrap,git


text:
var Promise = require('bluebird'),
    mongoose = Promise.promisifyAll(require('mongoose')),
    Message = mongoose.model('Message');

module.exports = {
  exists : Exists
};

function Exists(msgId,user) {

  var query = {
    '_id' : mongoose.Types.ObjectId(msgId),
    '$or' : [
      {
        'from' : mongoose.Types.ObjectId(user.id)
      },
      {
        'to' : mongoose.Types.ObjectId(user.id)
      }
    ]
  };

  return new Promise(function(resolve,reject) {

    Message.findOne(query)
        .then(function(msgFound) {

          if(!msgFound) {
            reject('No message found with id ' + msgId + ' for user ' + user.id);
            return;
          }

          resolve(msgFound);
        })
        .catch(function(e) {
          reject(e);
        });
  });

}


text:
//
//  molecule.h
//  HelloOpenGL
//
//  Created by wantnon (yang chao) on 13-1-5.
//
//

#ifndef __HelloOpenGL__molecule__
#define __HelloOpenGL__molecule__

#include <iostream>
#include "sprite.h"
#include "timeCounter.h"
#include "c3d.h"
//分子作用--abc
#define MOLECULE_FUNC_noFunc 0 //无作用--abc
#define MOLECULE_FUNC_lifeAdd 1 //加生命--abc
#define MOLECULE_FUNC_noMatch 2 //无敌--abc
#define MOLECULE_FUNC_noShotBall 3 //失去射击能力--abc
#define MOLECULE_FUNC_keyAdd 4 //增加钥匙--abc
#define MOLECULE_FUNC_blast_and_lifeDec 5 //爆炸并掉血--abc
#define MOLECULE_FUNC_transport 6 //传送--abc
#define MOLECULE_FUNC_coinAdd 7 //加金币--abc
#define MOLECULE_FUNC_checkPointUpdate 8 //更新检查点--abc
//分子效果--abc
#define MOLECULEEFFECTTYPE_specifiedColorTransp 0
#define MOLECULEEFFECTTYPE_useColorValueAsAlpha 1
#define MOLECULEEFFECTTYPE_normal 2
//重启传送门时间--abc
#define RESTARTTRANSCOUNTVALUE 120
class Cmolecule:public Csprite
{
protected:
    vector<Cc3dTexture*> pFrameTexList;
public:
    string name;

    int i_curFrameTex;//当前用的是几号帧--abc
    int i_foeFrameTex;//上一刻用的是几号帧,只在回滚模式中记录和使用--abc
    float wDivh;//横纵比--abc
    int funcID;//功效--abc
    string startName;//传送起点名称--abc
    string destinationName;//传送终点名称--abc
    CtimeCounter revTimeCounter_restartTrans;//还差多少时间恢复传送--abc
    int effectType;//效果类型--abc
    CtimeCounter revTimeCounter_betweenFrame;//两相邻帧之间的倒计时,如果两帧之间不隔着空cycle,则其倒计时值为1
    int timeCountBetweenFrame;//两相邻帧之间的时间间隔,如果两帧率之间不隔着空cycle,则值为1
    Cmolecule(){
        timeCountBetweenFrame=1;
        effectType=MOLECULEEFFECTTYPE_specifiedColorTransp;
        wDivh=1;
        funcID=0;
        i_curFrameTex=-1;
        i_foeFrameTex=-1;
    }
    virtual~Cmolecule(){

    }
    vector<Cc3dTexture*> getFrameTexList()const {return pFrameTexList;}
    void addFrameTex(Cc3dTexture*texture){
        pFrameTexList.push_back(texture);
        texture->retain();

    }
    void setFuncIDWithFuncName(const string&funcName){
        if(funcName=="noFunc"){
            funcID=MOLECULE_FUNC_noFunc;
        }else if(funcName=="lifeAdd"){
            funcID=MOLECULE_FUNC_lifeAdd;
        }else if(funcName=="noMatch"){
            funcID=MOLECULE_FUNC_noMatch;
        }else if(funcName=="noShotBall"){
            funcID=MOLECULE_FUNC_noShotBall;
        }else if(funcName=="keyAdd"){
            funcID=MOLECULE_FUNC_keyAdd;
        }else if(funcName=="blast_and_lifeDec"){
            funcID=MOLECULE_FUNC_blast_and_lifeDec;
        }else if(funcName=="transport"){
            funcID=MOLECULE_FUNC_transport;
        }else if(funcName=="coinAdd"){
            funcID=MOLECULE_FUNC_coinAdd;
        }else if(funcName=="checkPointUpdate"){
            funcID=MOLECULE_FUNC_checkPointUpdate;
        }else{
            cout<<"error:不识别的funcName:"<<funcName<<endl;
            assert(false);
        }

    }
    void useTex(int i){//指定使用frameTexList中哪个帧来作为当前texture
        i_curFrameTex=i;
        int n=(int)pFrameTexList.size();
        this->getMesh()->getSubMeshByIndex(0)->setTexture(pFrameTexList[i%n]);//如果i越界则取余--abc
    }
    void useLastTex(){
        int nTex=(int)pFrameTexList.size();
        useTex(nTex-1);
    }
    bool useNextFrameTex(){//使用下一帧,如果没有下一帧,则绕回,返回是否已播完此轮--abc
        if(revTimeCounter_betweenFrame.getCount()!=0){//如果倒计时还没结束--abc
            //继续倒计时,然后返回--abc
            revTimeCounter_betweenFrame.doCount_dec();
            return false;
        }//如果倒计时已结束--abc
        revTimeCounter_betweenFrame.setValue(timeCountBetweenFrame);//重设倒计时值--abc
        bool lastFrameOfCurRollFinished=false;
        int n=(int)pFrameTexList.size();
        i_curFrameTex++;
        if(i_curFrameTex>=n){
            lastFrameOfCurRollFinished=true;
            i_curFrameTex-=n;
        }
        this->getMesh()->getSubMeshByIndex(0)->setTexture(pFrameTexList[i_curFrameTex]);
        return lastFrameOfCurRollFinished;
    }
    bool useNextFrameTex_notRewind(){//使用下一帧,如果没有下一帧,则停止在当前帧,返回是否已播完此轮--abc
        if(revTimeCounter_betweenFrame.getCount()!=0){//如果倒计时还没结束--abc
            //继续倒计时,然后返回--abc
            revTimeCounter_betweenFrame.doCount_dec();
            return false;
        }//如果倒计时已结束--abc
        revTimeCounter_betweenFrame.setValue(timeCountBetweenFrame);//重设倒计时值--abc
        bool lastFrameOfCurRollFinished=false;
        int n=(int)pFrameTexList.size();
        i_curFrameTex++;
        if(i_curFrameTex>=n){
            lastFrameOfCurRollFinished=true;
            i_curFrameTex--;
        }
        this->getMesh()->getSubMeshByIndex(0)->setTexture(pFrameTexList[i_curFrameTex]);
        return lastFrameOfCurRollFinished;
    }
    void useNextFrameTex_rollback(){//使用下一帧,如果没有下一帧,回滚--abc
        if(revTimeCounter_betweenFrame.getCount()!=0){//如果倒计时还没结束--abc
            //继续倒计时,然后返回--abc
            revTimeCounter_betweenFrame.doCount_dec();
            return;
        }//如果倒计时已结束--abc
        revTimeCounter_betweenFrame.setValue(timeCountBetweenFrame);//重设倒计时值--abc
        if(i_curFrameTex==i_foeFrameTex) {
            i_curFrameTex++;

        }else if(i_curFrameTex>i_foeFrameTex){
            i_foeFrameTex=i_curFrameTex;
            i_curFrameTex++;
            if(i_curFrameTex>=(int)pFrameTexList.size()){
                i_curFrameTex-=2;
            }
        }else if(i_curFrameTex<i_foeFrameTex){
            i_foeFrameTex=i_curFrameTex;
            i_curFrameTex--;
            if(i_curFrameTex<0){
                i_curFrameTex+=2;
            }

        }
        this->getMesh()->getSubMeshByIndex(0)->setTexture(pFrameTexList[i_curFrameTex]);
    }
    void loadFrameTexList(const string&clipName){//clipName最后一个字符必须是"/"
        if(clipName[(int)clipName.size()-1]!='/'){
            cout<<"error:clipName最后一个字符必须是'/' !";
            assert(false);
        }
        //获得config文件的路径--abc
        string configFileNameWithExt=clipName+"config.txt";
        //------------------获得config文件绝对路径--abc
        string configPathName=Cc3dFileUtils::sharedFileUtils()->getFullPath(configFileNameWithExt);
        //打开文件--abc
        FILE  *fp=NULL;
        fp=fopen(configPathName.c_str(),"r");
        if(fp==NULL)
        {
            cout<<"Open "<<configPathName<<" failed!"<<endl;
            assert(false);
        }
        //------------------提取文件信息--abc
        char buffer[1024]={0};
        //提取帧数--abc
        int nFrame;//帧数--abc
        fscanf(fp, "%d",&nFrame);
        //提取透明色--abc
        float t_transpColor[4]={1,1,1,1};
        fscanf(fp, "%f",&t_transpColor[0]);
        fscanf(fp, "%f",&t_transpColor[1]);
        fscanf(fp, "%f",&t_transpColor[2]);
        transpColor.init(t_transpColor);
        //提取横纵比--abc
        fscanf(fp,"%f",&wDivh);
        //提取effect
        string effectStr;
        char _buffer[1024];
        fscanf(fp, "%s",buffer);
        fscanf(fp, "%s",_buffer);
        effectStr=_buffer;
        if(effectStr=="specifiedColorTransp"){
            effectType=MOLECULEEFFECTTYPE_specifiedColorTransp;
        }else if(effectStr=="useColorValueAsAlpha"){
            effectType=MOLECULEEFFECTTYPE_useColorValueAsAlpha;
        }else if(effectStr=="normal"){
            effectType=MOLECULEEFFECTTYPE_normal;
        }else{
            cout<<"error:未知的effect类型:"<<effectStr<<endl;
            assert(false);
        }
        //提取timeCountBetweenFrame
        fscanf(fp, "%s",buffer);
        fscanf(fp, "%d",&timeCountBetweenFrame);
        //关闭文件--abc
        fclose(fp);
        //------------------获得clipName的最后一级名--abc
        string clipNameLastSeg;//clipName的最后一级名--abc
        string clipNameLastSeg_reverse;//clipNameLastSeg的逆序--abc
        int len_clipName=(int)clipName.size();
        for(int i=len_clipName-2;i>=0;i--){
            if(clipName[i]=='/'){
                break;
            }else{
                clipNameLastSeg_reverse+=clipName[i];
            }
        }//得到clipNameLastSeg_reverse
        int len_clipNameLastSeg_reverse=(int)clipNameLastSeg_reverse.size();
        for(int i=len_clipNameLastSeg_reverse-1;i>=0;i--){
            clipNameLastSeg.push_back(clipNameLastSeg_reverse[i]);
        }//得到clipNameLastSeg
  //      cout<<"hihi:"<<clipNameLastSeg<<endl;
        //------------------制作各图片文件名--abc
        vector<string> imageNameList;
        for(int i=0;i<nFrame;i++){
            string numStr=numberToStr(i+1);//注意,编号是从1开始的--abc
            if((int)numStr.size()==1){//如果是一位数"k",则改成"0k"
                numStr="0"+numStr;
            }
            string imageName=clipName+clipNameLastSeg+"_"+numStr+".png";
            imageNameList.push_back(imageName);
        }//得到imageNameList
        //------------------根据imageNameList加载纹理--abc
        for(int i=0;i<nFrame;i++){
            string&imageName=imageNameList[i];
            Cc3dTexture*ptex=Cc3dTextureCache::sharedTextureCache()->addImage(imageName);
            this->addFrameTex(ptex);
        }

    }

};
#endif /* defined(__HelloOpenGL__molecule__) */


text:
example_description = <<DESC

  Sub Plans Example
  ===================

  This example shows, how singleton actions can be used for making sure
  there is only one instance of the action running at a time.

  Singleton actions try to obtain a lock at the beggining of their plan
  phase and fail if they can't do so. In run phase they check if they
  have the lock and try to acquire it again if they don't. These actions
  release the lock at the end of their finalize phase.

DESC

require_relative 'example_helper'

class SingletonExample < Dynflow::Action
  include Dynflow::Action::Singleton

  def run
    sleep 10
  end
end

class SingletonExampleA < SingletonExample; end
class SingletonExampleB < SingletonExample; end

if $0 == __FILE__
  ExampleHelper.world.action_logger.level = Logger::INFO
  ExampleHelper.world
  t1 = ExampleHelper.world.trigger(SingletonExampleA)
  t2 = ExampleHelper.world.trigger(SingletonExampleA)
  ExampleHelper.world.trigger(SingletonExampleA) unless SingletonExampleA.singleton_locked?(ExampleHelper.world)
  t3 = ExampleHelper.world.trigger(SingletonExampleB)
  db = ExampleHelper.world.persistence.adapter.db

  puts example_description
  puts <<-MSG.gsub(/^.*\|/, '')
    |  3 execution plans were triggered:
    |  #{t1.id} should finish successfully
    |  #{t3.id} should finish successfully because it is a singleton of different class
    |  #{t2.id} should fail because #{t1.id} holds the lock
    |
    |  You can see the details at
    |    #{ExampleHelper::DYNFLOW_URL}/#{t1.id}
    |    #{ExampleHelper::DYNFLOW_URL}/#{t2.id}
    |    #{ExampleHelper::DYNFLOW_URL}/#{t3.id}
    |
  MSG
  ExampleHelper.run_web_console
end


text:
---
title: Feature matching
categories:
  - Research
  - Dev
tags:
  - Computer Vision
---

Feature matching is a critical part in many vision problems, such as estimation of various matrices (projection, homography, essential, fundamental, relative post, etc), tracking, SfM and SLAM, just to name a few. I will discuss here in this post implementation of the feature matching algorithms implemented in [open3DCV]({{site.url}}{{site.baseurl}}/open3DCV/).

### Result

    Demonstrative result of feature matching.

### Base class: `matcher`
There is a base class `matcher` that all actual matching algorithms need to extend. The `match` method takes two vectors of descriptors and returns the indexes of the matching pair. Note that there are two declarations of `match` method, the second provides an additional parameter - a function pointer, that allows to use the user-defined distance function.

```cpp
class Matcher
{
public:
    Matcher() { };
    Matcher(Matcher_Param r_matcher_param);
    virtual ~Matcher() { };

    virtual void init_param(Matcher_Param r_matcher_param) = 0;
    virtual int match(const vector<Vecf>& desc1, const vector<Vecf>& desc2, vector<Match>& matches) = 0;
    virtual int match(const vector<Vecf>& desc1, const vector<Vecf>& desc2, vector<Match>& matches, float (*dist_metric)(const Vecf& desc1, const Vecf& desc2)) = 0;

protected:
    Matcher_Param matcher_param_;
};
```

### Parameter: `Matcher_Param`
We need a structure type to pass the parameters to the specific `matcher` class, which is defined as follows

```cpp
struct Matcher_Param
{
    // all matchers
    float ratio = 0.8;

    // Flann matcher
    int ndims = 128;
    int leaf_max_size = 10;
    int nresults = 3;

    Matcher_Param() { };
    Matcher_Param(const float r_ratio) : ratio(r_ratio) { };
    Matcher_Param(const float r_ratio, const int r_ndims, const int r_leaf_max_size, const int r_nresults) :
                  ratio(r_ratio), ndims(r_ndims), leaf_max_size(r_leaf_max_size), nresults(r_nresults) { };
};
```

### Data structure: `Match`
This is the class to store the matching feature points, I should probably rename it to `DMatch` to avoid confusion.

```cpp
class Match
{
public:
    Match () { };
    Match (int r_ikey1, int r_ikey2, float dist) :
        ikey1_(r_ikey1), ikey2_(r_ikey2), dist_(dist) { };

    int ikey1_;
    int ikey2_;
    float dist_;
};
```

### Distance metrics
I implemented two of the most used distance metrics for now, sum of squared distance (SSD) and sum of absolute difference (SAD). The can be passed onto the function pointer when call the `matcher` method.

```cpp
inline float l2_dist(const Vecf& desc1, const Vecf& desc2)
{
//    return (desc1 - desc2).squaredNorm();
    return (desc1 - desc2).norm();
};

inline float l1_dist(const Vecf& desc1, const Vecf& desc2)
{
    return (desc1 - desc2).lpNorm<1>();
}
```

### Brute-force method
This is the simplest, yet most computationally expensive method. It iterates all possible point pairs and see if the cost function is below a user-specified threshold.

```cpp
inline int Matcher_Brute_Force::match(const vector<Vecf>& desc1, const vector<Vecf>& desc2, vector<Match>& matches)
{
    return match(desc1, desc2, matches, l2_dist);
}

inline int Matcher_Brute_Force::match(const vector<Vecf>& desc1, const vector<Vecf>& desc2, vector<Match>& matches, float (*dist_metric)(const Vecf& desc1, const Vecf& desc2))
{
    float dist = 0, min_dist = 1e8, sec_min_dist = 1e8, ratio = matcher_param_.ratio;
    int ind_min_key = 0;

    for (int i = 0; i < desc1.size(); ++i)
    {
        min_dist = sec_min_dist = 1e8;
        for (int j = 0; j < desc2.size(); ++j)
        {
            dist = dist_metric(desc1[i], desc2[j]);
            if (dist < min_dist)
            {
                sec_min_dist = min_dist;
                min_dist = dist;
                ind_min_key = j;
            }
            else if (dist < sec_min_dist)
            {
                sec_min_dist = dist;
            }
        }
        if (min_dist < ratio * sec_min_dist)
        {
            Match m(i, ind_min_key, min_dist);
            matches.push_back(m);
        }
    }

    return 0;
}
```

### ANN method
[FLANN](http://www.cs.ubc.ca/research/flann/) is short for Fast Library for Approximate Nearest Neighbors, which is proposed by Marius Muja and David Lowe. There are some similar libraries, such as [ANN](https://www.cs.umd.edu/~mount/ANN/), [ANNOY](https://github.com/spotify/annoy). Here is a [benchmark](https://github.com/erikbern/ann-benchmarks) for comparing the performance of approximate nearest neighbors algorithms. I used a simplified version of FLANN called [nanoflann](https://github.com/jlblancoc/nanoflann) since I want the dependencies of open3DCV as simple as possible.

My implementation is adapted from the example code `vector_of_vectors_example.cpp`. There is one place that needs a heads-up, this function call of `init(IndexType* indices_, DistanceType* dist_)` has to be invoked everytime you do a search of nearest neighbor. The reason is best explained using the source code, see below

```cpp
// implementation from nanoflann.h
inline void init(IndexType* indices_, DistanceType* dists_)
{
    indices = indices_;
    dists = dists_;
    count = 0;
    if (capacity)
        dists[capacity-1] = (std::numeric_limits<DistanceType>::max)();
}
```

As we can see that `init` need to re-initialize `dist[]` to max values. Otherwise, the distances from the previous search is still stored in `dist[]`. The full implementation is as follows:

```cpp
inline int Matcher_Flann::match(const vector<Vecf>& desc1, const vector<Vecf>& desc2, vector<Match>& matches)
{
    return match(desc1, desc2, matches, l2_dist);
}

inline int Matcher_Flann::match(const vector<Vecf>& desc1, const vector<Vecf>& desc2, vector<Match>& matches, float (*dist_metric)(const Vecf& desc1, const Vecf& desc2))
{
    // use the one with larger keypoints to construct kd-tree
    size_t nkeys1 = desc1.size(), nkeys2 = desc2.size();
    const vector<Vecf>& desc_source = nkeys1 < nkeys2 ? desc1 : desc2;
    const vector<Vecf>& desc_target = nkeys1 < nkeys2 ? desc2 : desc1;
    Matching_Dirc matching_dirc = nkeys1 < nkeys2 ? FORWARD : BACKWARD;

    // construct a kd-tree index
    typedef KDTreeVectorOfVectorsAdaptor<vector<Vecf>, float>  kd_tree_t;

    int leaf_max_size = matcher_param_.leaf_max_size;
    kd_tree_t desc_index(matcher_param_.ndims, desc_target, leaf_max_size /* max leaf */);
    desc_index.index->buildIndex();

    // do knn searches
    int nresults = matcher_param_.nresults;
    vector<size_t> ret_indexes(nresults);
    vector<float> dists(nresults);

    nanoflann::KNNResultSet<float> result_set(nresults);

    for (int i = 0; i < desc_source.size(); ++i)
    {
        result_set.init(&ret_indexes[0], &dists[0]); // has to be inside loop, there is a 'dist' variable that needs to be set as MAX
        desc_index.index->findNeighbors(result_set, desc_source[i].data(), nanoflann::SearchParams(10));
        if (dists[0] < matcher_param_.ratio * dists[1])
        {
            if (matching_dirc == FORWARD)
            {
                Match match(i, static_cast<int>(ret_indexes[0]), dists[0]);
                matches.push_back(match);
            }
            else
            {
                Match match(static_cast<int>(ret_indexes[0]), i, dists[0]);
                matches.push_back(match);
            }
        }
    }

    return 0;
}
```


text:
package org.cojen.util;

import java.lang.ref.SoftReference;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Alternative to the standard Bean introspector. One key difference is that
 * this introspector ensures interface properties are properly
 * discovered. Also, indexed properties can have an index of any type.
 *
 * @author Brian S O'Neill
 */
public class BeanIntrospector {
    // Weakly maps Class objects to softly referenced BeanProperty maps.
    private static Map<Class, SoftReference<Map<String, BeanProperty>>> cPropertiesCache =
        new WeakIdentityMap<Class, SoftReference<Map<String, BeanProperty>>>();

    public static void main(String[] args) throws Exception {
        System.out.println(getAllProperties(Class.forName(args[0])));
    }

    /**
     * Returns a Map of all the available properties on a given class including
     * write-only and indexed properties.
     *
     * @return Map<String, BeanProperty> an unmodifiable mapping of property
     * names (Strings) to BeanProperty objects.
     *
     */
    public static Map<String, BeanProperty> getAllProperties(Class clazz) {
        synchronized (cPropertiesCache) {
            Map<String, BeanProperty> properties;
            SoftReference<Map<String, BeanProperty>> ref = cPropertiesCache.get(clazz);
            if (ref != null) {
                properties = ref.get();
                if (properties != null) {
                    return properties;
                }
            }
            properties = createProperties(clazz);
            cPropertiesCache.put(clazz, new SoftReference<Map<String, BeanProperty>>(properties));
            return properties;
        }
    }

    private static Map<String, BeanProperty> createProperties(Class clazz) {
        if (clazz == null || clazz.isPrimitive()) {
            return Collections.emptyMap();
        }

        Map<String, BeanProperty> properties = new HashMap<String, BeanProperty>();
        fillInProperties(clazz, properties);

        // Properties defined in Object are also available to interfaces.
        if (clazz.isInterface()) {
            fillInProperties(Object.class, properties);
        }

        // Ensure that all implemented interfaces are properly analyzed.
        Class[] interfaces = clazz.getInterfaces();
        for (int i=0; i<interfaces.length; i++) {
            fillInProperties(interfaces[i], properties);
        }

        return Collections.unmodifiableMap(properties);
    }

    /**
     * @param clazz Class to introspect
     * @param properties Receives properties as name->property entries
     */
    private static void fillInProperties(Class clazz, Map<String, BeanProperty> properties) {
        Method[] methods = clazz.getMethods();

        Method method;
        String name;
        Class type;
        Class[] params;
        SimpleProperty property;
        IndexedProperty indexedProperty;

        // Gather non-conflicting "get" accessors
        for (int i=0; i<methods.length; i++) {
            method = methods[i];
            if (Modifier.isStatic(method.getModifiers()) ||
                (type = method.getReturnType()) == void.class ||
                method.getParameterTypes().length > 0 ||
                (name = extractPropertyName(method, "get")) == null) {
                continue;
            }
            if (properties.containsKey(name)) {
                property = (SimpleProperty) properties.get(name);
                SimpleProperty withCovariant = property.addCovariantType(type);
                if (withCovariant == null) {
                    if (property.getReadMethod() != null) {
                        continue;
                    }
                } else {
                    properties.put(name, property = withCovariant);
                    if (type != property.getType() && property.getReadMethod() != null) {
                        // Primary type not changed so don't change read method.
                        continue;
                    }
                }
            } else {
                property = new SimpleProperty(name, type);
                properties.put(name, property);
            }
            property.setReadMethod(method);
        }

        // Gather non-conflicting "is" accessors.
        for (int i=0; i<methods.length; i++) {
            method = methods[i];
            if (Modifier.isStatic(method.getModifiers()) ||
                (type = method.getReturnType()) != boolean.class ||
                method.getParameterTypes().length > 0 ||
                (name = extractPropertyName(method, "is")) == null) {
                continue;
            }
            if (properties.containsKey(name)) {
                property = (SimpleProperty) properties.get(name);
                if (type != property.getType() || property.getReadMethod() != null) {
                    continue;
                }
            } else {
                property = new SimpleProperty(name, type);
                properties.put(name, property);
            }
            property.setReadMethod(method);
        }

        // Gather non-conflicting mutators.
        for (int i=0; i<methods.length; i++) {
            method = methods[i];
            if (Modifier.isStatic(method.getModifiers()) ||
                method.getReturnType() != void.class ||
                (params = method.getParameterTypes()).length != 1 ||
                (name = extractPropertyName(method, "set")) == null) {
                continue;
            }
            type = params[0];
            if (properties.containsKey(name)) {
                property = (SimpleProperty) properties.get(name);
                SimpleProperty withCovariant = property.addCovariantType(type);
                if (withCovariant == null) {
                    if (property.getWriteMethod() != null) {
                        continue;
                    }
                } else {
                    properties.put(name, property = withCovariant);
                    if (type != property.getType() && property.getWriteMethod() != null) {
                        // Primary type not changed so don't change write method.
                        continue;
                    }
                }
            } else {
                property = new SimpleProperty(name, type);
                properties.put(name, property);
            }
            property.setWriteMethod(method);
        }

        // Gather non-conflicting indexed property accessors.
        for (int i=0; i<methods.length; i++) {
            method = methods[i];
            if (Modifier.isStatic(method.getModifiers()) ||
                (type = method.getReturnType()) == void.class ||
                (params = method.getParameterTypes()).length != 1 ||
                (name = extractPropertyName(method, "get")) == null) {
                continue;
            }
            if (properties.containsKey(name)) {
                property = (SimpleProperty) properties.get(name);
                if (type != property.getType()) {
                    continue;
                }
                if (property instanceof IndexedProperty) {
                    indexedProperty = (IndexedProperty) property;
                } else {
                    indexedProperty = new IndexedProperty(property);
                    properties.put(name, indexedProperty);
                }
            } else {
                indexedProperty = new IndexedProperty(name, type);
                properties.put(name, indexedProperty);
            }
            indexedProperty.addIndexedReadMethod(method);
        }

        // Gather non-conflicting indexed property mutators.
        for (int i=0; i<methods.length; i++) {
            method = methods[i];
            if (Modifier.isStatic(method.getModifiers()) ||
                method.getReturnType() != void.class ||
                (params = method.getParameterTypes()).length != 2 ||
                (name = extractPropertyName(method, "set")) == null) {
                continue;
            }
            type = params[1];
            if (properties.containsKey(name)) {
                property = (SimpleProperty) properties.get(name);
                if (type != property.getType()) {
                    continue;
                }
                if (property instanceof IndexedProperty) {
                    indexedProperty = (IndexedProperty) property;
                } else {
                    indexedProperty = new IndexedProperty(property);
                    properties.put(name, indexedProperty);
                }
            } else {
                indexedProperty = new IndexedProperty(name, type);
                properties.put(name, indexedProperty);
            }
            indexedProperty.addIndexedWriteMethod(method);
        }
    }

    /**
     * Returns null if prefix pattern doesn't match
     */
    private static String extractPropertyName(Method method, String prefix) {
        String name = method.getName();
        if (!name.startsWith(prefix)) {
            return null;
        }
        if (name.length() == prefix.length()) {
            return "";
        }
        name = name.substring(prefix.length());
        if (!Character.isUpperCase(name.charAt(0)) || name.indexOf('$') >= 0) {
            return null;
        }

        // Decapitalize the name only if it doesn't begin with two uppercase
        // letters.

        if (name.length() == 1 || !Character.isUpperCase(name.charAt(1))) {
            char chars[] = name.toCharArray();
            chars[0] = Character.toLowerCase(chars[0]);
            name = new String(chars);
        }

        return name.intern();
    }

    private static class SimpleProperty implements BeanProperty {
        private static final Class[] EMPTY = new Class[0];

        private final String mName;
        private final Class mType;
        private final Class[] mCovariantTypes;

        private Method mReadMethod;
        private Method mWriteMethod;

        SimpleProperty(String name, Class type) {
            this(name, type, null);
        }

        SimpleProperty(String name, Class type, Class[] covariantTypes) {
            mName = name;
            mType = type;
            if (covariantTypes == null || covariantTypes.length == 0) {
                mCovariantTypes = EMPTY;
            } else {
                mCovariantTypes = covariantTypes;
            }
        }

        public String getName() {
            return mName;
        }

        public Class getType() {
            return mType;
        }

        public Class[] getCovariantTypes() {
            if (mCovariantTypes.length == 0) {
                return EMPTY;
            }
            return mCovariantTypes.clone();
        }

        public Method getReadMethod() {
            return mReadMethod;
        }

        public Method getWriteMethod() {
            return mWriteMethod;
        }

        public int getIndexTypesCount() {
            return 0;
        }

        public Class getIndexType(int index) {
            throw new IndexOutOfBoundsException();
        }

        public Method getIndexedReadMethod(int index) {
            throw new IndexOutOfBoundsException();
        }

        public Method getIndexedWriteMethod(int index) {
            throw new IndexOutOfBoundsException();
        }

        public String toString() {
            String str = "BeanProperty{name=" + getName() + ", type=" + getType().getName();
            Class[] covariantTypes = getCovariantTypes();
            if (covariantTypes.length > 0) {
                str = str + ", covariantTypes=" + Arrays.toString(covariantTypes);
            }
            return str + '}';
        }

        /**
         * @return null if no change
         */
        SimpleProperty addCovariantType(Class type) {
            if (mType == type) {
                return null;
            }
            for (Class covariant : mCovariantTypes) {
                if (covariant == type) {
                    return null;
                }
            }

            // Find most specialized type.

            Class newType = mType;

            if (mType.isAssignableFrom(type)) {
                newType = type;
            }
            for (Class covariant : mCovariantTypes) {
                if (covariant.isAssignableFrom(type)) {
                    newType = type;
                }
            }

            Class[] newCovariant = new Class[1 + mCovariantTypes.length];
            System.arraycopy(mCovariantTypes, 0, newCovariant, 1, mCovariantTypes.length);

            newCovariant[0] = newType == mType ? type : mType;

            SimpleProperty property = new SimpleProperty(mName, newType, newCovariant);

            property.mReadMethod = mReadMethod;
            property.mWriteMethod = mWriteMethod;

            return property;
        }

        void setReadMethod(Method method) {
            mReadMethod = method;
        }

        void setWriteMethod(Method method) {
            mWriteMethod = method;
        }
    }

    private static class IndexedProperty extends SimpleProperty {
        private Method[] mIndexedReadMethods;
        private Method[] mIndexedWriteMethods;

        IndexedProperty(String name, Class type) {
            super(name, type);
        }

        IndexedProperty(String name, Class type, Class[] covariantTypes) {
            super(name, type, covariantTypes);
        }

        IndexedProperty(BeanProperty property) {
            super(property.getName(), property.getType(), property.getCovariantTypes());
            setReadMethod(property.getReadMethod());
            setWriteMethod(property.getWriteMethod());
        }

        public int getIndexTypesCount() {
            Method[] methods = mIndexedReadMethods;
            if (methods != null) {
                return methods.length;
            }
            methods = mIndexedWriteMethods;
            return methods == null ? 0 : methods.length;
        }

        public Class getIndexType(int index) {
            Method[] methods = mIndexedReadMethods;
            if (methods != null) {
                Method method = methods[0];
                if (method != null) {
                    return method.getParameterTypes()[0];
                }
            }
            methods = mIndexedWriteMethods;
            if (methods != null) {
                Method method = methods[index];
                if (method != null) {
                    return method.getParameterTypes()[0];
                }
            }
            if (index >= getIndexTypesCount()) {
                throw new IndexOutOfBoundsException();
            }
            return null;
        }

        public Method getIndexedReadMethod(int index) {
            return mIndexedReadMethods[index];
        }

        public Method getIndexedWriteMethod(int index) {
            return mIndexedWriteMethods[index];
        }

        public String toString() {
            StringBuffer buf = new StringBuffer();
            buf.append("BeanProperty{name=");
            buf.append(getName());
            buf.append(", type=");
            buf.append(getType().getName());
            Class[] covariantTypes = getCovariantTypes();
            if (covariantTypes.length > 0) {
                buf.append(", covariantTypes=");
                buf.append(Arrays.toString(covariantTypes));
            }
            buf.append(", ");
            int count = getIndexTypesCount();
            for (int i=0; i<count; i++) {
                if (i > 0) {
                    buf.append(", ");
                }
                buf.append("indexType[");
                buf.append(i);
                buf.append("]=");
                buf.append(getIndexType(0));
            }
            buf.append('}');
            return buf.toString();
        }

        IndexedProperty addCovariantType(Class type) {
            SimpleProperty property = super.addCovariantType(type);
            if (property == null) {
                return null;
            }

            IndexedProperty ix = new IndexedProperty(property);
            ix.mIndexedReadMethods = mIndexedReadMethods;
            ix.mIndexedWriteMethods = mIndexedWriteMethods;

            return ix;
        }

        void addIndexedReadMethod(Method method) {
            Class indexType = method.getParameterTypes()[0];
            int count = getIndexTypesCount();
            int i;
            for (i=0; i<count; i++) {
                if (getIndexType(i) == indexType) {
                    break;
                }
            }
            if (i >= count) {
                expandCapactity();
            }
            if (mIndexedReadMethods[i] == null) {
                mIndexedReadMethods[i] = method;
            }
        }

        void addIndexedWriteMethod(Method method) {
            Class indexType = method.getParameterTypes()[0];
            int count = getIndexTypesCount();
            int i;
            for (i=0; i<count; i++) {
                if (getIndexType(i) == indexType) {
                    break;
                }
            }
            if (i >= count) {
                expandCapactity();
            }
            if (mIndexedWriteMethods[i] == null) {
                mIndexedWriteMethods[i] = method;
            }
        }

        private void expandCapactity() {
            int count = getIndexTypesCount();
            Method[] methods = new Method[count + 1];
            if (mIndexedReadMethods != null) {
                System.arraycopy(mIndexedReadMethods, 0, methods, 0, count);
            }
            mIndexedReadMethods = methods;
            methods = new Method[count + 1];
            if (mIndexedWriteMethods != null) {
                System.arraycopy(mIndexedWriteMethods, 0, methods, 0, count);
            }
            mIndexedWriteMethods = methods;
        }
    }
}


text:
package org.apache.logging.log4j.core.appender;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configurator;

/**
 * Shows how to use ANSI escape codes to color messages. Each message is printed to the console in color, but the rest
 * of the log entry (time stamp for example) is in the default color for that console.
 *

 * Running from a Windows command line from the root of the project:
 *

 *
 *

 * java -classpath log4j-core\target\test-classes;log4j-core\target\classes;log4j-api\target\classes;%HOME%\.m2\repository\org\fusesource\jansi\jansi\1.14\jansi-1.14.jar; org.apache.logging.log4j.core.appender.ConsoleAppenderAnsiMessagesMain log4j-core/target/test-classes/log4j2-console.xml
 *

 */
public class Jira739Test {

    private static final Logger LOG = LogManager.getLogger(Jira739Test.class);

    public static void main(final String[] args) {
        try (final LoggerContext ctx = Configurator.initialize(Jira739Test.class.getName(),
                "target/test-classes/LOG4J2-739.xml")) {
            for (int i = 0; i < 10; i++) {
                LOG.trace("Entering Log4j Example " + i + " times");
                LOG.error("Ohh!Failed!");
                LOG.trace("Exiting Log4j Example." + i + " times");
            }
        }
    }

}


text:
namespace java {
  namespace lang {
    class InterruptedException;
    class Class;
  }
  namespace util {
    namespace concurrent {
      class TimeUnit;
      class TimeoutException;
      class ExecutionException;
    }
  }
}
template<class T> class JArray;

namespace java {
  namespace util {
    namespace concurrent {

      class Future : public ::java::lang::Object {
      public:
        enum {
          mid_cancel_bb0c7673,
          mid_get_846352c3,
          mid_get_c84b4f45,
          mid_isCancelled_54c6a16a,
          mid_isDone_54c6a16a,
          max_mid
        };

        static ::java::lang::Class *class$;
        static jmethodID *mids$;
        static bool live$;
        static jclass initializeClass(bool);

        explicit Future(jobject obj) : ::java::lang::Object(obj) {
          if (obj != NULL)
            env->getClass(initializeClass);
        }
        Future(const Future& obj) : ::java::lang::Object(obj) {}

        jboolean cancel(jboolean) const;
        ::java::lang::Object get() const;
        ::java::lang::Object get(jlong, const ::java::util::concurrent::TimeUnit &) const;
        jboolean isCancelled() const;
        jboolean isDone() const;
      };
    }
  }
}

#include <Python.h>

namespace java {
  namespace util {
    namespace concurrent {
      extern PyTypeObject PY_TYPE(Future);

      class t_Future {
      public:
        PyObject_HEAD
        Future object;
        PyTypeObject *parameters[1];
        static PyTypeObject **parameters_(t_Future *self)
        {
          return (PyTypeObject **) &(self->parameters);
        }
        static PyObject *wrap_Object(const Future&);
        static PyObject *wrap_jobject(const jobject&);
        static PyObject *wrap_Object(const Future&, PyTypeObject *);
        static PyObject *wrap_jobject(const jobject&, PyTypeObject *);
        static void install(PyObject *module);
        static void initialize(PyObject *module);
      };
    }
  }
}

#endif


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe 'ESCopy::Engine' do
end


text:
/*
 * Service class
 * Created on 17 déc. 2012 ( Time 15:39:59 )
 */

package org.demo.bookorder.service;

import java.util.List;

import org.demo.bookorder.bean.BookOrder;
import org.demo.bookorder.dao.JpaBookOrderDAO;
import org.telosys.starterkits.strutsjpa.EntityManagerHelper;
import org.telosys.starterkits.strutsjpa.IServices;
import javax.persistence.PersistenceException;

import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

public class BookOrderServices implements IServices<BookOrder, Integer> {

	protected final Logger LOG = LoggerFactory.getLogger(BookOrderServices.class);

	public BookOrder load(final Integer id) {
		if (LOG.isDebugEnabled()) LOG.debug("load");
		BookOrder bookorder;
		try {
			EntityManagerHelper.beginTransaction();
			JpaBookOrderDAO bookorderDAO = new JpaBookOrderDAO();
			bookorder = bookorderDAO.findById(id);
			EntityManagerHelper.commitAndCloseEntityManager();
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
		return bookorder ;
	}

	public BookOrder save(final BookOrder entity) {
		if (LOG.isDebugEnabled()) LOG.debug("save");
		BookOrder entityNew;
		try {
			EntityManagerHelper.beginTransaction();
			JpaBookOrderDAO bookorderDAO = new JpaBookOrderDAO();
			entityNew = bookorderDAO.update(entity);
			EntityManagerHelper.commitAndCloseEntityManager();
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
		return entityNew;
	}

	public void delete(final Integer id) {
		if (LOG.isDebugEnabled()) LOG.debug("delete");
		try {
			EntityManagerHelper.beginTransaction();
			JpaBookOrderDAO bookorderDAO = new JpaBookOrderDAO();
			bookorderDAO.delete(id);
			EntityManagerHelper.commitAndCloseEntityManager();
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
	}

	public List<BookOrder> search(final BookOrder bookorder) {
		if (LOG.isDebugEnabled()) LOG.debug("search");
		List<BookOrder> liste;
		try {
			EntityManagerHelper.beginTransaction();
			JpaBookOrderDAO bookorderDAO = new JpaBookOrderDAO();
			liste = bookorderDAO.search(bookorder);
			EntityManagerHelper.commitAndCloseEntityManager();
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
		return liste;
	}

}


text:
package AsposeCellsCloud::Object::Hyperlink;

require 5.6.0;
use strict;
use warnings;
use utf8;
use JSON qw(decode_json);
use Data::Dumper;
use Module::Runtime qw(use_module);
use Log::Any qw($log);
use Date::Parse;
use DateTime;

use base "AsposeCellsCloud::Object::BaseObject";

#
#
#
#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
#

my $swagger_types = {
    'Address' => 'string',
    'Area' => 'CellArea',
    'ScreenTip' => 'string',
    'TextToDisplay' => 'string',
    'link' => 'Link'
};

my $attribute_map = {
    'Address' => 'Address',
    'Area' => 'Area',
    'ScreenTip' => 'ScreenTip',
    'TextToDisplay' => 'TextToDisplay',
    'link' => 'link'
};

# new object
sub new {
    my ($class, %args) = @_;
    my $self = {
        #
        'Address' => $args{'Address'},
        #
        'Area' => $args{'Area'},
        #
        'ScreenTip' => $args{'ScreenTip'},
        #
        'TextToDisplay' => $args{'TextToDisplay'},
        #
        'link' => $args{'link'}
    };

    return bless $self, $class;
}

# get swagger type of the attribute
sub get_swagger_types {
    return $swagger_types;
}

# get attribute mappping
sub get_attribute_map {
    return $attribute_map;
}

1;


text:
////////////////////////////////////////////////////////////////////////////////
// Tweening demo
// tutorial: http://learningthreejs.com/blog/2011/08/17/tweenjs-for-smooth-animation/
////////////////////////////////////////////////////////////////////////////////

/*global THREE, document, window, Stats, TWEEN*/

var camera, scene, renderer, stats;
var cameraControls;
var clock = new THREE.Clock();

var cylinder, sphere, cube;

var bevelRadius = 1.9;	// TODO: 2.0 causes some geometry bug.

var headlight;

var bird;

function init() {
	var canvasWidth = 846;
	var canvasHeight = 494;
	// For grading the window is fixed in size; here's general code:
	//var canvasWidth = window.innerWidth;
	//var canvasHeight = window.innerHeight;

	// RENDERER
	renderer = new THREE.WebGLRenderer( { antialias: true } );
	renderer.gammaInput = true;
	renderer.gammaOutput = true;
	renderer.setSize(canvasWidth, canvasHeight);
	renderer.setClearColorHex( 0x0, 1.0 );
	renderer.shadowMapEnabled = true;

	var container = document.getElementById('container');
	container.appendChild( renderer.domElement );

	// CAMERA
	camera = new THREE.PerspectiveCamera( 35, canvasWidth/ canvasHeight, 1, 4000 );
	camera.position.set( -657, 220, 1120 );

	// CONTROLS
	cameraControls = new THREE.OrbitAndPanControls(camera, renderer.domElement);
	cameraControls.target.set(0,310,0);

	// STATS
	stats = new Stats();
	stats.setMode( 0 );
	stats.domElement.style.position = 'absolute';
	stats.domElement.style.top = '0px';
	stats.domElement.style.zIndex = 100;
	container.appendChild( stats.domElement );

	stats.domElement.children[ 0 ].children[ 0 ].style.color = "#aaa";
	stats.domElement.children[ 0 ].style.background = "transparent";
	stats.domElement.children[ 0 ].children[ 1 ].style.display = "none";

	fillScene();
}

function fillScene() {
	scene = new THREE.Scene();
	//scene.fog = new THREE.Fog( 0x0, 2000, 4000 );

	// LIGHTS
	scene.add( new THREE.AmbientLight( 0x222222 ) );

	headlight = new THREE.PointLight( 0xFFFFFF, 1.0 );
	scene.add( headlight );

	var light = new THREE.SpotLight( 0xFFFFFF, 1.0 );
	light.position.set( -600, 1200, 300 );
	light.angle = 20 * Math.PI / 180;
	light.exponent = 1;
	light.target.position.set( 0, 200, 0 );
	light.castShadow = true;

	scene.add( light );

	var lightSphere = new THREE.Mesh(
		new THREE.SphereGeometry( 10, 12, 6 ),
		new THREE.MeshBasicMaterial() );
	lightSphere.position.copy( light.position );

	scene.add( lightSphere );

	///////////////////////

	// GROUND

	// put grid lines every 10000/100 = 100 units
	var solidGround = new THREE.Mesh(
		new THREE.PlaneGeometry( 10000, 10000 ),
		new THREE.MeshPhongMaterial({ color: 0xFFFFFF,
			// polygonOffset moves the plane back from the eye a bit, so that the lines on top of
			// the grid do not have z-fighting with the grid:
			// Factor == 1 moves it back relative to the slope (more on-edge means move back farther)
			// Units == 4 is a fixed amount to move back, and 4 is usually a good value
			polygonOffset: true, polygonOffsetFactor: 1.0, polygonOffsetUnits: 4.0
		}));
	solidGround.rotation.x = -Math.PI / 2;
	solidGround.receiveShadow = true;

	scene.add( solidGround );

	var ground = new THREE.Mesh(
		new THREE.PlaneGeometry( 10000, 10000, 100, 100 ),
		new THREE.MeshBasicMaterial( { color: 0x0, wireframe: true } ) );
	ground.rotation.x = - Math.PI / 2;

	scene.add( ground );

	//////////////////////////////
	// Glass
	var glass = createGlass(260);
	glass.position = new THREE.Vector3( -245, 125, 0);
	scene.add(glass);

	//////////////////////////////
	// Bird
	bird = new THREE.Object3D();
	createDrinkingBird( bird );

	scene.add( bird );

	// TWEEN
	// tutorial: http://learningthreejs.com/blog/2011/08/17/tweenjs-for-smooth-animation/
	var updateBird = function(){
		bird.animated.rotation.z = current.z;
	};
	var current = { z: 0 };

	var drinkingRotation = { z: 103 * Math.PI/180 };
	var backRotation = { z: -22 * Math.PI/180 };
	var wobbleRotation = { z: 22 * Math.PI/180 };
	var back2Rotation = { z: -8 * Math.PI/180 };

	var tweenForward = new TWEEN.Tween(current).to(drinkingRotation, 3000 );
	tweenForward.onUpdate(updateBird);
	tweenForward.easing(TWEEN.Easing.Cubic.In);

	// don't do anything: drink
	var tweenPause = new TWEEN.Tween(current).to(drinkingRotation, 500 );
	tweenPause.onUpdate(updateBird);

	var tweenBackward = new TWEEN.Tween(current).to(backRotation, 1200);
	tweenBackward.onUpdate(updateBird);
	tweenBackward.easing(TWEEN.Easing.Quadratic.InOut);

	var tweenWobble = new TWEEN.Tween(current).to(wobbleRotation, 1000);
	tweenWobble.onUpdate(updateBird);
	tweenWobble.easing(TWEEN.Easing.Quadratic.InOut);

	var tweenBackward2 = new TWEEN.Tween(current).to(back2Rotation, 900);
	tweenBackward2.onUpdate(updateBird);
	tweenBackward2.easing(TWEEN.Easing.Quadratic.InOut);

	// have one call the other next, and back
	tweenForward.chain( tweenPause );
	tweenPause.chain( tweenBackward );
	tweenBackward.chain( tweenWobble );
	tweenWobble.chain( tweenBackward2 );
	tweenBackward2.chain( tweenForward );

	// get this chain going
	tweenForward.start();
}

function createGlass(height) {
	var cupMaterial = new THREE.MeshPhongMaterial( { color: 0x0, specular: 0xFFFFFF, shininess: 100, opacity: 0.3, transparent: true } );
	var waterMaterial = new THREE.MeshLambertMaterial( {
		color: 0x1F8BAF
		//opacity: 0.7,
		//transparent: true
	} );

	var glassGeometry = new THREE.CylinderGeometry(120, 100, height, 32);
	var glassMesh = new THREE.Mesh( glassGeometry, cupMaterial );
	var glassObject = new THREE.Object3D();
	glassObject.add(glassMesh);

	var glassWater = new THREE.Mesh( new THREE.CylinderGeometry(120, 100, height, 32), waterMaterial);
	glassWater.scale = new THREE.Vector3(0.9, 0.85, 0.9);
	glassWater.position = new THREE.Vector3(0, -10, 0);
	glassObject.add(glassWater);
	return glassObject;
}

// Supporting frame for the bird - base + legs + feet
function createSupport( bsupport ) {
	var legMaterial = new THREE.MeshPhongMaterial( { shininess: 4 } );
	legMaterial.color.setHex( 0xAdA79b );
	legMaterial.specular.setRGB( 0.5, 0.5, 0.5 );
	legMaterial.ambient.copy( legMaterial.color );

	var footMaterial = new THREE.MeshPhongMaterial( { color: 0x960f0b, shininess: 30 } );
	footMaterial.specular.setRGB( 0.5, 0.5, 0.5 );
	footMaterial.ambient.copy( footMaterial.color );

	// base
	cube = new THREE.Mesh(
		new THREE.BeveledBlockGeometry( 20+64+110, 4, 2*77+12, bevelRadius ), footMaterial );
	cube.position.x = -45;	// (20+32) - half of width (20+64+110)/2
	cube.position.y = 4/2;	// half of height
	cube.position.z = 0;	// centered at origin
	bsupport.add( cube );

	// feet
	cube = new THREE.Mesh(
		new THREE.BeveledBlockGeometry( 20+64+110, 52, 6, bevelRadius ), footMaterial );
	cube.position.x = -45;	// (20+32) - half of width (20+64+110)/2
	cube.position.y = 52/2;	// half of height
	cube.position.z = 77 + 6/2;	// offset 77 + half of depth 6/2
	bsupport.add( cube );

	cube = new THREE.Mesh(
		new THREE.BeveledBlockGeometry( 20+64+110, 52, 6, bevelRadius ), footMaterial );
	cube.position.x = -45;	// (20+32) - half of width (20+64+110)/2
	cube.position.y = 52/2;	// half of height
	cube.position.z = -(77 + 6/2);	// negative offset 77 + half of depth 6/2
	bsupport.add( cube );

	cube = new THREE.Mesh(
		new THREE.BeveledBlockGeometry( 64, 104, 6, bevelRadius ), footMaterial );
	cube.position.x = 0;	// centered on origin along X
	cube.position.y = 104/2;
	cube.position.z = 77 + 6/2;	// negative offset 77 + half of depth 6/2
	bsupport.add( cube );

	cube = new THREE.Mesh(
		new THREE.BeveledBlockGeometry( 64, 104, 6, bevelRadius ), footMaterial );
	cube.position.x = 0;	// centered on origin along X
	cube.position.y = 104/2;
	cube.position.z = -(77 + 6/2);	// negative offset 77 + half of depth 6/2
	bsupport.add( cube );

	// legs
	cube = new THREE.Mesh(
		new THREE.BeveledBlockGeometry( 60, 282+4, 4, bevelRadius ), legMaterial );
	cube.position.x = 0;	// centered on origin along X
	cube.position.y = 104 + 282/2 - 2;
	cube.position.z = 77 + 6/2;	// negative offset 77 + half of depth 6/2
	bsupport.add( cube );

	cube = new THREE.Mesh(
		new THREE.BeveledBlockGeometry( 60, 282+4, 4, bevelRadius ), legMaterial );
	cube.position.x = 0;	// centered on origin along X
	cube.position.y = 104 + 282/2 - 2;
	cube.position.z = -(77 + 6/2);	// negative offset 77 + half of depth 6/2
	bsupport.add( cube );
}

// Body of the bird - body and the connector of body and head
function createBody(bbody) {
	var bodyMaterial = new THREE.MeshPhongMaterial( { shininess: 100 } );
	bodyMaterial.color.setRGB( 31/255, 86/255, 169/255 );
	bodyMaterial.specular.setRGB( 0.5, 0.5, 0.5 );
	bodyMaterial.ambient.copy( bodyMaterial.color );

	var glassMaterial = new THREE.MeshPhongMaterial( { color: 0x0, specular: 0xFFFFFF, shininess: 100, opacity: 0.3, transparent: true } );
	glassMaterial.ambient.copy( glassMaterial.color );

	var crossbarMaterial = new THREE.MeshPhongMaterial( { color: 0x808080, specular: 0xFFFFFF, shininess: 400 } );
	crossbarMaterial.ambient.copy( crossbarMaterial.color );

	// body
	sphere = new THREE.Mesh(
		new THREE.SphereGeometry( 104/2, 32, 16, 0, Math.PI * 2, Math.PI/2, Math.PI ), bodyMaterial );
	sphere.position.x = 0;
	sphere.position.y = 160;
	sphere.position.z = 0;
	bbody.add( sphere );

	// cap for top of hemisphere
	cylinder = new THREE.Mesh(
		new THREE.CylinderGeometry( 104/2, 104/2, 0, 32 ), bodyMaterial );
	cylinder.position.x = 0;
	cylinder.position.y = 160;
	cylinder.position.z = 0;
	bbody.add( cylinder );

	cylinder = new THREE.Mesh(
		new THREE.CylinderGeometry( 12/2, 12/2, 390 - 100, 32 ), bodyMaterial );
	cylinder.position.x = 0;
	cylinder.position.y = 160 + 390/2 - 100;
	cylinder.position.z = 0;
	bbody.add( cylinder );

	// glass stem
	sphere = new THREE.Mesh(
		new THREE.SphereGeometry( 116/2, 32, 16 ), glassMaterial );
	sphere.position.x = 0;
	sphere.position.y = 160;
	sphere.position.z = 0;
	bbody.add( sphere );

	cylinder = new THREE.Mesh(
		new THREE.CylinderGeometry( 24/2, 24/2, 390, 32 ), glassMaterial );
	cylinder.position.x = 0;
	cylinder.position.y = 160 + 390/2;
	cylinder.position.z = 0;
	bbody.add( cylinder );

	// crossbar
	cylinder = new THREE.Mesh(
		new THREE.CylinderGeometry( 5, 5, 200, 32 ), crossbarMaterial );
	cylinder.position.set( 0, 360, 0 );
	cylinder.rotation.x = 90 * Math.PI / 180.0;
	bbody.add( cylinder );
}

// Head of the bird - head + hat
function createHead(bhead) {
	var headMaterial = new THREE.MeshLambertMaterial( );
	headMaterial.color.r = 104/255;
	headMaterial.color.g = 1/255;
	headMaterial.color.b = 5/255;
	headMaterial.ambient.copy( headMaterial.color );

	var hatMaterial = new THREE.MeshPhongMaterial( { shininess: 100 } );
	hatMaterial.color.r = 24/255;
	hatMaterial.color.g = 38/255;
	hatMaterial.color.b = 77/255;
	hatMaterial.specular.setRGB( 0.5, 0.5, 0.5 );
	hatMaterial.ambient.copy( hatMaterial.color );

	var eyeMaterial = new THREE.MeshPhongMaterial( { color: 0x000000, specular: 0x303030, shininess: 4 } );
	eyeMaterial.ambient.copy( eyeMaterial.color );

	// head
	sphere = new THREE.Mesh(
		new THREE.SphereGeometry( 104/2, 32, 16 ), headMaterial );
	sphere.position.x = 0;
	sphere.position.y = 160 + 390;
	sphere.position.z = 0;
	bhead.add( sphere );

	// hat
	cylinder = new THREE.Mesh(
		new THREE.CylinderGeometry( 142/2, 142/2, 10, 32 ), hatMaterial );
	cylinder.position.x = 0;
	cylinder.position.y = 160 + 390 + 40 + 10/2;
	cylinder.position.z = 0;
	bhead.add( cylinder );

	cylinder = new THREE.Mesh(
		new THREE.CylinderGeometry( 80/2, 80/2, 70, 32 ), hatMaterial );
	cylinder.position.x = 0;
	cylinder.position.y = 160 + 390 + 40 + 10 + 70/2;
	cylinder.position.z = 0;
	bhead.add( cylinder );

	// nose
	cylinder = new THREE.Mesh(
		new THREE.CylinderGeometry( 6, 14, 70, 32 ), headMaterial );
	cylinder.position.set( -70, 530, 0 );
	cylinder.rotation.z = 90 * Math.PI / 180.0;
	bhead.add( cylinder );

	// eyes
	var sphGeom = new THREE.SphereGeometry( 10, 32, 16 );

	// left eye
	sphere = new THREE.Mesh( sphGeom, eyeMaterial );
	sphere.position.set( -48, 560, 0 );
	var eye = new THREE.Object3D();
	eye.add( sphere );
	eye.rotation.y = 20 * Math.PI / 180.0;
	bhead.add( eye );

	// right eye
	sphere = new THREE.Mesh( sphGeom, eyeMaterial );
	sphere.position.set( -48, 560, 0 );
	eye = new THREE.Object3D();
	eye.add( sphere );
	eye.rotation.y = -20 * Math.PI / 180.0;
	bhead.add( eye );
}

function createDrinkingBird(bbird) {
	var support = new THREE.Object3D();
	var body = new THREE.Object3D();
	var head = new THREE.Object3D();

	// MODELS
	// base + legs + feet
	createSupport(support);

	// body + body/head connector
	createBody(body);

	// head + hat
	createHead(head);

	// make moving piece

	var bodyhead = new THREE.Object3D();
	bodyhead.add(body);
	bodyhead.add(head);

	// Student: change pivot point
	// pivotHeight is the height of the crossbar
	var pivotHeight = 360;
	body.position.y = -pivotHeight;
	head.position.y = -pivotHeight;
	bodyhead.position.y = pivotHeight;

	// add field for animated part, for simplicity
	bbird.animated = bodyhead;

	bbird.add(support);
	bbird.add(bodyhead);

	// go through all objects and set the meshes (only)
	// so that they cast shadows
	bbird.traverse( function ( object ) {
		if ( object instanceof THREE.Mesh ) {
			object.castShadow = true;
			object.receiveShadow = true;
		}
	} );

}

function animate() {
	window.requestAnimationFrame(animate);
	render();
}

function render() {
	var delta = clock.getDelta();
	cameraControls.update(delta);

	headlight.position.copy( camera.position );
	stats.update();
	TWEEN.update();
	renderer.render(scene, camera);
}

init();
animate();


text:
namespace awsmSeeSharpGame.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.0-30225")]
    public sealed partial class init : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(init));

        string IMigrationMetadata.Id
        {
            get { return "201506171125545_init"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
<?php
/**
*
*/
class Pdf_controller extends CI_Controller
{

	public function __construct()
	{
		parent:: __construct();
		$this->load->model('Model_pdf');
		$this->load->library('pdf_Library');
	}

	public function generate_item_report(){

		if (isset($_POST['print'])){
			$fromdate = $_POST['datepicker1'];
			$todate = $_POST['datepicker2'];
			$report_type = $_POST['reportType'];

			$date = date_create_from_format("m/d/Y", $fromdate);
			$from = date_format($date, "Y-m-d");
			$date1 = date_create_from_format("m/d/Y", $todate);
			$to = date_format($date1, "Y-m-d");

			if ($report_type == 'Type1') {
				$data['items'] = $this->Model_pdf->select_items_type1($from,$to);
				$this->load->view('items_report_type1', $data);

			}elseif ($report_type == 'Type2') {
				$data['items'] = $this->Model_pdf->select_items_type2($from,$to);
				$this->load->view('items_report_type2', $data);

			}elseif ($report_type == 'Type3') {
				$data['items'] = $this->Model_pdf->select_items_type3($from,$to);
				$this->load->view('items_report_type3', $data);

			}elseif ($report_type == 'Type4') {
				$data['items'] = $this->Model_pdf->select_items_type4($from,$to);
				$this->load->view('items_report_type4', $data);
			}else{
				// Enter a print message
			}
		}else if (isset($_POST['generate'])){
			$fromdate = $_POST['datepicker1'];
			$todate = $_POST['datepicker2'];
			$report_type = $_POST['reportType'];

			$date = date_create_from_format("m/d/Y", $fromdate);
			$from = date_format($date, "Y-m-d");
			$date1 = date_create_from_format("m/d/Y", $todate);
			$to = date_format($date1, "Y-m-d");

			if ($report_type == 'Type1') {
				$data['items'] = $this->Model_pdf->select_items_type1($from,$to);
				$data['report_type'] = $report_type;
				$this->load->view('ReportsView', $data);

			}elseif ($report_type == 'Type2') {
				$data['items'] = $this->Model_pdf->select_items_type2($from,$to);
				$data['report_type'] = $report_type;
				$this->load->view('ReportsView', $data);

			}elseif ($report_type == 'Type3') {
				$data['items'] = $this->Model_pdf->select_items_type3($from,$to);
				$data['report_type'] = $report_type;
				$this->load->view('ReportsView', $data);

			}elseif ($report_type == 'Type4') {
				$data['items'] = $this->Model_pdf->select_items_type4($from,$to);
				$data['report_type'] = $report_type;
				$this->load->view('ReportsView', $data);
			}else{
				// Enter a print message
			}
		}
	}

	public function generate_report_table($datepicker1,$datepicker2,$reportType){

		$fromdate = $datepicker1;
		$todate = $datepicker2;
		$report_type = $reportType;

		echo $report_type;

		$date = date_create_from_format("m/d/Y", $fromdate);
		$from = date_format($date, "Y-m-d");
		$date1 = date_create_from_format("m/d/Y", $todate);
		$to = date_format($date1, "Y-m-d");

		if ($report_type == 'Type1') {
			$data['items'] = $this->Model_pdf->select_items_type1($from,$to);
			$this->load->view('items_report_type1', $data);

		}elseif ($report_type == 'Type2') {
			$data['items'] = $this->Model_pdf->select_items_type2($from,$to);
			$this->load->view('items_report_type2', $data);

		}elseif ($report_type == 'Type3') {
			$data['items'] = $this->Model_pdf->select_items_type3($from,$to);
			$this->load->view('items_report_type3', $data);

		}elseif ($report_type == 'Type4') {
			$data['items'] = $this->Model_pdf->select_items_type4($from,$to);
			$this->load->view('items_report_type4', $data);
		}else{
			// Enter a print message
		}
	}
}


text:
"""`appengine_config` gets loaded when starting a new application instance."""
import sys
import os.path
# add `lib` subdirectory to `sys.path`, so our `main` module can load
# third-party libraries.

sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib'))


text:
import AuthenticatedRoute from 'ghost-admin/routes/authenticated';
import CurrentUserSettings from 'ghost-admin/mixins/current-user-settings';
import styleBody from 'ghost-admin/mixins/style-body';
import {inject as service} from '@ember/service';

export default AuthenticatedRoute.extend(styleBody, CurrentUserSettings, {
    settings: service(),

    titleToken: 'Settings - Apps',
    classNames: ['settings-view-apps'],

    beforeModel() {
        this._super(...arguments);
        return this.get('session.user')
            .then(this.transitionAuthor())
            .then(this.transitionEditor());
    },

    // we don't want to set the model property but we do want to ensure we have
    // up-to-date settings so pause via afterModel
    afterModel() {
        return this.get('settings').reload();
    }
});


text:
function virtualenv_prompt_info(){
  [[ -n ${VIRTUAL_ENV} ]] || return
  echo "${ZSH_THEME_VIRTUALENV_PREFIX:=[}${VIRTUAL_ENV:t}${ZSH_THEME_VIRTUALENV_SUFFIX:=]}"
}

# disables prompt mangling in virtual_env/bin/activate
export VIRTUAL_ENV_DISABLE_PROMPT=0


text:
#ifndef __CHARGE_MANAGER_H
#define __CHARGE_MANAGER_H

#include "common.h"

/* Charge port that indicates no active port */
#define CHARGE_SUPPLIER_NONE -1
#define CHARGE_PORT_NONE -1
#define CHARGE_CEIL_NONE -1

/* Initial charge state */
#define CHARGE_CURRENT_UNINITIALIZED -1
#define CHARGE_VOLTAGE_UNINITIALIZED -1

/* Charge tasks report available current and voltage */
struct charge_port_info {
	int current;
	int voltage;
};

/* Called by charging tasks to update their available charge */
void charge_manager_update_charge(int supplier,
				  int port,
				  struct charge_port_info *charge);

/* Partner port dualrole capabilities */
enum dualrole_capabilities {
	CAP_UNKNOWN,
	CAP_DUALROLE,
	CAP_DEDICATED,
};

/* Called by charging tasks to indicate partner dualrole capability change */
void charge_manager_update_dualrole(int port, enum dualrole_capabilities cap);

/* Update charge ceiling for a given port */
void charge_manager_set_ceil(int port, int ceil);

/* Select an 'override port', which is always the preferred charge port */
int charge_manager_set_override(int port);
int charge_manager_get_override(void);

/* Returns the current active charge port, as determined by charge manager */
int charge_manager_get_active_charge_port(void);

#ifdef CONFIG_USB_PD_LOGGING
/* Save power state log entry for the given port */
void charge_manager_save_log(int port);
#endif

/* Board-level callback functions */

/*
 * Set the active charge port. Returns EC_SUCCESS if the charge port is
 * accepted, returns ec_error_list status otherwise.
 */
int board_set_active_charge_port(int charge_port);

/* Set the charge current limit. */
void board_set_charge_limit(int charge_ma);

/* Called on delayed override timeout */
void board_charge_manager_override_timeout(void);

#endif /* __CHARGE_MANAGER_H */


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public sealed class PlayerMech : MonoBehaviour {
    public static Color[] colorBag = new Color[2];
    public static int bagPosition = 0;
    public GameObject bagColor, bagColor1;

	void Start()
	{
        SetColorPower();
    }

    private void Update()
    {
        BagColorsUI1();
        BagColorsUI2();
        BagControls();
    }

    //Asigna el color que hay en la posicion principal de la mochila al piso
    void OnTriggerStay(Collider other)
	{
		if (other.tag == "Piso" && Input.GetKey(KeyCode.Space))
		{
			other.GetComponent<Renderer> ().material.color = colorBag[bagPosition];
		}
	}

    void SetColorPower()
    {// De manera Aleatoria, selecciona los colores que van a aparecer en el principio
        int colorPackage = Random.Range(0,3);
        if (colorPackage == 0)
        {
            colorBag[0] = Color.red;
            colorBag[1] = Color.cyan;
        }
        else if (colorPackage == 1)
        {
            colorBag[0] = Color.red;
            colorBag[1] = Color.magenta;
        }
        else if (colorPackage == 2)
        {
            colorBag[0] = Color.yellow;
            colorBag[1] = Color.cyan;
        }
        else if (colorPackage == 3)
        {
            colorBag[0] = Color.yellow;
            colorBag[1] = Color.magenta;
        }
    }

    void BagColorsUI1()
    { // Cambia el color del icono que refloja el color principal que hay en la mochila
        if (colorBag[0] == Color.blue)
        {
            bagColor.GetComponent<Image>().color = Color.blue;
        }
        else if (colorBag[0] == Color.red)
        {
            bagColor.GetComponent<Image>().color = Color.red;
        }
        else if (colorBag[0] == Color.yellow)
        {
            bagColor.GetComponent<Image>().color = Color.yellow;
        }
        else if (colorBag[0] == Color.cyan)
        {
            bagColor.GetComponent<Image>().color = Color.cyan;
        }
        else if (colorBag[0] == Color.magenta)
        {
            bagColor.GetComponent<Image>().color = Color.magenta;
        }
    }

    void BagColorsUI2()
    {// Cambia el color del icono que refleja el color secundario que hay en la mochila
        if (colorBag[1] == Color.blue)
        {
            bagColor1.GetComponent<Image>().color = Color.blue;
        }
        else if (colorBag[1] == Color.red)
        {
            bagColor1.GetComponent<Image>().color = Color.red;
        }
        else if (colorBag[1] == Color.yellow)
        {
            bagColor1.GetComponent<Image>().color = Color.yellow;
        }
        else if (colorBag[1] == Color.cyan)
        {
            bagColor1.GetComponent<Image>().color = Color.cyan;
        }
        else if (colorBag[1] == Color.magenta)
        {
            bagColor1.GetComponent<Image>().color = Color.magenta;
        }
    }

    void ChangingColor() // Contiene la funcion para cambiar el color primario por el secundaro y viceversa
    {
        GameObject auxG = bagColor;
        bagColor = bagColor1;
        bagColor1 = auxG;
    }

    void BagControls() // Contiene los controles para cambiar los colores en las casillas de la mochila
    {
        if (Input.GetKeyDown(KeyCode.LeftShift) && bagPosition == 0)
        {
            bagPosition++;
            ChangingColor();
        }
        else if (Input.GetKeyDown(KeyCode.LeftShift) && bagPosition == 1)
        {
            bagPosition--;
            ChangingColor();
        }
    }
}


text:
package me.xiaoge.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name = "users")
public class User implements Serializable {

	private static final long serialVersionUID = -4060739788760795254L;

	@Id
	@GeneratedValue
	private Long id;

	@NotEmpty
	private String name;

	@NotEmpty
	private String password;

	@Email
	@NotEmpty
	private String email;

	@NotNull
	private String address;

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}

}


text:
package org.apache.asterix.dataflow.data.nontagged.printers.adm;

import java.io.IOException;
import java.io.PrintStream;

import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.data.IPrinter;
import org.apache.hyracks.algebricks.data.utils.WriteValueTools;
import org.apache.hyracks.data.std.primitive.ShortPointable;

public class ShortWithoutTypeInfoPrinter implements IPrinter {

    public static final ShortWithoutTypeInfoPrinter INSTANCE = new ShortWithoutTypeInfoPrinter();

    @Override
    public void init() {

    }

    @Override
    public void print(byte[] b, int s, int l, PrintStream ps) throws AlgebricksException {
        short d = ShortPointable.getShort(b, s);
        try {
            WriteValueTools.writeInt((int)d, ps);
        } catch (IOException e) {
            throw new AlgebricksException(e);
        }
    }
}


text:
<?php

namespace PayPal\Test\Api;

use PayPal\Api\Links;

/**
 * Class Links
 *
 * @package PayPal\Test\Api
 */
class LinksTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Gets Json String of Object Links
     * @return string
     */
    public static function getJson()
    {
        return '{"href":"TestSample","rel":"TestSample","targetSchema":' .HyperSchemaTest::getJson() . ',"method":"TestSample","enctype":"TestSample","schema":' .HyperSchemaTest::getJson() . '}';
    }

    /**
     * Gets Object Instance with Json data filled in
     * @return Links
     */
    public static function getObject()
    {
        return new Links(self::getJson());
    }

    /**
     * Tests for Serialization and Deserialization Issues
     * @return Links
     */
    public function testSerializationDeserialization()
    {
        $obj = new Links(self::getJson());
        $this->assertNotNull($obj);
        $this->assertNotNull($obj->getHref());
        $this->assertNotNull($obj->getRel());
        $this->assertNotNull($obj->getTargetSchema());
        $this->assertNotNull($obj->getMethod());
        $this->assertNotNull($obj->getEnctype());
        $this->assertNotNull($obj->getSchema());
        $this->assertEquals(self::getJson(), $obj->toJson());
        return $obj;
    }

    /**
     * @depends testSerializationDeserialization
     * @param Links $obj
     */
    public function testGetters($obj)
    {
        $this->assertEquals($obj->getHref(), "TestSample");
        $this->assertEquals($obj->getRel(), "TestSample");
        $this->assertEquals($obj->getTargetSchema(), HyperSchemaTest::getObject());
        $this->assertEquals($obj->getMethod(), "TestSample");
        $this->assertEquals($obj->getEnctype(), "TestSample");
        $this->assertEquals($obj->getSchema(), HyperSchemaTest::getObject());
    }

}


text:
PAK is a Ruby library for reading Quake PAK files. Currently it's in a very rough state.

## Installation

Add this line to your application's Gemfile:

    gem 'pak'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install pak

## Usage

    require 'pak'

    PAK::Archive.open('/path/to/file.pak') do |pak|

    	pak.each do |file|

    		puts file.path

    	end

    end

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
import {ChangeDetectorRef, Component, NgZone, ViewChild} from '@angular/core';
import {AlertController, IonicPage, NavController, NavParams, ViewController} from 'ionic-angular';
import {Team} from "../../scheduling/teams";
import {Person} from "../../scheduling/people";
import {RootStore} from "../../store/root";
import {ObjectValidation} from "../../scheduling/shared";
import {PageUtils} from "../page-utils";
import {NamedObject} from "../../scheduling/base-types";
import {Logger, LoggingService} from "ionic-logging-service";
import {AccessControlProvider, ResourceType} from "../../providers/access-control/access-control";

@IonicPage({
    name: 'page-team',
    defaultHistory: ['page-teams', 'home']
})
@Component({
    selector: 'page-team',
    templateUrl: 'team.html',
})
export class TeamPage {
    team: Team;
    callback: (add: boolean) => void;
    @ViewChild('peoplelist') pc;
    private logger: Logger;

    constructor(public navCtrl: NavController,
                public viewCtrl: ViewController,
                public pageUtils: PageUtils,
                public alertCtrl: AlertController,
                public access: AccessControlProvider,
                public cd: ChangeDetectorRef,
                private logService: LoggingService,
                public zone: NgZone,
                public rootStore: RootStore,
                public navParams: NavParams) {
        this.team = navParams.get('team');
        this.callback = navParams.get('callback');
        this.logger = this.logService.getLogger('page.team')
    }

    get has_add_button() {
        return this.callback != null && this.canManage;
    }

    get has_edit_button() {
        return this.callback == null && this.canManage;
    }

    get canManage() {
        return this.access.canUpdateAny(ResourceType.Team);
    }

    ionViewDidLoad() {
        if (this.has_add_button) {
            this.viewCtrl.showBackButton(false);
        }
        if (!this.team) {
            // No team? go back to the teams list
            this.navCtrl.pop();
        } else {
        }
    }

    send_cancel() {
        this.callback(false);
        this.navCtrl.pop();
    }

    send_ok() {
        this.navCtrl.pop().then(() => {
            try {
                this.callback(true);
            } catch (err) {
                this.pageUtils.showValidationError(ObjectValidation.simple(err));
            }
        });
    }

    get okButtonDisabled(): boolean {
        if (!this.team) {
            return true;
        }
        if (!this.team.name) {
            return true;
        }
        if (this.team.name.length == 0) {
            return true;
        }
        return false;
    }

    add_person_to_team(person: Person) {
        this.team.add(person);
        this.rootStore.asyncSaveOrUpdateDb(this.team);
    }

    delete_from_team(person: Person) {
        this.team.remove(person);

    }

    addFromExisting() {
        // Show a selection of people, with add/cancel button
        let alert = this.alertCtrl.create({
            title: "Select people to add"
        });
        let people_not_in_list = this.rootStore.people.all.filter(p => this.team.findPersonInTeam(p) == null);
        if (people_not_in_list.length == 0) {
            let validation = ObjectValidation.simple("All people are already in the list");
            this.pageUtils.showValidationError(validation);
            return;
        }
        for (let p of NamedObject.sortByName(people_not_in_list)) {
            alert.addInput({
                type: 'checkbox',
                value: p.uuid,
                label: p.name
            })
        }
        alert.addButton({
            text: 'Add',
            handler: (uuids) => {
                let dismissTransition = alert.dismiss();
                dismissTransition.then(() => {
                    this.addExistingUUIDsToTeam(uuids)
                });
                // this.addExistingUUIDsToTeam(uuids);
                // return true;
                return false;
            }
        });
        alert.addButton({
            text: 'Cancel',
            role: 'cancel',
            handler: () => {

            }
        });
        alert.present();
    }

    addExistingUUIDsToTeam(uuids) {
        for (let uuid of uuids) {
            let person = this.rootStore.findByUUID(uuid) as Person;
            this.team.add(person);

            // For some reason, the change to the data isn't enough
            this.cd.detectChanges();
            this.logger.info(`Added ${uuid} to team`);
        }
    }
}