text:
<?php

##|+PRIV
##|*IDENT=page-status-carp
##|*NAME=Status: CARP
##|*DESCR=Allow access to the 'Status: CARP' page.
##|*MATCH=status_carp.php*
##|-PRIV

require_once("guiconfig.inc");
require_once("globals.inc");

unset($interface_arr_cache);
unset($interface_ip_arr_cache);

function find_ipalias($carpif) {
	global $config;

	$ips = array();
	foreach ($config['virtualip']['vip'] as $vip) {
		if ($vip['mode'] != "ipalias") {
			continue;
		}
		if ($vip['interface'] != $carpif) {
			continue;
		}
		$ips[] = "{$vip['subnet']}/{$vip['subnet_bits']}";
	}

	return ($ips);
}

$status = get_carp_status();

if ($_POST['carp_maintenancemode'] != "") {
	if (!isset($config["virtualip_carp_maintenancemode"])) {
		$maintenancemode = true;
		$savemsg = gettext("Entering Persistent CARP Maintenance Mode.");
	} else {
		$maintenancemode = false;
		$savemsg = gettext("Leaving Persistent CARP Maintenance Mode.");
	}
	/* allow to switch to Persistent Maintenance Mode if CARP is disabled
	 * see https://redmine.pfsense.org/issues/11727 */
	interfaces_carp_set_maintenancemode($maintenancemode);
	if ($status == 0) {
		$_POST['disablecarp'] = "off";
	}
}

if ($_POST['disablecarp'] != "") {
	init_config_arr(array('virtualip', 'vip'));
	$viparr = &$config['virtualip']['vip'];
	if ($status != 0) {
		set_single_sysctl('net.inet.carp.allow', '0');
		foreach ($viparr as $vip) {
			if ($vip['mode'] != "carp" && $vip['mode'] != "ipalias")
				continue;
			if ($vip['mode'] == "ipalias" && substr($vip['interface'], 0, 4) != "_vip")
				continue;
			interface_vip_bring_down($vip);
		}
		$savemsg = sprintf(gettext("%s IPs have been disabled. Please note that disabling does not survive a reboot and some configuration changes will re-enable."), $carp_counter);
		$status = 0;
	} else {
		$savemsg .= gettext("CARP has been enabled.");
		foreach ($viparr as $vip) {
			switch ($vip['mode']) {
				case "carp":
					interface_carp_configure($vip);
					break;
				case 'ipalias':
					if (substr($vip['interface'], 0, 4) == "_vip") {
						interface_ipalias_configure($vip);
					}
					break;
			}
		}
		interfaces_sync_setup();
		set_single_sysctl('net.inet.carp.allow', '1');
		$status = 1;
	}
}

$carp_detected_problems = get_single_sysctl("net.inet.carp.demotion");

if (!empty($_POST['resetdemotion'])) {
	set_single_sysctl("net.inet.carp.demotion", 0 - $carp_detected_problems);
	sleep(1);
	$carp_detected_problems = get_single_sysctl("net.inet.carp.demotion");
}

$pgtitle = array(gettext("Status"), gettext("CARP"));
$shortcut_section = "carp";

include("head.inc");
if ($savemsg) {
	print_info_box($savemsg, 'success');
}

$carpcount = 0;
foreach(config_get_path('virtualip/vip', []) as $carp) {
	if ($carp['mode'] == "carp") {
		$carpcount++;
		break;
	}
}

// If $carpcount > 0 display buttons then display table
// otherwise display error box and quit

