text:
<?php
#**************************************************************************
#  openSIS is a free student information system for public and non-public
#  schools from Open Solutions for Education, Inc. web: www.os4ed.com
#
#  openSIS is  web-based, open source, and comes packed with features that
#  include student demographic info, scheduling, grade book, attendance,
#  report cards, eligibility, transcripts, parent portal,
#  student portal and more.
#
#  Visit the openSIS web site at http://www.opensis.com to learn more.
#  If you have question regarding this system or the license, please send
#  an email to info@os4ed.com.
#
#  This program is released under the terms of the GNU General Public License as
#  published by the Free Software Foundation, version 2 of the License.
#  See license.txt.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#***************************************************************************************
include('../../Redirect_modules.php');
DrawBC("Users > ".ProgramTitle());

if(clean_param($_REQUEST['values'],PARAM_NOTAGS) && ($_POST['values'] || $_REQUEST['ajax']))
{
	if(clean_param($_REQUEST['tab'],PARAM_ALPHAMOD)=='password')
	{
            $column_name= PASSWORD;
            $pass_current= paramlib_validation($column_name,$_REQUEST['values']['current']);
            $pass_new= paramlib_validation($column_name,$_REQUEST['values']['new']);
            $pass_verify= paramlib_validation($column_name,$_REQUEST['values']['verify']);

            $pass_new_after= md5($pass_new);

            $profile_RET = DBGet(DBQuery('SELECT s.PROFILE FROM staff s , staff_school_relationship ssr WHERE s.STAFF_ID=ssr.STAFF_ID AND s.STAFF_ID=\''.User('STAFF_ID').'\' AND ssr.SYEAR=\''.UserSyear().'\''));

            $sql=DBQuery('SELECT PASSWORD FROM staff s , staff_school_relationship ssr where s.password=\''.$pass_new_after.'\'  AND ssr.SYEAR=\''.UserSyear().'\'');
            $number=mysql_num_rows($sql);

		if($pass_new != $pass_verify)
			$error = 'Your new passwords did not match.';

                elseif($number>0)
                {
                   echo 'This password is alredy taken';
                }

		else
		{
			$password_RET = DBGet(DBQuery('SELECT PASSWORD FROM staff s , staff_school_relationship ssr WHERE s.STAFF_ID AND ssr.STAFF_ID AND s.STAFF_ID=\''.User('STAFF_ID').'\' AND ssr.SYEAR=\''.UserSyear().'\''));
                        if($password_RET[1]['PASSWORD'] != md5($pass_current))
				$error = 'Your current password was incorrect.';
			else
			{
				DBQuery('UPDATE staff SET PASSWORD=\''.md5($pass_new).'\' WHERE STAFF_ID=\''.User('STAFF_ID').'\'');
				$note = 'Your new password was saved.';
			}
		}

		/*
		if(strtolower($_REQUEST['values']['new'])!=strtolower($_REQUEST['values']['verify']))
			$error = 'Your new passwords did not match.';
		else
		{
			$password_RET = DBGet(DBQuery("SELECT PASSWORD FROM staff WHERE STAFF_ID='".User('STAFF_ID')."' AND SYEAR='".UserSyear()."'"));
			if(strtolower($password_RET[1]['PASSWORD'])!=md5(strtolower($_REQUEST['values']['current'])))
				$error = 'Your current password was incorrect.';
			else
			{
				DBQuery("UPDATE staff SET PASSWORD='".md5($_REQUEST['values']['new'])."' WHERE STAFF_ID='".User('STAFF_ID')."' AND SYEAR='".UserSyear()."'");
				$note = 'Your new password was saved.';
			}
		}
		*/
	}
	else
	{
		$current_RET = DBGet(DBQuery('SELECT TITLE,VALUE,PROGRAM FROM program_user_config WHERE USER_ID=\''.User('STAFF_ID').'\' AND PROGRAM IN (\''.'Preferences'.'\',\''.'StudentFieldsSearch'.'\',\''.'StudentFieldsView'.'\') '),array(),array('PROGRAM','TITLE'));

		if($_REQUEST['tab']=='student_listing' && $_REQUEST['values']['Preferences']['SEARCH']!='Y')
			$_REQUEST['values']['Preferences']['SEARCH'] = 'N';
		if($_REQUEST['tab']=='student_listing' && $_REQUEST['values']['Preferences']['DEFAULT_FAMILIES']!='Y')
			$_REQUEST['values']['Preferences']['DEFAULT_FAMILIES'] = 'N';
		if($_REQUEST['tab']=='student_listing' && $_REQUEST['values']['Preferences']['DEFAULT_ALL_SCHOOLS']!='Y')
			$_REQUEST['values']['Preferences']['DEFAULT_ALL_SCHOOLS'] = 'N';
		if($_REQUEST['tab']=='display_options' && $_REQUEST['values']['Preferences']['HIDDEN']!='Y')
			$_REQUEST['values']['Preferences']['HIDDEN'] = 'N';
		if($_REQUEST['tab']=='display_options' && $_REQUEST['values']['Preferences']['HIDE_ALERTS']!='Y')
			$_REQUEST['values']['Preferences']['HIDE_ALERTS'] = 'N';
		if($_REQUEST['tab']=='display_options' && $_REQUEST['values']['Preferences']['THEME']!=$current_RET['Preferences']['THEME'][1]['VALUE'])
		{
			echo '';
                        $flag=1;
		}
		if(clean_param($_REQUEST['tab'],PARAM_ALPHAMOD)=='student_fields')
		{
			DBQuery('DELETE FROM program_user_config WHERE USER_ID=\''.User('STAFF_ID').'\' AND PROGRAM IN (\''.'StudentFieldsSearch'.'\',\''.'StudentFieldsView'.'\')');

			foreach($_REQUEST['values'] as $program=>$values)
			{
				foreach($values as $name=>$value)
				{
					if(isset($value))
						DBQuery('INSERT INTO program_user_config (USER_ID,PROGRAM,TITLE,VALUE) values(\''.User('STAFF_ID').'\',\''.$program.'\',\''.$name.'\',\''.$value.'\')');
				}
			}
		}
		else
		{
			foreach($_REQUEST['values'] as $program=>$values)
			{
				foreach($values as $name=>$value)
				{
					if(!$current_RET[$program][$name] && $value!='')
						DBQuery('INSERT INTO program_user_config (USER_ID,PROGRAM,TITLE,VALUE) values(\''.User('STAFF_ID').'\',\''.$program.'\',\''.$name.'\',\''.$value.'\')');
					elseif($value!='')
						DBQuery('UPDATE program_user_config SET VALUE=\''.$value.'\' WHERE USER_ID=\''.User('STAFF_ID').'\' AND PROGRAM=\''.$program.'\' AND TITLE=\''.$name.'\'');
					else
						DBQuery('DELETE FROM program_user_config WHERE USER_ID=\''.User('STAFF_ID').'\' AND PROGRAM=\''.$program.'\' AND TITLE=\''.$name.'\'');
				}
			}
		}
		// So Preferences() will get the new values
		unset($_openSIS['Preferences']);
	}
	unset($_REQUEST['values']);
	unset($_SESSION['_REQUEST_vars']['values']);
        if($flag==1)
            echo "";
        else
            header("Location:Modules.php?modname=Users/Preferences.php");

}

unset($_REQUEST['search_modfunc']);
unset($_SESSION['_REQUEST_vars']['search_modfunc']);

