text:
A dynamic array with amortized growth cost.

This is the most commonly used array for dynamically allocated data.

## Constructors

### this

```C#
this{copy: Vector<T>};
this{move copy: Vector<T>};
```

#### Brief

Copy/move constructor.

Creates a new instance containing a copy of the input parameter, or moves the data if the input parameter is an expiring value.

#### Parameters
> *copy* => the vector to copy/move from
***

## Methods

### @attr

```C#
def @attr(copy: Vector<T>);
def @attr(move copy: Vector<T>);
```

#### Brief
Assignment/move operator.

Assign the current instance with a copy or a move of the input data.

#### Parameters
> *copy* => the vector to copy/move from
***

### Add

```C#
def Add(item: T);
def Add(move item: T);
def Add(items: Vector<T>);
def Add(items: CArray<T>);
```

#### Brief
Append a single item or a collection to the end of the vector.

#### Parameters
> *item* => the item to append
> *items* => the item collection to append
***

### Fill

```C#
def Fill(value: T);
def Fill(items: Vector<T>);
def Fill(items: CArray<T>);
```

#### Brief
Copies over all the elements in the static array.

If a single value is provided, all elements will be initialized with it.

If an array is provided, elements will be copied over in sequence. If the source array is exhausted, the reading index will be reset to 0 and the copying resumed.

#### Parameters
> *value* => the value to fill with
> *items* => the array to use
***

### FindIndex

```C#
func FindIndex(item: T): PtrSize;
func FindIndex(item: T, start: PtrSize): PtrSize;
```

#### Brief
Searches for an item in the array and returns the first index at which it was found or [-1][sys.core.lang.PtrSize] if the item was not found.

The search starts on an index given by the `start` parameter if present or from index 0 otherwise.

#### Parameters
> *item* => the item to search for
> *start* => the start index for the search
#### Returns
> the index where the item was found
***

### BinaryIndex

```C#
func BinaryIndex(item: T): PtrSize;
func BinaryIndex(item: T, start: PtrSize): PtrSize;
```

#### Brief
Searches for an item in the array and returns the first index at which it was found or [-1][sys.core.lang.PtrSize] if the item was not found. It uses a binary search algorithm and the contents of the container must be sorted in ascending order. If the elements are not sorted, the result is unpredictable.

The search starts on an index given by the `start` parameter if present or from index 0 otherwise.

#### Parameters
> *item* => the item to search for
> *start* => the start index for the search
#### Returns
> the index where the item was found
***

### Insert

```C#
def Insert(pos: PtrSize, item: T);
def Insert(pos: PtrSize, items: CArray<T>);
def Insert(pos: PtrSize, items: Vector<T>);
```

#### Brief
Inserts an item or a collection of items into the array at a given position.

THe array will grow to accommodate the inserted items.

#### Parameters
> *pos* => the position to insert to
> *item* => the item to insert
> *items* => the items to insert
***

### Delete

```C#
def Delete(item: T): PtrSize;
def Delete(items: CArray<T>): PtrSize;
def Delete(items: Vector<T>): PtrSize;
```

#### Brief
Searches for the first occurrence of an item within the array and if found it removes it.

#### Parameters
> *item* => the item to delete
> *items* => the items to delete
#### Returns
> the number of deleted items
***

### DeleteAll

```C#
def DeleteAll(item: T): PtrSize;
def DeleteAll(item: CArray<T>): PtrSize;
def DeleteAll(item: Vector<T>): PtrSize;
```

#### Brief
Searches for all the occurrences of an item within the array and if found removes them all.

#### Parameters
> *item* => the item to remove
#### Returns
> the number of deleted items
***

### DeleteIndex

```C#
def DeleteIndex(item: PtrSize): PtrSize;
def DeleteIndex(items: CArray<PtrSize>): PtrSize;
def DeleteIndex(items: Vector<PtrSize>): PtrSize;
```

#### Brief
Deletes an item at a given index from the array.

#### Parameters
> *item* => the index to delete
> *items* => an array of indices to delete
#### Returns
> the number of deleted items
***

### Reverse

```C#
def Reverse();
def Reverse(start: PtrSize, end: PtrSize);
```

#### Brief
Reverses the contents of the array, from beginning to end or between two input indices.

#### Parameters
> *start* => the start index
> *end* => the end index
***

### Sum

```C#
func Sum(): T;
```

#### Brief
Returns the sum of all the items in the array.

#### Returns
> the sum
***

### Sort

```C#
def Sort();
def Sort(low: Int, high: Int);
```

#### Brief
Sorts the content of the array in ascending order, from beginning to end or between two input indices.

#### Parameters
> *low* => the start index
> *high* => the end index
***

### SortDesc

```C#
def SortDesc();
def SortDesc(low: Int, high: Int);
```

#### Brief
Sorts the content of the array in descending order, from beginning to end or between two input indices.

#### Parameters
> *low* => the start index
> *high* => the end index
***

### @write

```C#
func @write(ref stream: Stream);
```

#### Brief
Writes each element of the array to a stream as an Utf8 text.

The item count is included.

#### Parameters
> *stream* => the output stream
***

### @shl

```C#
@shl(ref v: Vector<T>, data: T): ref Vector<T>;
```

#### Brief
Appends a vector `v` to the array.
***

## Properties

### Length

```C#
property Length: PtrSize
```

#### Brief
Read and writes the length of the vector.
***

### Capacity

```C#
property Capacity: PtrSize
```

#### Brief
Read and writes the capacity of the vector.

Capacity can't be set lower than the Length.
***

### @index

```C#
property @index: ref T; get;
```

#### Brief
Reads and writes a given index from the vector.

Accessing an invalid index is an error.
***

### At

```C#
property At: ref T; get;
```

#### Brief
Reads and writes a given index from the vector.

Accessing an index greater than Length will cause all the missing values to be default constructed.
***

### SysDataPointer

```C#
property SysDataPointer: Ptr<T>; get;
```

#### Brief
Returns a pointer to the data.
***

[sys.core.lang.PtrSize]: sys.core.lang.PtrSize.api.md "sys.core.lang.PtrSize"


text:
#include "antlr3lexer.h"

/* The function prototypes are in Lexer.chs */

ANTLR3_COMMON_TOKEN *LT(ANTLR3_INPUT_STREAM *input, int lti)
{
  return input->_LT(input, (ANTLR3_INT32)lti);
}

ANTLR3_STRING *tokenGetAntlrString(ANTLR3_COMMON_TOKEN *token)
{
  return token->getText(token);
}

redpajama_set_name: RedPajamaGithub