if ($carpcount == 0) {
	print_info_box(gettext('No CARP interfaces have been defined.') . '
' .
				   '' .
				   gettext("High availability sync settings can be configured here.") .
				   '');
} else {
?>

<?=gettext("CARP Maintenance");?>

				<form action="status_carp.php" method="post">
<?php
	if ($status != 0) {
		$carp_enabled = true;
	} else {
		$carp_enabled = false;
	}

	// Sadly this needs to be here so that it is inside the form
	if ($carp_detected_problems != 0) {
		print_info_box(
			gettext("CARP has detected a problem and this unit has a non-zero demotion status.") .
			"
" .
			gettext("Check the link status on all interfaces configured with CARP VIPs and ") .
			sprintf(gettext('search the %1$sSystem Log%2$s for CARP demotion-related events.'), "", "") .
			"

" .
			'<button type="submit" class="btn btn-warning" name="resetdemotion" id="resetdemotion" value="' .
			gettext("Reset CARP Demotion Status") .
			'">' .
			gettext("Reset CARP Demotion Status") .
			'</button>',
			'danger'
		);
	}

?>
				<button type="submit" class="btn btn-warning" name="disablecarp" value="<?=($carp_enabled ? gettext("Temporarily Disable CARP") : gettext("Enable CARP"))?>" ><i class="fa fa-<?=($carp_enabled) ? 'ban' : 'check' ; ?> icon-embed-btn"><?=($carp_enabled ? gettext("Temporarily Disable CARP") : gettext("Enable CARP"))?></button>
				<button type="submit" class="btn btn-info" name="carp_maintenancemode" id="carp_maintenancemode" value="<?=(isset($config["virtualip_carp_maintenancemode"]) ? gettext("Leave Persistent CARP Maintenance Mode") : gettext("Enter Persistent CARP Maintenance Mode"))?>" ><?=(isset($config["virtualip_carp_maintenancemode"]) ? gettext("Leave Persistent CARP Maintenance Mode") : gettext("Enter Persistent CARP Maintenance Mode"))?></button>

<?=gettext('CARP Status')?>

							<?=gettext("Interface and VHID")?>
							<?=gettext("Virtual IP Address")?>
							<?=gettext("Status")?>

<?php
	foreach ($config['virtualip']['vip'] as $carp) {
		if ($carp['mode'] != "carp") {
			continue;
		}

		$icon = '';
		$vhid = $carp['vhid'];
		$status = get_carp_interface_status("_vip{$carp['uniqid']}");
		$aliases = find_ipalias("_vip{$carp['uniqid']}");

		if ($carp_enabled == false) {
			$icon = 'times-circle';
			$status = "DISABLED";
		} else {
			if ($status == "MASTER") {
				$icon = 'play-circle text-success';
			} else if ($status == "BACKUP") {
				$icon = 'pause-circle text-warning';
			} else if ($status == "INIT") {
				$icon = 'question-circle text-danger';
			}
		}
?>

						<?=convert_friendly_interface_to_friendly_descr($carp['interface'])?>@<?=$vhid?>

<?php
		printf("{$carp['subnet']}/{$carp['subnet_bits']}");
		for ($i = 0; $i < count($aliases); $i++) {
			printf("
{$aliases[$i]}");
		}
?>

						<i class="fa fa-<?=$icon?>"> <?=$status?>

<?php }?>

</form>

<?=gettext('State Synchronization Status')?>

		<?= gettext("State Creator Host IDs") ?>:

<?php
	$my_id = strtolower(ltrim(filter_get_host_id(), '0'));
	exec("/sbin/pfctl -vvss | /usr/bin/awk '/creatorid:/ {print $4;}' | /usr/bin/sort -u", $hostids);
	if (!is_array($hostids)) {
		$hostids = array();
	}
?>
<?php	foreach ($hostids as $hid):
		$hid = strtolower(ltrim($hid, '0')); ?>

				<?= $hid ?>
<?php		if ($hid == $my_id): ?>
				(<?= gettext("This node") ?>)
<?php		endif; ?>

<?php	endforeach; ?>

<?php
	print_info_box(sprintf(gettext(
		'When state synchronization is enabled and functioning properly the list of state creator host IDs will be identical on each node participating in state synchronization.%1$s%1$s' .
		'The state creator host ID for this node can be set to a custom value under System > High Avail Sync. ' .
		'If the state creator host ID has recently changed, the old ID will remain until all states using the old ID expire or are removed.'
		), '
'), 'info', false);
?>

<?php
}

include("foot.inc");


text:
<?php
// == Common Functions ==
// i18n alias function
function todolist_i18n($hash, $echo = false) {
  return i18n(TODOLIST_ID . '/' . $hash, $echo);
}

// Get the configuration object that we want to pass on to our JavaScript
function todolist_js_config($echo = false) {
  // Basic configuration to pass on
  $config = array(
    "api_url" => TODOLIST_APIURL,
    "js_base_url" => TODOLIST_JSURL,
    "i18n" => array(),
  );

  // Load all i18n hashes for current language  (using a language file we know exists)
  require(TODOLIST_PLUGINPATH . 'lang/en_US.php');

  foreach ($i18n as $hash => $string) {
    $config['i18n'][$hash] = todolist_i18n($hash);
  }

  if ($echo) {
    echo json_encode($config);
  } else {
    return $config;
  }
}

// Load a (.vue) component
function todolist_component($name) {
  $content = @file_get_contents(TODOLIST_PLUGINPATH . 'components/' . $name . '.vue');
  echo $content;
}

redpajama_set_name: RedPajamaGithub


text:
package be.seriousbusiness.brusselnieuws.rss.reader.model.mapper;

import java.io.IOException;
import java.net.MalformedURLException;

import org.dozer.Mapper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import be.seriousbusiness.brusselnieuws.rss.datastore.model.dto.impl.AuthorDTOImpl;
import be.seriousbusiness.brusselnieuws.rss.datastore.model.dto.impl.factory.AuthorDTOImplFactory;
import be.seriousbusiness.brusselnieuws.rss.reader.model.impl.AuthorImpl;
import be.seriousbusiness.brusselnieuws.rss.reader.model.impl.factory.AuthorImplFactory;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:config/test-brusselnieuws-rss-reader-model-dozer-config.xml")
public class AuthorDTOImplAuthorImplMapperTest {
	@Autowired(required=true)
	@Qualifier("brusselNieuwsRssReaderModelDozerBeanMapper")
	private Mapper mapper;

	@Test
	public void testAuthorDTOImplToAuthorImplMapping() throws IOException{
		final AuthorDTOImpl authorDTOImpl=AuthorDTOImplFactory.createBrusselNieuws();
		final AuthorImpl authorImpl=mapper.map(authorDTOImpl, AuthorImpl.class);
		Assert.assertEquals("The ids are not equal",authorDTOImpl.getId(),authorImpl.getId());
		Assert.assertEquals("The names are not equal",authorDTOImpl.getName().trim().toLowerCase(),authorImpl.getName());
	}

	@Test
	public void testAuthorImplToAuthorDTOImplMapping() throws IllegalArgumentException, MalformedURLException{
		final AuthorImpl authorImpl=AuthorImplFactory.createFMBrussel();
		final AuthorDTOImpl authorDTOImpl=mapper.map(authorImpl,AuthorDTOImpl.class);
		Assert.assertEquals("The ids are not equal",authorImpl.getId(),authorDTOImpl.getId());
		Assert.assertEquals("The names are not equal",authorImpl.getName(),authorDTOImpl.getName());
	}

}


text:
jui.define("chart.brush.polygon.scatter",
	[ "util.base", "util.math", "util.color", "chart.polygon.point" ],
	function(_, MathUtil, ColorUtil, PointPolygon) {

	/**
	 * @class chart.brush.polygon.scatter
	 * @extends chart.brush.polygon.core
	 */
	var PolygonScatterBrush = function() {
		this.createScatter = function(data, target, dataIndex, targetIndex) {
			var color = this.color(dataIndex, targetIndex),
				zkey = this.brush.zkey,
				r = this.brush.size / 2,
				x = this.axis.x(dataIndex),
				y = this.axis.y(data[target]),
				z = null;

			if(_.typeCheck("function", zkey)) {
				var zk = zkey.call(this.chart, data);
				z = this.axis.z(zk);
			} else {
				z = this.axis.z(data[zkey]);
			}

			if(color.indexOf("radial") == -1) {
				color = this.chart.color(
					"radial(40%,40%,100%,0%,0%) 0% " +
					ColorUtil.lighten(color, this.chart.theme("polygonScatterRadialOpacity")) +
					",70% " +
					color
				);
			}

			var p = new PointPolygon(x, y, z);
			this.calculate3d(p);

			var elem = this.chart.svg.circle({
				r: r * MathUtil.scaleValue(z, 0, this.axis.depth, 1, p.perspective),
				fill: color,
				"fill-opacity": this.chart.theme("polygonScatterBackgroundOpacity"),
				cx: p.vectors[0].x,
				cy: p.vectors[0].y
			});

			if(data[target] != 0) {
				this.addEvent(elem, dataIndex, targetIndex);
			}

			return elem;
		}

		this.draw = function() {
			var g = this.chart.svg.group(),
				datas = this.listData(),
				targets = this.brush.target;

			for(var i = 0; i < datas.length; i++) {
				for(var j = 0; j < targets.length; j++) {
					var p = this.createScatter(datas[i], targets[j], i, j);
					g.append(p);
				}
			}

			return g;
		}
	}

		PolygonScatterBrush.setup = function() {
		return {
			zkey: null,

			/** @cfg {Number} [size=7]  Determines the size of a starter. */
			size: 7,
			/** @cfg {Boolean} [clip=false] If the brush is drawn outside of the chart, cut the area. */
			clip: false
		};
	}

	return PolygonScatterBrush;
}, "chart.brush.polygon.core");


text:
@interface FetchMessageCommentsResponseProcessor : AsynchronousResponseProcessor
{
    id messageKey;
    id projectKey;
    id delegate;

    NSArray * commentKeys;
    NSArray * comments;
    NSArray * authors;
}

@property (nonatomic, copy, readonly) id messageKey;
@property (nonatomic, copy, readonly) id projectKey;
@property (nonatomic, assign, readonly) id delegate;

+ (id)processorWithMessageKey:(id)aMessageKey
                   projectKey:(id)aProjectKey
                     delegate:(id)aDelegate;

- (id)initWithMessageKey:(id)aMessageKey
              projectKey:(id)aProjectKey
                delegate:(id)aDelegate;

@end


text:
@implementation ILUtils

+ (NSString*)chompedString: (NSString*)orig {
    return [orig stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

+ (id)loadClassNamed: (NSString*)className {
    NSArray *nibEntries = @[];
    NSNib *nib          = [[NSNib alloc] initWithNibNamed: className bundle: [NSBundle mainBundle]];
    [nib instantiateWithOwner: nil topLevelObjects: &nibEntries];
    return [ILUtils firstObjectOf: nibEntries meetsBlock:^BOOL (id obj, NSUInteger idx) {
        if ([obj isKindOfClass: NSClassFromString(className)]) {
            return YES;
        }
        return NO;
    }];
}

+ (id)firstObjectOf:(NSArray *)array meetsBlock:(BOOL (^)(id obj, NSUInteger idx))block {
    __block id result = nil;
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (block(obj,idx)) {
            result = obj;
            *stop = 1;
        }
    }];
    return result;
}

@end


text:
local FoliageActor = Inherit(ObjectBase)

function FoliageActor:Ctor(Component, Index)
	self.m_Component = UInstancedStaticMeshComponent.Cast(Component)
	self.m_Index = Index
	local TransForm = FTransform.New()
	self.m_Component:GetInstanceTransform(Index, TransForm, true)
	self.m_Pos = TransForm:Break()
	self.m_Pos.Z = 200
end

function FoliageActor:K2_GetActorLocation()
	return self.m_Pos
end

function FoliageActor:OnDamage(DamageData)
	DamageData:GetFrom():GetPlayerController():RemoveFoliage(self.m_Component, self.m_Index)
	-- :RemoveFoliage(self.m_Component, Index)
	-- A_(, DamageData:GetAmount())
end
return FoliageActor


text:
import { Component, Input } from '@angular/core';

import { Player } from '../../../model/Player';
import { Game } from '../../../model/Game';

import { PlayerStatus } from '../../../enum/PlayerStatus';
import { GameStatus } from '../../../enum/GameStatus';

import { GameAnimation } from '../../../animations/GameAnimation';
import { PlaySelectAnimation } from '../../../animations/PlaySelectAnimation';

@Component({
  selector: 'play-table',
  templateUrl: './play-table.component.html',
  styleUrls: ['./play-table.component.css'],
  animations: [GameAnimation, PlaySelectAnimation]
})

export class PlayTableComponent {
  @Input() player: Player;
  @Input() otherPlayer: Player;
  @Input() game: Game;
  @Input() notice: string;
  @Input() playerNotice: string;

  PlayerStatus = PlayerStatus;
  GameStatus = GameStatus;

  JSON = JSON;

  isGameInProgress(): boolean {
    return this.game.gameStatus == GameStatus.IN_PROGRESS
      || this.game.gameStatus.toString() == GameStatus[GameStatus.IN_PROGRESS];
  }

  isGameDraw(): boolean {
    return this.game.gameStatus == GameStatus.DRAW
      || this.game.gameStatus.toString() == GameStatus[GameStatus.DRAW];
  }

  isPlayerWon(): boolean {
    return this.player.status == PlayerStatus.Won
      || this.player.status.toString() == PlayerStatus[PlayerStatus.Won];
  }

  isPlayerLost(): boolean {
    return this.player.status == PlayerStatus.Lost
      || this.player.status.toString() == PlayerStatus[PlayerStatus.Lost];
  }

  isPlayerOut(): boolean {
    return this.player.status == PlayerStatus.Out
      || this.player.status.toString() == PlayerStatus[PlayerStatus.Out];
  }
}


text:
#region copyright

/* * * * * * * * * * * * * * * * * * * * * * * * * */
/* Carl Zeiss IMT (IZfM Dresden)                   */
/* Softwaresystem PiWeb                            */
/* (c) Carl Zeiss 2020                             */
/* * * * * * * * * * * * * * * * * * * * * * * * * */

#endregion

namespace Zeiss.PiWeb.Api.Rest.Tests
{
	#region usings

	using System;
	using System.Collections.Generic;
	using System.Net;
	using System.Text;
	using System.Threading.Tasks;

	#endregion

	internal sealed class WebServer : IDisposable
	{
		#region members

		private readonly HttpListener _Listener = new HttpListener();
		private readonly IDictionary<string, Func<string>> _Responses = new Dictionary<string, Func<string>>();

		#endregion

		#region constructors

		private WebServer( int port )
		{
			var prefix = $"http://+:{port}/";
			_Listener.Prefixes.Add( prefix );
		}

		#endregion

		#region methods

		public static WebServer StartNew( int port )
		{
			var server = new WebServer( port );

			server.Start();

			return server;
		}

		private void Start()
		{
			_Listener.Start();

			Task.Run( async () =>
			{
				while( _Listener.IsListening )
				{
					var ctx = await _Listener.GetContextAsync();

					try
					{
						var rstr = CreateResponse( ctx.Request );
						var buf = Encoding.UTF8.GetBytes( rstr );
						ctx.Response.ContentLength64 = buf.Length;
						await ctx.Response.OutputStream.WriteAsync( buf, 0, buf.Length );
					}
					finally
					{
						ctx.Response.OutputStream.Close();
					}
				}
			} );
		}

		public void RegisterResponse( string uri, Func<string> response )
		{
			_Responses[ uri ] = response;
		}

		public void RegisterResponse( string uri, string response )
		{
			RegisterResponse( uri, () => response );
		}

		private string CreateResponse( HttpListenerRequest request )
		{
			if( _Responses.TryGetValue( request.RawUrl, out var response ) )
				return response();

			return string.Empty;
		}

		#endregion

		#region interface IDisposable

		public void Dispose()
		{
			_Listener.Stop();
			_Listener.Close();
		}

		#endregion
	}
}


text:
FactoryGirl.define do
  factory :nizza_property_option, :class => 'Nizza::PropertyOption' do
    property_id 1
code "MyString"
name "MyString"
position 1
  end

end


text:
#ifndef LOOPFILTER_ARM_H
#define LOOPFILTER_ARM_H

#include "vpx_config.h"

#if HAVE_ARMV6
extern prototype_loopfilter_block(vp8_loop_filter_mbv_armv6);
extern prototype_loopfilter_block(vp8_loop_filter_bv_armv6);
extern prototype_loopfilter_block(vp8_loop_filter_mbh_armv6);
extern prototype_loopfilter_block(vp8_loop_filter_bh_armv6);
extern prototype_simple_loopfilter(vp8_loop_filter_bvs_armv6);
extern prototype_simple_loopfilter(vp8_loop_filter_bhs_armv6);
extern prototype_simple_loopfilter(vp8_loop_filter_simple_horizontal_edge_armv6);
extern prototype_simple_loopfilter(vp8_loop_filter_simple_vertical_edge_armv6);

#if !CONFIG_RUNTIME_CPU_DETECT
#undef  vp8_lf_normal_mb_v
#define vp8_lf_normal_mb_v vp8_loop_filter_mbv_armv6

#undef  vp8_lf_normal_b_v
#define vp8_lf_normal_b_v vp8_loop_filter_bv_armv6

#undef  vp8_lf_normal_mb_h
#define vp8_lf_normal_mb_h vp8_loop_filter_mbh_armv6

#undef  vp8_lf_normal_b_h
#define vp8_lf_normal_b_h vp8_loop_filter_bh_armv6

#undef  vp8_lf_simple_mb_v
#define vp8_lf_simple_mb_v vp8_loop_filter_simple_vertical_edge_armv6

#undef  vp8_lf_simple_b_v
#define vp8_lf_simple_b_v vp8_loop_filter_bvs_armv6

#undef  vp8_lf_simple_mb_h
#define vp8_lf_simple_mb_h vp8_loop_filter_simple_horizontal_edge_armv6

#undef  vp8_lf_simple_b_h
#define vp8_lf_simple_b_h vp8_loop_filter_bhs_armv6
#endif /* !CONFIG_RUNTIME_CPU_DETECT */

#endif /* HAVE_ARMV6 */

#if HAVE_ARMV7
extern prototype_loopfilter_block(vp8_loop_filter_mbv_neon);
extern prototype_loopfilter_block(vp8_loop_filter_bv_neon);
extern prototype_loopfilter_block(vp8_loop_filter_mbh_neon);
extern prototype_loopfilter_block(vp8_loop_filter_bh_neon);
extern prototype_simple_loopfilter(vp8_loop_filter_mbvs_neon);
extern prototype_simple_loopfilter(vp8_loop_filter_bvs_neon);
extern prototype_simple_loopfilter(vp8_loop_filter_mbhs_neon);
extern prototype_simple_loopfilter(vp8_loop_filter_bhs_neon);

#if !CONFIG_RUNTIME_CPU_DETECT
#undef  vp8_lf_normal_mb_v
#define vp8_lf_normal_mb_v vp8_loop_filter_mbv_neon

#undef  vp8_lf_normal_b_v
#define vp8_lf_normal_b_v vp8_loop_filter_bv_neon

#undef  vp8_lf_normal_mb_h
#define vp8_lf_normal_mb_h vp8_loop_filter_mbh_neon

#undef  vp8_lf_normal_b_h
#define vp8_lf_normal_b_h vp8_loop_filter_bh_neon

#undef  vp8_lf_simple_mb_v
#define vp8_lf_simple_mb_v vp8_loop_filter_mbvs_neon

#undef  vp8_lf_simple_b_v
#define vp8_lf_simple_b_v vp8_loop_filter_bvs_neon

#undef  vp8_lf_simple_mb_h
#define vp8_lf_simple_mb_h vp8_loop_filter_mbhs_neon

#undef  vp8_lf_simple_b_h
#define vp8_lf_simple_b_h vp8_loop_filter_bhs_neon
#endif /* !CONFIG_RUNTIME_CPU_DETECT */

#endif /* HAVE_ARMV7 */

#endif /* LOOPFILTER_ARM_H */


text:
package com.taobao.weex.ui.component;

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.WXSDKManager;
import com.taobao.weex.common.WXDomPropConstant;
import com.taobao.weex.dom.WXDomObject;
import com.taobao.weex.dom.WXStyle;
import com.taobao.weex.dom.WXTextDomObject;
import com.taobao.weex.ui.view.WXEditText;
import com.taobao.weex.utils.WXResourceUtils;
import com.taobao.weex.utils.WXUtils;

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

/**
 * Created by sospartan on 7/11/16.
 */
public abstract class AbstractEditComponent extends WXComponent<WXEditText> {

  private final InputMethodManager mInputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
  private String mBeforeText = "";
  private boolean mAutoFocus;
  private String mType = "text";

  public AbstractEditComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, boolean isLazy) {
    super(instance, dom, parent, isLazy);
  }

  @Override
  protected WXEditText initComponentHostView(Context context) {
    WXEditText inputView = new WXEditText(context);
    appleStyleAfterCreated(inputView);
    return inputView;
  }

  /**
   * Process view after created.
   *
   * @param editText
   */
  protected void appleStyleAfterCreated(WXEditText editText) {
    String alignStr = (String) mDomObj.style.get(WXDomPropConstant.WX_TEXTALIGN);
    int textAlign = getTextAlign(alignStr);
    if (textAlign <= 0) {
      textAlign = Gravity.LEFT;
    }
    editText.setGravity(textAlign | Gravity.CENTER_VERTICAL);
    int colorInt = WXResourceUtils.getColor("#999999");
    if (colorInt != Integer.MIN_VALUE) {
      editText.setHintTextColor(colorInt);
    }

    editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, WXStyle.getFontSize(mDomObj.style));
    editText.setText((String) mDomObj.attr.get("value"));
  }

  @Override
  public void addEvent(String type) {
    super.addEvent(type);
    if (mHost == null || TextUtils.isEmpty(type)) {
      return;
    }
    final TextView text = (WXEditText) mHost;

    if (type.equals(WXEventType.INPUT_CHANGE)) {
      text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        CharSequence mLastValue = text.getText();

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
          CharSequence newValue = text.getText();
          newValue = newValue == null ? "" : newValue;
          if (!hasFocus && !newValue.equals(mLastValue)) {
            mLastValue = newValue;

            String event = mDomObj.event.contains(WXEventType.INPUT_CHANGE) ? WXEventType.INPUT_CHANGE : null;
            fireEvent(event, newValue.toString());
          }
        }
      });
    } else if (type.equals(WXEventType.INPUT)) {
      text.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
          if (mBeforeText.equals(s.toString())) {
            return;
          }

          String event = mDomObj.event.contains(WXEventType.INPUT) ? WXEventType.INPUT : null;
          fireEvent(event, s.toString());

          mBeforeText = s.toString();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
      });
    }
  }

  private void fireEvent(String event, String value) {
    if (event != null) {
      Map<String, Object> params = new HashMap<>(2);
      params.put("value", value);
      params.put("timeStamp", System.currentTimeMillis());

      Map<String, Object> domChanges = new HashMap<>();
      Map<String, Object> attrsChanges = new HashMap<>();
      attrsChanges.put("value", value);
      domChanges.put("attrs", attrsChanges);

      WXSDKManager.getInstance().fireEvent(mInstanceId, mDomObj.ref, event, params, domChanges);
    }
  }

  @Override
  protected boolean setProperty(String key, Object param) {
    switch (key) {
      case WXDomPropConstant.WX_ATTR_INPUT_PLACEHOLDER:
        String placeholder = WXUtils.getString(param,null);
        if (placeholder != null)
          setPlaceholder(placeholder);
        return true;
      case WXDomPropConstant.WX_INPUT_PLACEHOLDER_COLOR:
        String placeholder_color = WXUtils.getString(param,null);
        if (placeholder_color != null)
          setPlaceholderColor(placeholder_color);
        return true;
      case WXDomPropConstant.WX_ATTR_INPUT_TYPE:
        String input_type = WXUtils.getString(param,null);
        if (input_type != null)
          setType(input_type);
        return true;
      case WXDomPropConstant.WX_ATTR_INPUT_AUTOFOCUS:
        Boolean result = WXUtils.getBoolean(param, null);
        if (result != null)
          setAutofocus(result);
        return true;
      case WXDomPropConstant.WX_COLOR:
        String color = WXUtils.getString(param,null);
        if (color != null)
          setColor(color);
        return true;
      case WXDomPropConstant.WX_FONTSIZE:
        String fontsize = WXUtils.getString(param,null);
        if (fontsize != null)
          setFontSize(fontsize);
        return true;
      case WXDomPropConstant.WX_TEXTALIGN:
        String text_align = WXUtils.getString(param,null);
        if (text_align != null)
          setTextAlign(text_align);
        return true;
      case WXDomPropConstant.WX_ATTR_INPUT_SINGLELINE:
        Boolean singLineResult = WXUtils.getBoolean(param, null);
        if (singLineResult != null)
          setSingleLine(singLineResult);
        return true;
      case WXDomPropConstant.WX_ATTR_INPUT_LINES:
        Integer lines = WXUtils.getInteger(param, null);
        if (lines != null)
          setLines(lines);
        return true;
      case WXDomPropConstant.WX_ATTR_INPUT_MAXLENGTH:
        Integer maxlength = WXUtils.getInteger(param, null);
        if (maxlength != null)
          setMaxLength(maxlength);
        return true;
    }
    return super.setProperty(key, param);
  }

  @WXComponentProp(name = WXDomPropConstant.WX_ATTR_INPUT_PLACEHOLDER)
  public void setPlaceholder(String placeholder) {
    if (placeholder == null || mHost == null) {
      return;
    }
    ((WXEditText) mHost).setHint(placeholder);
  }

  @WXComponentProp(name = WXDomPropConstant.WX_INPUT_PLACEHOLDER_COLOR)
  public void setPlaceholderColor(String color) {
    if (mHost != null && !TextUtils.isEmpty(color)) {
      int colorInt = WXResourceUtils.getColor(color);
      if (colorInt != Integer.MIN_VALUE) {
        ((WXEditText) mHost).setHintTextColor(colorInt);
      }
    }
  }

  @WXComponentProp(name = WXDomPropConstant.WX_ATTR_INPUT_TYPE)
  public void setType(String type) {
    if (type == null || mHost == null) {
      return;
    }
    mType = type;
    ((EditText) mHost).setRawInputType(getInputType(mType));
  }

  @WXComponentProp(name = WXDomPropConstant.WX_ATTR_INPUT_AUTOFOCUS)
  public void setAutofocus(boolean autofocus) {
    if (mHost == null) {
      return;
    }
    mAutoFocus = autofocus;
    EditText inputView = (EditText) mHost;
    if (mAutoFocus) {
      inputView.setFocusable(true);
      inputView.requestFocus();
      inputView.setFocusableInTouchMode(true);
      inputView.postDelayed(new Runnable() {
        @Override
        public void run() {
          showSoftKeyboard();
        }
      }, 16);
    } else {
      inputView.postDelayed(new Runnable() {
        @Override
        public void run() {
          hideSoftKeyboard();
        }
      }, 16);
    }
  }

  @WXComponentProp(name = WXDomPropConstant.WX_COLOR)
  public void setColor(String color) {
    if (mHost != null && !TextUtils.isEmpty(color)) {
      int colorInt = WXResourceUtils.getColor(color);
      if (colorInt != Integer.MIN_VALUE) {
        ((WXEditText) mHost).setTextColor(colorInt);
      }
    }
  }

  @WXComponentProp(name = WXDomPropConstant.WX_FONTSIZE)
  public void setFontSize(String fontSize) {
    if (mHost != null && fontSize != null && mDomObj.style != null) {
      ((WXEditText) mHost).setTextSize(TypedValue.COMPLEX_UNIT_PX, WXStyle.getFontSize(mDomObj.style));
    }
  }

  @WXComponentProp(name = WXDomPropConstant.WX_TEXTALIGN)
  public void setTextAlign(String textAlign) {
    int align = getTextAlign(textAlign);
    if (align > 0) {
      ((EditText) mHost).setGravity(align | Gravity.CENTER_VERTICAL);
    }
  }

  @WXComponentProp(name = WXDomPropConstant.WX_ATTR_INPUT_SINGLELINE)
  public void setSingleLine(boolean singleLine) {
    if (mHost == null) {
      return;
    }
    ((WXEditText) mHost).setSingleLine(singleLine);
  }

  @WXComponentProp(name = WXDomPropConstant.WX_ATTR_INPUT_LINES)
  public void setLines(int lines) {
    if (getHostView() == null) {
      return;
    }
    getHostView().setLines(lines);
  }

  @WXComponentProp(name = WXDomPropConstant.WX_ATTR_INPUT_MAXLENGTH)
  public void setMaxLength(int maxLength) {
    if (getHostView() == null) {
      return;
    }
    getHostView().setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
  }

  @Override
  public WXTextDomObject getDomObject() {
    return (WXTextDomObject) super.getDomObject();
  }

  private int getInputType(String type) {
    int inputType;
    switch (type) {
      case WXDomPropConstant.WX_ATTR_INPUT_TYPE_TEXT:
        inputType = InputType.TYPE_CLASS_TEXT;
        break;
      case WXDomPropConstant.WX_ATTR_INPUT_TYPE_DATE:
        inputType = InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_DATE;
        break;
      case WXDomPropConstant.WX_ATTR_INPUT_TYPE_DATETIME:
        inputType = InputType.TYPE_CLASS_DATETIME;
        break;
      case WXDomPropConstant.WX_ATTR_INPUT_TYPE_EMAIL:
        inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
        break;
      case WXDomPropConstant.WX_ATTR_INPUT_TYPE_PASSWORD:
        inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
        getHostView().setTransformationMethod(PasswordTransformationMethod.getInstance());
        break;
      case WXDomPropConstant.WX_ATTR_INPUT_TYPE_TEL:
        inputType = InputType.TYPE_CLASS_PHONE;
        break;
      case WXDomPropConstant.WX_ATTR_INPUT_TYPE_TIME:
        inputType = InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_TIME;
        break;
      case WXDomPropConstant.WX_ATTR_INPUT_TYPE_URL:
        inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI;
        break;
      default:
        inputType = InputType.TYPE_CLASS_TEXT;
    }
    return inputType;
  }

  private boolean showSoftKeyboard() {
    if (mHost == null) {
      return false;
    }
    return mInputMethodManager.showSoftInput(mHost, InputMethodManager.SHOW_IMPLICIT);
  }

  private void hideSoftKeyboard() {
    if (mHost != null) {
      mInputMethodManager.hideSoftInputFromWindow(mHost.getWindowToken(), 0);
    }
  }

  private int getTextAlign(String textAlign) {
    int align = Gravity.LEFT;
    if (TextUtils.isEmpty(textAlign)) {
      return align;
    }
    if (textAlign.equals(WXDomPropConstant.WX_TEXTALIGN_LEFT)) {
      align = Gravity.LEFT;
    } else if (textAlign.equals(WXDomPropConstant.WX_TEXTALIGN_CENTER)) {
      align = Gravity.CENTER;
    } else if (textAlign.equals(WXDomPropConstant.WX_TEXTALIGN_RIGHT)) {
      align = Gravity.RIGHT;
    }
    return align;
  }

}