if(!$_REQUEST['modfunc'])
{
	$current_RET = DBGet(DBQuery('SELECT TITLE,VALUE,PROGRAM FROM program_user_config WHERE USER_ID=\''.User('STAFF_ID').'\' AND PROGRAM IN (\''.'Preferences'.'\',\''.'StudentFieldsSearch'.'\',\''.'StudentFieldsView'.'\') '),array(),array('PROGRAM','TITLE'));

	if(!$_REQUEST['tab'])
		$_REQUEST['tab'] = 'display_options';

	echo "<FORM name=perf_form id=perf_form action=Modules.php?modname=$_REQUEST[modname]&tab=$_REQUEST[tab] method=POST onload='document.forms[0].submit;'>";
	//DrawHeader('','<INPUT type=submit value=Save>');
	echo '
';

	if(User('PROFILE')=='admin' || User('PROFILE')=='teacher')
		$tabs = array(array('title'=>'Display Options','link'=>"Modules.php?modname=$_REQUEST[modname]&tab=display_options"),array('title'=>'Student Listing','link'=>"Modules.php?modname=$_REQUEST[modname]&tab=student_listing"),array('title'=>'Password','link'=>"Modules.php?modname=$_REQUEST[modname]&tab=password"),array('title'=>'Student Fields','link'=>"Modules.php?modname=$_REQUEST[modname]&tab=student_fields"));
	else
		$tabs = array(array('title'=>'Display Options','link'=>"Modules.php?modname=$_REQUEST[modname]&tab=display_options"),array('title'=>'Password','link'=>"Modules.php?modname=$_REQUEST[modname]&tab=password"),array('title'=>'Student Fields','link'=>"Modules.php?modname=$_REQUEST[modname]&tab=student_fields"));

	$_openSIS['selected_tab'] = "Modules.php?modname=$_REQUEST[modname]&tab=".$_REQUEST['tab'];
	PopTable('header',$tabs);

	//echo '<fieldset>';

	if(clean_param($_REQUEST['tab'],PARAM_ALPHAMOD)=='student_listing')
	{
		echo '

';
		echo '
Student Name	<INPUT type=radio name=values[Preferences][NAME] value=Common'.((Preferences('NAME')=='Common')?' CHECKED':'').'>Common Name
<INPUT type=radio name=values[Preferences][NAME] value=Given'.((Preferences('NAME')=='Given')?' CHECKED':'').'>Given Name
';
		echo '
Student Sorting	<INPUT type=radio name=values[Preferences][SORT] value=Name'.((Preferences('SORT')=='Name')?' CHECKED':'').'>Name
<INPUT type=radio name=values[Preferences][SORT] value=Grade'.((Preferences('SORT')=='Grade')?' CHECKED':'').'>Grade, Name
';
		echo '
File Export Type	<INPUT type=radio name=values[Preferences][DELIMITER] value=Tab'.((Preferences('DELIMITER')=='Tab')?' CHECKED':'').'>Tab-Delimited (Excel)
<INPUT type=radio name=values[Preferences][DELIMITER] value=CSV'.((Preferences('DELIMITER')=='CSV')?' CHECKED':'').'>CSV (OpenOffice)
';
		echo '

	';
		echo '
<INPUT type=checkbox name=values[Preferences][SEARCH] value=Y'.((Preferences('SEARCH')=='Y')?' CHECKED':'').'>Display student search screen
';
		if(User('PROFILE')=='admin')
		{
			echo '
<INPUT type=checkbox name=values[Preferences][DEFAULT_FAMILIES] value=Y'.((Preferences('DEFAULT_FAMILIES')=='Y')?' CHECKED':'').'>Group by family by default
';
			echo '
<INPUT type=checkbox name=values[Preferences][DEFAULT_ALL_SCHOOLS] value=Y'.((Preferences('DEFAULT_ALL_SCHOOLS')=='Y')?' CHECKED':'').'>Search all schools by default
';
		}
		echo '

';
	}

	if(clean_param($_REQUEST['tab'],PARAM_ALPHAMOD)=='display_options')
	{
		echo '
';

		echo '
Theme

';
		if($handle = opendir($openSISPath.'themes/'))
		{
			while(false !== ($file = readdir($handle)))
			{
				if($file != "." && $file != ".." && !in_array($file,$IgnoreFiles))
				{
					echo '<INPUT type=radio name=values[Preferences][THEME] value='.$file.((Preferences('THEME')==$file)?' CHECKED':'').'>'.$file.'';
					$count++;

				}
			}
			closedir($handle);
			echo '

';
		}

		$colors = array('#85e1ff','#96f3c8','#e9f396','#f3bb96','#f396a7');
		echo '
Highlight Color

';
		foreach($colors as $color)
			echo '<INPUT type=radio name=values[Preferences][HIGHLIGHT] value='.$color.((Preferences('HIGHLIGHT')==$color)?' CHECKED':'').'>	';
		echo '

';

//		echo '
Currency

';
//              #  echo '
Currency

<SELECT name=values[Preferences][CURRENCY]>';
//		 $values = DBGet(DBQuery("SELECT  VALUE AS ID,TITLE FROM program_config WHERE PROGRAM='Currency' "));
//               # $values = array('USD' => 'US Dollar','GBP' => 'British Pound','EUR' => 'Euro','CAD' => 'Canadian Dollar','AUD' => 'Australian Dollar','JPY' => 'Japanese Yen','BRL' => 'Brazillian Real');
//		##foreach($values as $symbol => $name)
//			#echo '<OPTION value='.$symbol.((Preferences('CURRENCY')==$symbol)?' SELECTED':'').'>'.$name.'</OPTION>';
//		#echo '</SELECT>
';
//               $current_RET = DBGet(DBQuery("SELECT TITLE,VALUE,PROGRAM FROM program_user_config WHERE USER_ID='1' AND TITLE='CURRENCY' AND PROGRAM IN ('Preferences') ") );
//               $val = $current_RET[1]['VALUE'];
//               foreach($values as $symbol)
//                $symbols[$symbol['ID']] = $symbol['TITLE'];
//                echo SelectInput($val,'values[Preferences][CURRENCY]','',$symbols,'N/A');
//                echo '
';

		echo '
Date Format

<SELECT name=values[Preferences][MONTH]>';
//		$values = array('F','M','m','n');
                                    $values = array('F','M','n');
		foreach($values as $value)
			echo '<OPTION value='.$value.((Preferences('MONTH')==$value)?' SELECTED':'').'>'.date($value).'</OPTION>';
		echo '</SELECT> ';
		echo '<SELECT name=values[Preferences][DAY]>';
//		$values = array('d','j','jS');
                                    $values = array('j','jS');
		foreach($values as $value)
			echo '<OPTION value='.$value.((Preferences('DAY')==$value)?' SELECTED':'').'>'.date($value).'</OPTION>';
		echo '</SELECT> ';
		echo '<SELECT name=values[Preferences][YEAR]>';
		$values = array('Y','y');
		foreach($values as $value)
			echo '<OPTION value="'.$value.'"'.((Preferences('YEAR')==$value)?' SELECTED':'').'>'.date($value).'</OPTION>';
		echo '</SELECT>';
		echo '
';
		echo '
<INPUT type=checkbox name=values[Preferences][HIDE_ALERTS] value=Y'.((Preferences('HIDE_ALERTS')=='Y')?' CHECKED':'').'>Disable login alerts
';
		echo '
<INPUT type=checkbox name=values[Preferences][HIDDEN] value=Y'.((Preferences('HIDDEN')=='Y')?' CHECKED':'').'>Display data using hidden fields
';
		echo '
';
	}

	if(clean_param($_REQUEST['tab'],PARAM_ALPHAMOD)=='password')
	{
                echo '

';
		if($error)
			echo ErrorMessage(array($error));
		if($note)
			echo ErrorMessage(array($note),'note');
		echo '

Current Password	<INPUT type=password class=cell_floating name=values[current] AUTOCOMPLETE = off>

New Password	<INPUT type=password id=new_pass class=cell_floating name=values[verify] AUTOCOMPLETE = off onkeyup=passwordStrength(this.value);passwordMatch();>

Verify New Password	<INPUT type=password id=ver_pass class=cell_floating name=values[new] AUTOCOMPLETE = off onkeyup=passwordMatch()>

';
	}

	if(clean_param($_REQUEST['tab'],PARAM_ALPHAMOD)=='student_fields')
	{
		if(User('PROFILE_ID'))
			$custom_fields_RET = DBGet(DBQuery('SELECT CONCAT(\''.''.'\',sfc.TITLE,\''.''.'\') AS CATEGORY,cf.ID,cf.TITLE,\''.''.'\' AS SEARCH,\''.''.'\' AS DISPLAY FROM custom_fields cf,student_field_categories sfc WHERE sfc.ID=cf.CATEGORY_ID AND (SELECT DISTINCT CAN_USE FROM profile_exceptions WHERE PROFILE_ID=\''.User('PROFILE_ID').'\' AND MODNAME=CONCAT(\''.'Students/Student.php&category_id='.'\',cf.CATEGORY_ID))=\''.'Y'.'\' ORDER BY sfc.SORT_ORDER,sfc.TITLE,cf.SORT_ORDER,cf.TITLE'),array('SEARCH'=>'_make','DISPLAY'=>'_make'),array('CATEGORY'));
		else
			$custom_fields_RET = DBGet(DBQuery('SELECT CONCAT(\''.''.'\',sfc.TITLE,\''.''.'\') AS CATEGORY,cf.ID,cf.TITLE,\''.''.'\' AS SEARCH,\''.''.'\' AS DISPLAY FROM custom_fields cf,student_field_categories sfc WHERE sfc.ID=cf.CATEGORY_ID AND (SELECT DISTINCT CAN_USE FROM staff_exceptions WHERE USER_ID=\''.User('STAFF_ID').'\' AND MODNAME=CONCAT(\''.'Students/Student.php&category_id='.'\',cf.CATEGORY_ID))=\''.'Y'.'\' ORDER BY sfc.SORT_ORDER,sfc.TITLE,cf.SORT_ORDER,cf.TITLE'),array('SEARCH'=>'_make','DISPLAY'=>'_make'),array('CATEGORY'));

		$THIS_RET['ID'] = 'CONTACT_INFO';
		$custom_fields_RET[-1][1] = array('CATEGORY'=>'Contact Information','ID'=>'CONTACT_INFO','TITLE'=>' Contact Info Rollover','DISPLAY'=>_make('','DISPLAY'));
		$THIS_RET['ID'] = 'HOME_PHONE';
		$custom_fields_RET[-1][] = array('CATEGORY'=>'Contact Information','ID'=>'HOME_PHONE','TITLE'=>'Home Phone Number','DISPLAY'=>_make('','DISPLAY'));
		$THIS_RET['ID'] = 'GUARDIANS';
		$custom_fields_RET[-1][] = array('CATEGORY'=>'Contact Information','ID'=>'GUARDIANS','TITLE'=>'Guardians','DISPLAY'=>_make('','DISPLAY'));
		$THIS_RET['ID'] = 'ALL_CONTACTS';
		$custom_fields_RET[-1][] = array('CATEGORY'=>'Contact Information','ID'=>'ALL_CONTACTS','TITLE'=>'All Contacts','DISPLAY'=>_make('','DISPLAY'));

		$custom_fields_RET[0][1] = array('CATEGORY'=>'Addresses','ID'=>'ADDRESS','TITLE'=>'None','DISPLAY'=>_makeAddress(''));
		$custom_fields_RET[0][] = array('CATEGORY'=>'Addresses','ID'=>'ADDRESS','TITLE'=>' Residence','DISPLAY'=>_makeAddress('RESIDENCE'));
		$custom_fields_RET[0][] = array('CATEGORY'=>'Addresses','ID'=>'ADDRESS','TITLE'=>' Mailing','DISPLAY'=>_makeAddress('MAILING'));
		$custom_fields_RET[0][] = array('CATEGORY'=>'Addresses','ID'=>'ADDRESS','TITLE'=>' Bus Pickup','DISPLAY'=>_makeAddress('BUS_PICKUP'));
		$custom_fields_RET[0][] = array('CATEGORY'=>'Addresses','ID'=>'ADDRESS','TITLE'=>' Bus Dropoff','DISPLAY'=>_makeAddress('BUS_DROPOFF'));

		if(User('PROFILE')=='admin' || User('PROFILE')=='teacher')
			$columns = array('CATEGORY'=>'','TITLE'=>'Field','SEARCH'=>'Search','DISPLAY'=>'Expanded View');
		else
			$columns = array('CATEGORY'=>'','TITLE'=>'Field','DISPLAY'=>'Expanded View');
		ListOutputMod($custom_fields_RET,$columns,'','',array(),array(array('CATEGORY')));
	}

	//echo '</fieldset>';
	PopTable('footer');
	if($_REQUEST['tab']=='display_options')
	echo "<INPUT type=submit class=\"btn_medium\" value=Save >";
	else
	echo "<INPUT type=submit class=\"btn_medium\" value=Save onclick='formload_ajax(\"perf_form\");return pass_check();'>";
	echo '</FORM>';
}

function _make($value,$name)
{	global $THIS_RET,$categories_RET,$current_RET;

	switch($name)
	{
		case 'SEARCH':
			if($current_RET['StudentFieldsSearch'][$THIS_RET['ID']])
				$checked = ' checked';
			return '<INPUT type=checkbox name=values[StudentFieldsSearch]['.$THIS_RET['ID'].'] value=Y'.$checked.'>';
		break;

		case 'DISPLAY':
			if($current_RET['StudentFieldsView'][$THIS_RET['ID']])
				$checked = ' checked';
			return '<INPUT type=checkbox name=values[StudentFieldsView]['.$THIS_RET['ID'].'] value=Y'.$checked.'>';
		break;
	}
}

function _makeAddress($value)
{	global $current_RET;

	if($current_RET['StudentFieldsView']['ADDRESS'][1]['VALUE']==$value || (!$current_RET['StudentFieldsView']['ADDRESS'][1]['VALUE'] && $value==''))
		$checked = ' CHECKED';
	return '<INPUT type=radio name=values[StudentFieldsView][ADDRESS] value="'.$value.'"'.$checked.'>';
}
?>