text:
![Office UI Fabric](http://odux.azurewebsites.net/github/img/OfficeUIFabricLogoBluePadSm-01.png)

##Features

###Contents

- [Typography](#typography)
- [Color](#color)
- [Icons](#icons)
- [Animations](#animations)
- [Responsive grid](#responsive-grid)
- [Localization support](#localization)

For simple instructions for using Fabric features in Office Add-ins, see the article [Using Fabric with Office Add-ins](https://msdn.microsoft.com/EN-US/library/office/6f46dd69-2ba3-4b0f-9735-7d7394ca2731.aspx).
###Typography

####Base font classes

Fabric includes 10 **base** font classes that represent the type ramp for the Office Design Language. Each base class sets a default size, weight, and color.

![Type Ramp](http://odux.azurewebsites.net/github/img/TypeRamp.png)

####Helper font classes

Use one of several **helper** font classes to easily change the text weight.

![Helper Type](http://odux.azurewebsites.net/github/img/HelperType.png)

###Color

Fabric includes 9 theme colors and 11 neutral colors. Each has helper classes for text, border, background, and hover states. These color classes act as hooks into the suite-wide theming system. When the theming system is enabled and your app or add-in is consuming the suite navigation, these classes pick up the user's chosen theme.

Use **theme colors** in wayfinding, navigation, and key interactions like primary actions and current or selected indicators.

![Theme Colors](http://odux.azurewebsites.net/github/img/ThemeColors.png)

**Neutral colors** include black, gray, and white. Use darker shades of gray for primary content, such as text and titles. Use black sparingly for high-impact strings (labels, names) and hover states. Use lighter shades of gray for supporting graphic elements and page areas.

Fabric also includes **accent** colors.

![Accent Colors](http://odux.azurewebsites.net/github/img/AccentColors.png)

###Icons

Fabric uses a custom font for its iconography. This font contains glyphs that you can scale, color, and style in any way. You can even flip them for right-to-left localization.

To use the icons, combine the base `ms-Icon` class with a modifier class for the specific icon.
```html
<i class="ms-Icon ms-Icon--mail" aria-hidden="true"></i>
```
Note the `aria-hidden` attribute, which prevents screen readers from reading the icon. In cases where meaning is conveyed *only* through the icon, such as an icon-only navigation bar, be sure to apply an `aria-label` to the button for accessibility.

###Animations

Use the animation library to create web experiences that integrate with Office 365. You can use the animation CSS classes for navigation, panels, dialogs, and more. Animations include **directionality** (up, down, left, right relating to origin and completion of tasks), **enter/exit** (fade in, fade out, zoom in, zoom out), and **duration** (speed of enter/exit relating to urgency or content type).

When choosing a motion for side panels, consider the origin of the triggering element. Use the motion to create a link between the action and the resulting UI. For example, if the triggering element is on the right side of the interface, consider having the panel move in from the right.

When choosing a motion for dialogs, consider the origin and tone of the content. For a warning or error dialog, a quick fade in might be appropriate. If the dialog appears when a user chooses an item to get more information, a scale-up might be appropriate.

|CSS class    |Description  |Cubic bezier |Timing       |
|:-----------:|:-----------:|:-----------:|:-----------:|
|ms-u-slideRightIn40|Slide right 40px and fade in|0.1, 0.9, 0.2, 1|0.367s|
|ms-u-slideLeftIn40|Slide left 40px and fade in|0.1, 0.9, 0.2, 1|0.367s|
|ms-u-slideUpIn20| Slide up 20px and fade in| 0.1, 0.9, 0.2, 1| 0.367s|
|ms-u-slideUpIn10| Slide up 10px and fade in| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-slideDownIn20| Slide down 20px and fade in| 0.1, 0.9, 0.2, 1| 0.367s|
|ms-u-slideDownIn10| Slide down 10px and fade in| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-slideRightOut40| Slide right 40px and fade out| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-slideLeftOut40| Slide left 40px and fade out| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-slideUpOut20| Slide up 20px and fade out| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-slideUpOut10| Slide up 10px and fade out| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-slideDownOut20| Slide down 20px and fade out| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-slideDownOut10| Slide down 10px and fade out| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-scaleUpIn100| Scale up to 100% and fade in| 0.1, 0.9, 0.2, 1| 0.367s|
|ms-u-scaleDownIn100| Scale down to 100% and fade in| 0.1, 0.9, 0.2, 1| 0.367s|
|ms-u-scaleUpOut103| Scale up to 103% and fade out| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-scaleDownOut98| Scale down to 98% and fade out| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-fadeIn100| Fade in| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-fadeIn200| Fade in| 0.1, 0.25, 0.75, 0.9| 0.267s|
|ms-u-fadeIn400| Fade in| 0.1, 0.25, 0.75, 0.9| 0.367s|
|ms-u-fadeIn500| Fade in| 0.1, 0.25, 0.75, 0.9| 0.467s|
|ms-u-fadeOut100| Fade out| 0.1, 0.25, 0.75, 0.9| 0.167s|
|ms-u-fadeOut200| Fade out| 0.1, 0.25, 0.75, 0.9| 0.267s|
|ms-u-fadeOut400| Fade out| 0.1, 0.25, 0.75, 0.9| 0.367s|
|ms-u-fadeOut500| Fade out| 0.1, 0.25, 0.75, 0.9| 0.467s|

###Responsive grid

Forget serving static, device-specific layouts. Fabric comes with a mobile-first, 12-column, responsive grid that you can use to create flexible layouts for a variety of screen sizes and device types.

![Responsive grid](http://odux.azurewebsites.net/github/img/ResponsiveGrid.png)

####Using the responsive grid
A grid (`.ms-Grid`) can contain multiple rows (`.ms-Grid-row`), each of which has one or more columns (`.ms-Grid-col`). Utility classes (`.ms-u-sm6`) specify how large each column should be on small, medium, and large devices. The columns in a row should add up to 12 for each device size. The following:

```html
<div class="ms-Grid">
  <div class="ms-Grid-row">
    <div class="ms-Grid-col ms-u-sm6 ms-u-md4 ms-u-lg2">First</div>
    <div class="ms-Grid-col ms-u-sm6 ms-u-md8 ms-u-lg10">Second</div>
  </div>
</div>
```

Results in:

![ResultGrid](http://odux.azurewebsites.net/github/img/ResultGrid.png)

####Inheritance
Because Fabric is mobile-first, any layout defined for small screens is automatically inherited by medium and large screens. The small size utilities (`.ms-u-sm6`) are required. If you want to change the layout on larger screens, you can apply the other utility classes.

####Push and pull
You might want your column source order to differ from the display order, or to change the column display order based on the screen size. The push and pull utilities make this possible. Push moves a column to the right; pull moves it to the left.

###Localization support

####Right-to-left support
Fabric comes with an alternate CSS file for pages written in right-to-left (RTL) languages, such as Arabic and Hebrew. This reverses the order of columns in the responsive grid, which makes it easy to create an RTL layout without writing additional templates. Future versions of Fabric will also reverse some icons and provide additional helper utilities.

Apply the **dir** attribute to the HTML tag, and reference the RTL version of Fabric.
```html
<html dir="rtl">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="fabric-[version].rtl.min.css">
  </head>
  ...
</html>
```

####Language-optimized fonts
By default, Fabric presents all text using the Western European character set of Segoe UI. For languages with other characters, Fabric will either serve a version of Segoe UI with a different character set or use a system font.

The HTML **lang** attribute specifies the language of the element's content. This is typically applied to the root HTML element, where it will be inherited by the entire page. In this example the entire page is in Thai.
```html
<html lang="th-TH">...</html>
```

For pages with content in multiple languages, the **lang** attribute can be applied to individual elements. In this example, a page that is mostly Thai also contains some Vietnamese.
```html
<html lang="th-TH">
  ...
  <section lang="vi-VN">...</section>
</html>
```

Fabric supports 24 language codes. These codes use the font stacks listed in the following table.

|Language|Code|Font stack|
|:-----:|:-----:|:------:|
|Western European (default)| N/A| 'Segoe UI Web Regular', 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif|
|Japanese| ja-JP| YuGothic, "Meiryo UI", Meiryo, "MS Pgothic", Osaka, "Segoe UI", Tahoma, Arial, sans-serif|
| Korean                          | ko-KR    | "Malgun Gothic", Gulim,   "Segoe UI", Tahoma, Arial, sans-serif                               |
| Chinese   (simplified)          | ch-ZHS   | "Microsoft Yahei",   Verdana, Simsun, "Segoe UI", Tahoma, Arial, sans-serif                   |
| Chinese   (traditional)         | ch-ZHT   | "Microsoft Jhenghei",   Pmingliu, "Segoe UI", Tahoma, Arial, sans-serif                       |
| Hindi                           | hi-IN    | "Nirmala UI",   "Segoe UI", Tahoma, Arial, sans-serif                                         |
| Thai                            | th-TH    | 'Leelawadee UI Regular', 'Kmer   UI', 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif       |
| Arabic                          | ar       | 'Segoe UI Regular Arabic', 'Segoe   UI', 'Segoe WP', Tahoma, Arial, sans-serif                |
| Bulgarian                       | bg-BG    | 'Segoe UI Regular Cyrillic',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif              |
| Czech                           | cs-CZ    | 'Segoe UI Regular EastEuropean',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif          |
| Estonian                        | et-EE    | 'Segoe UI Regular EastEuropean',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif          |
| Croatian                        | hr-HR    | 'Segoe UI Regular EastEuropean',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif          |
| Hungarian                       | hu-HU    | 'Segoe UI Regular EastEuropean',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif          |
| Lithuanian                      | lt-LT    | 'Segoe UI Regular EastEuropean',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif          |
| Latvian   (Lettish)             | lv-LV    | 'Segoe UI Regular EastEuropean',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif          |
| Polish                          | pl-PL    | 'Segoe UI Regular EastEuropean',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif          |
| Serbian                         | lt-sr-SP | 'Segoe UI Regular EastEuropean',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif          |
| Russian                         | ru-RU    | 'Segoe UI Regular Cyrillic',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif              |
| Ukrainian                       | uk-UA    | 'Segoe UI Regular Cyrillic',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif              |
| Turkish                         | tr-TR    | 'Segoe UI Regular EastEuropean',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif          |
| Slovak                          | sk-SK    | 'Segoe UI Regular EastEuropean',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif          |
| Kazakh                          | kk-KZ    | 'Segoe UI Regular EastEuropean',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif          |
| Greek                           | el-GR    | 'Segoe UI Regular Greek', 'Segoe   UI', 'Segoe WP', Tahoma, Arial, sans-serif                 |
| Hebrew                          | he-IL    | 'Segoe UI Regular Hebrew', 'Segoe   UI', 'Segoe WP', Tahoma, Arial, sans-serif                |
| Vietnamese                      | vi-VN    | 'Segoe UI Regular Vietnamese',   'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif            |


text:
import request from '../utils/request';
import config from '../utils/config';

export async function launcher(data) {
  console.log('launcher,.....');
  data.token = localStorage.getItem('token');
  console.log(JSON.stringify(data));
  return request(data.flag === 1 ? `${config.server_addr}/upload` : `${config.server_addr}/RPNCommit`, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  });
}

export async function getsvc(data) {
  data.token = localStorage.getItem('token');
  console.log(JSON.stringify(data));
  return request(data.flag === 1 ? `${config.server_addr}/get_blog` : `${config.server_addr}/get_pnote`, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  });
}


text:
//
//  ActionLayers.m
//  FlameDragon
//
//  Created by sui toney on 11-11-19.
//  Copyright 2011 ms. All rights reserved.
//

#import "ActionLayers.h"
#import "BattleField.h"
#import "FDMoveCreatureActivity.h"
#import "FDExplodeActivity.h"
#import "FDTalkActivity.h"
#import "GameFormula.h"
#import "FDOperationActivity.h"
#import "TurnInfo.h"
#import "FDEmptyActivity.h"
#import "FDBatchActivity.h"
#import "UsableItemDefinition.h"
#import "DataDepot.h"
#import "ItemBox.h"
#import "MagicBox.h"
#import "ChapterInfo.h"
#import "FDLocalString.h"
#import "FightScene.h"
#import "MainGameScene.h"
#import "GameWinScene.h"
#import "GameOverScene.h"
#import "TitleScene.h"
#import "GameRecord.h"
#import "VillageScene.h"
#import "FightingInformation.h"
#import "FightingScene.h"
#import "MagicalInformation.h"
#import "MagicalScene.h"

@implementation ActionLayers

-(id) initWithField:(BattleFieldLayer *)fLayer Message:(MessageLayer *)mLayer
{
	self = [super init];

	fieldLayer = fLayer;
	messageLayer = mLayer;

	field = [fieldLayer getField];

	activityList = [[NSMutableArray alloc] init];

	isLocked = FALSE;

	synchronizeTick = 0;
	SYNCHRONIZE_TOTAL_INT = 1000;

	sideBar = [[SideBar alloc] init];
	[sideBar show:messageLayer];

	return self;
}

-(BattleFieldLayer *) getFieldLayer
{
	return fieldLayer;
}

-(MessageLayer *) getMessageLayer
{
	return messageLayer;
}

-(void) takeTick
{
	synchronizeTick = (synchronizeTick + 1) % SYNCHRONIZE_TOTAL_INT;

	[messageLayer updateScreen:synchronizeTick];

	if ([messageLayer getMessage] != nil) {
		// The message should block all the other ticks
		return;
	}

	[fieldLayer updateScreen:synchronizeTick];

	for (FDActivity *activity in activityList) {

		[activity takeTick:synchronizeTick];

		if ([activityList count] == 0) {
			break;
		}

		if ([activity hasFinished]) {

			//[activity postActivity];
			if ([activity getNext] != nil) {
				[activityList addObject:[activity getNext]];
			}

			[activityList removeObject:activity];
		}
	}
}

-(void) appendNewActivity:(FDActivity *)activity
{
	[activityList addObject:activity];
}

-(void) appendToMainActivity:(FDActivity *)activity
{
	FDActivity *last = [activityList count] > 0 ? [activityList objectAtIndex:0] : nil;
	if (last == nil)
	{
		[activityList addObject:activity];
	}
	else {
		[last appendToLast:activity];
	}
}

-(void) clearAllActivity
{
	[activityList removeAllObjects];
}

-(void) appendToCurrentActivity:(FDActivity *)activity
{
	FDActivity *last = [activityList count] > 0 ? [activityList objectAtIndex:[activityList count]-1] : nil;
	if (last == nil)
	{
		[activityList addObject:activity];
	}
	else {
		[last appendToNext:activity];
	}
}

-(void) appendToMainActivityMethod:(SEL)method Param1:(id)obj1 Param2:(id)obj2
{
	[self appendToMainActivityMethod:method Param1:obj1 Param2:obj2 Obj:self];
}

-(void) appendToMainActivityMethod:(SEL)method Param1:(id)obj1 Param2:(id)obj2 Obj:(id)obj
{
	FDOperationActivity *activity = [[FDOperationActivity alloc] initWithObject:obj Method:method Param1:obj1 Param2:obj2];
	[self appendToMainActivity:activity];
	[activity release];
}

-(void) appendToCurrentActivityMethod:(SEL)method Param1:(id)obj1 Param2:(id)obj2
{
	[self appendToCurrentActivityMethod:method Param1:obj1 Param2:obj2 Obj:self];
}

-(void) appendToCurrentActivityMethod:(SEL)method Param1:(id)obj1 Param2:(id)obj2 Obj:(id)obj
{
	FDOperationActivity *activity = [[FDOperationActivity alloc] initWithObject:obj Method:method Param1:obj1 Param2:obj2];
	[self appendToCurrentActivity:activity];
	[activity release];
}

-(void) prepareToMove:(FDCreature *)creature Location:(CGPoint)location
{
	// Show Creature Info

	creatureInfo = [[CreatureInfoBar alloc] initWithCreature:creature ClickedOn:location];
	[creatureInfo show:messageLayer];
}

-(void) clearCreatureInfo
{
	if (creatureInfo != nil) {
		[creatureInfo close];
		creatureInfo = nil;
	}
}

-(void) moveCreatureId:(int)creatureId To:(CGPoint)pos showMenu:(BOOL)willShowMenu
{
	FDCreature *creature = [field getCreatureById:creatureId];

	if (creature != nil) {
		[self moveCreature:creature To:pos showMenu:willShowMenu];
	}
}

-(void) moveCreature:(FDCreature *)creature To:(CGPoint)pos showMenu:(BOOL)willShowMenu
{
	if (creature == nil) {
		return;
	}

	// Set Cursor
	[field setCursorTo:[field getObjectPos:creature]];
	[field setCursorTo:pos];

	FDPath *path = [[[fieldLayer getField] getMovePath:creature To:pos] retain];

	for (int i = 0; i < [path getPosCount]; i++) {
		[self moveCreatureSimple:creature To:[path getPos:i]];
	}

	if (![FDPosition isEqual:[field getObjectPos:creature] With:pos]) {
		creature.hasMoved = TRUE;
	}

	if (willShowMenu)
	{
		CGPoint p = [path getTargetPos];
		[self appendToMainActivityMethod:@selector(showMenuO:At:) Param1:[NSNumber numberWithInt: 1] Param2:[FDPosition positionX:p.x Y:p.y] Obj:field];
	}
	[path release];
}

-(void) moveCreatureIdSimple:(int)creatureId To:(CGPoint)pos
{
	FDCreature *creature = [field getCreatureById:creatureId];
	[self moveCreatureSimple:creature To:pos];
}

-(void) moveCreatureSimple:(FDCreature *)creature To:(CGPoint)pos
{
	CGPoint loc = [field convertPosToLoc:pos];

	FDMoveCreatureActivity *act = [[FDMoveCreatureActivity alloc] initWithObject:creature ToLocation:loc Speed:1.8];
	[self appendToCurrentActivity:act];
	[act release];
}

-(void) attackFrom:(FDCreature *)creature Target:(FDCreature *)target
{
	NSLog(@"Attack from %d to %d.", [creature getIdentifier], [target getIdentifier]);

	BOOL fightBack = [field isNextTo:creature And:target] && [target canFightBack];
	FightingInformation *fightingInfo = [GameFormula dealWithAttack:creature Target:target Field:field fightBack:fightBack];
	[fightingInfo retain];

	NSLog(@"fightingInfo attack1: %d %d", [[fightingInfo getAttackInfo1] getBefore], [[fightingInfo getAttackInfo1] getAfter]);

	CGPoint pos = [field getObjectPos:creature];
	int backgroundImageId = [field getBackgroundPicId:pos];
	FightingScene *scene = [[FightingScene alloc] initWithSubject:creature Target:target Information:fightingInfo Background:backgroundImageId];
	[[CCDirector sharedDirector] pushScene: [CCTransitionFade transitionWithDuration:0.5 scene:scene]];

	[scene start];
	[fightingInfo release];

	NSMutableArray *targets = [[NSMutableArray alloc] init];
	[targets addObject:target];
	[scene setPostMethod:@selector(postFightAction:Targets:) param1:creature param2:targets Obj:self];
}

-(void) postFightAction:(FDCreature *)creature Targets:(NSMutableArray *)targets
{
	NSLog(@"Post Method for attacking.");

	[targets retain];
	NSMutableArray *dropItemList = [[NSMutableArray alloc] init];

	// Check whether the important game event is triggered
	[eventListener isNotified];

	if (creature.data.hpCurrent <= 0) {

		FDExplodeActivity *activity = [[FDExplodeActivity alloc] initWithObject:creature Field:field];
		[self appendToCurrentActivity:activity];
		[activity release];
	}

	FDBatchActivity *activity = [[FDBatchActivity alloc] init];
	for (FDCreature *target in targets) {

			if (target.data.hpCurrent <= 0) {
				FDExplodeActivity *act = [[FDExplodeActivity alloc] initWithObject:target Field:field];
				[activity addActivity:act];
				[act release];
			}
	}
	[self appendToCurrentActivity:activity];
	[activity release];
	//[targets release];

	// Check whether the important game event is triggered
	//[self appendToCurrentActivityMethod:@selector(isNotified) Param1:nil Param2:nil Obj:eventListener];
	// [eventListener isNotified];

	NSLog(@"Analyse dead complete.");

	// Drop Item
	BOOL cannotCarryMore = FALSE;
	for (FDCreature *target in targets) {

		if ([target getCreatureType] == CreatureType_Enemy && target.data.hpCurrent <= 0) {

			FDEnemy *enemy = (FDEnemy *)target;
			ItemDefinition *dropItem = [[DataDepot depot] getItemDefinition:[enemy getDropItem]];
			if (dropItem != nil) {
				[dropItemList addObject:dropItem];

				if (![dropItem isMoney]) {
					// Add item
					if ([creature isItemListFull]) {
						cannotCarryMore = TRUE;
					} else {
						[creature.data.itemList addObject:[NSNumber numberWithInt:dropItem.identifier]];
					}
				} else {
					// Add money
					money += [dropItem getMoneyQuantity];
				}
			}
		}
	}

	// Talk about experience/drop item
	FDCreature *talkerFriend = nil;
	FDCreature *target = ([targets count] > 0) ? [targets objectAtIndex:0] : nil;
	if (creature != nil && [creature isKindOfClass:[FDFriend class]] && creature.lastGainedExperience > 0 && creature.data.hpCurrent > 0)
	{
		talkerFriend = creature;
	}
	else if (target != nil && [target isKindOfClass:[FDFriend class]] && target.lastGainedExperience > 0 && target.data.hpCurrent > 0)
	{
		talkerFriend = target;
	}

	if (talkerFriend != nil) {

		NSString *message = [NSString stringWithFormat:[FDLocalString message:5], talkerFriend.lastGainedExperience];
		FDTalkActivity *talk = [[FDTalkActivity alloc] initWithCreature:talkerFriend Message:message Layer:messageLayer];
		[self appendToMainActivity:talk];
		[talk release];

		NSString *levelUpMsg = [talkerFriend updateExpAndLevelUp];
		if (levelUpMsg != nil) {

			TalkMessage *message = [[TalkMessage alloc] initWithCreature:talkerFriend Message:levelUpMsg];
			[self appendToMainActivityMethod:@selector(show:) Param1:messageLayer Param2:nil Obj:message];
			// [message show:messageLayer];
		}

		for (ItemDefinition *dropItem in dropItemList) {
			NSString *message = [NSString stringWithFormat:[FDLocalString message:21], dropItem.name];
			FDTalkActivity *talk = [[FDTalkActivity alloc] initWithCreature:talkerFriend Message:message Layer:messageLayer];
			[self appendToMainActivity:talk];
			[talk release];
		}

		if (cannotCarryMore) {
			FDTalkActivity *talk = [[FDTalkActivity alloc] initWithCreature:talkerFriend Message:[FDLocalString message:22] Layer:messageLayer];
			[self appendToMainActivity:talk];
			[talk release];
		}
	}

	NSLog(@"Notify.");

	// Check whether the important game event is triggered
	[self appendToMainActivityMethod:@selector(isNotified) Param1:nil Param2:nil Obj:eventListener];

	NSLog(@"End turn.");

	//End turn
	[self appendToMainActivityMethod:@selector(creatureActionDone:) Param1:creature Param2:nil Obj:self];

	[targets release];
	[dropItemList release];
}

-(void) magicFrom:(FDCreature *)creature TargetPos:(CGPoint)position Id:(int)magicId
{
	NSLog(@"Magic %d from %d to pos (%f, %f)", magicId, [creature getIdentifier], position.x, position.y);

	MagicDefinition *magic = [[DataDepot depot] getMagicDefinition:magicId];
	[creature updateMP:-magic.mpCost];
	[creature updateHP:0];

	BOOL areBadGuys = ([creature getCreatureType] == CreatureType_Friend && (magic.magicType == MagicType_Attack || magic.magicType == MagicType_Offensive))
					|| ([creature getCreatureType] == CreatureType_Enemy && (magic.magicType == MagicType_Recover || magic.magicType == MagicType_Defensive));

	NSMutableArray *targets = [field getCreaturesAt:position Range:magic.effectRange BadGuys:areBadGuys];
	NSLog(@"Target Creature count: %d", [targets count]);

	MagicalInformation *mInfo = [GameFormula dealWithMagic:magicId From:creature Target:targets Field:field];

	if (magic.magicType == MagicType_Attack) {
		CGPoint pos = [field getObjectPos:creature];
		int backgroundImageId = [field getBackgroundPicId:pos];
		MagicalScene *scene = [[MagicalScene alloc] initWithMagic:magicId Subject:creature Targets:targets Information:mInfo Background:backgroundImageId];
		[[CCDirector sharedDirector] pushScene: [CCTransitionFade transitionWithDuration:0.5 scene:scene]];
		[scene start];
		[scene setPostMethod:@selector(postFightAction:Targets:) param1:creature param2:targets Obj:self];
	} else {
		[self appendToMainActivityMethod:@selector(postFightAction:Targets:) Param1:creature Param2:targets Obj:self];
	}
}

/*
-(void) magicFrom:(FDCreature *)creature Targets:(NSArray *)targets Id:(int)magicId
{
	NSLog(@"Magic from %d to %d enemies", [creature getIdentifier], [targets count]);

	MagicDefinition *magic = [[DataDepot depot] getMagicDefinition:magicId];
	[creature updateMP:-magic.mpCost];
	[creature updateHP:0];

	MagicalInformation *mInfo = [GameFormula dealWithMagic:magicId From:creature Target:targets Field:field];

	CGPoint pos = [field getObjectPos:creature];
	int backgroundImageId = [field getBackgroundPicId:pos];
	MagicalScene *scene = [[MagicalScene alloc] initWithMagic:magicId Subject:creature Targets:targets Information:mInfo Background:backgroundImageId];
	[[CCDirector sharedDirector] pushScene: [CCTransitionFade transitionWithDuration:0.5 scene:scene]];

	[scene start];

	[scene setPostMethod:@selector(postFightAction:Targets:) param1:creature param2:targets Obj:self];
}
*/

-(void) useItem:(FDCreature *)creature ItemIndex:(int)itemIndex Target:(FDCreature *)target
{
	NSLog(@"Use Item.");

	int itemId = [creature getItemId:itemIndex];
	UsableItemDefinition * itemDef = (UsableItemDefinition *)[[DataDepot depot] getItemDefinition:itemId];
	[itemDef usedBy:target];

	[creature.data removeItem:itemIndex];

	[self appendToMainActivityMethod:@selector(creatureActionDone:) Param1:creature Param2:nil Obj:self];
}

-(void) giveItem:(FDCreature *)creature ItemIndex:(int)itemIndex Target:(FDCreature *)target
{
	NSLog(@"Gave Item.");

	int itemId = [creature getItemId:itemIndex];

	[creature.data removeItem:itemIndex];
	[target addItem:itemId];

	creature.hasActioned = TRUE;
}

-(void) exchangeItem:(FDCreature *)creature ItemIndex:(int)itemIndex Target:(FDCreature *)target ItemIndex:(int)backItemIndex
{
	NSLog(@"Exchange Item.");

	int itemId = [creature getItemId:itemIndex];
	int backItemId = [target getItemId:backItemIndex];

	[creature.data removeItem:itemIndex];
	[target.data removeItem:backItemIndex];

	[target addItem:itemId];
	[creature addItem:backItemId];

	creature.hasActioned = TRUE;
}

-(void) pickUpTreasure:(FDCreature *) creature
{
	FDTreasure *treasure = [field getTreasureAt:[field getObjectPos:creature]];

	if (treasure == nil || [treasure hasOpened]) {
		return;
	}

	NSLog(@"Creature picked up the treasure.");

	[treasure setOpened];
	ItemDefinition *item = [treasure getItem];

	// If the treasure is money, add to money
	if ([item isMoney]) {
		// Add to money
		money += [item getMoneyQuantity];
		return;
	}
	else {
		[creature.data.itemList addObject:[NSNumber numberWithInt:item.identifier]];
	}
}

-(void) exchangeTreasure:(FDCreature *)creature withItem:(int)itemIndex
{
	FDTreasure *treasure = [field getTreasureAt:[field getObjectPos:creature]];

	if (treasure == nil || [treasure hasOpened])
	{
		return;
	}

	NSLog(@"Exchange picked up the treasure.");

	ItemDefinition *item = [treasure getItem];

	// Note: the item could not be money

	[creature.data.itemList addObject:[NSNumber numberWithInt:item.identifier]];

	[treasure changeItemId:[[creature.data.itemList objectAtIndex:itemIndex] intValue]];

	[creature dropItem:itemIndex];
}

-(void) creatureActionDone:(FDCreature *)creature
{
	if (creature != nil) {

		creature.hasActioned = TRUE;

		[self appendToCurrentActivityMethod:@selector(creatureEndTurn:) Param1:creature Param2:nil Obj:self];
	}
}

-(void) creatureEndTurn:(FDCreature *)creature
{
	NSLog(@"End turn for creature %d", [creature getIdentifier]);

	// Recover some HP
	if (!creature.hasMoved && !creature.hasActioned) {
		int recoverHp = [GameFormula recoverHpFromRest:creature];

		NSLog(@"Recover HP %d for creature.", recoverHp);
		[creature updateHP:recoverHp];
	}

	[creature endTurn];

	if ([creature getCreatureType] == CreatureType_Enemy) {
		//[enemyAiHandler isNotified];
		[self appendToCurrentActivityMethod:@selector(isNotified) Param1:nil Param2:nil Obj:enemyAiHandler];
	}
	if ([creature getCreatureType] == CreatureType_Npc) {
		//[npcAiHandler isNotified];
		[self appendToCurrentActivityMethod:@selector(isNotified) Param1:nil Param2:nil Obj:npcAiHandler];
	}

	[self appendToCurrentActivityMethod:@selector(checkEndTurn) Param1:nil Param2:nil Obj:self];
}

-(void) creaturePendAction:(FDCreature *)creature
{
	NSLog(@"Pend Action for creature %d", [creature getIdentifier]);

	[creature pendAction];

	if ([creature getCreatureType] == CreatureType_Enemy) {
		//[enemyAiHandler isNotified];
		[self appendToCurrentActivityMethod:@selector(isNotified) Param1:nil Param2:nil Obj:enemyAiHandler];
	}
	if ([creature getCreatureType] == CreatureType_Npc) {
		//[npcAiHandler isNotified];
		[self appendToCurrentActivityMethod:@selector(isNotified) Param1:nil Param2:nil Obj:npcAiHandler];
	}
}

-(void) checkEndTurn
{
	if (turnType == TurnType_Friend)
	{
		for (FDCreature *creature in [field getFriendList]) {
			if (!creature.hasActioned && creature.data.statusFrozen <= 0) {
				return;
			}
		}
		[self endFriendTurn];
	}
	else if	(turnType == TurnType_NPC)
	{
		for (FDCreature *creature in [field getNpcList]) {
			if (!creature.hasActioned && creature.data.statusFrozen <= 0) {
				return;
			}
		}
		[self endNpcTurn];
	}
	else if (turnType == TurnType_Enemy)
	{
		for (FDCreature *creature in [field getEnemyList]) {
			if (!creature.hasActioned && creature.data.statusFrozen <= 0) {
				return;
			}
		}
		[self endEnemyTurn];
	}
}

-(void) startFriendTurn
{
	NSLog(@"Start Friend Turn");

	turnType = TurnType_Friend;

	// reset all creatures
	[field startNewTurn];

	NSLog(@"Stared NewTurn %d", [self isInteractiveBusy]);
	if ([self isInteractiveBusy]) {
		NSLog(@"isInteractiveBusy");
	}

	// Show the turn Number
	[self appendToMainActivityMethod:@selector(showTurnInfo) Param1:nil Param2:nil];

	// Set Cursor the first friend
	FDCreature *firstFriend = [[field getFriendList] objectAtIndex:0];
	CGPoint pos = [field getObjectPos:firstFriend];
	[self appendToMainActivityMethod:@selector(setCursorObjTo:) Param1:[FDPosition positionX:pos.x Y:pos.y] Param2:nil Obj:field];
}

-(void) endFriendTurn
{
	NSLog(@"End Friend Turn");

	// End all friends
	for (FDCreature *friend in [field getFriendList]) {
		[self creatureEndTurn:friend];
	}

	// Trigger the friend turn actions
	[eventListener isNotified];
	//[npcAiHandler isNotified];

	// To Avoid seeing so many disabled friends, enable them just after user interaction finished.
	for (FDCreature *friend in [field getFriendList]) {
		[friend startTurn];
	}

	[self appendToMainActivityMethod:@selector(startNpcTurn) Param1:nil Param2:nil];
}

-(void) startNpcTurn
{
	NSLog(@"Start Npc Turn");

	turnType = TurnType_NPC;

	// If there is no NPC
	if ([[field getNpcList] count] > 0) {
		turnType = TurnType_NPC;
		[npcAiHandler isNotified];
	}
	else {
		[self endNpcTurn];
	}
}

-(void) endNpcTurn
{
	NSLog(@"End Npc Turn");

	// End all Npcs
	for (FDCreature *npc in [field getNpcList]) {
		[npc endTurn];
	}

	// Trigger the Npc turn actions
	[eventListener isNotified];

	// To Avoid seeing so many disabled NPCs, enable them just after user interaction finished.
	for (FDCreature *npc in [field getNpcList]) {
		[npc startTurn];
	}

	[self appendToMainActivityMethod:@selector(startEnemyTurn) Param1:nil Param2:nil];
}

-(void) startEnemyTurn
{
	NSLog(@"Start Enemy Turn");

	turnType = TurnType_Enemy;
	[enemyAiHandler isNotified];

}

-(void) endEnemyTurn
{
	NSLog(@"End Enemy Turn");

	// End all enemies
	for (FDCreature *enemy in [field getEnemyList]) {
		[enemy endTurn];
	}

	// Trigger Events
	[eventListener isNotified];

	// Status checking
	for (FDCreature *c in [field getFriendList]) {
		[c.data updateStatusInTurn];
	}
	for (FDCreature *c in [field getNpcList]) {
		[c.data updateStatusInTurn];
	}
	for (FDCreature *c in [field getEnemyList]) {
		[c.data updateStatusInTurn];
	}

	// Show new turn
	turnNo ++;
	[self appendToMainActivityMethod:@selector(startFriendTurn) Param1:nil Param2:nil];
}

-(void) startNewGame:(ChapterRecord *)info
{
	//[field loadMapData:level];
	chapterId = info.chapterId;
	turnNo = 0;
	money = info.money;

	// Load Friends
	for(CreatureRecord *record in [info friendRecords])
	{
		FDFriend *creature = [[FDFriend alloc] initWithDefinition:record.definitionId Id:record.creatureId Data:record.data];

		if (creature.data.hpCurrent > 0) {
			[[field getUnsettledCreatureList] addObject:creature];
		} else {
			[[field getDeadCreatureList] addObject:creature];
		}

		[creature release];
	}

	[self runGame];
}

-(void) loadGame:(BattleRecord *)info // withEvents:(BOOL)loadEvents
{
	//[field loadMapData:info.levelNo];

	chapterId = info.chapterId;
	turnNo = info.turnNo;
	money = info.money;

	// Load Creatures
	for(CreatureRecord *record in [info friendRecords])
	{
		FDFriend *creature = [[FDFriend alloc] initWithDefinition:record.definitionId Id:record.creatureId Data:record.data];
		[field addFriend:creature Position:record.location];
		[creature release];

	}

	for(CreatureRecord *record in [info enemyRecords])
	{
		FDEnemy *creature = [[FDEnemy alloc] initWithDefinition:record.definitionId Id:record.creatureId Data:record.data];
		[field addEnemy:creature Position:record.location];
		[creature release];

	}
	for(CreatureRecord *record in [info npcRecords])
	{
		FDNpc *creature = [[FDNpc alloc] initWithDefinition:record.definitionId Id:record.creatureId Data:record.data];
		[field addNpc:creature Position:record.location];
		[creature release];

	}

	for(CreatureRecord *record in [info deadCreatureRecords])
	{
		FDCreature *creature;

		switch (record.creatureType) {
			case CreatureType_Friend:
				creature = [[FDFriend alloc] initWithDefinition:record.definitionId Id:record.creatureId Data:record.data];
				break;
			case CreatureType_Enemy:
				creature = [[FDEnemy alloc] initWithDefinition:record.definitionId Id:record.creatureId Data:record.data];
				break;
			case CreatureType_Npc:
				creature = [[FDNpc alloc] initWithDefinition:record.definitionId Id:record.creatureId Data:record.data];
				break;
			default:
				break;
		}
		[[field getDeadCreatureList] addObject:creature];
		[creature release];
	}

	for (TreasureRecord *record in [info treasureRecords]) {
		FDTreasure *treasure = [field getTreasureAt:record.location];
		if (treasure != nil) {

			if (record.hasOpened) {
				[treasure setOpened];
			}
			else {
				[treasure changeItemId:record.itemId];
			}
		}
	}

	// Load the active events
	if (!info.withAllEvents) {
		[eventListener loadState:[info activeEventIds]];
	}

	turnNo --;	// TODO: bug

	[self runGame];
}

-(void) runGame
{
	turnType = TurnType_Friend;

	// Trigger Events
	[eventListener isNotified];

	// Show new turn
	turnNo ++;
	[self appendToMainActivityMethod:@selector(startFriendTurn) Param1:nil Param2:nil];
}

-(void) saveGame
{
	NSLog(@"Saving Game");

	BattleRecord *info = [[BattleRecord alloc] initWithChapter:chapterId];
	info.turnNo = turnNo;
	info.money = money;

	for(FDCreature *creature in [field getFriendList])
	{
		CreatureRecord *record = [field generateCreatureRecord:creature];
		[[info friendRecords] addObject:record];
	}

	for(FDCreature *creature in [field getEnemyList])
	{
		CreatureRecord *record = [field generateCreatureRecord:creature];
		[[info enemyRecords] addObject:record];
	}

	for(FDCreature *creature in [field getNpcList])
	{
		CreatureRecord *record = [field generateCreatureRecord:creature];
		[[info npcRecords] addObject:record];
	}

	for(FDCreature *creature in [field getDeadCreatureList])
	{
		CreatureRecord *record = [field generateCreatureRecord:creature];
		[[info deadCreatureRecords] addObject:record];
	}

	NSMutableArray *treasureList = [field getTreasureList];
	for (FDTreasure *treasure in treasureList) {
		TreasureRecord *record = [field generateTreasureRecord:treasure];
		[[info treasureRecords] addObject:record];
	}

	NSMutableArray *activeEventIds = [eventListener saveState];
	[[info activeEventIds] addObjectsFromArray:activeEventIds];

	GameRecord *gameRecord = [[GameRecord readFromSavedFile] retain];
	[gameRecord setBattleRecord:info];
	[gameRecord saveRecord];

	[info release];
	[gameRecord release];
}

-(ChapterRecord *) composeChapterRecord
{
	ChapterRecord *record = [[ChapterRecord alloc] initWithChapter:chapterId + 1];
	record.money = money;

	for(FDCreature *creature in [field getFriendList])
	{
		CreatureRecord *r = [field generateCreatureRecord:creature];
		[r.data recoverHealth];
		[r.data clearAllStatus];

		[[record friendRecords] addObject:r];
	}

	for (FDCreature *creature in [field getDeadCreatureList]) {

		if ([creature getCreatureType] == CreatureType_Friend) {
			CreatureRecord *r = [field generateCreatureRecord:creature];
			[r.data recoverHealth];
			[r.data clearAllStatus];

			[[record friendRecords] addObject:r];
		}
	}

	[[record friendRecords] sortUsingSelector:@selector(compareRecords:)];

	return record;
}

-(void) showItemStatus:(FDCreature *)creature
{
	NSLog(@"Show creature item status");

	ItemBox *ibox = [[ItemBox alloc] initWithCreature:creature Type:ItemOperatingType_ShowOnly];
	[ibox show:messageLayer];
}

-(void) showMagicStatus:(FDCreature *)creature
{
	NSLog(@"Show creature magic status");

	MagicBox *box = [[MagicBox alloc] initWithCreature:creature Type:MagicOperatingType_ShowOnly];
	[box show:messageLayer];
}

-(void) showItemStatusAsync:(FDCreature *)creature
{
	[self appendToCurrentActivityMethod:@selector(showItemStatus:) Param1:creature Param2:nil];
}

-(void) showMagicStatusAsync:(FDCreature *)creature
{
	[self appendToCurrentActivityMethod:@selector(showMagicStatus:) Param1:creature Param2:nil];
}

-(void) showTurnInfo
{
	TurnInfo *info = [[TurnInfo alloc] initWithNo:turnNo];
	[info show:messageLayer];
	[info release];
}

-(void) showChapterInfo
{
	ChapterInfo *info = [[ChapterInfo alloc] init];

	[info setFriendCount:[[field getFriendList] count] EnemyCount:[[field getEnemyList] count] NpcCount:[[field getNpcList] count]];
	[info setChapterNo:chapterId TurnNo:turnNo];
	[info setCondition:chapterId];
	[info setMoney:money];

	[info show:messageLayer];
	[info release];
}

-(void) gameOver
{
	// [self clearAllActivity];

	GameOverScene *scene = [GameOverScene node];
	[[CCDirector sharedDirector] pushScene: [CCTransitionFade transitionWithDuration:0.5 scene:scene]];
}

-(void) gameWin
{
	[self clearAllActivity];
	NSLog(@"Game Win.");

	//ChapterRecord *record = [ChapterRecord sampleRecord];
	ChapterRecord *record = [self composeChapterRecord];

	if (chapterId < 8) {
		VillageScene *scene = [VillageScene node];
		[scene loadWithRecord:record];
		[[CCDirector sharedDirector] pushScene: [CCTransitionFade transitionWithDuration:1.5 scene:scene]];
	} else {
		GameWinScene *scene = [GameWinScene node];
		[[CCDirector sharedDirector] pushScene: [CCTransitionFade transitionWithDuration:1.5 scene:scene]];
	}
}

-(void) gameQuit
{
	NSLog(@"Game Quit.");

	[self clearAllActivity];

	TitleScene *scene = [TitleScene node];
	[[CCDirector sharedDirector] pushScene: [CCTransitionFade transitionWithDuration:1.0 scene:scene]];
}

-(void) gameContinue
{
	GameRecord *record = [GameRecord readFromSavedFile];
	BattleRecord *info = [record.battleRecord retain];
	//[record saveRecord];

	MainGameScene *mainGame = [MainGameScene node];
	[mainGame loadWithInfo:info];

	[[CCDirector sharedDirector] pushScene: [CCTransitionFade transitionWithDuration:1.0 scene:mainGame]];

	[info release];
}

-(int) getTurnNumber
{
	return turnNo;
}

-(TurnType) getTurnType
{
	return turnType;
}

-(BOOL) isInteractiveBusy
{
	for(FDActivity *activity in activityList)
	{
		if ([activity blocksInteraction]) {
			return TRUE;
		}
	}
	return FALSE;
}

-(BOOL) isLocked
{
	return isLocked;
}

-(void) setEventListener:(IListener *)listener
{
	eventListener = [listener retain];
}

-(void) setEnemyAiHandler:(IListener *)listener
{
	enemyAiHandler = [listener retain];
}

-(void) setNpcAiHandler:(IListener *)listener
{
	npcAiHandler = [listener retain];
}

-(void) showTestData
{
	FDActivity *a = [activityList objectAtIndex:[activityList count]-1];
	while (a !=nil) {

		//NSLog([a debugInfo]);
		a = [a getNext];
	}
}

-(void) dealloc
{
	[activityList release];

	if (eventListener != nil) {
		[eventListener release];
		eventListener = nil;
	}

	if (enemyAiHandler != nil) {
		[enemyAiHandler release];
		enemyAiHandler = nil;
	}

	if (npcAiHandler != nil) {
		[npcAiHandler release];
		npcAiHandler = nil;
	}

	[super dealloc];

}

@end


text:
package reka.email.smtp;

import static reka.util.Util.unchecked;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

import reka.data.MutableData;
import reka.flow.ops.Operation;
import reka.flow.ops.OperationContext;
import reka.util.StringWithVars;

public class SmtpSendOperation implements Operation {

	private final String host, username, password;
	private final int port;

	private final StringWithVars from, to, replyTo, subject, body;

	public SmtpSendOperation(
			String host,
			int port,
			String username,
			String password,
			StringWithVars from,
			StringWithVars to,
			StringWithVars replyTo,
			StringWithVars subject,
			StringWithVars body) {
		this.host = host;
		this.port = port;
		this.username = username;
		this.password = password;
		this.from = from;
		this.to = to;
		this.replyTo = replyTo;
		this.subject = subject;
		this.body = body;
	}

	@Override
	public void call(final MutableData data, OperationContext ctx) {

		try {

			SimpleEmail email = new SimpleEmail();

			email.setHostName(host);
			email.setSmtpPort(port);

			if (username != null && password != null) {
				email.setAuthentication(username, password);
			}

			email.setSubject(subject.apply(data));
			email.setFrom(from.apply(data));
			email.addTo(to.apply(data));

			if (replyTo != null) {
				email.addReplyTo(replyTo.apply(data));
			}

			email.setMsg(body.apply(data));

			email.send();

			/*
			return executor.submit(new Callable<MutableData>(){

				@Override
				public MutableData call() throws Exception {
					email.send();
					return data;
				}

			});
			*/

		} catch (EmailException e) {
			throw unchecked(e);
		}

	}

}


text:
package backend

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
)

type Backend interface {
	LatestVersion(checkForSuccessFile bool) (string, error)
	Download(version string, destPath string) error
	DisplayPath(version string) string
}

// A basic backend for the local filesystem
type LocalBackend struct {
	path string
}

func NewLocalBackend(path string) *LocalBackend {
	return &LocalBackend{path}
}

func (lb *LocalBackend) LatestVersion(checkForSuccess bool) (string, error) {
	files, err := ioutil.ReadDir(lb.path)
	if err != nil {
		return "", err
	}

	// ReadDir returns sorted paths. pick the last directory
	for i := len(files) - 1; i >= 0; i-- {
		if files[i].IsDir() {
			name := files[i].Name()
			fullPath := filepath.Join(lb.path, name)
			if !checkForSuccess || lb.checkForSuccessFile(fullPath) {
				return name, nil
			}
		}
	}

	return "", fmt.Errorf("No valid subdirectories in %s!", lb.path)
}

func (lb *LocalBackend) Download(version string, destPath string) error {
	return nil // noop
}

func (lb *LocalBackend) DisplayPath(version string) string {
	return filepath.Join(lb.path, version)
}

func (lb *LocalBackend) checkForSuccessFile(path string) bool {
	if _, err := os.Stat(filepath.Join(path, "_SUCCESS")); err == nil {
		return true
	} else {
		return false
	}
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.wan.demoweather.ChooseAreaFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>


text:
liblcf is a library to handle RPG Maker 2000 and 2003 game data.
It can read and write LCF and XML files.

liblcf is part of the EasyRPG Project. More information is available
at the project website: https://easyrpg.org/

## Documentation

Documentation is available at the documentation wiki: https://wiki.easyrpg.org

## Requirements

- [Expat] for XML reading support.
- [ICU] for character encoding detection and conversion (recommended).

## Source code

liblcf development is hosted by GitHub, project files are available
in this git repository:

https://github.com/EasyRPG/liblcf

Released versions are also available at our Download Archive:

https://easyrpg.org/downloads/

## Building

### Autotools Makefile method:

Building requirements:

- pkg-config
- GNU make

Step-by-step instructions:

    tar xf liblcf-0.7.0.tar.xz # unpack the tarball
    cd liblcf-0.7.0            # enter in the package directory
    ./configure --prefix /usr  # find libraries, set options
    make                       # compile the library
    sudo make install          # install system-wide

Additional building requirements when using the source tree (git):

- autoconf >= 2.69
- automake >= 1.11.4
- libtool

To generate the "configure" script, run before following the above section:

    autoreconf -i

Read more detailed instructions at:

https://wiki.easyrpg.org/development/compiling/liblcf/autotools

### CMake method:

Building requirements:

- pkg-config (Not on Windows)
- CMake >= 3.10

Step-by-step instructions:

    tar xf liblcf-0.7.0.tar.xz            # unpack the tarball
    cd liblcf-0.7.0                       # enter in the package directory
    cmake . -DCMAKE_BUILD_TYPE=Release    # configure project
    cmake --build .                       # compile the library
    sudo cmake --build . --target install # install system-wide

Read more detailed instructions at:

https://wiki.easyrpg.org/development/compiling/liblcf/cmake

CMake is the only supported way to build liblcf for Windows. All dependencies
must be installed with [vcpkg].

## Tools

### LCF2XML

LCF2XML is a small tool to convert RPG Maker 2000 and 2003 data format
(LMU, LMT, LDB, LSD, ...) to XML and vice-versa.

## Bug reporting

Available options:

* File an issue at https://github.com/EasyRPG/liblcf/issues
* Open a thread at https://community.easyrpg.org/
* Chat with us via IRC: [#easyrpg at irc.libera.chat]

## License

liblcf is Free/Libre Open Source Software, released under the MIT License.
See the file [COPYING] for copying conditions.

### 3rd party software

liblcf includes code of the following 3rd party software:

- [inih] under New BSD license.
- [string-view-lite] and [span-lite] under Boost Software License, Version 1.0.

See the source code comment headers for license details.

[Expat]: https://libexpat.github.io
[ICU]: http://icu-project.org
[vcpkg]: https://github.com/Microsoft/vcpkg
[#easyrpg at irc.libera.chat]: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat/#easyrpg?nick=rpgguest??
[COPYING]: COPYING
[inih]: https://github.com/benhoyt/inih
[string-view-lite]: https://github.com/martinmoene/string-view-lite
[span-lite]: https://github.com/martinmoene/span-lite


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Soc. bot. Genève, 2 sér. 4: 301 (1912)

#### Original name
Ciliciopodium hyalinum Dasz.

### Remarks
null


text:
chrome.extension.sendMessage({}, function(response) {
	var readyStateCheckInterval = setInterval(function() {
	if (document.readyState === "complete") {
		clearInterval(readyStateCheckInterval);

		// ----------------------------------------------------------
		// This part of the script triggers when page is done loading
		console.log("Hello. QuizTeX is working on this site.");
		// ----------------------------------------------------------

		var parse = /\$.+\$/;

		$('.qDef').each(function(i, obj) {
    		var content = $(obj).text().match(parse);
    		if(content)
    			content = content[0]
    		if(content){
    			content = content.substring(1, content.length-1);
    			$(obj).html("");
			}
		});

		$('.qWord').each(function(i, obj) {
    		var content = $(obj).text().match(parse);
    		if(content)
    			content = content[0]
    		if(content){
    			content = content.substring(1, content.length-1);
    			$(obj).html("");
			}
		});

	}
	}, 10);
});


text:
<?php
define('DB_HOST', 'localhost:3306');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'semestralka');


text:
#ifndef _w32_net_tcp_Stream_hpp__
#define _w32_net_tcp_Stream_hpp__

// Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/*!
 * @file w32.net.tcp/Stream.hpp
 * @author Andre Caron
 */

#include "__configure__.hpp"
#include <w32.net/StreamSocket.hpp>
#include <w32.net.ipv4/EndPoint.hpp>
#include <w32.net.tcp/Listener.hpp>

namespace w32 { namespace io {

    class InputStream;
    class OutputStream;
    class Stream;

} }

namespace w32 { namespace net { namespace tcp {

    /*!
     * @ingroup w32-net
     * @brief Transfer Control Protocol, connection socket.
     */
    class Stream :
        public StreamSocket
    {
        /* nested types. */
    public:
        typedef ::LPFN_CONNECTEX ConnectEx;

        /* class methods. */
    public:
        static ConnectEx lookup_connect_ex (::SOCKET handle);

        /* construction. */
    public:
        /*!
         * @brief Wrap an existing TCP socket stream handle.
         */
        explicit Stream ( Handle handle );

        /*!
         * @brief Create an unconnected socket (for async connect/accept).
         */
        Stream ();

            /*!
             * @brief Wait for a connection (server side).
             */
        Stream ( Listener& listener );
        Stream ( Listener& listener, ipv4::EndPoint& peer );

            /*!
             * @brief Connect to a server (client side).
             */
        Stream ( const ipv4::EndPoint& peer );

        /* methods. */
    public:
        ipv4::EndPoint host () const;
        ipv4::EndPoint peer () const;

        ConnectEx connect_ex () const;

        /* operators . */
    public:
        operator io::Stream () const;
        operator io::InputStream () const;
        operator io::OutputStream () const;
    };

} } }

#endif /* _w32_net_tcp_Stream_hpp__ */


text:
import pytest

from awx.main.access import (
    ProjectAccess,
)

@pytest.mark.django_db
@pytest.mark.parametrize("role", ["admin_role", "project_admin_role"])
def test_access_admin(role, organization, project, user):
    a = user('admin', False)
    project.organization = organization

    role = getattr(organization, role)
    role.members.add(a)

    access = ProjectAccess(a)
    assert access.can_read(project)
    assert access.can_add(None)
    assert access.can_add({'organization': organization.id})
    assert access.can_change(project, None)
    assert access.can_change(project, {'organization': organization.id})
    assert access.can_admin(project, None)
    assert access.can_admin(project, {'organization': organization.id})
    assert access.can_delete(project)


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="edu.gatech.seclass.Weight" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="122dp"
        android:onClick="sendMessage"
        android:text="Pounds to Kilograms" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="42dp"
        android:onClick="sendMessage"
        android:text="Kilograms to Pounds" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="66dp"
        android:text="Choose an option below:"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>


text:
package de.hpi.bpt.chimera.model.fragment.bpmn.gateway;

import javax.persistence.Entity;

import de.hpi.bpt.chimera.model.fragment.bpmn.AbstractControlNode;

@Entity
public class AbstractGateway extends AbstractControlNode {

}


text:
package com.thinkbiganalytics.kylo.catalog.spark;

import com.thinkbiganalytics.kylo.catalog.api.KyloCatalogDataSetAccess;

import java.util.List;
import java.util.Map;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import scala.collection.JavaConversions;
import scala.collection.Seq;

/**
 * A skeletal implementation of {@link KyloCatalogDataSetAccess} that provides default implementations for several methods.
 *
 * @param <R> builder type
 */
@SuppressWarnings("unchecked")
public abstract class AbstractKyloCatalogDataSetAccess<R extends KyloCatalogDataSetAccess> implements KyloCatalogDataSetAccess<R> {

    @Nonnull
    @Override
    public final R addFiles(@Nullable final List<String> paths) {
        if (paths != null) {
            for (final String path : paths) {
                addFile(path);
            }
        }
        return (R) this;
    }

    @Nonnull
    @Override
    public final R addFiles(@Nullable final Seq<String> paths) {
        if (paths != null) {
            addFiles(JavaConversions.seqAsJavaList(paths));
        }
        return (R) this;
    }

    @Nonnull
    @Override
    public final R addJars(@Nullable final Seq<String> paths) {
        if (paths != null) {
            addJars(JavaConversions.seqAsJavaList(paths));
        }
        return (R) this;
    }

    @Nonnull
    @Override
    public final R option(@Nonnull final String key, final boolean value) {
        return option(key, Boolean.toString(value));
    }

    @Nonnull
    @Override
    public final R option(@Nonnull final String key, final double value) {
        return option(key, Double.toString(value));
    }

    @Nonnull
    @Override
    public final R option(@Nonnull final String key, final long value) {
        return option(key, Long.toString(value));
    }

    @Nonnull
    @Override
    public final R options(@Nullable final Map<String, String> options) {
        if (options != null) {
            for (final Map.Entry<String, String> entry : options.entrySet()) {
                option(entry.getKey(), entry.getValue());
            }
        }
        return (R) this;
    }

    @Nonnull
    @Override
    public final R options(@Nullable final scala.collection.Map<String, String> options) {
        if (options != null) {
            options(JavaConversions.mapAsJavaMap(options));
        }
        return (R) this;
    }
}