text:
import vtk

def main():
    dataFn1, dataFn2, textureFn = get_program_parameters()
    colors = vtk.vtkNamedColors()

    # Read the data.
    pl3d = vtk.vtkMultiBlockPLOT3DReader()
    pl3d.SetXYZFileName(dataFn1)
    pl3d.SetQFileName(dataFn2)
    pl3d.SetScalarFunctionNumber(100)
    pl3d.SetVectorFunctionNumber(202)
    pl3d.Update()
    output = pl3d.GetOutput().GetBlock(0)

    # Make the wall (floor).
    wall = vtk.vtkStructuredGridGeometryFilter()
    wall.SetInputData(output)
    wall.SetExtent(0, 100, 0, 0, 0, 100)
    wallMap = vtk.vtkPolyDataMapper()
    wallMap.SetInputConnection(wall.GetOutputPort())
    wallMap.ScalarVisibilityOff()
    wallActor = vtk.vtkActor()
    wallActor.SetMapper(wallMap)
    wallActor.GetProperty().SetColor(colors.GetColor3d("PeachPuff"))

    # Make the fin (rear wall)
    fin = vtk.vtkStructuredGridGeometryFilter()
    fin.SetInputData(output)
    fin.SetExtent(0, 100, 0, 100, 0, 0)
    finMap = vtk.vtkPolyDataMapper()
    finMap.SetInputConnection(fin.GetOutputPort())
    finMap.ScalarVisibilityOff()
    finActor = vtk.vtkActor()
    finActor.SetMapper(finMap)
    finActor.GetProperty().SetColor(colors.GetColor3d("DarkSlateGray"))

    # Get the texture.
    tmap = vtk.vtkStructuredPointsReader()
    tmap.SetFileName(textureFn)
    texture = vtk.vtkTexture()
    texture.SetInputConnection(tmap.GetOutputPort())
    texture.InterpolateOff()
    texture.RepeatOff()

    # Create the rendering window, renderer, and interactive renderer.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Make the planes to threshold and texture.
    plane = list()
    thresh = list()
    planeMap = list()
    planeActor = list()
    # Define the extents of planes that we will use.
    planeExtents = [[10, 10, 0, 100, 0, 100],
                    [30, 30, 0, 100, 0, 100],
                    [35, 35, 0, 100, 0, 100]]
    # Now set up the pipeline.
    for i in range(0, len(planeExtents)):
        plane.append(vtk.vtkStructuredGridGeometryFilter())
        plane[i].SetInputData(output)
        plane[i].SetExtent(*planeExtents[i])
        thresh.append(vtk.vtkThresholdTextureCoords())
        thresh[i].SetInputConnection(plane[i].GetOutputPort())
        thresh[i].SetInputConnection(plane[i].GetOutputPort())
        # If you want an image similar to Fig 9-43(a) in the VTK textbook,
        # set thresh[i].ThresholdByUpper(1.5) for all planes.
        if i == 1:
            thresh[i].ThresholdByLower(1.5)
        elif i == 2:
            thresh[i].ThresholdBetween(1.5, 1.8)
        else:
            thresh[i].ThresholdByUpper(1.5)
        planeMap.append(vtk.vtkDataSetMapper())
        planeMap[i].SetInputConnection(thresh[i].GetOutputPort())
        planeMap[i].SetScalarRange(output.GetScalarRange())
        planeActor.append(vtk.vtkActor())
        planeActor[i].SetMapper(planeMap[i])
        planeActor[i].SetTexture(texture)
        #  The slight transparency gives a nice effect.
        planeActor[i].GetProperty().SetOpacity(0.999)
        ren.AddActor(planeActor[i])

    # Get an outline of the data set for context.
    outline = vtk.vtkStructuredGridOutlineFilter()
    outline.SetInputData(output)
    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())
    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineProp = outlineActor.GetProperty()
    outlineProp.SetColor(colors.GetColor3d("Black"))

    # Add the remaining actors to the renderer, set the background and size.
    ren.AddActor(outlineActor)
    ren.AddActor(wallActor)
    ren.AddActor(finActor)
    ren.SetBackground(colors.GetColor3d("MistyRose"))
    renWin.SetSize(512, 512)
    cam = vtk.vtkCamera()
    cam.SetClippingRange(1.51176, 75.5879)
    cam.SetFocalPoint(2.33749, 2.96739, 3.61023)
    cam.SetPosition(10.8787, 5.27346, 15.8687)
    cam.SetViewAngle(30)
    cam.SetViewUp(-0.0610856, 0.987798, -0.143262)
    ren.SetActiveCamera(cam)

    iren.Initialize()
    iren.Start()