text:
一些AngularJS中指令等练习。
# 启用[httpserver](https://github.com/indexzero/http-server)
npm install -g http-server
http-server 项目目录
# requireJS+angularJs

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/tilljoel/bgc-account.png?branch=master)](https://travis-ci.org/tilljoel/bgc-account)
[![Code Climate](https://codeclimate.com/github/tilljoel/bgc-account.png)](https://codeclimate.com/github/tilljoel/bgc-account)
# BGC::Account

Ruby Gem for Swedish account numbers.

* __Validate account checksum__
* __Normalize format__
* __Extract meta data from account number__

## Swedish Bank Accounts

[BGC, Bankgirocentralen](http://bgc.se) is the only clearing house in
Sweden and they control the payments infrastructure between Swedish
banks. Payments can be made to three different account types

* Bank Account
* Bankgiro
* Plusgiro (formerly Postgiro)

To protect against errors, all accounts has a simple checksum
using a weighted [Mod-10]
(http://www.bgc.se/upload/Gemensamt/Trycksaker/Manualer/10-MODUL.pdf)/[Mod-11](http://www.bgc.se/upload/Gemensamt/Trycksaker/Manualer/11-MODUL.pdf)
check digit. For some reason different banks decided to do the
checksum calculation on different subsets of the account number, which
makes it a little more complicated.

Some references used in the implementation

* [BGC - Mod 10](http://www.bgc.se/upload/Gemensamt/Trycksaker/Manualer/10-MODUL)
* [BGC - Mod 11 ](http://www.bgc.se/upload/Gemensamt/Trycksaker/Manualer/11-MODUL.pdf)
* [BGC - Check sum rules](http://www.bgc.se/upload/Gemensamt/Trycksaker/Manualer/BG910.pdf)
* [Bankgiro in swedish](http://sv.wikipedia.org/wiki/Bankgirot)
* [Plusgirot in swedish](http://sv.wikipedia.org/wiki/Plusgirot)
* [Danske bank - local swedish payments](https://www-2.danskebank.com/Link/BOCMSIUK/$file/BO_CMSI_UK.pdf)

# Installation

Add this line to your application's Gemfile:

```ruby
  gem 'bgc-account' # or add, :git => 'git://github.com/tilljoel/bgc-account.git'
```

And then execute:

```
  > bundle
```

Or install it yourself as:

```
  > gem install bgc-account
```

# Usage

### Bank Account

```ruby

# clearing and account number, everything except numbers are stripped
account = BGC::Account::BankAccount.new('8336-0', '17 088 212-0')

if account.valid?
  puts account.clearing_number # '83360'
  puts account.account_number  # '170882120'
  puts account.lb_format       # '0083360170882120'
  puts account.normalize       # '83360-170882120'
  puts account.bank_name       # 'Swedbank'
end

```

### Bankgiro

The Bankgiro number is not an account number, but an address that points to a
bank account. BGC helps with the routing to correct bank account.

```ruby

account = BGC::Account::Bankgiro.new('688-64 44')

if account.valid?
  puts account.account_number  # '6886444'
  puts account.lb_format       # '0000000006886444'
  puts account.normalize       # '688-6444'
  puts account.is_fundraising? # false (not correct serie or revoked license)
end

```

### Plusgiro

Plusgirot (formerly Postgirot) is a Swedish money transaction system developet
by the Swedish postal service, currently owned by Nordea. Plusgirot is
connected to BGC, enabling it to take deposits from other banks.

```ruby

account = BGC::Account::Plusgiro.new('818100-0')

if account.valid?
  puts account.account_number  # '8181000'
  puts account.lb_format       # '0000000008181000'
  puts account.normalize       # '818100-0'
  puts account.is_fundraising? # false (not correct serie or revoked license)
end

```

### Error handling

All classes use active_model validations and and support the usual methods

```ruby

account.valid?
account.invalid?
account.errors.any?
account.errors.added?(:account_number, :checksum)
account.errors.count
account.errors.messages

```

## BGC-related gems

I have some code for the BGC-LB and Swedbank-SUS format, it's a gem for
creating payment files for upload to your bank, probably will publish
them soon.

## Copyright

Copyright (c) 2012 Joel Larsson. See LICENSE for further details.

## Contributing

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

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/tilljoel/bgc-account/trend.png)](https://bitdeli.com/free "Bitdeli Badge")


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Extasy</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for:

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

Extasy

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

Extasy Class

            Defined in: lib/main.js:11

Constructor

Extasy

            (

                        child

                        parent

                        staticProps

)

            Class

                Defined in

        lib/main.js:11

Parameters:

                        child
                        Constructor

Constructor function for child class that you want to create

                        parent
                        Class | Array

A single class or an array of classes that you want the child to inherit from. The paren(t's/ts') methods will be put on the child's prototype. If the parent is a dynamic class (ie uses a constructor function) then the parent's prototype methods will be put on the child's prototype. If the parent is a static class (ie an object literal) then it's static methods will be put on the child's prototype. If an array of classes is passed in then these will be flattened (ie a single parent class combining all the methods to be inherited will be created) before applying to the child's prototype.

                        staticProps
                        Object

Optional instance methods to give the class when instantiated (won't be put on proto). By default the paren(t's/ts') instance methods are applied to the child as instance methods

Returns:

                        Class:

                    The child class is returned

Example:

Features

Accepts Constructor or Static Class Parents

Parent can be either a constructor or static class (ie constructor functions or object literals).

Constructor Parents

Parent's prototype methods are placed on child's prototype (static methods if parent is object literal).

function Child() {};
function Parent() {};
extend(Child, Parent);
var ChildInst = new Child();
assert(ChildInst.super_ === Parent.prototype);
assert(ChildInst.hello === 'world');

Static Parents

function Child() {};
var Parent = {};
extend(Child, Parent);
assert(Child.super_ === Parent);
var ChildInst = new Child();
assert(ChildInst.constructor.super_ === Parent);

Multiple Parents

function Child() {};
function Parent() {};
Parent.prototype.kinky = function () { return 'yes, ' + this.menage; };
function Parent2() {};
var Parent3 = {menage: 'a trois'};

// inherit
extend(Child, [Parent, Parent2, Parent3]);
var ChildInst = new Child();

assert(Child.prototype.kinky === Parent.prototype.kinky);
assert(ChildInst.constructor.prototype.kinky === Parent.prototype.kinky);
assert(Child.kinky() === 'yes, a trois');
assert(ChildInst.kinky() === 'yes, a trois');

Copies Constuctor* Parent's Instance Methods & Properties

Parent's instance methods are set as child instance methods if parent is a constructor class.
Does not do this for static classes because their 'instance' methods are put on the prototype

function Child() {};
function Parent() {};
Parent.prototype.random = 'randomness';
Parent.random = 'random';
Parent.bar = 'bar';
extend(Child, Parent);

// differences child class vs instance
var ChildInst = new Child();
assert(Child.bar === Parent.bar);
assert(Child.super_ === undefined);
assert(ChildInst.super_ !== undefined);
assert(Child.random === Parent.random);
assert(Child.random === 'random');
assert(ChildInst.constructor.random === 'random');
assert(ChildInst.super_.random === 'randomness');

Overloading

Overloading Constructor Class Parent

function Child() {};
function Parent() {};
Parent.prototype.foo = function () { return 'father'; };
extend(Child, Parent);

// extend the protoype after extending or else will fail...
Child.prototype.foo = function () {
    return 'you are my ' + this.super_.foo();
}

// initialise
var ChildInst = new Child();
assert(ChildInst.foo() === 'you are my father');

// overload
ChildInst.foo = function () {
    return 'you WERE my ' + this.super_.foo();
}
assert(ChildInst.foo() === 'you WERE my father');

Overloading Static Class Parent

function Child() {};
var Parent = {foo: function () { return 'father'; }};
extend(Child, Parent);

// can't overload thru prototype - need to do thru instance
assert(Child.super_.foo === Parent.foo);
assert(Child.prototype.foo === Parent.foo);
Child.foo = function () {
    return 'you are my ' + this.super_.foo();
}

// overloading instance
var ChildInst = new Child();
assert(Child.foo() === 'you are my father');
assert(ChildInst.constructor.foo() === 'you are my father');

Overloading Multiple Parents

function Child() {};
function Parent() {};
Parent.prototype.kinky = function () { return 'yes, ' + this.menage; };
function Parent2() {};
var Parent3 = {menage: 'a trois'};

// inherit
extend(Child, [Parent, Parent2, Parent3]);
var ChildInst = new Child();

// can't overload thru prototype - need to do thru instance
assert(Child.super_.kinky === Parent.prototype.kinky);
assert(Child.prototype.kinky === Parent.prototype.kinky);

// class overloading
Child.kinky = function () {
    return 'Q: Is my parent kinky? A: ' + this.super_.kinky();
};
assert(Child.kinky() === 'Q: Is my parent kinky? A: yes, a trois');
assert(ChildInst.kinky() !== 'Q: Is my parent kinky? A: yes, a trois');

// instance overloading
var ChildInstOverload = new Child();
t.equal(ChildInstOverload.kinky(),'yes, a trois');
ChildInstOverload.kinky = function () {
    return 'Q: Is my class\'s parent kinky? A: ' + this.constructor.super_.kinky();
};
t.equal(ChildInstOverload.kinky(),'Q: Is my class\'s parent kinky? A: yes, a trois');

Index

Item Index


text:
package mock.async;

import javax.jms.*;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QueueUtils {

    private static final Logger logger = LoggerFactory.getLogger(QueueUtils.class);

    private static final Connection connection;

    public static Connection getConnection() {
        return connection;
    }

    static {
        try {
            logger.debug("waiting for queue / connection ...");
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false&waitForStart=10000");
            connection = connectionFactory.createConnection();
            connection.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void send(String text, int delayMillis) {
        new Thread(() -> {
            try {
                logger.info("*** scheduled delay: {}", delayMillis);
                Thread.sleep(delayMillis);
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Destination destination = session.createQueue(QueueConsumer.QUEUE_NAME);
                MessageProducer producer = session.createProducer(destination);
                producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                TextMessage message = session.createTextMessage(text);
                producer.send(message);
                logger.info("*** sent message: {}", text);
                session.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).start();
    }

}


text:
@interface PodsDummy_Pods_TLTranstionLib_swift_Example : NSObject
@end
@implementation PodsDummy_Pods_TLTranstionLib_swift_Example
@end


text:
package e2e_node

import (
	"fmt"
	"time"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/util"
	"k8s.io/kubernetes/test/e2e/framework"

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

var _ = framework.KubeDescribe("Kubelet Container Manager", func() {
	f := NewDefaultFramework("kubelet-container-manager")
	Describe("oom score adjusting", func() {
		Context("when scheduling a busybox command that always fails in a pod", func() {
			var podName string

			BeforeEach(func() {
				podName = "bin-false" + string(util.NewUUID())
				pod := &api.Pod{
					ObjectMeta: api.ObjectMeta{
						Name:      podName,
						Namespace: f.Namespace.Name,
					},
					Spec: api.PodSpec{
						// Force the Pod to schedule to the node without a scheduler running
						NodeName: *nodeName,
						// Don't restart the Pod since it is expected to exit
						RestartPolicy: api.RestartPolicyNever,
						Containers: []api.Container{
							{
								Image:   ImageRegistry[busyBoxImage],
								Name:    podName,
								Command: []string{"/bin/false"},
							},
						},
					},
				}

				_, err := f.Client.Pods(f.Namespace.Name).Create(pod)
				Expect(err).To(BeNil(), fmt.Sprintf("Error creating Pod %v", err))
			})

			It("should have an error terminated reason", func() {
				Eventually(func() error {
					podData, err := f.Client.Pods(f.Namespace.Name).Get(podName)
					if err != nil {
						return err
					}
					if len(podData.Status.ContainerStatuses) != 1 {
						return fmt.Errorf("expected only one container in the pod %q", podName)
					}
					contTerminatedState := podData.Status.ContainerStatuses[0].State.Terminated
					if contTerminatedState == nil {
						return fmt.Errorf("expected state to be terminated. Got pod status: %+v", podData.Status)
					}
					if contTerminatedState.Reason != "Error" {
						return fmt.Errorf("expected terminated state reason to be error. Got %+v", contTerminatedState)
					}
					return nil
				}, time.Minute, time.Second*4).Should(BeNil())
			})

			It("should be possible to delete", func() {
				err := f.Client.Pods(f.Namespace.Name).Delete(podName, &api.DeleteOptions{})
				Expect(err).To(BeNil(), fmt.Sprintf("Error deleting Pod %v", err))
			})
		})
	})

})


text:
package com.marklogic.mapreduce.functions;

/**
 * Wrapper class for the cts:element-value-co-occurrences
 * lexicon function. Subclass this class to generate map input based on a
 * lexicon.
 *
 *

 *   Use this class with {@link com.marklogic.mapreduce.KeyValueInputFormat}
 *   or {@link com.marklogic.mapreduce.ValueInputFormat}.
 *

 *

 *   To generate map input from the lexicon function,
 *   create a subclass of this class and provide implementations
 *   of the methods that correspond to the function parameters you
 *   want to include in the call.
 *

 *

 *   For details, see "Using a Lexicon to Generate Key-Value Pairs"
 *   in the MarkLogic Connector for Hadoop Developer's Guide.
 *   For an example, see
 *   {@link com.marklogic.mapreduce.examples.LinkCountCooccurrences}.

 *

 *
 *

 *   All co-occurrences functions using this API do NOT preserve
 *   frequency order even if "frequency-order" option is specified.
 *

 *
 * @author jchen
 */
public abstract class ElemValueCooccurrences extends CooccurrencesFunction {

    /**
     * Get the value for the $element-name-1 parameter to the
     * lexicon function call, as a string. The returned string
     * must evaluate to an xs:QName when evaluated as XQuery.
     * For example: "xs:QName(\"wp:a\")".
     *
     * @return first element QName.
     */
    public abstract String getElementName1();

    /**
     * Get the value for the $element-name-2 parameter to the
     * lexicon function call, as a string. The returned string
     * must evaluate to an xs:QName when evaluated as XQuery.
     * For example: "xs:QName(\"wp:a\")".
     *
     * @return first element QName.
     */
    public abstract String getElementName2();

    @Override
    void appendFunctionName(StringBuilder buf) {
        buf.append("cts:element-value-co-occurrences");
    }

    @Override
    void appendNamesParams(StringBuilder buf) {
        // first element name
        buf.append(getElementName1()).append(",\n");
        // second element name
        buf.append(getElementName2()).append(",\n");
    }
}


text:
function splitquery(url) {
	var offset = url.indexOf('?');
	if (offset == -1)
		return [url, '']
	left = url.substr(0, offset);
	right = url.substr(offset);
	return [left, right];
}

function splitpath(path) {
	var offset = path.lastIndexOf('/');
	if (offset == -1)
		return [path, ''];
	return [path.substr(0, offset+1), path.substr(offset)];
}

var tmp = splitquery('' + window.location.href);
var homeURL = tmp[0] + '?';
var tmp = splitpath(homeURL);
var baseURL = tmp[0];

//Spinner handler
$(function() {
	// Prevent spinner from showing negative numbers
        var spinner = $("#spinner").spinner({
		spin: function(event, ui) {
		    if(ui.value < 0) {
			$(this).spinner("value", 0);
			return false;
		    }
		}
	    });

	var title = getParameterByName('title');
	// If title parameter is specified, keep it
	if (title != null)
	    title = 'title=' + title + '&'

	// Go button
        $("#go").click(function() {
		window.location.href = homeURL + title + 'hours=' + spinner.spinner("value");
	});
});

// Gets parameters from url address
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
    var results = regex.exec(location.search);
    if (results == null)
        return null;
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

// Taken from http://stackoverflow.com/questions/11841486/datatables-drill-down-rows-with-nested-independent-table
function fnFormatDetails(tableId, html) {
    var sOut = "
";
    sOut += html;
    sOut += "
";
    return sOut;
}

// Draws table
function dataHandler() {
    var iTableCounter = 1;
    var oTable, oInnerTable, detailsTableHtml;

    var hours = getParameterByName('hours') || "";
    var site = getParameterByName('site') || "";
    var summaryUrl = baseURL + "summary.wsgi?hours=" + hours + '&site=' + site;

    // Limit to a single search key?
    var autosearch = getParameterByName('search');

    $(document).ready(function() {
	    detailsTableHtml = $('#childTable').html();

	    // Add +/- column to table
	    var nCloneTh = document.createElement('th');
	    var nCloneTd = document.createElement('td');
	    nCloneTd.innerHTML = '';
	    nCloneTh.className = 'center';

	    $('#summaryTable thead tr').each(function () {
		    this.insertBefore(nCloneTh, this.childNodes[0]);
		});

	    $('#summaryTable tbody tr').each(function () {
		    this.insertBefore(nCloneTd.cloneNode(true), this.childNodes[0]);
		});

	    // Initialize DataTables for the 'details' table
	    var oTable = $('#summaryTable').dataTable({
		    "bJQueryUI": true,
		    "ajax": summaryUrl,
		    "bPaginate": false,
		    "aoColumns": [
	                          {
		                      "mDataProp": null,
		                      "sClass": "control center",
		                      "sDefaultContent": '',
				      "bSortable": false
	                          },
	                          { "data": "user" },
	                          { "data": "project" },
	                          { "data": "jobs" },
	                          { "data": "percentcompleted" },
	                          { "data": "walltime" },
	                          { "data": "cputime" },
	                          { "data": "efficiency" },
	                          { "data": "username", "visible": false }, // In order to submit username to wsgi in child
				 ],
		    "footerCallback": function ( row, data, start, end, display ) {
			var api = this.api(), data;

			for(var i=3;i<7;i++) {
			    if(i == 4)
				continue;
			    // Total jobs, wall time, and cpu time columns
			    data = api.column(i).data();
			    total = data.length ?
				data.reduce( function (a, b) {
				    return parseFloat(a) + parseFloat(b);
				}) :
				0;
			    // Update footer
			    $(api.column(i).footer()).html(Math.round(total));
			}
		    }
		});

	    // Add listener event for opening and closing details
	    $(document).on('click', '#summaryTable tbody td img', function () {
		    var nTr = $(this).parents('tr')[0];
		    var nTds = this;
		    var username = oTable.fnGetData(nTr, 8);
		    var urlAddr = baseURL + 'single-user.wsgi?hours=' + hours + ';user=' + username;

		    if(oTable.fnIsOpen(nTr)) {
			// Close row
			this.src = "http://i.imgur.com/SD7Dz.png";
			oTable.fnClose(nTr);
		    }
		    else {
			// Open row
			var rowIndex = oTable.fnGetPosition( $(nTds).closest('tr')[0] );

			this.src = "http://i.imgur.com/d4ICC.png";
			oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, detailsTableHtml), 'details');

			oInnerTable = $("#summaryTable_" + iTableCounter).dataTable({
				"bJQueryUI": true,
				"bFilter": false,
				"ajax": urlAddr,
				"aoColumns": [
			                      { "data": "site" },
			                      { "data": "jobs" },
			                      { "data": "percentcompleted" },
		              	              { "data": "walltime" },
			                      { "data": "cputime" },
			                      { "data": "efficiency" }
					     ],
				"bPaginate": false
			    });
			iTableCounter = iTableCounter + 1;
		    }
		});

        // populate the search
        if (autosearch) {
            $('#summaryTable_filter label input').val(autosearch);
            $('#summaryTable_filter label input').keyup();
         }
	});
}

// Change title and header if title is specified in url
var title = getParameterByName('title');
if (title != null) {
    $('title').text(title);
    $('#pagetitle').text(title);
}

// Hide table header?
var decor = getParameterByName('decoration');
if (decor == 'plain') {
    $('.table_header').hide();
}


text:
/**
 * DataZoom component entry
 */

import * as echarts from '../echarts';
import preprocessor from './visualMap/preprocessor';

import './visualMap/typeDefaulter';
import './visualMap/visualEncoding';
import './visualMap/ContinuousModel';
import './visualMap/ContinuousView';
import './visualMap/visualMapAction';

echarts.registerPreprocessor(preprocessor);


text:
module FinderHelpers
  def stub_content_item_from_content_store_for(base_path)
    @content_item = content_item_for_base_path(base_path)

    stub_content_store_has_item(base_path, @content_item)
  end
end

World(FinderHelpers)


text:
local Utils = require 'script/lua/utils'
local Scroller = require 'script/lua/scrolling_list'
local ListItem = require 'script/lua/list_button_item'
local RectMask = require 'script/lua/rect_mask'

local Actor = scaleform.Actor
local Component = scaleform.Component
local ContainerComponent = scaleform.ContainerComponent
local AnimationComponent = scaleform.AnimationComponent

-- These will be set in the start() procedure. We cannot access Scaleform's
-- stage at this point in time.
local child_container, this_actor, mask

local anim_out_time = 0.45
local container_size = {width=200, height=600}
local removed_indices = {}
local fading_out_indices = {}
local highlighted_view = nil

-- Views
local view_pool = {}

local function view_take(idx)
	local item
	if #view_pool > 0 then
		item = table.remove(view_pool, #view_pool)
	else
		item = ListItem.create()
	end
	ContainerComponent.add_actor(child_container, item.actor)
	return item
end

local function view_destroy(v)
	ListItem.destroy(v)
end

local function view_release(v)
	table.insert(view_pool, v)
	ContainerComponent.remove_actor(child_container, v.actor, false)
end

local function index_measure(state)
	local n = state % 4
	local base = 45 + n * 20
	local age = fading_out_indices[state]
	if age then
		return Utils.lerp(base, 0, math.pow(age / anim_out_time, 0.5))
	else
		return base
	end
end

local function view_set_size_and_alpha(v, idx)
	local height = index_measure(idx)
	local size = scaleform.Size()
	size.width = container_size.width
	size.height = height
	Actor.set_dimensions(v.image_actor, size)

	local age = fading_out_indices[idx]
	local base_alpha, text_alpha
	if age then
		base_alpha = Utils.clamp(1 - math.pow(age / (anim_out_time / 1.3), 1.75), 0, 1)
		text_alpha = Utils.clamp(1 - math.pow(age / (anim_out_time / 5), 2), 0, 1)
	else
		base_alpha = 1
		text_alpha = 1
	end
	ListItem.set_alphas(v, base_alpha, text_alpha)
end

local function view_set_position(view, position)
	Actor.set_local_position(view.actor, {x=0, y=position})
end

-- Indices
local function string_for_index(idx)
	return "Item " .. tostring(idx)
end

local function index_valid(idx)
	assert(idx, "datum thing is not nil")
	return idx > 0 and (not removed_indices[idx])
end

local function set_state(v, idx)
	if idx then
		assert(index_valid(idx), "datum is valid")
		view_set_size_and_alpha(v, idx)
		ListItem.set_text(v, string_for_index(idx))
	else
		ListItem.set_text(v, "?")
	end
end

local function index_start()
	for i=1,1000 do
		if not removed_indices[i] then
			return i
		end
	end
	return nil
end

local function index_prev(idx)
	local i = idx - 1
	while i > 0 do
		if not removed_indices[i] then return i end
		i = i - 1
	end
	return nil
end

local function index_next(idx)
	local i = idx + 1
	while true do
		if not removed_indices[i] then return i end
		i = i + 1
	end
	return nil
end

local scrolling_list = Scroller.create{
	visible_length=function() return container_size.height end,
	data_start=index_start,
	data_prev=index_prev,
	data_next=index_next,
	data_valid=index_valid,
	data_measure=index_measure,
	view_take=view_take,
	view_release=view_release,
	view_set_data=set_state,
	view_set_position=view_set_position
}

local function point_in_size(p, size)
	return p.x >= 0 and p.x < size.width and p.y >= 0 and p.y < size.height
end

local function update(dt)
	RectMask.set_size(mask, container_size.width, container_size.height)

	local up_id = stingray.Mouse.button_id("wheel_down")
	local down_id = stingray.Mouse.button_id("wheel_up")
	local mouse_up = stingray.Mouse.pressed(up_id)
	local mouse_down = stingray.Mouse.pressed(down_id)
	local keyboard_up = Utils.is_key_down("down")
	local keyboard_down = Utils.is_key_down("up")
	local mouse_scroll_speed = 20
	local keyboard_scroll_speed = 500 * dt

	if Utils.was_key_pressed("x") then
		removed_indices = {}
	end

	if Utils.was_key_pressed("c") then
		Scroller.scroll_to(scrolling_list, 60, {visible_position=100})
	end
	if Utils.was_key_pressed("v") then
		Scroller.scroll_to(scrolling_list, 100, {visible_position=100})
	end
	if Utils.was_key_pressed("b") then
		Scroller.scroll_to(scrolling_list, 1, {visible_position=-100})
	end
	local val = 0
	if mouse_up then
		val = mouse_scroll_speed
	elseif mouse_down then
		val = -mouse_scroll_speed
	end

	if keyboard_up then
		val = val + keyboard_scroll_speed
	end
	if keyboard_down then
		val = val - keyboard_scroll_speed
	end

	if mouse_up or mouse_down or keyboard_up or keyboard_down then
		Scroller.scroll_by(scrolling_list, val)
	end
	Scroller.update(scrolling_list, dt)

	-- update sizing animation
	local removed = {}
	for item, age in pairs(fading_out_indices) do
		fading_out_indices[item] = age + dt
		if fading_out_indices[item] > anim_out_time then
			removed_indices[item] = true
			table.insert(removed, item)
		else
			local view = Scroller.view_for_item(scrolling_list, item)
			if view then
				view_set_size_and_alpha(view, item)
			end
		end
	end
	for i=1, #removed do
		fading_out_indices[removed[i]] = nil
	end

	-- highlighting

	local cursor_pos = scaleform.Point()
	if stingray then
		local p = stingray.Mouse.axis(stingray.Mouse.axis_id("cursor"), stingray.Mouse.RAW, 3)
		-- Not sure which one is correct
		-- local w, h = stingray.Application.back_buffer_size()
		local w, h = stingray.Gui.resolution()
		cursor_pos.x = p.x
		cursor_pos.y = h - p.y
	else
		cursor_pos.x = 0
		cursor_pos.y = 0
	end

	local from_stage = scaleform.Stage.transform_to_screen_matrix()
	-- Workaround for Scaleform bug
	-- http://forums.autodesk.com/t5/stingray/scaleform-stage-transform-to-screen-matrix-return-value/td-p/5822396
	from_stage = Matrix2F.Append(Matrix2F.Identity(), from_stage)
	local to_stage = Matrix2F.Invert(from_stage)
	local cursor_pos_stage = Matrix2F.Transform(to_stage, cursor_pos)
	local mouse_local = Actor.world_to_local(this_actor, cursor_pos_stage)

	local item = nil
	if point_in_size(mouse_local, container_size) then
		item = Scroller.item_at_position(scrolling_list, mouse_local.y)
	end

	local view = nil
	if item and (not fading_out_indices[item]) then
		view = Scroller.view_for_item(scrolling_list, item)
	end
	if view ~= highlighted_view then
		if highlighted_view then
			ListItem.set_hovered(highlighted_view, false)
		end
		highlighted_view = view
		if highlighted_view then
			ListItem.set_hovered(highlighted_view, true)
		end
	end

	if item and Utils.was_mouse_clicked("left") then
		if not fading_out_indices[item] then
			fading_out_indices[item] = 0
		end
	end
end

GlobalUI = GlobalUI or {}

function GlobalUI.start()
	local list = scaleform.Stage.actor_by_name_path("Scene0.list")
	local list_container = Actor.container(list)
	this_actor, child_container = Actor.create(list_container, ContainerComponent)
	mask = RectMask.create(this_actor)
end

function GlobalUI.update(dt)
	update(dt)
end

function GlobalUI.shutdown()
	Scroller.reset(scrolling_list)
	ContainerComponent.remove_actor(child_container, this_actor)
end


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;
class Application extends Model
{
	protected $fillable =
		[
	      "first_name",
	      "last_name",
	      "email",
	      "phone",
	      "address",
	      "city",
	      "state",
	      "zip",
	      "personalName",
	      "personalEmail",
	      "workName",
	      "workPhone",
	      "churchName",
	      "churchPhone",
	      "testimony",
	      "history",
	      "plans"
      	];
			public function isAccepted($email)
			{
				return is_null(User::whereEmail($email)->first());
			}
}


text:
import Network.AWS.S3Bucket
import Network.AWS.S3Object
import Network.AWS.AWSConnection
import Network.AWS.AWSResult
import System.Environment
import Data.Maybe

main = do mConn <- amazonS3ConnectionFromEnv
          let conn = fromJust mConn
          res <- listBuckets conn
          either print (mapM_ (putStrLn . bucket_name)) res


text:
package org.apache.oozie.command.bundle;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.oozie.BundleActionBean;
import org.apache.oozie.BundleJobBean;
import org.apache.oozie.CoordinatorJobBean;
import org.apache.oozie.ErrorCode;
import org.apache.oozie.client.Job;
import org.apache.oozie.client.OozieClient;
import org.apache.oozie.command.CommandException;
import org.apache.oozie.executor.jpa.BundleActionQueryExecutor;
import org.apache.oozie.executor.jpa.BundleJobGetJPAExecutor;
import org.apache.oozie.executor.jpa.CoordJobInsertJPAExecutor;
import org.apache.oozie.executor.jpa.BundleActionQueryExecutor.BundleActionQuery;
import org.apache.oozie.service.JPAService;
import org.apache.oozie.service.Services;
import org.apache.oozie.service.UUIDService;
import org.apache.oozie.service.StatusTransitService.StatusTransitRunnable;
import org.apache.oozie.test.XDataTestCase;
import org.apache.oozie.util.XConfiguration;

public class TestBundleStartXCommand extends XDataTestCase {

    private Services services;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        services = new Services();
        services.init();
    }

    @Override
    protected void tearDown() throws Exception {
        services.destroy();
        super.tearDown();
    }

    /**
     * Test : Start bundle job
     *
     * @throws Exception
     */
    public void testBundleStart1() throws Exception {
        BundleJobBean job = this.addRecordToBundleJobTable(Job.Status.PREP, false);

        JPAService jpaService = Services.get().get(JPAService.class);
        assertNotNull(jpaService);
        BundleJobGetJPAExecutor bundleJobGetExecutor = new BundleJobGetJPAExecutor(job.getId());
        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(job.getStatus(), Job.Status.PREP);

        new BundleStartXCommand(job.getId()).call();

        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(job.getStatus(), Job.Status.RUNNING);

        sleep(2000);

        List<BundleActionBean> actions = BundleActionQueryExecutor.getInstance().getList(
                BundleActionQuery.GET_BUNDLE_ACTIONS_STATUS_UNIGNORED_FOR_BUNDLE, job.getId());

        assertEquals(2, actions.size());
        assertEquals(true, actions.get(0).isCritical());
        assertEquals(job.getId(), actions.get(0).getBundleId());
        assertEquals(false, actions.get(1).isCritical());
        assertEquals(job.getId(), actions.get(0).getBundleId());
    }

    /**
     * Test : Start bundle job
     *
     * @throws Exception
     */
    public void testBundleStart2() throws Exception {
        BundleJobBean job = this.addRecordToBundleJobTable(Job.Status.PREP, false);

        final JPAService jpaService = Services.get().get(JPAService.class);
        assertNotNull(jpaService);

        Configuration jobConf = null;
        try {
            jobConf = new XConfiguration(new StringReader(job.getConf()));
        }
        catch (IOException ioe) {
            log.warn("Configuration parse error. read from DB :" + job.getConf(), ioe);
            throw new CommandException(ErrorCode.E1005, ioe);
        }

        Path appPath = new Path(jobConf.get(OozieClient.BUNDLE_APP_PATH), "bundle.xml");
        jobConf.set(OozieClient.BUNDLE_APP_PATH, appPath.toString());

        BundleSubmitXCommand submitCmd = new BundleSubmitXCommand(jobConf);
        submitCmd.call();

        BundleJobGetJPAExecutor bundleJobGetExecutor = new BundleJobGetJPAExecutor(submitCmd.getJob().getId());
        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals("bundle-app-name", job.getAppName());
        job = jpaService.execute(bundleJobGetExecutor);

        assertEquals(job.getStatus(), Job.Status.PREP);

        new BundleStartXCommand(job.getId()).call();

        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(job.getStatus(), Job.Status.RUNNING);

        sleep(2000);

        List<BundleActionBean> actions = BundleActionQueryExecutor.getInstance().getList(
                BundleActionQuery.GET_BUNDLE_ACTIONS_STATUS_UNIGNORED_FOR_BUNDLE, job.getId());
        assertEquals(2, actions.size());

        final String jobId = job.getId();
        waitFor(200000, new Predicate() {
            public boolean evaluate() throws Exception {
                List<BundleActionBean> actions = BundleActionQueryExecutor.getInstance().getList(
                        BundleActionQuery.GET_BUNDLE_ACTIONS_STATUS_UNIGNORED_FOR_BUNDLE, jobId);
                return actions.get(0).getStatus().equals(Job.Status.RUNNING)
                        && actions.get(1).getStatus().equals(Job.Status.RUNNING);
            }
        });

        actions = BundleActionQueryExecutor.getInstance().getList(BundleActionQuery.GET_BUNDLE_ACTIONS_STATUS_UNIGNORED_FOR_BUNDLE,
                job.getId());
        assertEquals(Job.Status.RUNNING, actions.get(0).getStatus());
        assertEquals(true, actions.get(0).isCritical());
        assertEquals(job.getId(), actions.get(0).getBundleId());
        assertEquals(Job.Status.RUNNING, actions.get(1).getStatus());
        assertEquals(false, actions.get(1).isCritical());
        assertEquals(job.getId(), actions.get(1).getBundleId());
    }

    /**
     * Test : Start bundle job when certain coord jobs are not enabled
     *
     * @throws Exception
     */
    public void testBundleStart3() throws Exception {
        BundleJobBean job = this.addRecordToBundleJobTableDisabledCoord(Job.Status.PREP);

        JPAService jpaService = Services.get().get(JPAService.class);
        assertNotNull(jpaService);
        BundleJobGetJPAExecutor bundleJobGetExecutor = new BundleJobGetJPAExecutor(job.getId());
        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(job.getStatus(), Job.Status.PREP);

        new BundleStartXCommand(job.getId()).call();

        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(job.getStatus(), Job.Status.RUNNING);

        sleep(2000);

        List<BundleActionBean> actions = BundleActionQueryExecutor.getInstance()
                .getList(BundleActionQuery.GET_BUNDLE_ACTIONS_STATUS_UNIGNORED_FOR_BUNDLE, job.getId());

        assertEquals(1, actions.size());
        assertEquals(job.getId(), actions.get(0).getBundleId());
    }

    /**
     * Test : Start bundle job with dryrun
     *
     * @throws Exception
     */
    public void testBundleStartDryrun() throws Exception {
        BundleJobBean job = this.addRecordToBundleJobTable(Job.Status.PREP, false);

        JPAService jpaService = Services.get().get(JPAService.class);
        assertNotNull(jpaService);
        BundleJobGetJPAExecutor bundleJobGetExecutor = new BundleJobGetJPAExecutor(job.getId());
        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(job.getStatus(), Job.Status.PREP);

        new BundleStartXCommand(job.getId(), true).call();

        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(job.getStatus(), Job.Status.RUNNING);

        sleep(2000);

        List<BundleActionBean> actions = BundleActionQueryExecutor.getInstance().getList(
                BundleActionQuery.GET_BUNDLE_ACTIONS_STATUS_UNIGNORED_FOR_BUNDLE, job.getId());

        assertEquals(2, actions.size());
        assertEquals(true, actions.get(0).isCritical());
        assertEquals(job.getId(), actions.get(0).getBundleId());
        assertEquals(false, actions.get(1).isCritical());
        assertEquals(job.getId(), actions.get(1).getBundleId());
    }

    /**
     * Test : Start bundle job but jobId is wrong
     *
     * @throws Exception
     */
    public void testBundleStartNegative1() throws Exception {
        this.addRecordToBundleJobTable(Job.Status.PREP, false);

        try {
            new BundleStartXCommand("bundle-id").call();
            fail("Job doesn't exist. Should fail.");
        }
        catch (CommandException ce) {
            // Job doesn't exist. Exception is expected.
        }
    }

    /**
     * Test : Start bundle job that contains bad coordinator job
     *
     * @throws Exception
     */
    public void testBundleStartNegative2() throws Exception {
        BundleJobBean job = this.addRecordToBundleJobTableNegative(Job.Status.PREP);

        final JPAService jpaService = Services.get().get(JPAService.class);
        assertNotNull(jpaService);
        final BundleJobGetJPAExecutor bundleJobGetExecutor = new BundleJobGetJPAExecutor(job.getId());
        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(job.getStatus(), Job.Status.PREP);

        new BundleStartXCommand(job.getId()).call();

        waitFor(120000, new Predicate() {
            public boolean evaluate() throws Exception {
                BundleJobBean job1 = jpaService.execute(bundleJobGetExecutor);
                return job1.getStatus().equals(Job.Status.FAILED);
            }
        });
        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(Job.Status.FAILED, job.getStatus());
    }

    public static class DummyUUIDService extends UUIDService {
        boolean firstTime = true;
        @Override
        public String generateId(ApplicationType type) {
            if (type.equals(ApplicationType.COORDINATOR) && firstTime) {
                firstTime = false;
                return "dummy-coord-id";
            }
            else {
                return super.generateId(type);
            }
        }
    }

    public void testBundleStartWithFailedCoordinator() throws Exception {
        services.destroy();
        services = new Services();
        String excludeServices[] = { "org.apache.oozie.service.UUIDService",
                "org.apache.oozie.service.StatusTransitService" };
        Configuration conf = services.getConf();
        setClassesToBeExcluded(conf, excludeServices);
        conf.set(Services.CONF_SERVICE_CLASSES,
                conf.get(Services.CONF_SERVICE_CLASSES) + "," + DummyUUIDService.class.getName());
        services.init();
        CoordinatorJobBean coordJob = new CoordinatorJobBean();
        coordJob.setId("dummy-coord-id");
        JPAService jpaService = Services.get().get(JPAService.class);
        CoordJobInsertJPAExecutor coordInsertCmd = new CoordJobInsertJPAExecutor(coordJob);
        jpaService.execute(coordInsertCmd);
        BundleJobBean job = addRecordToBundleJobTable(Job.Status.PREP, false);
        BundleJobGetJPAExecutor bundleJobGetExecutor = new BundleJobGetJPAExecutor(job.getId());
        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(job.getStatus(), Job.Status.PREP);
        new BundleStartXCommand(job.getId()).call();
        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(job.getStatus(), Job.Status.RUNNING);
        sleep(2000);
        List<BundleActionBean> actions = BundleActionQueryExecutor.getInstance().getList(
                BundleActionQuery.GET_BUNDLE_ACTIONS_STATUS_UNIGNORED_FOR_BUNDLE, job.getId());
        assertNull(actions.get(0).getCoordId());
        assertEquals(Job.Status.FAILED, actions.get(0).getStatus());
        Runnable runnable = new StatusTransitRunnable();
        //1st run of StatusTransitionService changes bundle to running
        runnable.run();
        sleep(2000);
        //2nd run changes bundle to DoneWithError
        runnable.run();
        sleep(2000);
        job = jpaService.execute(bundleJobGetExecutor);
        assertEquals(job.getStatus(), Job.Status.DONEWITHERROR);
    }

}


text:
@interface XWEntityUserModalOperation : XWEntityBaseModalOperation

@end


text:
delete peer1..scope_info
insert into peer1..scope_info(scope_name) values ('sales')

delete peer2..scope_info
insert into peer2..scope_info(scope_name) values ('sales')

delete peer3..scope_info
insert into peer3..scope_info(scope_name) values ('sales')
go

--
-- ========================================================================================================================================================================
--  Cleanup content and metadata
-- ========================================================================================================================================================================
--
delete peer1..scope_info
delete peer1..orders
delete peer1..orders_tracking
delete peer1..order_details
delete peer1..order_details_tracking

delete peer2..scope_info
delete peer2..orders
delete peer2..orders_tracking
delete peer2..order_details
delete peer2..order_details_tracking

delete peer3..scope_info
delete peer3..orders
delete peer3..orders_tracking
delete peer3..order_details
delete peer3..order_details_tracking

go

--
-- ========================================================================================================================================================================
--  DML - Test Code
-- ========================================================================================================================================================================
--

insert into orders (order_id, order_date) values(1, GetDate())
insert into orders (order_id, order_date) values(4, GetDate())

update orders set order_date = GetDate() where order_id = 4

delete orders where order_id = 3

insert into order_details (order_id, order_details_id, product) values(7, 2 , 'DVD')
insert into order_details (order_id, order_details_id, product) values(3, 3 , 'CD')
insert into order_details (order_id, order_details_id, product) values(4, 2 , 'Floppy Disk')

update order_details set product = 'HDTV' where order_id =2
update order_details set order_details_id = 11 where order_id in (20,21,23)

delete peer1..orders where order_id = 1282

select @@dbts

select * from peer1..orders
select * from peer2..orders
select * from peer3..orders

select * from peer1..orders_tracking
select * from peer2..orders_tracking
select * from peer3..orders_tracking

select * from peer1..order_details
select * from peer2..order_details
select * from peer3..order_details

select * from peer1..order_details_tracking
select * from peer2..order_details_tracking
select * from peer3..order_details_tracking

select * from peer1 ..scope_info
select * from peer2 ..scope_info
select * from peer3 ..scope_info


text:
using CommandLine;
using NodaTime.TimeZones;
using NodaTime.TimeZones.Cldr;
using NodaTime.TzdbCompiler.Tzdb;
using NodaTime.Xml;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace NodaTime.TzdbCompiler
{
    /// <summary>
    /// Main entry point for the time zone information compiler. In theory we could support
    /// multiple sources and formats but currently we only support one:
    /// https://www.iana.org/time-zones. This system refers to it as TZDB.
    /// This also requires a windowsZone.xml file from the Unicode CLDR repository, to
    /// map Windows time zone names to TZDB IDs.
    /// </summary>
    internal sealed class Program
    {
        /// <summary>
        /// Runs the compiler from the command line.
        /// </summary>
        /// <param name="arguments">The command line arguments. Each compiler defines its own.</param>
        /// <returns>0 for success, non-0 for error.</returns>
        private static async Task<int> Main(string[] arguments)
        {
            CompilerOptions options = new CompilerOptions();
            ICommandLineParser parser = new CommandLineParser(new CommandLineParserSettings(Console.Error) { MutuallyExclusive = true });
            if (!parser.ParseArguments(arguments, options))
            {
                return 1;
            }

            var tzdbCompiler = new TzdbZoneInfoCompiler();
            var tzdb = await tzdbCompiler.CompileAsync(options.SourceDirectoryName!);
            tzdb.LogCounts();
            if (options.ZoneId != null)
            {
                tzdb.GenerateDateTimeZone(options.ZoneId);
                return 0;
            }
            var windowsZones = LoadWindowsZones(options, tzdb.Version);
            if (options.WindowsOverride != null)
            {
                var overrideFile = CldrWindowsZonesParser.Parse(options.WindowsOverride);
                windowsZones = MergeWindowsZones(windowsZones, overrideFile);
            }
            LogWindowsZonesSummary(windowsZones);
            var writer = new TzdbStreamWriter();
            using (var stream = CreateOutputStream(options))
            {
                writer.Write(tzdb, windowsZones, NameIdMappingSupport.StandardNameToIdMap, stream);
            }

            if (options.OutputFileName != null)
            {
                Console.WriteLine("Reading generated data and validating...");
                var source = Read(options);
                source.Validate();
            }

            if (options.XmlSchema is object)
            {
                Console.WriteLine($"Writing XML schema to {options.XmlSchema}");
                var source = Read(options);
                var provider = new DateTimeZoneCache(source);
                XmlSerializationSettings.DateTimeZoneProvider = provider;
                var settings = new XmlWriterSettings { Indent = true, NewLineChars = "\n", Encoding = new UTF8Encoding() };
                using var xmlWriter = XmlWriter.Create(options.XmlSchema, settings);
                XmlSchemaDefinition.NodaTimeXmlSchema.Write(xmlWriter);
            }
            return 0;
        }

        /// <summary>
        /// Loads the best windows zones file based on the options. If the WindowsMapping option is
        /// just a straight file, that's used. If it's a directory, this method loads all the XML files
        /// in the directory (expecting them all to be mapping files) and then picks the best one based
        /// on the version of TZDB we're targeting - basically, the most recent one before or equal to the
        /// target version.
        /// </summary>
        private static WindowsZones LoadWindowsZones(CompilerOptions options, string targetTzdbVersion)
        {
            var mappingPath = options.WindowsMapping!;
            if (File.Exists(mappingPath))
            {
                return CldrWindowsZonesParser.Parse(mappingPath);
            }
            if (!Directory.Exists(mappingPath))
            {
                throw new Exception($"{mappingPath} does not exist as either a file or a directory");
            }
            var xmlFiles = Directory.GetFiles(mappingPath, "*.xml");
            if (xmlFiles.Length == 0)
            {
                throw new Exception($"{mappingPath} does not contain any XML files");
            }
            var allFiles = xmlFiles
                .Select(file => CldrWindowsZonesParser.Parse(file))
                .OrderByDescending(zones => zones.TzdbVersion)
                .ToList();

            var versions = string.Join(", ", allFiles.Select(z => z.TzdbVersion).ToArray());

            var bestFile = allFiles
                .Where(zones => StringComparer.Ordinal.Compare(zones.TzdbVersion, targetTzdbVersion) <= 0)
                .FirstOrDefault();

            if (bestFile is null)
            {
                throw new Exception($"No zones files suitable for version {targetTzdbVersion}. Found versions targeting: [{versions}]");
            }
            Console.WriteLine($"Picked Windows Zones with TZDB version {bestFile.TzdbVersion} out of [{versions}] as best match for {targetTzdbVersion}");
            return bestFile;
        }

        private static void LogWindowsZonesSummary(WindowsZones windowsZones)
        {
            Console.WriteLine("Windows Zones:");
            Console.WriteLine($"  Version: {windowsZones.Version}");
            Console.WriteLine($"  TZDB version: {windowsZones.TzdbVersion}");
            Console.WriteLine($"  Windows version: {windowsZones.WindowsVersion}");
            Console.WriteLine($"  {windowsZones.MapZones.Count} MapZones");
            Console.WriteLine($"  {windowsZones.PrimaryMapping.Count} primary mappings");
        }

        private static Stream CreateOutputStream(CompilerOptions options)
        {
            // If we don't have an actual file, just write to an empty stream.
            // That way, while debugging, we still get to see all the data written etc.
            if (options.OutputFileName is null)
            {
                return new MemoryStream();
            }
            string file = Path.ChangeExtension(options.OutputFileName, "nzd");
            return File.Create(file);
        }

        private static TzdbDateTimeZoneSource Read(CompilerOptions options)
        {
            string file = Path.ChangeExtension(options.OutputFileName!, "nzd");
            using (var stream = File.OpenRead(file))
            {
                return TzdbDateTimeZoneSource.FromStream(stream);
            }
        }

        /// <summary>
        /// Merge two WindowsZones objects together. The result has versions present in override,
        /// but falling back to the original for versions absent in the override. The set of MapZones
        /// in the result is the union of those in the original and override, but any ID/Territory
        /// pair present in both results in the override taking priority, unless the override has an
        /// empty "type" entry, in which case the entry is removed entirely.
        ///
        /// While this method could reasonably be in WindowsZones class, it's only needed in
        /// TzdbCompiler - and here is as good a place as any.
        ///
        /// The resulting MapZones will be ordered by Windows ID followed by territory.
        /// </summary>
        /// <param name="windowsZones">The original WindowsZones</param>
        /// <param name="overrideFile">The WindowsZones to override entries in the original</param>
        /// <returns>A merged zones object.</returns>
        internal static WindowsZones MergeWindowsZones(WindowsZones originalZones, WindowsZones overrideZones)
        {
            var version = overrideZones.Version == "" ? originalZones.Version : overrideZones.Version;
            var tzdbVersion = overrideZones.TzdbVersion == "" ? originalZones.TzdbVersion : overrideZones.TzdbVersion;
            var windowsVersion = overrideZones.WindowsVersion == "" ? originalZones.WindowsVersion : overrideZones.WindowsVersion;

            // Work everything out using dictionaries, and then sort.
            var mapZones = originalZones.MapZones.ToDictionary(mz => new { mz.WindowsId, mz.Territory });
            foreach (var overrideMapZone in overrideZones.MapZones)
            {
                var key = new { overrideMapZone.WindowsId, overrideMapZone.Territory };
                if (overrideMapZone.TzdbIds.Count == 0)
                {
                    mapZones.Remove(key);
                }
                else
                {
                    mapZones[key] = overrideMapZone;
                }
            }
            var mapZoneList = mapZones
                .OrderBy(pair => pair.Key.WindowsId)
                .ThenBy(pair => pair.Key.Territory)
                .Select(pair => pair.Value)
                .ToList();
            return new WindowsZones(version, tzdbVersion, windowsVersion, mapZoneList);
        }
    }
}


text:
require_relative '../../spec_helper'
require_relative 'shared/equal_value'

describe "Range#==" do
  it_behaves_like :range_eql, :==

  it "returns true if the endpoints are ==" do
    (0..1).should == (0..1.0)
  end
end


text:
<?php

class RolePanelComponent
{
	const E_ADD = 'add';
	const E_REMOVE = 'remove';

	public $frame;
	public $user;
	public $selectedRole;

	private $roleListTree;
	private $roleListStore;

	private $roleCombo;
	private $roleComboStore;

	private $addButton;
	private $removeButton;
	private $statusLabel;

	public function __construct ()
	{
		$this->frame = new GtkFrame ();
		$frameBox = new GtkVBox (false, 10);
		$frameBox->set_border_width (10);
		$titleBox = new GtkHBox (false, 10);
		$titleLabel = new GtkLabel ("User Roles");
		$titleLabel->set_markup ("User Roles");
		$titleLabel->set_alignment (0, 0.5);
		$this->statusLabel = new GtkLabel ("");
		$this->statusLabel->set_alignment (1, 0.5);
		$titleBox->pack_start ($titleLabel, true, true, 0);
		$titleBox->pack_end ($this->statusLabel, true, true, 0);
		$frameBox->pack_start ($titleBox, false, false, 0);
		$this->frame->add ($frameBox);

		$this->roleListStore = new GtkRefListStore (Gobject::TYPE_STRING);
		$this->roleListTree = new GtkRefTreeView ($this->roleListStore);
		$this->roleListTree->set_headers_visible (false);
		$roleListSelection = $this->roleListTree->get_selection ();
		$roleListSelection->set_mode (Gtk::SELECTION_SINGLE);
		$roleListSelection->connect ('changed', array ($this, 'selectRoleToRemove'));

		$rolesWindow = new GtkScrolledWindow ();
		$rolesWindow->set_policy (Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
		$rolesWindow->set_shadow_type (Gtk::SHADOW_ETCHED_IN);
		$rolesWindow->add ($this->roleListTree);
		$frameBox->pack_start ($rolesWindow, true, true, 0);

		$renderer = new GtkCellRendererText ();
		$renderer->set_property ("editable", false);
		$column = new GtkTreeViewColumn ('Role', $renderer, "text", 0);
		$column->set_expand (true);
		$column->set_resizable (false);
		$this->roleListTree->append_column ($column);

		$this->roleComboStore = new GtkRefListStore (Gobject::TYPE_STRING);
		$this->roleComboStore->refInsert (RoleEnum::getList());
		$this->roleCombo = new GtkRefComboBox ($this->roleComboStore);
		$roleCell = new GtkCellRendererText ();
		$roleCell->set_property ('ellipsize', Pango::ELLIPSIZE_END);
		$this->roleCombo->pack_start ($roleCell);
		$this->roleCombo->set_attributes ($roleCell, 'text', 0);
		$this->roleCombo->connect ('changed', array ($this, 'selectRoleToAdd'));

		$this->addButton = new GtkButton ("Add");
		$this->addButton->set_sensitive (false);
		$this->removeButton = new GtkButton ("Remove");
		$this->removeButton->set_sensitive (false);
		$this->enableForm (false);

		$buttonBox = new GtkHBox (false, 8);
		$buttonBox->pack_end ($this->removeButton, false, false, 0);
		$buttonBox->pack_end ($this->addButton, false, false, 0);
		$buttonBox->pack_end ($this->roleCombo, true, true, 0);
		$frameBox->pack_end ($buttonBox, false, false, 0);
	}

	public function addEventListener ($event, $obj, $methodName)
	{
		switch ($event)
		{
			case self::E_ADD:
				$this->addButton->connect ('clicked', array ($obj, $methodName));
				break;

			case self::E_REMOVE:
				$this->removeButton->connect ('clicked', array ($obj, $methodName));
				break;
		}
	}

	public function setUserRoles (array $roles)
	{
		$this->roleListStore->refClear ();

		if (count ($roles) > 0)
		{
			foreach ($roles as $roleEnum)
			{
				$userRoles [$roleEnum] = RoleEnum::getValue ($roleEnum);
			}
			$this->roleListStore->refInsert (isset ($userRoles) ? $userRoles : array ());
		}
	}

	public function addUserRole ($enum, $value)
	{
		$this->roleListStore->refAdd ($enum, $value);
	}

	public function removeActiveRole ()
	{
		$activeRole = $this->roleListTree->getSingleActiveRefID ();
		$this->roleListStore->refRemove ($activeRole);
	}

	public function selectRoleToRemove ()
	{
		if ($this->roleListTree->get_selection()->count_selected_rows () > 0)
		{
			$this->selectedRole = $this->roleListTree->getSingleActiveRefID ();
			$this->roleCombo->set_active (-1);
			$this->removeButton->set_sensitive (true);
		}
		else
		{
			$this->removeButton->set_sensitive (false);
		}
	}

	public function selectRoleToAdd ()
	{
		if ($this->roleCombo->get_active () > -1)
		{
			$this->selectedRole = $this->roleCombo->getActiveRefID ();
			$this->roleListTree->get_selection()->unselect_all ();
			$this->addButton->set_sensitive (true);
		}
		else
		{
			$this->addButton->set_sensitive (false);
		}
	}

	public function enableForm ($is)
	{
		$this->roleCombo->set_sensitive ($is);
		$this->roleListTree->set_sensitive ($is);
	}

	public function reset ()
	{
		$this->roleCombo->set_active (-1);
		$this->addButton->set_sensitive (false);
		$this->removeButton->set_sensitive (false);
		$this->enableForm ($this->user ? true : false);
		$this->statusLabel->set_label ($this->user ? $this->user->getGivenName () : '');
	}
}


text:
"use strict";

window.onload = function () {
  // cata https://www.codewars.com/kata/53db96041f1a7d32dc0004d2/train/javascript
  function list(names) {
    function doneOrNot(board) {//your code here
    }
  } // ======================================================
  // Testu

  var accessorObj = {
    _name: 'Arfat',

    get name() {
      return this._name;
    },

    set name(value) {
      this._name = value;
    }

  };
  console.log(accessorObj.name);
  accessorObj.name = 'Ivan';
  console.log(accessorObj.name);
};


text:
<?php
/**
 * PHP VCS wrapper authored interface
 *
 * This file is part of vcs-wrapper.
 *
 * vcs-wrapper is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; version 3 of the License.
 *
 * vcs-wrapper is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with vcs-wrapper; if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @package VCSWrapper
 * @subpackage Core
 * @version $Revision: 1859 $
 * @license http://www.gnu.org/licenses/lgpl-3.0.txt LGPLv3
 */

/*
 * Interface for resources with available user information
 *
 * This interface should be implemented by resources which have information
 * about the authors which changed / created the contents available.
 */
interface vcsAuthored extends vcsVersioned
{
    /**
     * Get author
     *
     * Return author information for the resource. Optionally the $version
     * parameter may be passed to the method to specify a version the author
     * information should be returned for.
     *
     * @param mixed $version
     * @return string
     */
    public function getAuthor( $version = null );
}


text:
A bit of experimentation to get used to how error handling works
with [md/catch](https://github.com/ztellman/manifold/blob/master/docs/deferred.md#composing-with-deferreds)
and dereferencing deferred.

The main points to take away from this are (they may seem obvious):

1. Do not dereference a deferred early. Doing so will cause error handling for
that deferred to follow the normal java/clojure try and except flow.
2. *Do* dereference as close as possible to the point of consumption. Place any
deferred error handling that the asynchronous process needs, inside of its
deferred chain.

## what this is; how do I use it?

Use this by writing tests cases for behavior you want to understand. Run these
test cases with `lein test`.

This will spin up a small http server locally. I've chosen to test with http as my use
case was understanding how to handle error conditions returned when making http requests.


text:
// <auto-generated />
using System;
using BioEngine.Core.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

namespace BioEngine.Admin.Migrations
{
    [DbContext(typeof(BioDbContext))]
    partial class BioDbContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("Relational:MaxIdentifierLength", 63)
                .HasAnnotation("ProductVersion", "6.0.0-preview.7.21378.4")
                .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);

            modelBuilder.Entity("BioEngine.Core.Data.Entities.Page", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("uuid");

                    b.Property<string>("Blocks")
                        .IsRequired()
                        .ValueGeneratedOnAdd()
                        .HasColumnType("jsonb")
                        .HasColumnName("Blocks")
                        .HasDefaultValueSql("'[]'");

                    b.Property<DateTimeOffset>("DateAdded")
                        .HasColumnType("timestamp with time zone");

                    b.Property<DateTimeOffset?>("DatePublished")
                        .HasColumnType("timestamp with time zone");

                    b.Property<DateTimeOffset>("DateUpdated")
                        .HasColumnType("timestamp with time zone");

                    b.Property<bool>("IsPublished")
                        .HasColumnType("boolean");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("text");

                    b.Property<string>("Url")
                        .IsRequired()
                        .HasColumnType("text");

                    b.HasKey("Id");

                    b.ToTable("Pages");
                });

            modelBuilder.Entity("BioEngine.Core.Data.Entities.Post", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("uuid");

                    b.Property<string>("AuthorId")
                        .IsRequired()
                        .HasColumnType("text");

                    b.Property<string>("Blocks")
                        .IsRequired()
                        .ValueGeneratedOnAdd()
                        .HasColumnType("jsonb")
                        .HasColumnName("Blocks")
                        .HasDefaultValueSql("'[]'");

                    b.Property<DateTimeOffset>("DateAdded")
                        .HasColumnType("timestamp with time zone");

                    b.Property<DateTimeOffset?>("DatePublished")
                        .HasColumnType("timestamp with time zone");

                    b.Property<DateTimeOffset>("DateUpdated")
                        .HasColumnType("timestamp with time zone");

                    b.Property<int?>("ForumPostId")
                        .HasColumnType("integer");

                    b.Property<int?>("ForumTopicId")
                        .HasColumnType("integer");

                    b.Property<bool>("IsPublished")
                        .HasColumnType("boolean");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("text");

                    b.Property<string>("Url")
                        .IsRequired()
                        .HasColumnType("text");

                    b.HasKey("Id");

                    b.ToTable("Posts");
                });

            modelBuilder.Entity("BioEngine.Core.Data.Entities.Section", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("uuid");

                    b.Property<string>("Blocks")
                        .IsRequired()
                        .ValueGeneratedOnAdd()
                        .HasColumnType("jsonb")
                        .HasColumnName("Blocks")
                        .HasDefaultValueSql("'[]'");

                    b.Property<DateTimeOffset>("DateAdded")
                        .HasColumnType("timestamp with time zone");

                    b.Property<DateTimeOffset?>("DatePublished")
                        .HasColumnType("timestamp with time zone");

                    b.Property<DateTimeOffset>("DateUpdated")
                        .HasColumnType("timestamp with time zone");

                    b.Property<bool>("IsPublished")
                        .HasColumnType("boolean");

                    b.Property<Guid?>("ParentId")
                        .HasColumnType("uuid");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("text");

                    b.Property<int>("Type")
                        .HasColumnType("integer");

                    b.Property<string>("Url")
                        .IsRequired()
                        .HasColumnType("text");

                    b.HasKey("Id");

                    b.ToTable("Sections");

                    b.HasDiscriminator<int>("Type");
                });

            modelBuilder.Entity("BioEngine.Core.Data.Entities.Site", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("uuid");

                    b.Property<DateTimeOffset>("DateAdded")
                        .HasColumnType("timestamp with time zone");

                    b.Property<DateTimeOffset>("DateUpdated")
                        .HasColumnType("timestamp with time zone");

                    b.Property<int>("ForumId")
                        .HasColumnType("integer");

                    b.Property<bool>("IsMain")
                        .HasColumnType("boolean");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("text");

                    b.Property<string>("Url")
                        .IsRequired()
                        .HasColumnType("text");

                    b.HasKey("Id");

                    b.ToTable("Sites");
                });

            modelBuilder.Entity("BioEngine.Core.Data.Entities.Tag", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("uuid");

                    b.Property<DateTimeOffset>("DateAdded")
                        .HasColumnType("timestamp with time zone");

                    b.Property<DateTimeOffset>("DateUpdated")
                        .HasColumnType("timestamp with time zone");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("text");

                    b.HasKey("Id");

                    b.ToTable("Tags");
                });

            modelBuilder.Entity("PageSite", b =>
                {
                    b.Property<Guid>("PagesId")
                        .HasColumnType("uuid");

                    b.Property<Guid>("SitesId")
                        .HasColumnType("uuid");

                    b.HasKey("PagesId", "SitesId");

                    b.HasIndex("SitesId");

                    b.ToTable("PageSites", (string)null);
                });

            modelBuilder.Entity("PostSection", b =>
                {
                    b.Property<Guid>("PostsId")
                        .HasColumnType("uuid");

                    b.Property<Guid>("SectionsId")
                        .HasColumnType("uuid");

                    b.HasKey("PostsId", "SectionsId");

                    b.HasIndex("SectionsId");

                    b.ToTable("PostSections", (string)null);
                });

            modelBuilder.Entity("PostTag", b =>
                {
                    b.Property<Guid>("PostsId")
                        .HasColumnType("uuid");

                    b.Property<Guid>("TagsId")
                        .HasColumnType("uuid");

                    b.HasKey("PostsId", "TagsId");

                    b.HasIndex("TagsId");

                    b.ToTable("PostTags", (string)null);
                });

            modelBuilder.Entity("SectionSite", b =>
                {
                    b.Property<Guid>("SectionsId")
                        .HasColumnType("uuid");

                    b.Property<Guid>("SitesId")
                        .HasColumnType("uuid");

                    b.HasKey("SectionsId", "SitesId");

                    b.HasIndex("SitesId");

                    b.ToTable("SectionSites", (string)null);
                });

            modelBuilder.Entity("BioEngine.Core.Data.Entities.Developer", b =>
                {
                    b.HasBaseType("BioEngine.Core.Data.Entities.Section");

                    b.Property<string>("Data")
                        .IsRequired()
                        .ValueGeneratedOnUpdateSometimes()
                        .HasColumnType("jsonb")
                        .HasColumnName("Data");

                    b.ToTable("Sections");

                    b.HasDiscriminator().HasValue(1);
                });

            modelBuilder.Entity("BioEngine.Core.Data.Entities.Game", b =>
                {
                    b.HasBaseType("BioEngine.Core.Data.Entities.Section");

                    b.Property<string>("Data")
                        .IsRequired()
                        .ValueGeneratedOnUpdateSometimes()
                        .HasColumnType("jsonb")
                        .HasColumnName("Data");

                    b.ToTable("Sections");

                    b.HasDiscriminator().HasValue(2);
                });

            modelBuilder.Entity("BioEngine.Core.Data.Entities.Topic", b =>
                {
                    b.HasBaseType("BioEngine.Core.Data.Entities.Section");

                    b.Property<string>("Data")
                        .IsRequired()
                        .HasColumnType("jsonb")
                        .HasColumnName("Data");

                    b.ToTable("Sections");

                    b.HasDiscriminator().HasValue(3);
                });

            modelBuilder.Entity("PageSite", b =>
                {
                    b.HasOne("BioEngine.Core.Data.Entities.Page", null)
                        .WithMany()
                        .HasForeignKey("PagesId")
                        .OnDelete(DeleteBehavior.Cascade)
                        .IsRequired();

                    b.HasOne("BioEngine.Core.Data.Entities.Site", null)
                        .WithMany()
                        .HasForeignKey("SitesId")
                        .OnDelete(DeleteBehavior.Cascade)
                        .IsRequired();
                });

            modelBuilder.Entity("PostSection", b =>
                {
                    b.HasOne("BioEngine.Core.Data.Entities.Post", null)
                        .WithMany()
                        .HasForeignKey("PostsId")
                        .OnDelete(DeleteBehavior.Cascade)
                        .IsRequired();

                    b.HasOne("BioEngine.Core.Data.Entities.Section", null)
                        .WithMany()
                        .HasForeignKey("SectionsId")
                        .OnDelete(DeleteBehavior.Cascade)
                        .IsRequired();
                });

            modelBuilder.Entity("PostTag", b =>
                {
                    b.HasOne("BioEngine.Core.Data.Entities.Post", null)
                        .WithMany()
                        .HasForeignKey("PostsId")
                        .OnDelete(DeleteBehavior.Cascade)
                        .IsRequired();

                    b.HasOne("BioEngine.Core.Data.Entities.Tag", null)
                        .WithMany()
                        .HasForeignKey("TagsId")
                        .OnDelete(DeleteBehavior.Cascade)
                        .IsRequired();
                });

            modelBuilder.Entity("SectionSite", b =>
                {
                    b.HasOne("BioEngine.Core.Data.Entities.Section", null)
                        .WithMany()
                        .HasForeignKey("SectionsId")
                        .OnDelete(DeleteBehavior.Cascade)
                        .IsRequired();

                    b.HasOne("BioEngine.Core.Data.Entities.Site", null)
                        .WithMany()
                        .HasForeignKey("SitesId")
                        .OnDelete(DeleteBehavior.Cascade)
                        .IsRequired();
                });
#pragma warning restore 612, 618
        }
    }
}


text:
<?php

function wpaal_import_export() {
	global $wpdb;
	$table_name = $wpdb->prefix . "automated_links";

	?>

Import Links

				Upload your datafeed. The format should be keyword,url. The separator is the character who separate the columns, it can be a comma ( , ), a vertical bar ( | ) or a tab ( exactly 4 spaces ). For tab, just write "tab" in the text field. If you don't know, open the feed file in notepad or any other simple text editor. You can edit your datafeed in Microsoft Excell or Libre Office Calc. Make sure you save the file in csv format ( not in xls or odt ). Upon saving, you can select the separator. All the links inside the datafeed will be added to your affiliate links.

			<form name="aal_import_form" method="post" enctype="multipart/form-data" onsubmit="">
			Upload the file here:    <input name="aal_import_file" type="file" />

			Separator: <select name="aal_import_separator" onchange="if(document.aal_import_form.aal_import_separator.options[document.aal_import_form.aal_import_separator.selectedIndex].value == 'other') document.aal_import_form.aal_import_other.style.display = 'block'; else document.aal_import_form.aal_import_other.style.display = 'none';">
			<option value="|">| ( vertical line )</option>
			<option value="tab">Tab</option>
			<option value=",">, ( comma )</option>
			<option value=";">; ( semicolon )</option>
			<option value=".">. ( dot )</option>
			<option value="other">other ( specify below )</option>
			</select>

<input type="text" name="aal_import_other" value="|" style="display: none;"/>

			<input  class="button-primary"  type="submit" value="Import" /><input type="hidden" name="MAX_FILE_SIZE" value="10000000" /><input type="hidden" name="aal_import_check" value="1" />
			</form>

Export Links

				Here you can export your links so you can import to another blog or to make a backup. You can import this file later using the "Import" tab.

			<form name="aal_export_form" method="post" enctype="multipart/form-data" onsubmit="">
			Separator: <select name="aal_export_separator">
			<option value="|">| ( vertical line )</option>
			<option value="tab">Tab</option>
			<option value=",">, ( comma )</option>
			<option value=";">; ( semicolon )</option>
			<option value=".">. ( dot )</option>
			</select>
			<input  class="button-primary"  type="submit" value="Click here to export your links" /><input type="hidden" name="aal_export_check" value="1" />
			</form>

If you have problems or questions about the plugin, or if you just want to send a suggestion or request to our team, you can use the support forum. Make sure that you consult our FAQ section first.

Export Settings

				Here you can export your plugin data, such as general settings, excluded posts, activated modules, api key, etc.

			<form name="aal_export_settings" method="post" enctype="multipart/form-data" onsubmit="">

			<input  class="button-primary"  type="submit" value="Click here to export your settings" /><input type="hidden" name="aal_export_settings_check" value="1" />
			</form>

Import Settings

				Here you can import Wp Auto Affiliate Links Settings if you have a previously exported backup

			<form name="aal_import_settings" method="post" enctype="multipart/form-data" onsubmit="">
			Upload the file here:    <input name="aal_importsettings_file" type="file" />

			<input  class="button-primary"  type="submit" value="Import" /><input type="hidden" name="MAX_FILE_SIZE" value="10000000" /><input type="hidden" name="aal_importsettings_check" value="1" />
			</form>

If you have problems or questions about the plugin, or if you just want to send a suggestion or request to our team, you can use the support forum. Make sure that you consult our FAQ section first.

	<?php
}

add_action('admin_init', 'aalImportSettingsAction');
function aalImportSettingsAction() {
global $wpdb;
        $table_name = $wpdb->prefix . "automated_links";
	if($_POST['aal_importsettings_check']) {

		//$sasid = filter_input(INPUT_POST, 'aal_sasid', FILTER_SANITIZE_SPECIAL_CHARS);
		//$scontent = file_get_contents($_FILES['aal_sasfeed']['tmp_name']);
		//print_r($_FILES['aal_sasfeed']);

		//$handle = fopen($_FILES['aal_importsettings_file']['tmp_name'], "r");
		$filename = $_FILES['aal_importsettings_file']['tmp_name'];
		if($filename) $data = file_get_contents($filename);

			if($data) $options = json_decode($data);
			if(($options)) foreach($options as $option => $value) {

				//remove old settings

				delete_option($option);

				//add new settings
				add_option($option,$value);

			}

		//fclose($handle);

		//wp_redirect("admin.php?page=aal_topmenu#aal_panel4");

		// echo $scontent;

		//die();

	}

}

?>


text:
@implementation Toast

- (void)show:(CDVInvokedUrlCommand*)command {

  NSString *message  = [command.arguments objectAtIndex:0];
  NSString *duration = [command.arguments objectAtIndex:1];
  NSString *position = [command.arguments objectAtIndex:2];

  if (![position isEqual: @"top"] && ![position isEqual: @"center"] && ![position isEqual: @"bottom"]) {
    CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"invalid position. valid options are 'top', 'center' and 'bottom'"];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    return;
  }

  NSInteger durationInt;
  if ([duration isEqual: @"short"]) {
    durationInt = 2;
  } else if ([duration isEqual: @"long"]) {
    durationInt = 5;
  } else {
    CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"invalid duration. valid options are 'short' and 'long'"];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    return;
  }

  [self.webView makeToast:message duration:durationInt position:position];

  CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
  [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

@end


text:
require "trix_add_on/engine"

module TrixAddOn
  # Your code goes here...
end