def get_program_parameters():
    import argparse
    description = 'Demonstrating texture thresholding applied to scalar data from a simulation of fluid flow.'
    epilogue = '''
    There are three planes cutting the blunt fin with different thresholds set.
     From the left, the scalar threshold is set so that:
       1) Only data with a scalar value greater than or equal to 1.5 is shown.
       2) Only data with a scalar value less than or equal to 1.5 is shown.
       3) Only data with a scalar value between 1.5 and 1.8 inclusive is shown.
   '''
    parser = argparse.ArgumentParser(description=description, epilog=epilogue,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('dataFn1', help='bluntfinxyz.bin.')
    parser.add_argument('dataFn2', help='bluntfinq.bin.')
    parser.add_argument('textureFn', help='texThres2.vtk.')
    args = parser.parse_args()
    return args.dataFn1, args.dataFn2, args.textureFn

if __name__ == '__main__':
    main()


text:
package google_test

import (
	"fmt"
	"log"
	"net/http"
	"testing"

	"github.com/golang/oauth2"
	"github.com/golang/oauth2/google"
	"google.golang.org/appengine"
)

// Remove after Go 1.4.
// Related to https://codereview.appspot.com/107320046
func TestA(t *testing.T) {}

func Example_webServer() {
	// Your credentials should be obtained from the Google
	// Developer Console (https://console.developers.google.com).
	config, err := google.NewConfig(&oauth2.Options{
		ClientID:     "YOUR_CLIENT_ID",
		ClientSecret: "YOUR_CLIENT_SECRET",
		RedirectURL:  "YOUR_REDIRECT_URL",
		Scopes: []string{
			"https://www.googleapis.com/auth/bigquery",
			"https://www.googleapis.com/auth/blogger"},
	})
	if err != nil {
		log.Fatal(err)
	}

	// Redirect user to Google's consent page to ask for permission
	// for the scopes specified above.
	url := config.AuthCodeURL("state", "online", "auto")
	fmt.Printf("Visit the URL for the auth dialog: %v", url)

	// Handle the exchange code to initiate a transport
	t, err := config.NewTransportWithCode("exchange-code")
	if err != nil {
		log.Fatal(err)
	}
	client := http.Client{Transport: t}
	client.Get("...")
}

func Example_serviceAccountsJSON() {
	// Your credentials should be obtained from the Google
	// Developer Console (https://console.developers.google.com).
	// Navigate to your project, then see the "Credentials" page
	// under "APIs & Auth".
	// To create a service account client, click "Create new Client ID",
	// select "Service Account", and click "Create Client ID". A JSON
	// key file will then be downloaded to your computer.
	config, err := google.NewServiceAccountJSONConfig(
		"/path/to/your-project-key.json",
		"https://www.googleapis.com/auth/bigquery",
	)
	if err != nil {
		log.Fatal(err)
	}
	// Initiate an http.Client. The following GET request will be
	// authorized and authenticated on the behalf of
	// your service account.
	client := http.Client{Transport: config.NewTransport()}
	client.Get("...")

	// If you would like to impersonate a user, you can
	// create a transport with a subject. The following GET
	// request will be made on the behalf of user@example.com.
	client = http.Client{Transport: config.NewTransportWithUser("user@example.com")}
	client.Get("...")
}

func Example_serviceAccounts() {
	// Your credentials should be obtained from the Google
	// Developer Console (https://console.developers.google.com).
	config, err := google.NewServiceAccountConfig(&oauth2.JWTOptions{
		Email: "xxx@developer.gserviceaccount.com",
		// The contents of your RSA private key or your PEM file
		// that contains a private key.
		// If you have a p12 file instead, you
		// can use `openssl` to export the private key into a PEM file.
		//
		//    $ openssl pkcs12 -in key.p12 -out key.pem -nodes
		//
		// Supports only PEM containers without a passphrase.
		PrivateKey: []byte("PRIVATE KEY CONTENTS"),
		Scopes: []string{
			"https://www.googleapis.com/auth/bigquery",
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	// Initiate an http.Client, the following GET request will be
	// authorized and authenticated on the behalf of
	// xxx@developer.gserviceaccount.com.
	client := http.Client{Transport: config.NewTransport()}
	client.Get("...")

	// If you would like to impersonate a user, you can
	// create a transport with a subject. The following GET
	// request will be made on the behalf of user@example.com.
	client = http.Client{Transport: config.NewTransportWithUser("user@example.com")}
	client.Get("...")
}

func Example_appEngine() {
	c := appengine.NewContext(nil)
	config := google.NewAppEngineConfig(c, "https://www.googleapis.com/auth/bigquery")
	// The following client will be authorized by the App Engine
	// app's service account for the provided scopes.
	client := http.Client{Transport: config.NewTransport()}
	client.Get("...")
}

func Example_computeEngine() {
	// If no other account is specified, "default" is used.
	config := google.NewComputeEngineConfig("")
	client := http.Client{Transport: config.NewTransport()}
	client.Get("...")
}


text:
package org.apache.predictionio.data.storage.elasticsearch

import java.io.IOException

import scala.collection.JavaConverters._

import org.apache.http.entity.ContentType
import org.apache.http.nio.entity.NStringEntity
import org.apache.http.util.EntityUtils
import org.apache.predictionio.data.storage.StorageClientConfig
import org.apache.predictionio.data.storage.StorageClientException
import org.elasticsearch.client.RestClient
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization.write

import grizzled.slf4j.Logging

class ESSequences(client: RestClient, config: StorageClientConfig, metadataName: String) extends Logging {
  implicit val formats = DefaultFormats
  private val metadataKey = "sequences"
  private val index = metadataName + "_" + metadataKey
  private val estype = {
    val mappingJson =
      ("mappings" ->
        ("properties" ->
          ("n" -> ("enabled" -> false))))

    ESUtils.createIndex(client, index, compact(render(mappingJson)))
  }

  def genNext(name: String): Long = {
    try {
      val entity = new NStringEntity(write("n" -> name), ContentType.APPLICATION_JSON)
      val response = client.performRequest(
        "PUT",
        s"/$index/$estype/$name",
        Map("refresh" -> "false").asJava,
        entity)
      val jsonResponse = parse(EntityUtils.toString(response.getEntity))
      val result = (jsonResponse \ "result").extract[String]
      result match {
        case "created" =>
          (jsonResponse \ "_version").extract[Long]
        case "updated" =>
          (jsonResponse \ "_version").extract[Long]
        case _ =>
          throw new IllegalStateException(s"[$result] Failed to update $index/$estype/$name")
      }
    } catch {
      case e: IOException =>
        throw new StorageClientException(s"Failed to update $index/$estype/$name", e)
    }
  }
}


text:
package edu.cmu.cs.db.peloton.test.generate.util;

import edu.cmu.cs.db.peloton.test.common.DatabaseDefinition;
import edu.cmu.cs.db.peloton.test.generate.ast.Ast;
import edu.cmu.cs.db.peloton.test.generate.ast.Context;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static edu.cmu.cs.db.peloton.test.generate.ast.Ast.ExpressionType.BOOLEAN;
import static edu.cmu.cs.db.peloton.test.generate.ast.Ast.ExpressionType.NUMERIC;
import static edu.cmu.cs.db.peloton.test.generate.ast.Ast.ExpressionType.VARCHAR;

/**
 * Created by tianyuli on 4/1/17.
 */
public final class RandomUtils {
    private static final double CONSTANT_PROB = 0.2;

    public static <E> E randomElement(List<E> elems, Random random) {
        return elems.get(random.nextInt(elems.size()));
    }

    public static <E> E randomElement(Set<E> elems, Random random) {
        return randomElement(elems.stream(), elems.size(), random);
    }

    public static <E> E randomElement(Stream<E> elems, int count, Random random) {
        return elems.skip(random.nextInt(count))
                .findFirst()
                .orElseThrow(IllegalArgumentException::new);
    }

    public static <E> E randomElement(Stream<E> elems, Random random) {
        return randomElement(elems.collect(Collectors.toList()), random);
    }

    public static String constantOf(Ast.ExpressionType type, Random random) {
        switch (type) {
            case NUMERIC:
                return Double.toString(random.nextDouble());
            case VARCHAR:
                int length = random.nextInt(10);
                StringBuilder result = new StringBuilder("\'");
                for (int i = 0; i < length; i++) {
                    result.append((char) (random.nextInt(26) + 'a'));
                }
                result.append("\'");
                return result.toString();
            case BOOLEAN:
                return random.nextBoolean() ? "TRUE" : "FALSE";
            case ANY:
                return constantOf(randomElement(Arrays.asList(NUMERIC, VARCHAR, BOOLEAN), random), random);
            default:
                throw new IllegalArgumentException("Unimplemented");
        }
    }

    public static Optional<String> noConstantOf(DatabaseDefinition db,
                                                Context context,
                                                Ast.ExpressionType type,
                                                Random random) {
        List<String> columns = context.valuesOf(Ast.Sort.TABLE).stream()
                .flatMap(t -> db.getTable(t).entrySet().stream()
                        .filter(e -> Ast.ExpressionType.fromJDBCType(e.getValue().getType()).matches(type))
                        .map(e -> t + "." + e.getKey()))
                .collect(Collectors.toList());
        return columns.isEmpty() ? Optional.empty() : Optional.of(randomElement(columns, random));
    }

    public static String valueOf(DatabaseDefinition db, Context context, Ast.ExpressionType type, Random random) {
        if (random.nextDouble() < CONSTANT_PROB) {
            return constantOf(type, random);
        }
        return noConstantOf(db, context, type, random).orElseGet(() -> constantOf(type, random));
    }
}


text:
@class NSError, NSMutableArray, NSMutableDictionary, NSObject<OS_dispatch_queue>, NSString;

@interface LZFileCache : NSObject
{
    _Bool _bCleaned;
    _Bool _bCacheFinish;
    int _fileFD;
    int _status;
    NSError *_innerError;
    unsigned long long _cacheType;
    NSObject<OS_dispatch_queue> *_fileOptQueue;
    void *_queueContext;
    NSString *_fileName;
    NSString *_cfgfileName;
    void *_mapBuf;
    unsigned long long _fileSize;
    NSMutableArray *_writeRanges;
    NSMutableArray *_readRanges;
    NSMutableDictionary *_dicOptItems;
    NSMutableDictionary *_dicmapRefforread;
    long long _fileCacheErrorType;
}

+ (void)preheat:(void *)arg1 size:(unsigned long long)arg2;
+ (int)pageSize;
+ (id)cfgPath:(id)arg1;
@property(nonatomic) long long fileCacheErrorType; // @synthesize fileCacheErrorType=_fileCacheErrorType;
@property(nonatomic) _Bool bCacheFinish; // @synthesize bCacheFinish=_bCacheFinish;
@property(nonatomic) _Bool bCleaned; // @synthesize bCleaned=_bCleaned;
@property(nonatomic) int status; // @synthesize status=_status;
@property(retain, nonatomic) NSMutableDictionary *dicmapRefforread; // @synthesize dicmapRefforread=_dicmapRefforread;
@property(retain, nonatomic) NSMutableDictionary *dicOptItems; // @synthesize dicOptItems=_dicOptItems;
@property(retain, nonatomic) NSMutableArray *readRanges; // @synthesize readRanges=_readRanges;
@property(retain, nonatomic) NSMutableArray *writeRanges; // @synthesize writeRanges=_writeRanges;
@property(nonatomic) unsigned long long fileSize; // @synthesize fileSize=_fileSize;
@property(nonatomic) void *mapBuf; // @synthesize mapBuf=_mapBuf;
@property(nonatomic) int fileFD; // @synthesize fileFD=_fileFD;
@property(retain, nonatomic) NSString *cfgfileName; // @synthesize cfgfileName=_cfgfileName;
@property(retain, nonatomic) NSString *fileName; // @synthesize fileName=_fileName;
@property(nonatomic) void *queueContext; // @synthesize queueContext=_queueContext;
@property(retain, nonatomic) NSObject<OS_dispatch_queue> *fileOptQueue; // @synthesize fileOptQueue=_fileOptQueue;
@property(readonly, nonatomic) unsigned long long cacheType; // @synthesize cacheType=_cacheType;
@property(retain) NSError *innerError; // @synthesize innerError=_innerError;
- (void).cxx_destruct;
- (void)loadfilecfg;
- (void)savefileCfg;
- (void)fileCacheSuccess;
- (void)mergeRanges:(id)arg1;
- (void)refreshReadRanges;
- (_Bool)readFileInner:(id)arg1 range:(struct _LzRange)arg2 data:(id *)arg3;
- (_Bool)openFileAndSetupMapInner:(id)arg1;
- (_Bool)loadCacheInfoInner;
- (struct _LzRange)calcDownloadRangeInner:(struct _LzRange)arg1;
- (id)mergeInfo;
- (void)releaseFile;
- (void)releaseMapping;
- (unsigned long long)fileRealSize;
- (_Bool)isFileCacheFinished;
- (_Bool)loadCacheInfo;
- (struct _LzRange)calcDownloadRange:(struct _LzRange)arg1;
- (_Bool)stopCaching:(_Bool)arg1;
- (long long)fileCachedLength:(long long *)arg1 lastOffset:(long long *)arg2;
- (long long)fileCachedLength:(long long *)arg1;
- (void)close:(_Bool)arg1;
- (_Bool)readFile:(id)arg1 range:(struct _LzRange)arg2 data:(id *)arg3;
- (void)endRead:(id)arg1;
- (void)finishWirte:(id)arg1;
- (void)cleanFileCaching;
- (_Bool)writeFile:(id)arg1 data:(id)arg2 isFinish:(_Bool *)arg3;
- (_Bool)openFileAndSetupMap:(id)arg1;
@property(readonly, nonatomic) NSString *filePath;
- (void)dealloc;
- (id)initWithFile:(id)arg1 queue:(id)arg2 context:(void *)arg3 type:(unsigned long long)arg4;
- (id)init;

@end


text:
Object.defineProperty(exports, "__esModule", { value: true });
var content_view_1 = require("../content-view");
var Border = (function (_super) {
    __extends(Border, _super);
    function Border() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Border.prototype, "cornerRadius", {
        get: function () {
            if (typeof this.borderRadius === "number") {
                return this.borderRadius;
            }
            return 0;
        },
        set: function (value) {
            this.borderRadius = value;
        },
        enumerable: true,
        configurable: true
    });
    Border.prototype.onMeasure = function (widthMeasureSpec, heightMeasureSpec) {
        var width = content_view_1.layout.getMeasureSpecSize(widthMeasureSpec);
        var widthMode = content_view_1.layout.getMeasureSpecMode(widthMeasureSpec);
        var height = content_view_1.layout.getMeasureSpecSize(heightMeasureSpec);
        var heightMode = content_view_1.layout.getMeasureSpecMode(heightMeasureSpec);
        var horizontalBorderLength = this.effectiveBorderLeftWidth + this.effectiveBorderRightWidth;
        var verticalBorderLength = this.effectiveBorderTopWidth + this.effectiveBorderBottomWidth;
        var result = content_view_1.View.measureChild(this, this.layoutView, content_view_1.layout.makeMeasureSpec(width - horizontalBorderLength, widthMode), content_view_1.layout.makeMeasureSpec(height - verticalBorderLength, heightMode));
        var widthAndState = content_view_1.View.resolveSizeAndState(result.measuredWidth + horizontalBorderLength, width, widthMode, 0);
        var heightAndState = content_view_1.View.resolveSizeAndState(result.measuredHeight + verticalBorderLength, height, heightMode, 0);
        this.setMeasuredDimension(widthAndState, heightAndState);
    };
    Border.prototype.onLayout = function (left, top, right, bottom) {
        var horizontalBorderLength = this.effectiveBorderLeftWidth + this.effectiveBorderRightWidth;
        var verticalBorderLength = this.effectiveBorderTopWidth + this.effectiveBorderBottomWidth;
        content_view_1.View.layoutChild(this, this.layoutView, this.effectiveBorderLeftWidth, this.effectiveBorderTopWidth, right - left - horizontalBorderLength, bottom - top - verticalBorderLength);
    };
    return Border;
}(content_view_1.ContentView));
Border = __decorate([
    Deprecated
], Border);
exports.Border = Border;
//# sourceMappingURL=border.js.map


text:
class ABetterFinderRename < Cask
  version :latest
  sha256 :no_check

  url 'http://www.publicspace.net/download/ABFRX.dmg'
  appcast 'http://www.publicspace.net/app/signed_abfr9.xml'
  homepage 'http://www.publicspace.net/ABetterFinderRename/'
  license :commercial

  app 'A Better Finder Rename 9.app'
end


text:
#pragma once
#include <aws/sts/STS_EXPORTS.h>
#include <aws/sts/STSRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace STS
{
namespace Model
{

  /**
   */
  class AWS_STS_API GetSessionTokenRequest : public STSRequest
  {
  public:
    GetSessionTokenRequest();
    Aws::String SerializePayload() const override;

  protected:
    void DumpBodyToUrl(Aws::Http::URI& uri ) const override;

  public:
    /**
     *
The duration, in seconds, that the credentials should remain valid.
     * Acceptable durations for IAM user sessions range from 900 seconds (15 minutes)
     * to 129600 seconds (36 hours), with 43200 seconds (12 hours) as the default.
     * Sessions for AWS account owners are restricted to a maximum of 3600 seconds (one
     * hour). If the duration is longer than one hour, the session for AWS account
     * owners defaults to one hour.

     */
    inline int GetDurationSeconds() const{ return m_durationSeconds; }

    /**
     *
The duration, in seconds, that the credentials should remain valid.
     * Acceptable durations for IAM user sessions range from 900 seconds (15 minutes)
     * to 129600 seconds (36 hours), with 43200 seconds (12 hours) as the default.
     * Sessions for AWS account owners are restricted to a maximum of 3600 seconds (one
     * hour). If the duration is longer than one hour, the session for AWS account
     * owners defaults to one hour.

     */
    inline void SetDurationSeconds(int value) { m_durationSecondsHasBeenSet = true; m_durationSeconds = value; }

    /**
     *
The duration, in seconds, that the credentials should remain valid.
     * Acceptable durations for IAM user sessions range from 900 seconds (15 minutes)
     * to 129600 seconds (36 hours), with 43200 seconds (12 hours) as the default.
     * Sessions for AWS account owners are restricted to a maximum of 3600 seconds (one
     * hour). If the duration is longer than one hour, the session for AWS account
     * owners defaults to one hour.

     */
    inline GetSessionTokenRequest& WithDurationSeconds(int value) { SetDurationSeconds(value); return *this;}

    /**
     *
The identification number of the MFA device that is associated with the IAM
     * user who is making the GetSessionToken call. Specify this value if
     * the IAM user has a policy that requires MFA authentication. The value is either
     * the serial number for a hardware device (such as GAHT12345678) or
     * an Amazon Resource Name (ARN) for a virtual device (such as
     * arn:aws:iam::123456789012:mfa/user). You can find the device for an
     * IAM user by going to the AWS Management Console and viewing the user's security
     * credentials.

The regex used to validated this parameter is a string of
     * characters consisting of upper- and lower-case alphanumeric characters with no
     * spaces. You can also include underscores or any of the following characters:
     * =,.@:/-

     */
    inline const Aws::String& GetSerialNumber() const{ return m_serialNumber; }

    /**
     *
The identification number of the MFA device that is associated with the IAM
     * user who is making the GetSessionToken call. Specify this value if
     * the IAM user has a policy that requires MFA authentication. The value is either
     * the serial number for a hardware device (such as GAHT12345678) or
     * an Amazon Resource Name (ARN) for a virtual device (such as
     * arn:aws:iam::123456789012:mfa/user). You can find the device for an
     * IAM user by going to the AWS Management Console and viewing the user's security
     * credentials.

The regex used to validated this parameter is a string of
     * characters consisting of upper- and lower-case alphanumeric characters with no
     * spaces. You can also include underscores or any of the following characters:
     * =,.@:/-

     */
    inline void SetSerialNumber(const Aws::String& value) { m_serialNumberHasBeenSet = true; m_serialNumber = value; }

    /**
     *
The identification number of the MFA device that is associated with the IAM
     * user who is making the GetSessionToken call. Specify this value if
     * the IAM user has a policy that requires MFA authentication. The value is either
     * the serial number for a hardware device (such as GAHT12345678) or
     * an Amazon Resource Name (ARN) for a virtual device (such as
     * arn:aws:iam::123456789012:mfa/user). You can find the device for an
     * IAM user by going to the AWS Management Console and viewing the user's security
     * credentials.

The regex used to validated this parameter is a string of
     * characters consisting of upper- and lower-case alphanumeric characters with no
     * spaces. You can also include underscores or any of the following characters:
     * =,.@:/-

     */
    inline void SetSerialNumber(Aws::String&& value) { m_serialNumberHasBeenSet = true; m_serialNumber = std::move(value); }

    /**
     *
The identification number of the MFA device that is associated with the IAM
     * user who is making the GetSessionToken call. Specify this value if
     * the IAM user has a policy that requires MFA authentication. The value is either
     * the serial number for a hardware device (such as GAHT12345678) or
     * an Amazon Resource Name (ARN) for a virtual device (such as
     * arn:aws:iam::123456789012:mfa/user). You can find the device for an
     * IAM user by going to the AWS Management Console and viewing the user's security
     * credentials.

The regex used to validated this parameter is a string of
     * characters consisting of upper- and lower-case alphanumeric characters with no
     * spaces. You can also include underscores or any of the following characters:
     * =,.@:/-

     */
    inline void SetSerialNumber(const char* value) { m_serialNumberHasBeenSet = true; m_serialNumber.assign(value); }

    /**
     *
The identification number of the MFA device that is associated with the IAM
     * user who is making the GetSessionToken call. Specify this value if
     * the IAM user has a policy that requires MFA authentication. The value is either
     * the serial number for a hardware device (such as GAHT12345678) or
     * an Amazon Resource Name (ARN) for a virtual device (such as
     * arn:aws:iam::123456789012:mfa/user). You can find the device for an
     * IAM user by going to the AWS Management Console and viewing the user's security
     * credentials.

The regex used to validated this parameter is a string of
     * characters consisting of upper- and lower-case alphanumeric characters with no
     * spaces. You can also include underscores or any of the following characters:
     * =,.@:/-

     */
    inline GetSessionTokenRequest& WithSerialNumber(const Aws::String& value) { SetSerialNumber(value); return *this;}

    /**
     *
The identification number of the MFA device that is associated with the IAM
     * user who is making the GetSessionToken call. Specify this value if
     * the IAM user has a policy that requires MFA authentication. The value is either
     * the serial number for a hardware device (such as GAHT12345678) or
     * an Amazon Resource Name (ARN) for a virtual device (such as
     * arn:aws:iam::123456789012:mfa/user). You can find the device for an
     * IAM user by going to the AWS Management Console and viewing the user's security
     * credentials.

The regex used to validated this parameter is a string of
     * characters consisting of upper- and lower-case alphanumeric characters with no
     * spaces. You can also include underscores or any of the following characters:
     * =,.@:/-

     */
    inline GetSessionTokenRequest& WithSerialNumber(Aws::String&& value) { SetSerialNumber(std::move(value)); return *this;}

    /**
     *
The identification number of the MFA device that is associated with the IAM
     * user who is making the GetSessionToken call. Specify this value if
     * the IAM user has a policy that requires MFA authentication. The value is either
     * the serial number for a hardware device (such as GAHT12345678) or
     * an Amazon Resource Name (ARN) for a virtual device (such as
     * arn:aws:iam::123456789012:mfa/user). You can find the device for an
     * IAM user by going to the AWS Management Console and viewing the user's security
     * credentials.

The regex used to validated this parameter is a string of
     * characters consisting of upper- and lower-case alphanumeric characters with no
     * spaces. You can also include underscores or any of the following characters:
     * =,.@:/-

     */
    inline GetSessionTokenRequest& WithSerialNumber(const char* value) { SetSerialNumber(value); return *this;}

    /**
     *
The value provided by the MFA device, if MFA is required. If any policy
     * requires the IAM user to submit an MFA code, specify this value. If MFA
     * authentication is required, and the user does not provide a code when requesting
     * a set of temporary security credentials, the user will receive an "access
     * denied" response when requesting resources that require MFA authentication.

     *
The format for this parameter, as described by its regex pattern, is a
     * sequence of six numeric digits.

     */
    inline const Aws::String& GetTokenCode() const{ return m_tokenCode; }

    /**
     *
The value provided by the MFA device, if MFA is required. If any policy
     * requires the IAM user to submit an MFA code, specify this value. If MFA
     * authentication is required, and the user does not provide a code when requesting
     * a set of temporary security credentials, the user will receive an "access
     * denied" response when requesting resources that require MFA authentication.

     *
The format for this parameter, as described by its regex pattern, is a
     * sequence of six numeric digits.

     */
    inline void SetTokenCode(const Aws::String& value) { m_tokenCodeHasBeenSet = true; m_tokenCode = value; }

    /**
     *
The value provided by the MFA device, if MFA is required. If any policy
     * requires the IAM user to submit an MFA code, specify this value. If MFA
     * authentication is required, and the user does not provide a code when requesting
     * a set of temporary security credentials, the user will receive an "access
     * denied" response when requesting resources that require MFA authentication.

     *
The format for this parameter, as described by its regex pattern, is a
     * sequence of six numeric digits.

     */
    inline void SetTokenCode(Aws::String&& value) { m_tokenCodeHasBeenSet = true; m_tokenCode = std::move(value); }

    /**
     *
The value provided by the MFA device, if MFA is required. If any policy
     * requires the IAM user to submit an MFA code, specify this value. If MFA
     * authentication is required, and the user does not provide a code when requesting
     * a set of temporary security credentials, the user will receive an "access
     * denied" response when requesting resources that require MFA authentication.

     *
The format for this parameter, as described by its regex pattern, is a
     * sequence of six numeric digits.

     */
    inline void SetTokenCode(const char* value) { m_tokenCodeHasBeenSet = true; m_tokenCode.assign(value); }

    /**
     *
The value provided by the MFA device, if MFA is required. If any policy
     * requires the IAM user to submit an MFA code, specify this value. If MFA
     * authentication is required, and the user does not provide a code when requesting
     * a set of temporary security credentials, the user will receive an "access
     * denied" response when requesting resources that require MFA authentication.

     *
The format for this parameter, as described by its regex pattern, is a
     * sequence of six numeric digits.

     */
    inline GetSessionTokenRequest& WithTokenCode(const Aws::String& value) { SetTokenCode(value); return *this;}

    /**
     *
The value provided by the MFA device, if MFA is required. If any policy
     * requires the IAM user to submit an MFA code, specify this value. If MFA
     * authentication is required, and the user does not provide a code when requesting
     * a set of temporary security credentials, the user will receive an "access
     * denied" response when requesting resources that require MFA authentication.

     *
The format for this parameter, as described by its regex pattern, is a
     * sequence of six numeric digits.

     */
    inline GetSessionTokenRequest& WithTokenCode(Aws::String&& value) { SetTokenCode(std::move(value)); return *this;}

    /**
     *
The value provided by the MFA device, if MFA is required. If any policy
     * requires the IAM user to submit an MFA code, specify this value. If MFA
     * authentication is required, and the user does not provide a code when requesting
     * a set of temporary security credentials, the user will receive an "access
     * denied" response when requesting resources that require MFA authentication.

     *
The format for this parameter, as described by its regex pattern, is a
     * sequence of six numeric digits.

     */
    inline GetSessionTokenRequest& WithTokenCode(const char* value) { SetTokenCode(value); return *this;}

  private:
    int m_durationSeconds;
    bool m_durationSecondsHasBeenSet;
    Aws::String m_serialNumber;
    bool m_serialNumberHasBeenSet;
    Aws::String m_tokenCode;
    bool m_tokenCodeHasBeenSet;
  };

} // namespace Model
} // namespace STS
} // namespace Aws


text:
@interface DVTFilePath (PersistenceFSEventsMonitoring)
- (BOOL)subpathsChangedSinceDate:(id)arg1 withBlock:(dispatch_block_t)arg2;
- (id)relativePathOnVolume;
- (void)doneAddingChangedFilesFromStream:(struct __FSEventStream *)arg1;
- (void)addChangedFilePath:(char *)arg1;
@end


text:
package io.github.biezhi.wechat.utils;

import java.io.*;
import java.security.MessageDigest;

public class MD5Checksum {

   public static byte[] createChecksum(String filename) throws Exception {
       InputStream fis =  new FileInputStream(filename);

       byte[] buffer = new byte[1024];
       MessageDigest complete = MessageDigest.getInstance("MD5");
       int numRead;

       do {
           numRead = fis.read(buffer);
           if (numRead > 0) {
               complete.update(buffer, 0, numRead);
           }
       } while (numRead != -1);

       fis.close();
       return complete.digest();
   }

   // see this How-to for a faster way to convert
   // a byte array to a HEX string
   public static String getMD5Checksum(String filename) {
       try {
           byte[] b = createChecksum(filename);
           String result = "";

           for (int i=0; i < b.length; i++) {
               result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
           }
           return result;
       } catch (Exception e){
           return "";
       }
   }

   public static void main(String args[]) {
       try {
           System.out.println(getMD5Checksum("apache-tomcat-5.5.17.exe"));
           // output :
           //  0bb2827c5eacf570b6064e24e0e6653b
           // ref :
           //  http://www.apache.org/dist/
           //          tomcat/tomcat-5/v5.5.17/bin
           //              /apache-tomcat-5.5.17.exe.MD5
           //  0bb2827c5eacf570b6064e24e0e6653b *apache-tomcat-5.5.17.exe
       }
       catch (Exception e) {
           e.printStackTrace();
       }
   }
}


text:
<?php

namespace YiiMinifyClientScriptPackage;

class PhpParserHelperTest extends \PHPUnit_Framework_TestCase
{

    public function testFindFirstReturnArrayStatement()
    {
        $parser = new \PhpParser\Parser(new \PhpParser\Lexer\Emulative());
        $this->assertNull(PhpParserHelper::findFirstReturnArrayStatement($parser->parse('<?php $a = 1;')));
        $this->assertInstanceOf('\PhpParser\Node\Stmt\Return_', PhpParserHelper::findFirstReturnArrayStatement($parser->parse('<?php return array(1,2,3);')));
    }

    public function testArrayGetItemByKey()
    {
        $parser         = new \PhpParser\Parser(new \PhpParser\Lexer\Emulative());
        $phpCode        = '<?php return array("a" => 1);';
        $statements     = $parser->parse($phpCode);
        $arrayStatement = $statements[0]->expr;

        $this->assertNull(PhpParserHelper::arrayGetItemByKey($arrayStatement, 'b'));
        $this->assertInstanceOf('\PhpParser\Node\Expr\ArrayItem', PhpParserHelper::arrayGetItemByKey($arrayStatement, 'a'));
    }

    public function testArrayGetValueByKey()
    {
        $parser         = new \PhpParser\Parser(new \PhpParser\Lexer\Emulative());
        $phpCode        = '<?php return array("a" => 1);';
        $statements     = $parser->parse($phpCode);
        $arrayStatement = $statements[0]->expr;

        $this->assertNull(PhpParserHelper::arrayGetValueByKey($arrayStatement, 'b'));

        $lnumber = PhpParserHelper::arrayGetValueByKey($arrayStatement, 'a');
        $this->assertInstanceOf('\PhpParser\Node\Scalar\LNumber', $lnumber);
        $this->assertEquals(1, $lnumber->value);
    }

    public function testArrayGetValues()
    {
        $parser = new \PhpParser\Parser(new \PhpParser\Lexer\Emulative());

        $phpCode        = '<?php return array("a" => "b", "b" => "a");';
        $statements     = $parser->parse($phpCode);
        $arrayStatement = $statements[0]->expr;
        $actual         = PhpParserHelper::arrayGetValues($arrayStatement);
        $this->assertEquals(array('b', 'a'), $actual);

        $phpCode        = '<?php return array(2, 1);';
        $statements     = $parser->parse($phpCode);
        $arrayStatement = $statements[0]->expr;
        $actual         = PhpParserHelper::arrayGetValues($arrayStatement);

        $this->assertEquals(2, count($actual));
        $this->assertInstanceOf('\PhpParser\Node\Scalar\LNumber', $actual[0]);
        $this->assertEquals(2, $actual[0]->value);

        $this->assertInstanceOf('\PhpParser\Node\Scalar\LNumber', $actual[1]);
        $this->assertEquals(1, $actual[1]->value);
    }

    public function testGenerateArray()
    {
        $expected = array('a', '1', 'b', '2', 'c', '3', 'd', '4');
        $actual   = PhpParserHelper::generateArray($expected);

        $this->assertInstanceOf('\PhpParser\Node\Expr\Array_', $actual);
        $this->assertEquals(count($expected), count($actual->items));

        foreach ($expected as $index => $expectedValue) {
            $actualItem = $actual->items[$index];
            $this->assertInstanceOf('\PhpParser\Node\Expr\ArrayItem', $actualItem);

            $actualItemValue = $actualItem->value;
            $this->assertInstanceOf('\PhpParser\Node\Scalar\String_', $actualItemValue);

            $this->assertEquals($expectedValue, $actualItemValue->value);
        }
    }

}


text:
local table = table or {}

-- clear the table
function table.clear(self)
    for k in next, self do
        rawset(self, k, nil)
    end
end

-- join all objects and tables
function table.join(...)

    local result = {}
    for _, t in ipairs({...}) do
        if type(t) == "table" then
            for k, v in pairs(t) do
                if type(k) == "number" then table.insert(result, v)
                else result[k] = v end
            end
        else
            table.insert(result, t)
        end
    end
    return result
end

-- join all objects and tables to self
function table.join2(self, ...)

    for _, t in ipairs({...}) do
        if type(t) == "table" then
            for k, v in pairs(t) do
                if type(k) == "number" then table.insert(self, v)
                else self[k] = v end
            end
        else
            table.insert(self, t)
        end
    end
    return self
end

-- append all objects to array
function table.append(array, ...)
    for _, value in ipairs({...}) do
        table.insert(array, value)
    end
    return array
end

-- copy the table to self
function table.copy(copied)

    -- init it
    copied = copied or {}

    -- copy it
    local result = {}
    for k, v in pairs(table.wrap(copied)) do
        result[k] = v
    end

    -- ok
    return result
end

-- copy the table to self
function table.copy2(self, copied)

    -- check
    assert(self)

    -- init it
    copied = copied or {}

    -- clear self first
    table.clear(self)

    -- copy it
    for k, v in pairs(table.wrap(copied)) do
        self[k] = v
    end

end

-- inherit interfaces and create a new instance
function table.inherit(...)

    -- init instance
    local classes = {...}
    local instance = {}
    local metainfo = {}
    for _, clasz in ipairs(classes) do
        for k, v in pairs(clasz) do
            if type(v) == "function" then
                if k:startswith("__") then
                    if metainfo[k] == nil then
                        metainfo[k] = v
                    end
                else
                    if instance[k] == nil then
                        instance[k] = v
                    else
                        instance["_super_" .. k] = v
                    end
                end
            end
        end
    end
    setmetatable(instance, metainfo)

    -- ok?
    return instance
end

-- inherit interfaces from the given class
function table.inherit2(self, ...)

    -- check
    assert(self)

    -- init instance
    local classes = {...}
    local metainfo = getmetatable(self) or {}
    for _, clasz in ipairs(classes) do
        for k, v in pairs(clasz) do
            if type(v) == "function" then
                if k:startswith("__") then
                    if metainfo[k] == nil then
                        metainfo[k] = v
                    end
                else
                    if self[k] == nil then
                        self[k] = v
                    else
                        self["_super_" .. k] = v
                    end
                end
            end
        end
    end

    -- ok?
    return self
end

-- slice table array
function table.slice(self, first, last, step)

    -- slice it
    local sliced = {}
    for i = first or 1, last or #self, step or 1 do
        sliced[#sliced + 1] = self[i]
    end
    return sliced
end

-- is array?
function table.is_array(array)
    return type(array) == "table" and array[1] ~= nil
end

-- is dictionary?
function table.is_dictionary(dict)
    return type(dict) == "table" and dict[1] == nil
end

-- dump table
function table.dump(self, deflate)
    local str = string.dump(self, deflate)
    if str then
        io.write(str)
    end
end

-- unwrap object if be only one
function table.unwrap(object)
    if type(object) == "table" then
        if #object == 1 then
            return object[1]
        end
    end
    return object
end

-- wrap object to table
function table.wrap(object)

    -- no object?
    if nil == object then
        return {}
    end

    -- wrap it if not table
    if type(object) ~= "table" then
        return {object}
    end

    -- ok
    return object
end

-- remove repeat from the given array
function table.unique(array, barrier)

    -- remove repeat for array
    if table.is_array(array) then

        -- not only one?
        if table.getn(array) ~= 1 then

            -- done
            local exists = {}
            local unique = {}
            for _, v in ipairs(array) do

                -- exists barrier? clear the current existed items
                if barrier and barrier(v) then
                    exists = {}
                end

                -- add unique item
                if type(v) == "string" then
                    if not exists[v] then
                        exists[v] = true
                        table.insert(unique, v)
                    end
                else
                    local key = "\"" .. tostring(v) .. "\""
                    if not exists[key] then
                        exists[key] = true
                        table.insert(unique, v)
                    end
                end
            end

            -- update it
            array = unique
        end
    end

    -- ok
    return array
end

-- return module: table
return table


text:
/

#ifndef _BUFFERFILTER_H_
#define _BUFFERFILTER_H_

#include <SIBCUtil.h>
#include <SIBCString.h>

#include "CXSIFilter.h"

#define BUFFER_FILTER_NAME	"Buffer"
#define BUFFER_FILTER_ID		"buf"

#ifdef	_PSX2
#define BUFFER_SIZE				(32 * 1024)
#else
#define	BUFFER_SIZE				(128 * 1024)
#endif
//! Buffer filter.
/*
* This class will gather up to a certain size of data until it calls its subfilter to
* write or it will read up to a certain size in one go and answer to request until it
* has exhausted the data at which point it will ask its subfilter for more data.
*/
class CBufferFilter : public CXSIFilter
{
public:
	/*!
	 * Constructor
	*/
	CBufferFilter();
	/*!
	 * Destructor
	*/
	virtual ~CBufferFilter();

	/*! Opens the file for either reading or writing
	 * \param in_szFilename	Filename
	 * \param in_Mode	mode
	*/
	int	Open ( CSIBCString in_szFilename,  _SI_FILE_MODE in_Mode );
	/*! Closes the file when finished
	*/
	int	Close ();

	/*! Reads a number of bytes into the buffer passed in.
	 * \param out_pBuffer	output buffer
	 * \param in_lSize	number of bytes to read
	 * \return	int		number of bytes read.
	*/
	int Read ( SI_Char * out_pBuffer, SI_Long in_lSize );
	/*! Writes a number of bytes to the file
	 * \param in_pBuffer	input buffer
	 * \param in_lSize	number of bytes to write
	 * \return int		number of bytes written
	*/
	int Write( SI_Char * in_pBuffer,  SI_Long in_lSize );

	/*! Tests whether we have reached the end of file
	 * \return int	flag for end of file (1 - end of file, 0 - not end of file)
	*/
	int Eof();
	/*! Returns the current position in the file.
	 * \returns int	position in the file (0 - beginning)
	*/
	int Tell();

private:
	void	Flush();
	void	FillBuffer();

	char	*m_pBuffer;
	long	m_lPosition;
	SI_Long	m_lSizeRead;
	bool	m_bHeaderSkipped;
};

#endif


text:
import { _each, isPlainObject, isArray, deepAccess } from '../src/utils.js';
import { registerBidder } from '../src/adapters/bidderFactory.js'
import find from 'prebidjs-polyfill/find.js'
import { VIDEO, BANNER, NATIVE } from '../src/mediaTypes.js'
import { Renderer } from '../src/Renderer.js'
import { config } from '../src/config.js';

const ENDPOINT = 'https://ad.yieldlab.net'
const BIDDER_CODE = 'yieldlab'
const BID_RESPONSE_TTL_SEC = 300
const CURRENCY_CODE = 'EUR'
const OUTSTREAMPLAYER_URL = 'https://ad.adition.com/dynamic.ad?a=o193092&ma_loadEvent=ma-start-event'
const GVLID = 70

export const spec = {
  code: BIDDER_CODE,
  gvlid: GVLID,
  supportedMediaTypes: [VIDEO, BANNER, NATIVE],

  isBidRequestValid: function (bid) {
    if (bid && bid.params && bid.params.adslotId && bid.params.supplyId) {
      return true
    }
    return false
  },

  /**
   * This method should build correct URL
   * @param validBidRequests
   * @returns {{method: string, url: string}}
   */
  buildRequests: function (validBidRequests, bidderRequest) {
    const adslotIds = []
    const timestamp = Date.now()
    const query = {
      ts: timestamp,
      json: true
    }

    _each(validBidRequests, function (bid) {
      adslotIds.push(bid.params.adslotId)
      if (bid.params.targeting) {
        query.t = createTargetingString(bid.params.targeting)
      }
      if (bid.userIdAsEids && Array.isArray(bid.userIdAsEids)) {
        query.ids = createUserIdString(bid.userIdAsEids)
      }
      if (bid.params.customParams && isPlainObject(bid.params.customParams)) {
        for (let prop in bid.params.customParams) {
          query[prop] = bid.params.customParams[prop]
        }
      }
      if (bid.schain && isPlainObject(bid.schain) && Array.isArray(bid.schain.nodes)) {
        query.schain = createSchainString(bid.schain)
      }

      const iabContent = getContentObject(bid)
      if (iabContent) {
        query.iab_content = createIabContentString(iabContent)
      }
    })

    if (bidderRequest) {
      if (bidderRequest.refererInfo && bidderRequest.refererInfo.referer) {
        query.pubref = bidderRequest.refererInfo.referer
      }

      if (bidderRequest.gdprConsent) {
        query.gdpr = (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean') ? bidderRequest.gdprConsent.gdprApplies : true
        if (query.gdpr) {
          query.consent = bidderRequest.gdprConsent.consentString
        }
      }
    }

    const adslots = adslotIds.join(',')
    const queryString = createQueryString(query)

    return {
      method: 'GET',
      url: `${ENDPOINT}/yp/${adslots}?${queryString}`,
      validBidRequests: validBidRequests,
      queryParams: query
    }
  },

  /**
   * Map ad values and pricing and stuff
   * @param serverResponse
   * @param originalBidRequest
   */
  interpretResponse: function (serverResponse, originalBidRequest) {
    const bidResponses = []
    const timestamp = Date.now()
    const reqParams = originalBidRequest.queryParams

    originalBidRequest.validBidRequests.forEach(function (bidRequest) {
      if (!serverResponse.body) {
        return
      }

      let matchedBid = find(serverResponse.body, function (bidResponse) {
        return bidRequest.params.adslotId == bidResponse.id
      })

      if (matchedBid) {
        const adUnitSize = bidRequest.sizes.length === 2 && !isArray(bidRequest.sizes[0]) ? bidRequest.sizes : bidRequest.sizes[0]
        const adSize = bidRequest.params.adSize !== undefined ? parseSize(bidRequest.params.adSize) : (matchedBid.adsize !== undefined) ? parseSize(matchedBid.adsize) : adUnitSize
        const extId = bidRequest.params.extId !== undefined ? '&id=' + bidRequest.params.extId : ''
        const adType = matchedBid.adtype !== undefined ? matchedBid.adtype : ''
        const gdprApplies = reqParams.gdpr ? '&gdpr=' + reqParams.gdpr : ''
        const gdprConsent = reqParams.consent ? '&consent=' + reqParams.consent : ''
        const pvId = matchedBid.pvid !== undefined ? '&pvid=' + matchedBid.pvid : ''
        const iabContent = reqParams.iab_content ? '&iab_content=' + reqParams.iab_content : ''

        const bidResponse = {
          requestId: bidRequest.bidId,
          cpm: matchedBid.price / 100,
          width: adSize[0],
          height: adSize[1],
          creativeId: '' + matchedBid.id,
          dealId: (matchedBid['c.dealid']) ? matchedBid['c.dealid'] : matchedBid.pid,
          currency: CURRENCY_CODE,
          netRevenue: false,
          ttl: BID_RESPONSE_TTL_SEC,
          referrer: '',
          ad: `<script src="${ENDPOINT}/d/${matchedBid.id}/${bidRequest.params.supplyId}/?ts=${timestamp}${extId}${gdprApplies}${gdprConsent}${pvId}${iabContent}"></script>`,
          meta: {
            advertiserDomains: (matchedBid.advertiser) ? matchedBid.advertiser : 'n/a'
          }
        }

        if (isVideo(bidRequest, adType)) {
          const playersize = getPlayerSize(bidRequest)
          if (playersize) {
            bidResponse.width = playersize[0]
            bidResponse.height = playersize[1]
          }
          bidResponse.mediaType = VIDEO
          bidResponse.vastUrl = `${ENDPOINT}/d/${matchedBid.id}/${bidRequest.params.supplyId}/?ts=${timestamp}${extId}${gdprApplies}${gdprConsent}${pvId}${iabContent}`
          if (isOutstream(bidRequest)) {
            const renderer = Renderer.install({
              id: bidRequest.bidId,
              url: OUTSTREAMPLAYER_URL,
              loaded: false
            })
            renderer.setRender(outstreamRender)
            bidResponse.renderer = renderer
          }
        }

        if (isNative(bidRequest, adType)) {
          const url = `${ENDPOINT}/d/${matchedBid.id}/${bidRequest.params.supplyId}/?ts=${timestamp}${extId}${gdprApplies}${gdprConsent}${pvId}`
          bidResponse.adUrl = url
          bidResponse.mediaType = NATIVE
          const nativeImageAssetObj = find(matchedBid.native.assets, e => e.id === 2)
          const nativeImageAsset = nativeImageAssetObj ? nativeImageAssetObj.img : {url: '', w: 0, h: 0};
          const nativeTitleAsset = find(matchedBid.native.assets, e => e.id === 1)
          const nativeBodyAsset = find(matchedBid.native.assets, e => e.id === 3)
          bidResponse.native = {
            title: nativeTitleAsset ? nativeTitleAsset.title.text : '',
            body: nativeBodyAsset ? nativeBodyAsset.data.value : '',
            image: {
              url: nativeImageAsset.url,
              width: nativeImageAsset.w,
              height: nativeImageAsset.h,
            },
            clickUrl: matchedBid.native.link.url,
            impressionTrackers: matchedBid.native.imptrackers,
          };
        }

        bidResponses.push(bidResponse)
      }
    })
    return bidResponses
  }
};

/**
 * Is this a video format?
 * @param {Object} format
 * @param {String} adtype
 * @returns {Boolean}
 */
function isVideo(format, adtype) {
  return deepAccess(format, 'mediaTypes.video') && adtype.toLowerCase() === 'video'
}

/**
 * Is this a native format?
 * @param {Object} format
 * @param {String} adtype
 * @returns {Boolean}
 */
function isNative(format, adtype) {
  return deepAccess(format, 'mediaTypes.native') && adtype.toLowerCase() === 'native'
}

/**
 * Is this an outstream context?
 * @param {Object} format
 * @returns {Boolean}
 */
function isOutstream(format) {
  let context = deepAccess(format, 'mediaTypes.video.context')
  return (context === 'outstream')
}

/**
 * Gets optional player size
 * @param {Object} format
 * @returns {Array}
 */
function getPlayerSize(format) {
  let playerSize = deepAccess(format, 'mediaTypes.video.playerSize')
  return (playerSize && isArray(playerSize[0])) ? playerSize[0] : playerSize
}

/**
 * Expands a 'WxH' string as a 2-element [W, H] array
 * @param {String} size
 * @returns {Array}
 */
function parseSize(size) {
  return size.split('x').map(Number)
}

/**
 * Creates a string out of an array of eids with source and uid
 * @param {Array} eids
 * @returns {String}
 */
function createUserIdString(eids) {
  let str = []
  for (let i = 0; i < eids.length; i++) {
    str.push(eids[i].source + ':' + eids[i].uids[0].id)
  }
  return str.join(',')
}

/**
 * Creates a querystring out of an object with key-values
 * @param {Object} obj
 * @returns {String}
 */
function createQueryString(obj) {
  let str = []
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      let val = obj[p]
      if (p !== 'schain' && p !== 'iab_content') {
        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(val))
      } else {
        str.push(p + '=' + val)
      }
    }
  }
  return str.join('&')
}

/**
 * Creates an unencoded targeting string out of an object with key-values
 * @param {Object} obj
 * @returns {String}
 */
function createTargetingString(obj) {
  let str = []
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      let key = p
      let val = obj[p]
      str.push(key + '=' + val)
    }
  }
  return str.join('&')
}

/**
 * Creates a string out of a schain object
 * @param {Object} schain
 * @returns {String}
 */
function createSchainString(schain) {
  const ver = schain.ver || ''
  const complete = (schain.complete === 1 || schain.complete === 0) ? schain.complete : ''
  const keys = ['asi', 'sid', 'hp', 'rid', 'name', 'domain', 'ext']
  const nodesString = schain.nodes.reduce((acc, node) => {
    return acc += `!${keys.map(key => node[key] ? encodeURIComponentWithBangIncluded(node[key]) : '').join(',')}`
  }, '')
  return `${ver},${complete}${nodesString}`
}

/**
 * Get content object from bid request
 * First get content from bidder params;
 * If not provided in bidder params, get from first party data under 'ortb2.site.content' or 'ortb2.app.content'
 * @param {Object} bid
 * @returns {Object}
 */
function getContentObject(bid) {
  if (bid.params.iabContent && isPlainObject(bid.params.iabContent)) {
    return bid.params.iabContent
  }

  const globalContent = config.getConfig('ortb2.site') ? config.getConfig('ortb2.site.content')
    : config.getConfig('ortb2.app.content')
  if (globalContent && isPlainObject(globalContent)) {
    return globalContent
  }
  return undefined
}

/**
 * Creates a string for iab_content object
 * @param {Object} iabContent
 * @returns {String}
 */
function createIabContentString(iabContent) {
  const arrKeys = ['keywords', 'cat']
  let str = []
  for (let key in iabContent) {
    if (iabContent.hasOwnProperty(key)) {
      const value = (arrKeys.indexOf(key) !== -1 && Array.isArray(iabContent[key]))
        ? iabContent[key].map(node => encodeURIComponent(node)).join('|') : encodeURIComponent(iabContent[key])
      str.push(''.concat(key, ':', value))
    }
  }
  return encodeURIComponent(str.join(','))
}

/**
 * Encodes URI Component with exlamation mark included. Needed for schain object.
 * @param {String} str
 * @returns {String}
 */
function encodeURIComponentWithBangIncluded(str) {
  return encodeURIComponent(str).replace(/!/g, '%21')
}

/**
 * Handles an outstream response after the library is loaded
 * @param {Object} bid
 */
function outstreamRender(bid) {
  bid.renderer.push(() => {
    window.ma_width = bid.width
    window.ma_height = bid.height
    window.ma_vastUrl = bid.vastUrl
    window.ma_container = bid.adUnitCode
    window.document.dispatchEvent(new Event('ma-start-event'))
  });
}

registerBidder(spec)


text:
This class represents a set of [database objects](dataobject), such as the results of a query. It is the base for all
[datamodel](datamodel)-related querying. It implements the [Iterator
interface](http://php.net/manual/en/language.oop5.iterations.php) introduced in PHP5.

Relations (has_many/many_many) are described in
[ComponentSet](http://api.silverstripe.org/trunk/sapphire/model/ComponentSet.html), a subclass of DataObjectSet.

# Usage

## Getting the size

`$mySet->Count();`{php}

## Getting an single element

	:::php
	$myFirstDataObject = $mySet->First();
	$myLastDataObject = $mySet->Last();

## Getting multiple elements

	:::php
	$mySpecialDataObjects = $mySet->find('Status', 'special');
	$startingFromTen = $mySet->getOffset(10);
	$tenToTwenty = $mySet->getRange(10, 10);

## Getting one property

	:::php
	$myIDArray = $mySet->column('ID');

## Grouping

You can group a set by a specific column. Consider using [SQLQuery](SQLQuery) with a *GROUP BY* statement for enhanced
performance.
`$groupedSet = $mySet->groupBy('Lastname');`{php}

## Sorting

Sort a set by a specific column.
`<code php>`$mySet->sort('Lastname'); //ascending
$mySet->sort('Lastname', 'DESC'); //descending`</code>`

This works on the object itself, so do NOT do something like this:
`$sortedSet = $mySet->sort('Lastname'); //ascending`{php}

## Merge with other DataObjectSets

	:::php
	$myFirstSet->merge($mySecondSet);
	// $myFirstSet now contains all combined values

## Mapping for Dropdowns

When using [DropdownField](DropdownField) and its numerous subclasses to select a value from a set, you can easily map
the records to a compatible array:

	:::php
	$map = $mySet->toDropDownMap('ID', 'Title');
	$dropdownField = new DropdownField('myField', 'my label', $map);

## Converting to array

`$myArray = $mySet->toArray();`{php}

## Output as HTML-list

Use [buildNestedUL](http://doc.silverstripe.com/assets/classes/default/DataObjectSet.html#buildNestedUL) to return a
nested unordered list out of a "chain" of DataObject-relations.

## Checking for existence

It is good practice to check for empty sets before doing any iteration.

	:::php
	$mySet = DataObject::get('Players');
	if($mySet->exists()) foreach($mySet as $player)
	// ...

## Paging

DataObjects have native support for dealing with **pagination**.
See *setPageLimits*, *setPageLength*, etc.

FIXME Complete pagination documentation

# API Documentation

[Click here for the API documentation](http://api.silverstripe.org/trunk/sapphire/model/DataObjectSet.html).


text:
'use strict';
import '../css/main.css';
import { ready, request } from '../common/ajax-functions';

import axios from 'axios';

(function () {
  const addButton = document.querySelector('.btn-add');
  const deleteButton = document.querySelector('.btn-delete');
  const clicksDisplay = document.querySelector('.click-amount');
  const apiUrl = 'http://127.0.0.1:3300/api/:id/clicks';

  function ready(fn) {
    if (typeof fn !== 'funciton') return;

    if (document.readyState === 'complete') {
      return fn();
    }

    document.addEventListener('DOMContentLoaded', fn, false);
  }

  const request = (method, url, callback) => {

    return axios[method](url)
      .then((result) => {
        console.log(result.data);
        if (callback) callback(result.data);
      })
  }

  const updateClicks = (data) => {
    clicksDisplay.innerHTML = data.clicks;
  };

  ready(request('get', apiUrl, updateClicks));

  addButton.addEventListener('click', () => {
    request('post', apiUrl)
      .then(request('get', apiUrl, updateClicks));
  }, false);

  deleteButton.addEventListener('click', () => {
    request('delete', apiUrl)
      .then(request('get', apiUrl, updateClicks));
  }, false);

})();


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

require APPPATH.'/libraries/restserver/REST_Controller.php';
class Test extends REST_Controller
{
    public function index_get()
    {
        // Display all books
        //echo 'get-func';
        $id = $this->get('id');
        $this->response(array('id1'=>1,'id2'=>2,'pars3'=>$id,), 200);
    }

    public function index_post()
    {
        // Create a new book
        //echo 'post-func';
        $id = $this->post('id');
        $this->response(array('id1'=>1,'id2'=>2,'pars3'=>$id,), 200);
    }

}


text:
/*!
 * Module dependencies.
 */

var util = require('util'),
    payomatic = require('../'),
	super_ = require('../core/type');

var mapping = {
    "stripe": {
        "id": "id",
        "amount": "amount",
        "chargeId": "charge",
        "currencyCode": "currency",
        "reasonCode": "reason",
        "receiptNumber": "receipt_number",
        "refundedAmount": "amount_refunded"
    }
};

/**
 * Refund Type Constructor
 * @extends Type
 * @constructor {Object} options, object with properties
 * @api public
 */

function Refund(options, brand) {

	Refund.super_.call(this, options);

	if (brand && typeof brand === 'string' && brand.length > 0) {
	    this.brand = brand;
	}

	Object.defineProperty(this, 'id', {
	    get: function () {
	        if (this.get('id')) {
	            return this.get('id');
	        }
	        else {
	            this.set('id', this._options[mapping[this.brand].id] ||this._options.id);
	            return this.get('id');
	        }
	    }
        , set: function (value) { this.set('id', value) }
	})

	Object.defineProperty(this, 'amount', {
	    get: function () {
	        if (this.get('amount')) {
	            return this.get('amount');
	        }
	        else {
	            this.set('amount', this._options[mapping[this.brand].amount] ||this._options.amount);
	            return this.get('amount');
	        }
	    }
        , set: function (value) { this.set('amount', value) }
	})

	Object.defineProperty(this, 'chargeId', {
	    get: function () {
	        if (this.get('chargeId')) {
	            return this.get('chargeId');
	        }
	        else {
	            this.set('chargeId', this._options[mapping[this.brand].chargeId] ||this._options.chargeId);
	            return this.get('chargeId');
	        }
	    }
        , set: function (value) { this.set('chargeId', value) }
	})

	Object.defineProperty(this, 'currencyCode', {
	    get: function () {
	        if (this.get('currencyCode')) {
	            return this.get('currencyCode');
	        }
	        else {
	            this.set('currencyCode', this._options[mapping[this.brand].currencyCode] ||this._options.currencyCode);
	            return this.get('currencyCode');
	        }
	    }
        , set: function (value) { this.set('currencyCode', value) }
	})

	Object.defineProperty(this, 'reasonCode', {
	    get: function () {
	        if (this.get('reasonCode')) {
	            return this.get('reasonCode');
	        }
	        else {
	            this.set('reasonCode', this._options[mapping[this.brand].reasonCode] ||this._options.reasonCode);
	            return this.get('reasonCode');
	        }
	    }
        , set: function (value) { this.set('reasonCode', value) }
	})

	Object.defineProperty(this, 'receiptNumber', {
	    get: function () {
	        if (this.get('receiptNumber')) {
	            return this.get('receiptNumber');
	        }
	        else {
	            this.set('receiptNumber', this._options[mapping[this.brand].receiptNumber] ||this._options.receiptNumber);
	            return this.get('receiptNumber');
	        }
	    }
        , set: function (value) { this.set('receiptNumber', value) }
	})

	Object.defineProperty(this, 'refundedAmount', {
	    get: function () {
	        if (this.get('refundedAmount')) {
	            return this.get('refundedAmount');
	        }
	        else {
	            this.set('refundedAmount', this._options[mapping[this.brand].refundedAmount] ||this._options.refundedAmount);
	            return this.get('refundedAmount');
	        }
	    }
        , set: function (value) { this.set('refundedAmount', value) }
	})

    /**
     * returns the brand specific request object
     *
     * @api public
     */
	this.toRequest = function () {

	    var req = {};

	    switch (this.brand) {
			case 'stripe':
	            req.refund = {};
	            req.refund.id = this.chargeId;
	            if (this.refundedAmount) req.refund.amount = this.refundedAmount;
				if (this.reasonCode) req.refund.reason = this.reasonCode;

	            break;
	        case 'none':
	            break;
	        default:
	            throw new Error('Types must have a brand defined');
	    }

	    return req;
	};

	return this;
}

/*!
 * Inherit from type
 */

util.inherits(Refund, super_);

/*!
 * Export class
 */

exports = module.exports = Refund;