text:
app.controller('CustomerController', function($scope, $http) {

  $scope.isScheduling = false;

  $scope.schedule = function(person) {
    $scope.isScheduling = true;
    $scope.schedulee = person;
  };

  $scope.stopScheduling = function() {
    $scope.isScheduling = false;
  };

});


text:
import React from 'react';
import { connect } from 'react-redux';
import { startLogin } from '../actions/auth';

export const LoginPage = ({ startLogin }) => (

Expense Manager

Welcome to your personal expense manager!

      <button className="button" onClick={startLogin}>Login</button>

);

const mapDispatchToProps = (dispatch) => ({
  startLogin: () => dispatch(startLogin())
});

export default connect(undefined, mapDispatchToProps)(LoginPage);

redpajama_set_name: RedPajamaGithub


text:
#include "lua.h"
#include "lauxlib.h"

#include "libxml/xmlerror.h"
/* TODO: wrap the error object so user code can retrieve and query the last
 * error */
/* Mostly ripped from code in parser.c and error.c in libxml. Not ideal, but
 * it seems impossible to hook into libxml's error string generation */
int xml_push_error(lua_State *L, xmlErrorPtr err)
{
  if (err==NULL)
    luaL_error(L, "a NULL error was raised. Should not happen");

  char *file = err->file;
  int line = err->line;
/*  int code = err->code; */
  int domain = err->domain;
  xmlErrorLevel level = err->level;
  const xmlChar *name = NULL;
  xmlNodePtr node = err->node;

  luaL_Buffer buf;
  luaL_buffinit(L, &buf);
  luaL_Buffer *B = &buf;

  if ((node != NULL) && (node->type == XML_ELEMENT_NODE))
    name = node->name;

  if (file != NULL)
  {
    lua_pushfstring(L, "%s:%d: ", file, line);
    luaL_addvalue(B);
  }
  else if ((line != 0) && (domain == XML_FROM_PARSER))
  {
    lua_pushfstring(L, "Entity: line %d: ", line);
    luaL_addvalue(B);
  }
  if (name != NULL)
  {
    lua_pushfstring(L, "element %s: ", name);
    luaL_addvalue(B);
  }
  switch (domain)
  {
    case XML_FROM_PARSER:
      luaL_addstring(B, "parser ");
      break;
    case XML_FROM_NAMESPACE:
      luaL_addstring(B, "namespace ");
      break;
    case XML_FROM_DTD:
    case XML_FROM_VALID:
      luaL_addstring(B, "validity ");
      break;
    case XML_FROM_HTML:
      luaL_addstring(B, "HTML parser ");
      break;
    case XML_FROM_MEMORY:
      luaL_addstring(B, "memory ");
      break;
    case XML_FROM_OUTPUT:
      luaL_addstring(B, "output ");
      break;
    case XML_FROM_IO:
      luaL_addstring(B, "I/O ");
      break;
    case XML_FROM_XINCLUDE:
      luaL_addstring(B, "XInclude ");
      break;
    case XML_FROM_XPATH:
      luaL_addstring(B, "XPath ");
      break;
    case XML_FROM_XPOINTER:
      luaL_addstring(B, "parser ");
      break;
    case XML_FROM_REGEXP:
      luaL_addstring(B, "regexp ");
      break;
    case XML_FROM_MODULE:
      luaL_addstring(B, "module ");
      break;
    case XML_FROM_SCHEMASV:
      luaL_addstring(B, "Schemas validity ");
      break;
    case XML_FROM_SCHEMASP:
      luaL_addstring(B, "Schemas parser ");
      break;
    case XML_FROM_RELAXNGP:
      luaL_addstring(B, "Relax-NG parser ");
      break;
    case XML_FROM_RELAXNGV:
      luaL_addstring(B, "Relax-NG validity ");
      break;
    case XML_FROM_CATALOG:
      luaL_addstring(B, "Catalog ");
      break;
    case XML_FROM_C14N:
      luaL_addstring(B, "C14N ");
      break;
    case XML_FROM_XSLT:
      luaL_addstring(B, "XSLT ");
      break;
    case XML_FROM_I18N:
      luaL_addstring(B, "encoding ");
      break;
    default:
      break;
  }
  switch (level) {
    case XML_ERR_NONE:
      luaL_addstring(B, ": ");
      break;
    case XML_ERR_WARNING:
      luaL_addstring(B, "warning : ");
      break;
    case XML_ERR_ERROR:
      luaL_addstring(B, "error : ");
      break;
    case XML_ERR_FATAL:
      luaL_addstring(B, "error : ");
      break;
  }

  if (err->message)
    luaL_addstring(B, err->message);

  luaL_pushresult(B);
  return 1;
}


text:
extern void asset_setmanager(AAssetManager *assetmgr);
void
Java_com_example_testej2d_MyHelper_nativeSetContext(JNIEnv *env, jobject thiz,
        jobject context, jobject assetmgr)
{
    asset_setmanager(AAssetManager_fromJava(env, assetmgr));
}


text:
class CreateDeviceInterfaces < ActiveRecord::Migration
  def change
    create_table :device_interfaces do |t|
      t.string :name
      t.integer :mrv_interface_id
      t.integer :device_id

      t.timestamps
    end
  end
end


text:
import { HistoryNodeOptionEvent, nodeOptionEvent } from '@/store/history/types';
import LineChart from './line-chart';

enum LineChartEventType {
  SELECT_SERIES_COLUMN = 'setSeriesColumn',
  SELECT_VALUE_COLUMN = 'setValueColumn',
  SELECT_GROUP_BY_COLUMN = 'setGroupByColumn',
  TOGGLE_POINTS_VISIBLE = 'setPointsVisible',
  TOGGLE_CURVE_DRAWING = 'setCurveDrawing',
  TOGGLE_LEGENDS_VISIBLE = 'setLegendsVisible',
  TOGGLE_X_AXIS_TICKS_VISIBLE = 'setXAxisTicksVisible',
  TOGGLE_Y_AXIS_TICKS_VISIBLE = 'setYAxisTicksVisible',
}

export const selectSeriesColumnEvent = (node: LineChart, column: number | null, prevColumn: number | null):
  HistoryNodeOptionEvent => {
  return nodeOptionEvent(
    LineChartEventType.SELECT_SERIES_COLUMN,
    'select series column',
    node,
    node.setSeriesColumn,
    column,
    prevColumn,
  );
};

export const selectValueColumnEvent = (node: LineChart, column: number | null, prevColumn: number | null):
  HistoryNodeOptionEvent => {
  return nodeOptionEvent(
    LineChartEventType.SELECT_VALUE_COLUMN,
    'select value column',
    node,
    node.setValueColumn,
    column,
    prevColumn,
  );
};

export const selectGroupByColumnEvent = (node: LineChart, column: number | null, prevColumn: number | null):
  HistoryNodeOptionEvent => {
  return nodeOptionEvent(
    LineChartEventType.SELECT_GROUP_BY_COLUMN,
    'select value column',
    node,
    node.setGroupByColumn,
    column,
    prevColumn,
  );
};

export const togglePointsVisibleEvent = (node: LineChart, value: boolean):
  HistoryNodeOptionEvent => {
  return nodeOptionEvent(
    LineChartEventType.TOGGLE_POINTS_VISIBLE,
    'toggle points',
    node,
    node.setPointsVisible,
    value,
    !value,
  );
};

export const toggleCurveDrawingEvent = (node: LineChart, value: boolean):
  HistoryNodeOptionEvent => {
  return nodeOptionEvent(
    LineChartEventType.TOGGLE_CURVE_DRAWING,
    'toggle curve',
    node,
    node.setCurveDrawing,
    value,
    !value,
  );
};

export const toggleLegendsVisibleEvent = (node: LineChart, value: boolean):
  HistoryNodeOptionEvent => {
  return nodeOptionEvent(
    LineChartEventType.TOGGLE_LEGENDS_VISIBLE,
    'toggle legends',
    node,
    node.setLegendsVisible,
    value,
    !value,
  );
};

export const toggleXAxisTicksVisibleEvent = (node: LineChart, value: boolean):
  HistoryNodeOptionEvent => {
  return nodeOptionEvent(
    LineChartEventType.TOGGLE_X_AXIS_TICKS_VISIBLE,
    'toggle X axis ticks',
    node,
    node.setXAxisTicksVisible,
    value,
    !value,
  );
};

export const toggleYAxisTicksVisibleEvent = (node: LineChart, value: boolean):
  HistoryNodeOptionEvent => {
  return nodeOptionEvent(
    LineChartEventType.TOGGLE_Y_AXIS_TICKS_VISIBLE,
    'toggle Y axis ticks',
    node,
    node.setYAxisTicksVisible,
    value,
    !value,
  );
};


text:
/*!
	@file
	@author		Albert Semenov
	@date		26/2009
*/
/*
	This file is part of MyGUI.

	MyGUI is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	MyGUI 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 MyGUI.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "pch.h"
#include "MyGUI_Precompiled.h"
#include "MyGUI_ResourceSkin.h"
#include "MyGUI_FactoryManager.h"
#include "MyGUI_LanguageManager.h"

namespace MyGUI
{

	ResourceSkin::ResourceSkin()
	{
	}

	ResourceSkin::~ResourceSkin()
	{
		for (MapWidgetStateInfo::iterator item = mStates.begin(); item != mStates.end(); ++ item)
		{
			for (VectorStateInfo::iterator info = (*item).second.begin(); info != (*item).second.end(); ++ info)
				delete (*info);
		}
		mStates.clear();
	}

	void ResourceSkin::deserialization(xml::ElementPtr _node, Version _version)
	{
		Base::deserialization(_node, _version);

		// парсим атрибуты скина
		std::string name, texture, tmp;
		IntSize size;
		_node->findAttribute("name", name);
		_node->findAttribute("texture", texture);
		if (_node->findAttribute("size", tmp)) size = IntSize::parse(tmp);

		LanguageManager& localizator = LanguageManager::getInstance();

		// вспомогательный класс для биндинга сабскинов
		SubWidgetBinding bind;

		// поддержка замены тегов в скинах
		if (_version >= Version(1, 1))
		{
			texture = localizator.replaceTags(texture);
		}

		setInfo(size, texture);

		// проверяем маску
		if (_node->findAttribute("mask", tmp))
			addProperty("MaskPick", tmp);

		// берем детей и крутимся, цикл с саб скинами
		xml::ElementEnumerator basis = _node->getElementEnumerator();
		while (basis.next())
		{
			if (basis->getName() == "Property")
			{
				// загружаем свойства
				std::string key, value;
				if (!basis->findAttribute("key", key)) continue;
				if (!basis->findAttribute("value", value)) continue;

				// поддержка замены тегов в скинах
				if (_version >= Version(1, 1))
				{
					value = localizator.replaceTags(value);
				}

				// добавляем свойство
				addProperty(key, value);
			}
			else if (basis->getName() == "Child")
			{
				ChildSkinInfo child(
					basis->findAttribute("type"),
					WidgetStyle::parse(basis->findAttribute("style")),
					basis->findAttribute("skin"),
					IntCoord::parse(basis->findAttribute("offset")),
					Align::parse(basis->findAttribute("align")),
					basis->findAttribute("layer"),
					basis->findAttribute("name")
				);

				xml::ElementEnumerator child_params = basis->getElementEnumerator();
				while (child_params.next("Property"))
					child.addParam(child_params->findAttribute("key"), child_params->findAttribute("value"));

				addChild(child);
				//continue;
			}
			else if (basis->getName() == "BasisSkin")
			{
				// парсим атрибуты
				std::string basisSkinType, tmp_str;
				IntCoord offset;
				Align align = Align::Default;
				basis->findAttribute("type", basisSkinType);
				if (basis->findAttribute("offset", tmp_str)) offset = IntCoord::parse(tmp_str);
				if (basis->findAttribute("align", tmp_str)) align = Align::parse(tmp_str);

				bind.create(offset, align, basisSkinType);

				// берем детей и крутимся, цикл со стейтами
				xml::ElementEnumerator state = basis->getElementEnumerator();

				// проверяем на новый формат стейтов
				bool new_format = false;
				// если версия меньше 1.0 то переименовываем стейты
				if (_version < Version(1, 0))
				{
					while (state.next())
					{
						if (state->getName() == "State")
						{
							const std::string& name_state = state->findAttribute("name");
							if ((name_state == "normal_checked") || (state->findAttribute("name") == "normal_check"))
							{
								new_format = true;
								break;
							}
						}
					}
					// обновляем
					state = basis->getElementEnumerator();
				}

				while (state.next())
				{
					if (state->getName() == "State")
					{
						// парсим атрибуты стейта
						std::string basisStateName;
						state->findAttribute("name", basisStateName);

						// если версия меньше 1.0 то переименовываем стейты
						if (_version < Version(1, 0))
						{
							// это обсолет новых типов
							if (basisStateName == "disable_check") basisStateName = "disabled_checked";
							else if (basisStateName == "normal_check") basisStateName = "normal_checked";
							else if (basisStateName == "active_check") basisStateName = "highlighted_checked";
							else if (basisStateName == "pressed_check") basisStateName = "pushed_checked";
							else if (basisStateName == "disable") basisStateName = "disabled";
							else if (basisStateName == "active") basisStateName = "highlighted";
							else if (basisStateName == "select") basisStateName = "pushed";
							else if (basisStateName == "pressed")
							{
								if (new_format) basisStateName = "pushed";
								else basisStateName = "normal_checked";
							}
						}

						// конвертируем инфу о стейте
						IStateInfo* data = nullptr;
						IObject* object = FactoryManager::getInstance().createObject("BasisSkin/State", basisSkinType);
						if (object != nullptr)
						{
							data = object->castType<IStateInfo>();
							data->deserialization(state.current(), _version);
						}

						// добавляем инфо о стайте
						bind.add(basisStateName, data, name);
					}
				}

				// теперь всё вместе добавляем в скин
				addInfo(bind);
			}

		}
	}

	void ResourceSkin::setInfo(const IntSize& _size, const std::string& _texture)
	{
		mSize = _size;
		mTexture = _texture;
	}

	void ResourceSkin::addInfo(const SubWidgetBinding& _bind)
	{
		checkState(_bind.mStates);
		mBasis.push_back(SubWidgetInfo(_bind.mType, _bind.mOffset, _bind.mAlign));
		checkBasis();
		fillState(_bind.mStates, mBasis.size() - 1);
	}

	void ResourceSkin::addProperty(const std::string& _key, const std::string& _value)
	{
		mProperties[_key] = _value;
	}

	void ResourceSkin::addChild(const ChildSkinInfo& _child)
	{
		mChilds.push_back(_child);
	}

	void ResourceSkin::clear()
	{
		for (MapWidgetStateInfo::iterator iter = mStates.begin(); iter != mStates.end(); ++iter)
		{
			for (VectorStateInfo::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2)
			{
				delete *iter2;
			}
		}
	}

	void ResourceSkin::checkState(const MapStateInfo& _states)
	{
		for (MapStateInfo::const_iterator iter = _states.begin(); iter != _states.end(); ++iter)
		{
			checkState(iter->first);
		}
	}

	void ResourceSkin::checkState(const std::string& _name)
	{
		// ищем такой же ключ
		MapWidgetStateInfo::const_iterator iter = mStates.find(_name);
		if (iter == mStates.end())
		{
			// добавляем новый стейт
			mStates[_name] = VectorStateInfo();
		}
	}

	void ResourceSkin::checkBasis()
	{
		// и увеличиваем размер смещений по колличеству сабвиджетов
		for (MapWidgetStateInfo::iterator iter = mStates.begin(); iter != mStates.end(); ++iter)
		{
			iter->second.resize(mBasis.size());
		}
	}

	void ResourceSkin::fillState(const MapStateInfo& _states, size_t _index)
	{
		for (MapStateInfo::const_iterator iter = _states.begin(); iter != _states.end(); ++iter)
		{
			mStates[iter->first][_index] = iter->second;
		}
	}

	const IntSize& ResourceSkin::getSize() const
	{
		return mSize;
	}

	const std::string& ResourceSkin::getTextureName() const
	{
		return mTexture;
	}

	const VectorSubWidgetInfo& ResourceSkin::getBasisInfo() const
	{
		return mBasis;
	}

	const MapWidgetStateInfo& ResourceSkin::getStateInfo() const
	{
		return mStates;
	}

	const MapString& ResourceSkin::getProperties() const
	{
		return mProperties;
	}

	const VectorChildSkinInfo& ResourceSkin::getChild() const
	{
		return mChilds;
	}

	const std::string& ResourceSkin::getSkinName() const
	{
		return mSkinName;
	}

} // namespace MyGUI


text:
Introduction
============
Authist is a Ruby on Rails plugin that provides a simple way to add role-based authorization to your application.
It can easily be plugged into any user or group models in your application, and allows you to define a set of access types that roles can provide.
Roles and users' participation in them can be changed at runtime, providing a highly customizable access control system to your
website administrators.

Authist is designed with a minimal impact on your own code architecture in mind. It creates a few database tables for itself, but does not change anything
whatsoever to the data of your own models, and only adds a minimal mixin to the model itself.
This allows it to peacefully integrate with most authentication libraries. Authist can also be used in combination with more
advanced authorization gems like Pundit to add runtime-editable access roles to their policies.

Installation
============
In order to use Authist in your rails application, first add Authist to your gemfile:

    gem 'authist'

Next, install the core migrations and initializer into your application:

    rails generate authist:install

This will create a new migration in db/migrate and an initializer in config/initializers.

Migrate your database and you can start creating authists!

Authists
========
An authist is a model that displays authistic behavior: it can have roles assigned to it, and the
model exposes a `has_access?` function which allows you to check whether it has a certain type of access. Authists are most often Users, but if you
have a user grouping system in your application, for example, a UserGroup could also be an authist.
In order to create an authist, you first need an existing model class. Next, you simply run the authist generator:

    rails generate authist User

This simply adds a module inclusion to your model:

```ruby
class User
  include Authist::Authism
end
```

You can now use this model as an authist:

    > u = User.first
    => #<User id: 1, username: "uhu">

    > u.roles
    => [#<Authist::Models::Role id: 1, name: "butcher", description: "A butcher", shoe_lacing: false, butching: true>]

    > u.has_access? :shoe_lacing
    => false

    > v = User.second
    => #<User id: 2, username: "Joe the Shoelacer">

    > v.roles
    => []

    > v.roles << Authist::Models::Role.find_by(name: 'shoe lacer')
    => [#<Authist::Models::Role id: 2, name: "shoe lacer", description: "A shoe lacer", shoe_lacing: true, butching: false>]

    > v.has_access? :shoe_lacing
    => true

    > v.roles = []
    => []

    > v.has_access? :shoe_lacing
    => false

Controller helpers
==================
For basic authorization Authist provides a few controller helpers. These are automatically available on the ApplicationController.
These helpers can be used for basic authorization. For more advanced authorization it may be better to use Authist in combination
with a gem like Pundit.

The controller helpers perform checks on the `current_user` and simply let you define some before_filters.
When their checks fail, they call `unauthorized_access` on the controller and abort the request. You can define this method in ApplicationController
or define/override it in the more specific Controllers to decide what happens when a controller fails authorization.

You can then use the helpers in your before_filters:

```ruby
class CommentsController < ApplicationController
  before_action :find_comment
  before_filter -> { access_required :blog_administration }, only: [:destroy]
  before_filter -> { user_or_access_required @comment.author, :blog_administration }, only: [:edit,:update]

  def unauthorized_access
    render json: { status: "error", message: "You do not have sufficient access for this operation." }
  end
end
```

Here are all the available helpers:

    access_required <access type> -- Checks if the current_user has a certain kind of access.
    user_or_access_required <user>, <access type> -- Checks if the current_user is either a specific user or has a specific kind of access.
                                                     Useful to allow personal + administrative access.
    user_required <user> -- Only check if the current_user is a specific user
    truth_required <boolean> -- Check if the boolean is true
    untruth_required <boolean> -- Check if the boolean is false

These helpers can be disabled in the Authist initializer.

User Groups
===========
In advanced systems, User Groups may be used. In these kinds of systems, both users and user groups can often have roles assigned,
where the user's roles override the group's roles. This section shows how to implement role-base authorization for such a system with Authist.

First, create a UserGroup model and make it an Authist:

```ruby
class UserGroup
  include Authist::Authism

  has_many :users

end
```

Now, create a User model and make it an Authist as well. You can then override its has_access? method to also check the user groups access roles.

```ruby
class User
  include Authist::Authism

  belongs_to :user_group

  def has_access? type
    super type or user_group.has_access? type
  end
end
```

That's all there is to it!

<!---
  Comment to self: This is an inclusive approach, these systems often have the ability to specifically deny access. Authist does not, at this time.
  This would be pretty easy to add though: just allow nils in the database and let has_access also potentially return nil, where nil signifies
  that no rule was found, which would also coerce to false in standard if checks. The Users and Roles could then check for nil specifically,
  and override true in a group with false in a User, but not override true in a group with nil in a User.
-->

<!---
  Comment to self: It feels annoying to not have control over the roles
-->

Adding Access Types
===================
Access types are symbols that specify an atomic kind of access. You will check if users have access of these types in your controllers (see above).
Access types are defined at development time and can be any valid database column name except `name`, `created_at` and `updated_at` (they are simply stored
as columns in the roles table). Example access types could be `:user_administration`, `:blog_administration`, `:order_administration`, etc.

To create the migration for a new access type, simply run

    rails generate authist:access_type my_access_type

and migrate the database.

Adding roles
============
Roles can be defined at runtime by creating instances of the `Authist::Models::Role` model. You will want to have a few basic roles defined by
default so your master admin can access the website though. For this, you can use the database seeds file (`db/seeds.rb`).
Below is an example configuration seed using the example access types from the previous section:

```ruby
user_administrator = Authist::Models::Role.create name: 'User administrator', user_administration: true
blog_administrator = Authist::Models::Role.create name: 'Blog administrator', blog_administration: true

User.create username: 'superadmin', roles: [user_administrator, blog_administrator]
```


text:
package id.ac.tazkia.dosen.entity;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name = "c_security_user_password")
public class UserPassword implements Serializable {

    private static final long serialVersionUID = -7371610187321351709L;

    @Id
    @Column(name = "id_user")
    @Getter @Setter
    private String id;

    @OneToOne
    @MapsId
    @JoinColumn(name = "id_user", nullable = false, columnDefinition = "varchar(36)")
    @Getter @Setter
    private User user;

    @NotNull
    @NotEmpty
    @Column
    @Getter @Setter
    private String password;

    public UserPassword() {
    }

    public UserPassword(User user, String password) {
        this.user = user;
        this.password = password;
    }

}


text:
package tokenbucket

import (
	"sync"
	"time"
)

type Bucket struct {
	capacity  int64
	tokens    chan struct{}
	rate      time.Duration // Add a token to the bucket every 1/r units of time
	rateMutex sync.Mutex
}

func NewBucket(rate time.Duration, capacity int64) *Bucket {

	//A bucket is simply a channel with a buffer representing the maximum size
	tokens := make(chan struct{}, capacity)

	b := &Bucket{capacity, tokens, rate, sync.Mutex{}}

	//Set off a function that will continuously add tokens to the bucket
	go func(b *Bucket) {
		ticker := time.NewTicker(rate)
		for _ = range ticker.C {
			b.tokens <- struct{}{}
		}
	}(b)

	return b
}

func (b *Bucket) GetRate() time.Duration {
	b.rateMutex.Lock()
	tmp := b.rate
	b.rateMutex.Unlock()
	return tmp
}

func (b *Bucket) SetRate(rate time.Duration) {
	b.rateMutex.Lock()
	b.rate = rate
	b.rateMutex.Unlock()
}

//AddTokens manually adds n tokens to the bucket
func (b *Bucket) AddToken(n int64) {
}

func (b *Bucket) withdrawTokens(n int64) error {
	for i := int64(0); i < n; i++ {
		<-b.tokens
	}
	return nil
}

func (b *Bucket) SpendToken(n int64) <-chan error {
	// Default to spending a single token
	if n < 0 {
		n = 1
	}

	c := make(chan error)
	go func(b *Bucket, n int64, c chan error) {
		c <- b.withdrawTokens(n)
		close(c)
		return
	}(b, n, c)

	return c
}

// Drain will empty all tokens in the bucket
// If the tokens are being added too quickly (if the rate is too fast)
// this will never drain
func (b *Bucket) Drain() error {
	// TODO replace this with a more solid approach (such as replacing the channel altogether)
	for {
		select {
		case _ = <-b.tokens:
			continue
		default:
			return nil
		}
	}
}


text:
Just install as usual:

```
rpm -iVh keypass.rpm
```

Once installed, configure your environment settings in `/etc/keypass.yml`, like
database connection. Please note that currently the application is shipped only
with Mysql drivers.

If needed, create the database and user with the following SQL commands:

```sql
CREATE DATABASE keypass;
CREATE USER keypass;
GRANT ALL ON keypass.* TO keypass@localhost IDENTIFIED BY 'keypass';
```

Populate database

```
$ sudo service keypass upgradedb
```

Start the server

```
$ sudo service keypass start
```

## Running manually

The application can be started from the command line in any OS (with Java
installed). It's pakaged as a single jar with all libraries embedded.

First, adjust the configuration file to fit your setup (mainly database
connectivity configuration).

If needed, create the database and user with the following SQL commands:

```sql
CREATE DATABASE keypass;
CREATE USER keypass;
GRANT ALL ON keypass.* TO keypass@localhost IDENTIFIED BY 'keypass';
```

Populate database

```
java -jar keypass-0.2.0.jar db migrate config.yml
```

Start the server

```
java -jar keypass-0.2.0.jar server
```

## Using a different database

Keypass already ships with Mysql drivers. You can use any other database
configuring it and adding the drivers.

To configure, change the database driver, JDBC URL and dialect.

```yaml
driverClass: com.mysql.jdbc.Driver

url: jdbc:mysql://localhost/keypass

properties:
  hibernate.dialect: org.hibernate.dialect.MySQLDialect
```

The driver class name and URL are provided by the driver vendor.

The dialects are defined by Hibernate: http://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/dialect/Dialect.html

Perform the usual operations (database setup, server launch) adding the driver
to the classpath.

```
java -cp <driver.jar> -jar keypass-0.2.0.jar db migrate config.yml
java -cp <driver.jar> -jar keypass-0.2.0.jar server
```


text:
namespace P09CountTheIntegers
{
    using System;

    public class StartUp
    {
        public static void Main(string[] args)
        {
            int integerCounter = 0;

            while (true)
            {
                try
                {
                    int num = int.Parse(Console.ReadLine());
                    integerCounter++;
                }
                catch (Exception)
                {
                    Console.WriteLine(integerCounter);
                    break;
                }
            }
        }
    }
}


text:
package org.psjava.ds.array;

import org.psjava.ds.ArrayFromItemGetter;
import org.psjava.util.GetterByIndex;

public class ReversedArray {

    public static <T> PSArray<T> wrap(final PSArray<T> original) {
        return ArrayFromItemGetter.create(original.size(), new GetterByIndex<T>() {
            @Override
            public T get(int index) {
                return original.get(original.size() - 1 - index);
            }
        });
    }

}


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

namespace osu.Game.Rulesets.Objects.Types
{
    /// <summary>
    /// A special type of HitObject, mostly used for legacy conversion of "holds".
    /// </summary>
    public interface IHasHold
    {
    }
}


text:
from normalization import count_normalization as cn
from mining import outliers as om
from preprocessing import clean_counts as cc
from entities import processing_rep as pr
from entities import datasets_rep as dr
from entities import methods_rep as mr
from entities import experiments_rep as er
from datasources import hdf_storage
from entities import identifier_generator
from config import APP_CONFIG

def process_job_request(data, method, thresholds, target_identifier):
    method_type_name = pr.get_type_from_method(method)

    return select_processing[method_type_name](data, method, thresholds)

def stream_detect_outliers_in_data(data, method, min_dist, max_samples, mining_id):
    # if exists -> get from db
    processing_result = None
    store_path = APP_CONFIG["application_files_location"] + APP_CONFIG["application_store_name"]
    data = dr.get_data_frame_from_hdf(data, store_path)
    # For demo purposes (cleaning)
    data = data[-(data.sum(1) <= 5)]
    if method == "kmeans_outliers":
        return om.cluster_outliers(data, data.index, max_samples=max_samples, min_dist=min_dist, mining_id=mining_id)

    if method == "mad":
        return om.mad_outliers(data, data.index, max_samples)

def get_detected_outliers(data, method, min_distance, min_samples):
    return "lol"

def remove_low_counts(data, method="sum", threshold=50, target_identifier=""):
    params = cc.CleanParameters("umc")
    params.min_sum_count = threshold
    report = cc.clean_gene_count_file(data, params)

    dataset = dr.create_data_set(report.dataset_identifier, "genes low counts removed", report.dataset_location)
    print(dataset.added_on)
    return dataset

def normalize_gene_counts(data, method, threshold=None, target_identifier="", experiment_identifier=""):
    # if exists -> get from db
    processing_result = cn.bioconductor_normalization(data, method)

    new_intern_identifier = identifier_generator.get_generated_guid_as_string()
    hdf_storage.store_hdf(processing_result.frame, new_intern_identifier)
    print("compressed pytable storage done")
    package = mr.get_package_by_name_and_version(processing_result.package,
                                                 processing_result.version).public_identifier
    dataset = dr.create_data_set(new_intern_identifier, package + "_" + target_identifier, "genes normalized dataset",
                                 package_identifier=package,
                                 experiment_identifier=experiment_identifier)
    print("new dataset saved")
    #er.link_dataset_to_experiment(experiment_identifier, dataset.public_identifier)
    print("new dataset linked")
    return dataset

def save_pre_processing(old_data, new_data, information):
    package_used = information.package
    package_version = information.version

def record_processing_to_db():
    pass

select_processing = {
    "Normalization RNA-seq": normalize_gene_counts,
    "Outlier detection": get_detected_outliers,
    "Low expression removal": remove_low_counts
}

# print process_job_request("lol", "mad", 5)


text:
package org.apache.kafka.clients.consumer;

import org.apache.kafka.common.utils.Serializer;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;

/**
 * This test case ensures OffsetAndMetadata class is serializable and is serialization compatible.
 * Note: this ensures that the current code can deserialize data serialized with older versions of the code, but not the reverse.
 * That is, older code won't necessarily be able to deserialize data serialized with newer code.
 */
public class SerializeCompatibilityOffsetAndMetadataTest {
    private String metadata = "test commit metadata";
    private String fileName = "serializedData/offsetAndMetadataSerializedfile";
    private long offset = 10;

    private void checkValues(OffsetAndMetadata deSerOAM) {
        //assert deserialized values are same as original
        assertEquals("Offset should be " + offset + " but got " + deSerOAM.offset(), offset, deSerOAM.offset());
        assertEquals("metadata should be " + metadata + " but got " + deSerOAM.metadata(), metadata, deSerOAM.metadata());
    }

    @Test
    public void testSerializationRoundtrip() throws IOException, ClassNotFoundException {
        //assert OffsetAndMetadata is serializable
        OffsetAndMetadata origOAM = new OffsetAndMetadata(offset, metadata);
        byte[] byteArray =  Serializer.serialize(origOAM);

        //deserialize the byteArray and check if the values are same as original
        Object deserializedObject = Serializer.deserialize(byteArray);
        assertTrue(deserializedObject instanceof OffsetAndMetadata);
        checkValues((OffsetAndMetadata) deserializedObject);
    }

    @Test
    public void testOffsetMetadataSerializationCompatibility() throws IOException, ClassNotFoundException {
        // assert serialized OffsetAndMetadata object in file (oamserializedfile under resources folder) is
        // deserializable into OffsetAndMetadata and is compatible
        Object deserializedObject = Serializer.deserialize(fileName);
        assertTrue(deserializedObject instanceof OffsetAndMetadata);
        checkValues((OffsetAndMetadata) deserializedObject);
    }
}


text:
package org.kie.workbench.common.stunner.core.client.session.command.impl;

import javax.enterprise.context.Dependent;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Default;
import javax.inject.Inject;

import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.CanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.event.command.CanvasCommandExecutedEvent;
import org.kie.workbench.common.stunner.core.client.canvas.event.command.CanvasCommandUndoneEvent;
import org.kie.workbench.common.stunner.core.client.canvas.event.registration.CurrentRegistryChangedEvent;
import org.kie.workbench.common.stunner.core.client.command.CanvasViolation;
import org.kie.workbench.common.stunner.core.client.command.RedoCommandHandler;
import org.kie.workbench.common.stunner.core.client.command.SessionCommandManager;
import org.kie.workbench.common.stunner.core.client.event.keyboard.KeyboardEvent;
import org.kie.workbench.common.stunner.core.client.session.ClientSession;
import org.kie.workbench.common.stunner.core.client.session.command.AbstractClientSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.impl.EditorSession;
import org.kie.workbench.common.stunner.core.command.Command;
import org.kie.workbench.common.stunner.core.command.CommandResult;
import org.kie.workbench.common.stunner.core.command.util.CommandUtils;

import static org.kie.soup.commons.validation.PortablePreconditions.checkNotNull;
import static org.kie.workbench.common.stunner.core.client.canvas.controls.keyboard.KeysMatcher.doKeysMatch;

@Dependent
@Default
public class RedoSessionCommand extends AbstractClientSessionCommand<EditorSession> {

    private final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager;
    private final RedoCommandHandler<Command<AbstractCanvasHandler, CanvasViolation>> redoCommandHandler;

    protected RedoSessionCommand() {
        this(null, null);
    }

    @Inject
    public RedoSessionCommand(final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
                              final RedoCommandHandler<Command<AbstractCanvasHandler, CanvasViolation>> redoCommandHandler) {
        super(false);
        this.redoCommandHandler = redoCommandHandler;
        this.sessionCommandManager = sessionCommandManager;
    }

    @Override
    public void bind(final EditorSession session) {
        super.bind(session);
        redoCommandHandler.setSession(getSession());

        bindCommand();
    }

    protected void bindCommand() {
        getSession().getKeyboardControl().addKeyShortcutCallback(this::onKeyDownEvent);
    }

    @Override
    public boolean accepts(final ClientSession session) {
        return session instanceof EditorSession;
    }

    void onKeyDownEvent(final KeyboardEvent.Key... keys) {
        if (isEnabled()) {
            handleCtrlShiftZ(keys);
        }
    }

    private void handleCtrlShiftZ(final KeyboardEvent.Key[] keys) {
        if (doKeysMatch(keys,
                        KeyboardEvent.Key.CONTROL,
                        KeyboardEvent.Key.SHIFT,
                        KeyboardEvent.Key.Z)) {
            this.execute();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public <V> void execute(final Callback<V> callback) {
        checkNotNull("callback",
                     callback);
        if (!redoCommandHandler.isEnabled()) {
            callback.onSuccess();
        }
        final CommandResult<?> result = redoCommandHandler.execute(getSession().getCanvasHandler(),
                                                                   sessionCommandManager);
        checkState();
        if (CommandUtils.isError(result)) {
            callback.onError((V) result);
        } else {
            callback.onSuccess();
        }
        getSession().getSelectionControl().clearSelection();
    }

    @SuppressWarnings("unchecked")
    void onCommandExecuted(final @Observes CanvasCommandExecutedEvent commandExecutedEvent) {
        checkNotNull("commandExecutedEvent",
                     commandExecutedEvent);
        if (null != getSession() && getSession().getCanvasHandler().equals(commandExecutedEvent.getCanvasHandler())) {
            if (null != commandExecutedEvent.getCommand()) {
                redoCommandHandler.onCommandExecuted(commandExecutedEvent.getCommand());
            }
            checkState();
        }
    }

    @SuppressWarnings("unchecked")
    void onCommandUndoExecuted(final @Observes CanvasCommandUndoneEvent commandUndoExecutedEvent) {
        checkNotNull("commandUndoExecutedEvent",
                     commandUndoExecutedEvent);
        CanvasHandler canvasHandler = commandUndoExecutedEvent.getCanvasHandler();
        if (null != getSession() && getSession().getCanvasHandler().equals(canvasHandler)) {
            if (null != commandUndoExecutedEvent.getCommand()) {
                redoCommandHandler.onUndoCommandExecuted(commandUndoExecutedEvent.getCommand());
            }
            checkState();
        }
    }

    void onCurrentRegistryChanged(final @Observes CurrentRegistryChangedEvent currentRegistryChangedEvent) {
        checkState();
    }

    void checkState() {
        setEnabled(null != getSession() && redoCommandHandler.isEnabled());
        fire();
    }
}


text:
PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;
static char * verbose;

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

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

String repositoryRoot;
CIMRepository *r;
const CIMNamespaceName NS = CIMNamespaceName ("TestCreateClass");
CIMQualifier d(CIMName("description"), String("*REMOVED*"));

const char *ProgName;

void TestOpenRepo(CIMRepository_Mode mode)
{
  if (verbose) cout << ProgName << "-TestOpenRepo()" << endl;
  // -- Create repository and "xyz" namespace:

    r = new CIMRepository(repositoryRoot, mode);

}

void TestCloseRepo()
{
  if (verbose) cout << ProgName << "-TestCloseRepo()" << endl;
  // -- close  repository

  delete  r;

}

void TestInitRepo()
{
  if (verbose) cout << ProgName << "-TestInitRepo()" << endl;

    try
    {
	r->createNameSpace(NS);
    }
    catch (AlreadyExistsException&)
    {
	// Ignore this!
    }

    // -- Declare the key qualifier:

    r->setQualifier(NS, CIMQualifierDecl(CIMName ("key"),true,CIMScope::PROPERTY));
    r->setQualifier(NS, CIMQualifierDecl(CIMName ("description"),String(),(CIMScope::PROPERTY + CIMScope::CLASS)));
    r->setQualifier(NS, CIMQualifierDecl(CIMName ("junk"),String(),(CIMScope::PROPERTY + CIMScope::CLASS)));

}

void TestCreateClass()
{

  if (verbose) cout << ProgName << "-TestCreateClass()" << endl;
    CIMClass c1(CIMName ("SuperClass"));
    c1.addQualifier(d);
    c1.addProperty(
		   CIMProperty(CIMName ("key"), Uint32(0))
		   .addQualifier(CIMQualifier(CIMName ("key"), true)));

    c1.addProperty(CIMProperty(CIMName ("ratio"), Real32(1.5)));
    c1.addProperty(CIMProperty(CIMName ("message"), String("Hello World")));

    // -- Create the class (get it back and compare):
    r->createClass(NS, c1);
    CIMConstClass cc1;
    cc1 = r->getClass(NS, CIMName ("SuperClass"),true,true, true);
    assert(c1.identical(cc1));
    assert(cc1.identical(c1));

    // -- Now create a sub class (get it back and compare):
	// c22 has one additional property than c1 (junk)

    CIMClass c2(CIMName ("SubClass"), CIMName ("SuperClass"));
	// Add new qualifier that will be local
	CIMQualifier j(CIMName("junk"), String("TestQualifier"));
	c2.addQualifier(j);

    c2.addProperty(CIMProperty(CIMName ("junk"), Real32(66.66)));
    r->createClass(NS, c2);
    CIMConstClass cc2;
    cc2 = r->getClass(NS, CIMName ("SubClass"), false, true, true);
	//XmlWriter::printClassElement(c2);
	//XmlWriter::printClassElement(cc2);

	assert(c2.identical(cc2));
    assert(cc2.identical(c2));

    // -- Modify "SubClass" (add new property)

    c2.addProperty(CIMProperty(CIMName ("newProperty"), Uint32(888)));
    r->modifyClass(NS, c2);
    cc2 = r->getClass(NS, CIMName ("SubClass"), false, true, true);
    assert(c2.identical(cc2));
    assert(cc2.identical(c2));
    // should test for this new property on "SubClass" also.

}

void TestEnumerateClass()
{
  if (verbose) cout << ProgName << "-TestEnumerateClass()" << endl;
    // -- Enumerate the class names: expect "SuperClass", "SubClass"

    Array<CIMName> classNames = r->enumerateClassNames(NS, CIMName (), true);
	if (verbose)
	{
	  cout << ProgName << "-Enumerated class names: ";
		for (Uint32 i = 0 ; i < classNames.size(); i++)
		{
		  cout << classNames[i].getString() << ", ";
		}
	  cout << endl;
	}

    BubbleSort(classNames);
    assert(classNames.size() == 2);
    assert(classNames[1] == CIMName ("SuperClass"));
    assert(classNames[0] == CIMName ("SubClass"));

}

void TestCreateInstance1()
{
  if (verbose) cout << ProgName << "-TestCreateInstance1()" << endl;
    // -- Create an instance of each class:

    CIMInstance inst0(CIMName ("SuperClass"));
    inst0.addProperty(CIMProperty(CIMName ("key"), Uint32(1)));
    r->createInstance(NS, inst0);

    CIMInstance inst1(CIMName ("SubClass"));
    inst1.addProperty(CIMProperty(CIMName ("key"), Uint32(2)));
    r->createInstance(NS, inst1);
}

void TestCreateInstance2()
{
  if (verbose) cout << ProgName << "-TestCreateInstance2()" << endl;
    // -- Create an instance of each class:

    CIMInstance inst0(CIMName ("SuperClass"));
    inst0.addProperty(CIMProperty(CIMName ("key"), Uint32(11)));
    r->createInstance(NS, inst0);

    CIMInstance inst1(CIMName ("SubClass"));
    inst1.addProperty(CIMProperty(CIMName ("key"), Uint32(22)));
    r->createInstance(NS, inst1);
}

void TestCreateInstance3()
{
  if (verbose) cout << ProgName << "-TestCreateInstance3()" << endl;
    // -- Create an instance of each class:

    CIMInstance inst0(CIMName ("SuperClass"));
    inst0.addProperty(CIMProperty(CIMName ("key"), Uint32(111)));
    r->createInstance(NS, inst0);

    CIMInstance inst1(CIMName ("SubClass"));
    inst1.addProperty(CIMProperty(CIMName ("key"), Uint32(222)));
    r->createInstance(NS, inst1);
}

void TestCreateInstance4()
{
  if (verbose) cout << ProgName << "-TestCreateInstance4()" << endl;
    // -- Create an instance of each class:

    CIMInstance inst0(CIMName ("SuperClass"));
    inst0.addProperty(CIMProperty(CIMName ("key"), Uint32(1111)));
    r->createInstance(NS, inst0);

    CIMInstance inst1(CIMName ("SubClass"));
    inst1.addProperty(CIMProperty(CIMName ("key"), Uint32(2222)));
    r->createInstance(NS, inst1);
}

void TestCreateInstance5()
{
  if (verbose) cout << ProgName << "-TestCreateInstance5()" << endl;
    // -- Create an instance of each class:

    CIMInstance inst0(CIMName ("SuperClass"));
    inst0.addProperty(CIMProperty(CIMName ("key"), Uint32(11111)));
    r->createInstance(NS, inst0);

    CIMInstance inst1(CIMName ("SubClass"));
    inst1.addProperty(CIMProperty(CIMName ("key"), Uint32(22222)));
    r->createInstance(NS, inst1);
}

void TestEnumerateInstance(Uint32 num)
{
  if (verbose) cout << ProgName << "-TestEnumerateInstance()" << endl;

    // -- Enumerate instances names:
    Array<CIMObjectPath> instanceNames =
	r->enumerateInstanceNames(NS, CIMName ("SuperClass"));

	if (verbose)
	{
	  cout << ProgName << "-Enumerated instance names: ";
		for (Uint32 i = 0 ; i < instanceNames.size(); i++)
		{
		  cout << instanceNames[i].toString() << ", ";
		}
	  cout << endl;
	}

    assert(instanceNames.size() == num*2);

}

void TestEnumerateInstances(Uint32 num)
{
  if (verbose) cout << ProgName << "-TestEnumerateInstances()" << endl;
    // -- Enumerate instances:

    Array<CIMInstance> namedInstances = r->enumerateInstances(NS,
        CIMName ("SuperClass"),true,false, true, true);

#ifdef NOTDEF
    // defined out becuase it is very verbose
	if (verbose)
	{
	  cout << ProgName << "-Enumerated instance names: ";
		for (Uint32 i = 0 ; i < namedInstances.size(); i++)
		{
		  cout << ((CIMObject )namedInstances[i]).toString() << ", ";
		}
	  cout << endl;
	}
#endif

    assert(namedInstances.size() == num*2);

}

void TestEnumerateInstancesForClass(Uint32 num)
{
  if (verbose) cout << ProgName << "-TestEnumerateInstancesForClass()" << endl;

    // test the enumerateInstancesFor Class function

    Array<CIMInstance>  namedInstances = r->enumerateInstancesForClass(NS,
        CIMName ("SuperClass"),true,false, true, true);

#ifdef NOTDEF
    // defined out becuase it is very verbose
	if (verbose)
	{
	  cout << ProgName << "-Enumerated instancs for Class-SuperClass: ";
		for (Uint32 i = 0 ; i < namedInstances.size(); i++)
		{
		  cout << ((CIMObject )namedInstances[i]).toString() << ", ";
		}
	  cout << endl;
	}
#endif

    assert(namedInstances.size() == num);

    namedInstances = r->enumerateInstancesForClass(NS,
        CIMName ("SubClass"),true,false, true, true);

#ifdef NOTDEF
    // defined out becuase it is very verbose
	if (verbose)
	{
	  cout << ProgName << "-Enumerated instancs for Class-SubClass: ";
		for (Uint32 i = 0 ; i < namedInstances.size(); i++)
		{
		  cout << ((CIMObject )namedInstances[i]).toString() << ", ";
		}
	  cout << endl;
	}
#endif

    assert(namedInstances.size() == num);

}

void TestQualifiers()
{
    // -- Create repository and "xyz" namespace:

    const CIMNamespaceName NS = CIMNamespaceName ("TestQualifiers");

    try
    {
	r->createNameSpace(NS);
    }
    catch (AlreadyExistsException&)
    {
	// Ignore this!
    }

    // -- Construct a qualifier declaration:

    CIMQualifierDecl q(CIMName ("abstract"), true, CIMScope::CLASS);
    r->setQualifier(NS, q);

    CIMQualifierDecl qq = r->getQualifier(NS, CIMName ("abstract"));

    assert(qq.identical(q));
    assert(q.identical(qq));

    // -- Delete the qualifier:

    r->deleteQualifier(NS, CIMName ("abstract"));

    // -- Delete the namespace:

    r->deleteNameSpace(NS);
}

int main(int argc, char** argv)
{
    verbose = getenv("PEGASUS_TEST_VERBOSE");
    ProgName = argv[0];

    const char* tmpDir = getenv ("PEGASUS_TMP");
    if (tmpDir == NULL)
    {
        repositoryRoot = ".";
    }
    else
    {
        repositoryRoot = tmpDir;
    }
    repositoryRoot.append("/repository");

    try
    {
      CIMRepository_Mode mode;
      CIMRepository_Mode modeother;
      int mixed_mode;

      if (!strcmp(argv[1],"XML") )
	{
	  mode.flag = CIMRepository_Mode::NONE;
	  modeother.flag = CIMRepository_Mode::BIN;
	  mixed_mode = 0;
	  if (verbose) cout << ProgName<< ": Single test using XML mode repository" << endl;
	}
      else if (!strcmp(argv[1],"BIN") )
	{
	  mode.flag = CIMRepository_Mode::BIN;
	  modeother.flag = CIMRepository_Mode::NONE;
	  mixed_mode = 0;
	  if (verbose) cout << ProgName<< ": Single test using BIN mode repository" << endl;
	}
      else if (!strcmp(argv[1],"XMLMIX") )
	{
	  mode.flag = CIMRepository_Mode::NONE;
	  modeother.flag = CIMRepository_Mode::BIN;
	  mixed_mode = 1;
	  if (verbose) cout << ProgName<< ": Mixed test using XML mode repository first" << endl;
	}
      else if (!strcmp(argv[1],"BINMIX") )
	{
	  mode.flag = CIMRepository_Mode::BIN;
	  modeother.flag = CIMRepository_Mode::NONE;
	  mixed_mode = 1;
	  if (verbose) cout << ProgName<< ": Mixed test using BIN mode repository first" << endl;
	}
      else
	{
	  cout << ProgName<< ": invalid argument: " << argv[1] << endl;
	  return 0;
	}

      TestOpenRepo(mode);
      TestInitRepo();
      TestCreateClass();
      TestEnumerateClass();
      TestCreateInstance1();
      if (mixed_mode)
	{
	  TestCloseRepo();
	  TestOpenRepo(modeother);
	}

      TestCreateInstance2();

      if (mixed_mode)
	{
	  TestCloseRepo();
	  TestOpenRepo(mode);
	}

      TestCreateInstance3();

      if (mixed_mode)
	{
	  TestCloseRepo();
	  TestOpenRepo(modeother);
	}
      TestCreateInstance4();

      if (mixed_mode)
	{
	  TestCloseRepo();
	  TestOpenRepo(mode);
	}

      TestCreateInstance5();
      TestEnumerateInstance(5);
      TestEnumerateInstances(5);
      TestEnumerateInstancesForClass(5);
      TestQualifiers();

    }
    catch (const Exception& e)
    {
	cout << argv[0] << " " << argv[1] << " " << e.getMessage() << endl;
	exit(1);
    }

    cout << ProgName << " " << argv[1] << " +++++ passed all tests" << endl;

    return 0;
}


text:
The standard observable iterator implementation for [`Emitter`](Emitter.md).

**Implements**
:   [`Icicle\Observable\ObservableIterator`](ObservableIterator.md)


text:
ActiveRecord::Schema.define(version: 20140618030148) do

  create_table "lines", force: true do |t|
    t.string   "name",       null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "lines_stations", force: true do |t|
    t.integer  "station_id", null: false
    t.integer  "line_id",    null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "stations", force: true do |t|
    t.string   "name",       null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


text:
<?php

namespace app\controllers;

use Yii;
use app\models\Banners;
use app\models\BannersSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\BadRequestHttpException;
use yii\web\UploadedFile;
use yii\filters\VerbFilter;

/**
 * BannerController implements the CRUD actions for Banners model.
 */
class BannerController extends Controller
{
    public function behaviors()
    {
        return [
            'access' =>
            [
                'class' => \yii\filters\AccessControl::className(),
                'only' => ['create', 'delete', 'update', 'view', 'index'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@']
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Banners models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BannersSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Banners model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Banners model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Banners();

        if ($model->load(Yii::$app->request->post())) {
            //Pega a instância do arquivo
            $model->image_file = UploadedFile::getInstance($model, 'image_file');

            //Salva o caminho no BD
            if ($model->url_imagem = $model->uploadBanner()) {

                if ($model->save()){
                    return $this->redirect(['view', 'id' => $model->id]);
                } else {
                    return $this->render('create', ['model' => $model,]);
                }

            } else {
                throw new BadRequestHttpException('Não foi possível enviar o arquivo');
            }

        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Banners model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $currentImage = $model->url_imagem;

        if ($model->load(Yii::$app->request->post())) {
            //Pega a instância do arquivo
            $model->image_file = UploadedFile::getInstance($model, 'image_file');

            //Salva o caminho no BD e apaga a imagem antiga
            if ($model->uploadBanner()) {
                $model->url_imagem = $model->uploadBanner();
                $model->deleteBanner($currentImage);
            }

            if ($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                return $this->render('update', ['model' => $model,]);
            }

        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Banners model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $model->deleteBanner($model->url_imagem);

        $this->findModel($id)->delete();
        return $this->redirect(['index']);
    }

    /**
     * Finds the Banners model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Banners the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Banners::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('A página solicitada não existe.');
        }
    }
}


text:
package ice.http.server.annotations;

import ice.http.server.view.View;

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Method(Method.HttpMethod.POST)
public @interface Post {
	String[] value();

	Class<? extends View> view() default View.class;

	String summary() default "";

	String description() default "";
}


text:
                        STRUKTUR ORGANISASI

Dinas Kebersihan dan Pertamanan Kabupaten Cianjur

                    <img src="<?php echo config_item('assets')?>img/struktur-organisasi.png" class="img-thumbnail img-responsive center-block">

                Link Terkait

                <?php $this->load->view('side_menu',array('menu'=>'profil')) ?>


text:
/*
 * Title:        GridSim Toolkit

 * Description:  GridSim (Grid Simulation) Toolkit for Modeling and Simulation
 *               of Parallel and Distributed Systems such as Clusters and Grids
 * License:      GPL - http://www.gnu.org/copyleft/gpl.html
 *
 */

package gridsim;

import eduni.simjava.Sim_event;
import eduni.simjava.Sim_system;
import gridsim.index.AbstractGIS;
import gridsim.net.InfoPacket;
import gridsim.net.Link;

import java.util.Calendar;
import java.util.LinkedList;

/**
 * GridResource extends the {@link gridsim.GridSimCore} class for
 * gaining communication and concurrent entity capabilities.
 * An instance of this class simulates a resource
 * with properties defined in an object of
 * {@link gridsim.ResourceCharacteristics} class.
 *

 * The process of creating a Grid resource is as follows:
 *

 *
 create PE (Processing Element) objects with a suitable MIPS (Million
 *      Instructions Per Second) or SPEC (Standard Performance Evaluation
 *      Corporation) rating;
 *
 assemble them together to create a machine;
 *
 group one or more objects of the machine to form a Grid resource
 *

 *

 * A resource having a single machine with one or more PEs (Processing Elements)
 * is managed as a time-shared system using a round-robin scheduling algorithm.
 * A resource with multiple machines is treated as a distributed memory cluster
 * and is managed as a space-shared system using FCFS (First Come Firt Serve)
 * scheduling policy or its variants.
 *

 * Since GridSim 2.2, other scheduling algorithm can be added externally
 * (without compiling or replacing the existing GridSim JAR file) into a
 * Grid resource. For more information, look on tutorial page or AllocPolicy
 * class.
 *

 * Since GridSim 3.0, different types of resources can be created externally
 * without modifying this class. You need to do the following:
 *

 *
 extends from this class
 *
 uses only a constructor from
 *          {@link #GridResource(String, double, ResourceCharacteristics,
 *                              ResourceCalendar, AllocPolicy)}
 *
 overrides {@link #registerOtherEntity()} method to register a
 *          different entity or tag to {@link gridsim.GridInformationService}.
 *          However, you also need to create a new child class extending from
 *          {@link gridsim.GridInformationService}.
 *
 overrides {@link #processOtherEvent(Sim_event)} method to process
 *          other incoming tags apart from the standard ones.
 *

 *

 * NOTE:
 *

 *
You do not need to override {@link #body()} method if you do step 3.
 *
A resource name can be found using <tt>super.get_name()</tt> method
 *         from {@link eduni.simjava.Sim_entity} class.
 *
A resource ID can be found using <tt>super.get_id()</tt> method
 *         from {@link eduni.simjava.Sim_entity} class.
 *

 *

 * Since GridSim 3.1, a network framework has been incorporated into this
 * simulation. To make use of this, you need to create a resource entity
 * only using the below constructors:
 *

 *
 {@link #GridResource(String, Link, ResourceCharacteristics,
 *                              ResourceCalendar, AllocPolicy)}
 *
 {@link #GridResource(String, Link, ResourceCharacteristics,
 *                              ResourceCalendar)}
 *
 {@link #GridResource(String, Link,  long,
 *               ResourceCharacteristics, double, double, double,
 *               LinkedList, LinkedList)}
 *

 *
 * Then you need to attach this entity into the overall network topology, i.e.
 * connecting this entity to a router, etc. See the examples for more details.
 *
 * @author       Manzur Murshed and Rajkumar Buyya
 * @author       Anthony Sulistio (re-design and re-written this class)
 * @since        GridSim Toolkit 1.0
 * @see gridsim.GridSimCore
 * @see gridsim.ResourceCharacteristics
 * @see gridsim.AllocPolicy
 * @invariant $none
 */
public class GridResource extends GridSimCore
{
    /** Characteristics of this resource */
    protected ResourceCharacteristics resource_;

    /** a ResourceCalendar object */
    protected ResourceCalendar resCalendar_;

    /** A resource's scheduler. This object is reponsible in scheduling and
     * and executing submitted Gridlets.
     */
    protected AllocPolicy policy_;

    /** A scheduler type of this resource, such as FCFS, Round Robin, etc */
    protected int policyType_;

    /** Integer object size, including its overhead */
    protected static final int SIZE = 12;

    /** Regional GIS entity name */
    protected String regionalGISName_;

    /**
     * Allocates a new GridResource object. When making a different type of
     * GridResource object, use
     * {@link #GridResource(String, double, ResourceCharacteristics,
     *                      ResourceCalendar, AllocPolicy)}
     * and then overrides {@link #processOtherEvent(Sim_event)}.
     *
     * @param name       the name to be associated with this entity (as
     *                   required by Sim_entity class from simjava package)
     * @param baud_rate  network communication or bandwidth speed
     * @param seed       the initial seed
     * @param resource   an object of ResourceCharacteristics
     * @param peakLoad   the load during peak times
     * @param offPeakLoad   the load during off peak times
     * @param relativeHolidayLoad   the load during holiday times
     * @param weekends   a linked-list contains the weekend days
     * @param holidays   a linked-list contains the public holidays
     * @throws Exception This happens when one of the following scenarios occur:
     *

     *
 creating this entity before initializing GridSim package
     *
 this entity name is <tt>null</tt> or empty
     *
 this entity has <tt>zero</tt> number of PEs (Processing
     *              Elements).

     *              No PEs mean the Gridlets can't be processed.
     *              A GridResource must contain one or more Machines.
     *              A Machine must contain one or more PEs.
     *

     * @see gridsim.GridSim#init(int, Calendar, boolean, String[], String[],
     *          String)
     * @see gridsim.GridSim#init(int, Calendar, boolean)
     * @see #GridResource(String, double,
     *          ResourceCharacteristics, ResourceCalendar, AllocPolicy)
     * @pre name != null
     * @pre baud_rate > 0
     * @pre resource != null
     * @post $none
     */
    public GridResource(String name, double baud_rate, long seed,
            ResourceCharacteristics resource, double peakLoad,
            double offPeakLoad, double relativeHolidayLoad,
            LinkedList weekends, LinkedList holidays) throws Exception
    {
        super(name, baud_rate);
        resource_ = resource;

        resCalendar_ = new ResourceCalendar(resource_.getResourceTimeZone(),
                peakLoad, offPeakLoad, relativeHolidayLoad, weekends,
                holidays, seed);

        policy_ = null;
        init();
    }

    /**
     * Allocates a new GridResource object. When making a different type of
     * GridResource object, use
     * {@link #GridResource(String, double, ResourceCharacteristics,
     *                      ResourceCalendar, AllocPolicy)}
     * and then overrides {@link #processOtherEvent(Sim_event)}.
     *
     * @param name       the name to be associated with this entity (as
     *                   required by Sim_entity class from simjava package)
     * @param baud_rate  network communication or bandwidth speed
     * @param resource   an object of ResourceCharacteristics
     * @param calendar   an object of ResourceCalendar
     * @throws Exception This happens when one of the following scenarios occur:
     *

     *
 creating this entity before initializing GridSim package
     *
 this entity name is <tt>null</tt> or empty
     *
 this entity has <tt>zero</tt> number of PEs (Processing
     *              Elements).

     *              No PEs mean the Gridlets can't be processed.
     *              A GridResource must contain one or more Machines.
     *              A Machine must contain one or more PEs.
     *

     * @see gridsim.GridSim#init(int, Calendar, boolean, String[], String[],
     *          String)
     * @see gridsim.GridSim#init(int, Calendar, boolean)
     * @see #GridResource(String, double,
     *          ResourceCharacteristics, ResourceCalendar, AllocPolicy)
     * @pre name != null
     * @pre baud_rate > 0
     * @pre resource != null
     * @pre calendar != null
     * @post $none
     */
    public GridResource(String name, double baud_rate,
                ResourceCharacteristics resource, ResourceCalendar calendar)
                throws Exception
    {
        super(name, baud_rate);
        resource_ = resource;

        resCalendar_ = calendar;
        policy_ = null;
        init();
    }

    /**
     * Allocates a new GridResource object. When making a different type of
     * GridResource object, use this constructor and then overrides
     * {@link #processOtherEvent(Sim_event)}.
     *
     * @param name       the name to be associated with this entity (as
     *                   required by Sim_entity class from simjava package)
     * @param baud_rate  network communication or bandwidth speed
     * @param resource   an object of ResourceCharacteristics
     * @param calendar   an object of ResourceCalendar
     * @param policy     a scheduling policy for this Grid resource. If no
     *                   scheduling policy is defined, the default one is
     *                   <tt>SpaceShared</tt>
     * @throws Exception This happens when one of the following scenarios occur:
     *

     *
 creating this entity before initializing GridSim package
     *
 this entity name is <tt>null</tt> or empty
     *
 this entity has <tt>zero</tt> number of PEs (Processing
     *              Elements).

     *              No PEs mean the Gridlets can't be processed.
     *              A GridResource must contain one or more Machines.
     *              A Machine must contain one or more PEs.
     *

     * @see gridsim.GridSim#init(int, Calendar, boolean, String[], String[],
     *          String)
     * @see gridsim.GridSim#init(int, Calendar, boolean)
     * @see gridsim.AllocPolicy
     * @pre name != null
     * @pre baud_rate > 0
     * @pre resource != null
     * @pre calendar != null
     * @pre policy != null
     * @post $none
     */
    public GridResource(String name, double baud_rate,
                ResourceCharacteristics resource, ResourceCalendar calendar,
                AllocPolicy policy) throws Exception
    {
        super(name, baud_rate);
        resource_ = resource;

        resCalendar_ = calendar;
        policy_ = policy;  // the order between policy and init() is important
        init();
    }

    /**
     * Allocates a new GridResource object. When making a different type of
     * GridResource object, use
     * {@link #GridResource(String, Link, ResourceCharacteristics,
     *                      ResourceCalendar, AllocPolicy)}
     * and then overrides {@link #processOtherEvent(Sim_event)}.
     *
     * @param name       the name to be associated with this entity (as
     *                   required by Sim_entity class from simjava package)
     * @param link       the link that will be used to connect this
     *                   GridResource to another Entity or Router.
     * @param seed       the initial seed
     * @param resource   an object of ResourceCharacteristics
     * @param peakLoad   the load during peak times
     * @param offPeakLoad   the load during off peak times
     * @param relativeHolidayLoad   the load during holiday times
     * @param weekends   a linked-list contains the weekend days
     * @param holidays   a linked-list contains the public holidays
     * @throws Exception This happens when one of the following scenarios occur:
     *

     *
 creating this entity before initializing GridSim package
     *
 this entity name is <tt>null</tt> or empty
     *
 this entity has <tt>zero</tt> number of PEs (Processing
     *              Elements).

     *              No PEs mean the Gridlets can't be processed.
     *              A GridResource must contain one or more Machines.
     *              A Machine must contain one or more PEs.
     *

     * @see gridsim.GridSim#init(int, Calendar, boolean, String[], String[],
     *          String)
     * @pre name != null
     * @pre link != null
     * @pre resource != null
     * @post $none
     */
    public GridResource(String name, Link link,  long seed,
                ResourceCharacteristics resource, double peakLoad,
                double offPeakLoad, double relativeHolidayLoad,
                LinkedList weekends, LinkedList holidays) throws Exception
    {
        super(name, link);
        resource_ = resource;

        resCalendar_ = new ResourceCalendar(resource_.getResourceTimeZone(),
                peakLoad, offPeakLoad, relativeHolidayLoad, weekends,
                holidays, seed);

        policy_ = null;
        init();
    }

    /**
     * Allocates a new GridResource object. When making a different type of
     * GridResource object, use
     * {@link #GridResource(String, Link, ResourceCharacteristics,
     *                      ResourceCalendar, AllocPolicy)}
     * and then overrides {@link #processOtherEvent(Sim_event)}.
     *
     * @param name       the name to be associated with this entity (as
     *                   required by Sim_entity class from simjava package)
     * @param link       the link that will be used to connect this
     *                   GridResource to another Entity or Router.
     * @param resource   an object of ResourceCharacteristics
     * @param calendar   an object of ResourceCalendar
     * @throws Exception This happens when one of the following scenarios occur:
     *

     *
 creating this entity before initializing GridSim package
     *
 this entity name is <tt>null</tt> or empty
     *
 this entity has <tt>zero</tt> number of PEs (Processing
     *              Elements).

     *              No PEs mean the Gridlets can't be processed.
     *              A GridResource must contain one or more Machines.
     *              A Machine must contain one or more PEs.
     *

     * @see gridsim.GridSim#init(int, Calendar, boolean, String[], String[],
     *          String)
     * @pre name != null
     * @pre link != null
     * @pre resource != null
     * @pre calendar != null
     * @post $none
     */
    public GridResource(String name, Link link,
                ResourceCharacteristics resource, ResourceCalendar calendar)
                throws Exception
    {
        super(name, link);
        resource_ = resource;

        resCalendar_ = calendar;
        policy_ = null;
        init();
    }

    /**
     * Allocates a new GridResource object. When making a different type of
     * GridResource object, use this constructor and then overrides
     * {@link #processOtherEvent(Sim_event)}.
     *
     * @param name       the name to be associated with this entity (as
     *                   required by Sim_entity class from simjava package)
     * @param link       the link that will be used to connect this
     *                   GridResource to another Entity or Router.
     * @param resource   an object of ResourceCharacteristics
     * @param calendar   an object of ResourceCalendar
     * @param policy     a scheduling policy for this Grid resource. If no
     *                   scheduling policy is defined, the default one is
     *                   <tt>SpaceShared</tt>
     * @throws Exception This happens when one of the following scenarios occur:
     *

     *
 creating this entity before initializing GridSim package
     *
 this entity name is <tt>null</tt> or empty
     *
 this entity has <tt>zero</tt> number of PEs (Processing
     *              Elements).

     *              No PEs mean the Gridlets can't be processed.
     *              A GridResource must contain one or more Machines.
     *              A Machine must contain one or more PEs.
     *

     * @see gridsim.GridSim#init(int, Calendar, boolean, String[], String[],
     *          String)
     * @see gridsim.AllocPolicy
     * @pre name != null
     * @pre link != null
     * @pre resource != null
     * @pre calendar != null
     * @pre policy != null
     * @post $none
     */
    public GridResource(String name, Link link,
            ResourceCharacteristics resource, ResourceCalendar calendar,
            AllocPolicy policy) throws Exception
    {
        super(name,link);
        resource_ = resource;

        resCalendar_ = calendar;
        policy_ = policy;  // the order between policy and init() is important
        init();
    }

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

    /**
     * Returns the allocation policy used by this Grid resource.
     * @return the allocation policy
     */
    public AllocPolicy getAllocationPolicy(){
    	return policy_;
    }

    /**
     * Returns the characteristics of the resource.
     * @return the resource characteristics
     */
    public ResourceCharacteristics getResourceCharacteristics() {
    	return resource_;
    }

    /**
     * Sets a regional GridInformationService (GIS) entity for this resource
     * to communicate with. This resource will then register its ID to the
     * regional GIS entity, rather than {@link GridInformationService} or
     * <tt>system GIS</tt>.
     * @param regionalGIS   name of regional GIS entity
     * @return <tt>true</tt> if it is successful, <tt>false</tt> otherwise
     * @pre regionalGIS != null
     * @post $none
     */
    public boolean setRegionalGIS(String regionalGIS)
    {
        if (regionalGIS == null || GridSim.getEntityId(regionalGIS) == -1) {
            return false;
        }

        regionalGISName_ = regionalGIS;
        return true;
    }

    /**
     * Sets a regional GridInformationService (GIS) entity for this resource
     * to communicate with. This resource will then register its ID to the
     * regional GIS entity, rather than {@link GridInformationService} or
     * <tt>system GIS</tt>.
     * @param gis   regional GIS entity object
     * @return <tt>true</tt> if it is successful, <tt>false</tt> otherwise
     * @pre gis != null
     * @post $none
     */
    public boolean setRegionalGIS(AbstractGIS gis)
    {
        if (gis == null) {
            return false;
        }

        return setRegionalGIS( gis.get_name() );
    }

    /**
     * Handles external events that are coming to this GridResource entity.
     * This method also registers the identity of this GridResource entity to
     * <tt>GridInformationService</tt> class.
     *

     * The services or tags available for this resource are:
     *

     *
 {@link gridsim.GridSimTags#RESOURCE_CHARACTERISTICS}

     *
 {@link gridsim.GridSimTags#RESOURCE_DYNAMICS}

     *
 {@link gridsim.GridSimTags#GRIDLET_SUBMIT}

     *
 {@link gridsim.GridSimTags#GRIDLET_CANCEL}

     *
 {@link gridsim.GridSimTags#GRIDLET_PAUSE}

     *
 {@link gridsim.GridSimTags#GRIDLET_RESUME}

     *
 {@link gridsim.GridSimTags#GRIDLET_MOVE}

     *
 {@link gridsim.GridSimTags#GRIDLET_STATUS}

     *

     *

     * This method also calls these methods in the following order:
     *

     *
 {@link #registerOtherEntity()} method
     *
 {@link #processOtherEvent(Sim_event)} method
     *

     *
     * @pre $none
     * @post $none
     */
    public void body()
    {
        // send the registration to GIS
        int register = 0;
        if (policyType_ == ResourceCharacteristics.ADVANCE_RESERVATION) {
            register = GridSimTags.REGISTER_RESOURCE_AR;
        }
        else {
            register = GridSimTags.REGISTER_RESOURCE;
        }

        // this resource should register to regional GIS.
        // However, if not specified, then register to system GIS (the
        // default GridInformationService) entity.
        int gisID = GridSim.getEntityId(regionalGISName_);
        if (gisID == -1) {
            gisID = GridSim.getGridInfoServiceEntityId();
        }
        // need to wait for few seconds before registering to a regional GIS.
        // This is because to allow all routers to fill in their routing tables
        else
        {
            super.sim_pause(GridSim.PAUSE);
            System.out.println(super.get_name() + ".body(): wait for " +
                GridSim.PAUSE + " seconds before registering to " +
                regionalGISName_);
        }

        // send the registration to GIS
        super.send(super.output, GridSimTags.SCHEDULE_NOW, register,
                new IO_data(new Integer(super.get_id()), SIZE, gisID) );

        // Below method is for a child class to override
        registerOtherEntity();

        // Process events until END_OF_SIMULATION is received from the
        // GridSimShutdown Entity
        Sim_event ev = new Sim_event();
        while ( Sim_system.running() )
        {
            super.sim_get_next(ev);

            // if the simulation finishes then exit the loop
            if (ev.get_tag() == GridSimTags.END_OF_SIMULATION)
            {
                policy_.setEndSimulation();
                break;
            }

            // process the received event
            processEvent(ev);
        }

        // remove I/O entities created during construction of this entity
        super.terminateIOEntities();
    }

    //////////////////// PROTECTED METHODS ///////////////////////////////////

    /**
     * Overrides this method when making a new and different type of resource.
     * This method is called by {@link #body()} for incoming unknown tags.
     *

     * Another approach is to override the
     * {@link gridsim.AllocPolicy#processOtherEvent(Sim_event)} method.
     * This approach is desirable if you do not want to create a new type of
     * grid resource.
     *
     * @param ev   a Sim_event object
     * @pre ev != null
     * @post $none
     */
    protected void processOtherEvent(Sim_event ev)
    {
        if (ev == null)
        {
            System.out.println(super.get_name() + ".processOtherEvent(): " +
                    "Error - an event is null.");
            return;
        }

        /****   // NOTE: now a resource passes a new event to the scheduler
        System.out.println(super.get_name()+".processOtherEvent(): Unable to " +
                "handle request from GridSimTags with tag number " +
                ev.get_tag() );
        *****/

        policy_.processOtherEvent(ev);
    }

    /**
     * Overrides this method when making a new and different type of resource.
     * This method is called by {@link #body()} to register other type to
     * {@link gridsim.GridInformationService} entity. In doing so, you
     * need to create a new child class extending from
     * {@link gridsim.GridInformationService}.
     *

     * NOTE: You do not need to override {@link #body()} method, if
     * you use this method.
     *
     * @pre $none
     * @post $none
     * @see gridsim.GridInformationService
     */
    protected void registerOtherEntity() {
        // empty. This should be override by a child class
    }

    //////////////////// PRIVATE METHODS ///////////////////////////////////

    /**
     * Initializes the resource allocation policy
     * @throws Exception    If number of PEs is zero
     * @pre $none
     * @post $none
     */
    private void init() throws Exception
    {
        // If this resource doesn't have any PEs then no useful at all
        if (resource_.getNumPE() == 0)
        {
            throw new Exception(super.get_name() + " : Error - this entity " +
                    "has no PEs. Therefore, can't process any Gridlets.");
        }

        // stores id of this class
        resource_.setResourceID( super.get_id() );

        // if internal allocation policy is used
        policyType_ = resource_.getResourceAllocationPolicy();
        if (policy_ == null)
        {
            switch (policyType_)
            {
                case ResourceCharacteristics.TIME_SHARED:
                    policy_ = new TimeShared(super.get_name(), "TimeShared");
                    break;

                case ResourceCharacteristics.SPACE_SHARED:
                    policy_ = new SpaceShared(super.get_name(), "SpaceShared");
                    break;

                default:
                    throw new Exception(super.get_name()+" : Error - supports"+
                            " only TimeShared or SpaceShared policy.");
            }
        }

        policy_.init(resource_, resCalendar_, super.output);
    }

    /**
     * Processes events or services that are available for this GridResource
     * @param ev    a Sim_event object
     * @pre ev != null
     * @post $none
     */
    private void processEvent(Sim_event ev)
    {
        int src_id = -1;
        switch ( ev.get_tag() )
        {
            // Resource characteristics inquiry
            case GridSimTags.RESOURCE_CHARACTERISTICS:
                src_id = ( (Integer) ev.get_data() ).intValue();
                super.send( super.output, 0.0, ev.get_tag(),
                        new IO_data(resource_,resource_.getByteSize(),src_id));
                break;

                // Resource dynamic info inquiry
            case GridSimTags.RESOURCE_DYNAMICS:
                src_id = ( (Integer) ev.get_data() ).intValue();
                super.send( super.output, 0.0, ev.get_tag(),
                        new IO_data(policy_.getTotalLoad(),
                                    Accumulator.getByteSize(), src_id) );
                break;

            case GridSimTags.RESOURCE_NUM_PE:
                src_id = ( (Integer) ev.get_data() ).intValue();
                int numPE = resource_.getNumPE();
                super.send( super.output, 0.0, ev.get_tag(),
                        new IO_data(new Integer(numPE), SIZE, src_id) );
                break;

            case GridSimTags.RESOURCE_NUM_FREE_PE:
                src_id = ( (Integer) ev.get_data() ).intValue();
                int numFreePE = resource_.getNumFreePE();
                super.send( super.output, 0.0, ev.get_tag(),
                        new IO_data(new Integer(numFreePE), SIZE, src_id) );
                break;

                // New Gridlet arrives
            case GridSimTags.GRIDLET_SUBMIT:
                processGridletSubmit(ev, false);
                break;

                // New Gridlet arrives, but the sender asks for an ack
            case GridSimTags.GRIDLET_SUBMIT_ACK:
                processGridletSubmit(ev, true);
                break;

                // Cancels a previously submitted Gridlet
            case GridSimTags.GRIDLET_CANCEL:
                processGridlet(ev, GridSimTags.GRIDLET_CANCEL);
                break;

                // Pauses a previously submitted Gridlet
            case GridSimTags.GRIDLET_PAUSE:
                processGridlet(ev, GridSimTags.GRIDLET_PAUSE);
                break;

                // Pauses a previously submitted Gridlet, but the sender
                // asks for an acknowledgement
            case GridSimTags.GRIDLET_PAUSE_ACK:
                processGridlet(ev, GridSimTags.GRIDLET_PAUSE_ACK);
                break;

                // Resumes a previously submitted Gridlet
            case GridSimTags.GRIDLET_RESUME:
                processGridlet(ev, GridSimTags.GRIDLET_RESUME);
                break;

                // Resumes a previously submitted Gridlet, but the sender
                // asks for an acknowledgement
            case GridSimTags.GRIDLET_RESUME_ACK:
                processGridlet(ev, GridSimTags.GRIDLET_RESUME_ACK);
                break;

                // Moves a previously submitted Gridlet to a different resource
            case GridSimTags.GRIDLET_MOVE:
                processGridletMove(ev, GridSimTags.GRIDLET_MOVE);
                break;

                // Moves a previously submitted Gridlet to a different resource
            case GridSimTags.GRIDLET_MOVE_ACK:
                processGridletMove(ev, GridSimTags.GRIDLET_MOVE_ACK);
                break;

                // Checks the status of a Gridlet
            case GridSimTags.GRIDLET_STATUS:
                processGridletStatus(ev);
                break;

                // Ping packet
            case GridSimTags.INFOPKT_SUBMIT:
                processPingRequest(ev);
                break;

                // other unknown tags are processed by this method
            default:
                processOtherEvent(ev);
                break;
        }
    }

    /**
     * Process the event for an User who wants to know the status of a Gridlet.
     * This GridResource will then send the status back to the User.
     * @param ev   a Sim_event object
     * @pre ev != null
     * @post $none
     */
    private void processGridletStatus(Sim_event ev)
    {
        int gridletId = 0;
        int userId = 0;
        int status = -1;

        try
        {
            // if a sender using gridletXXX() methods
            int data[] = (int[]) ev.get_data();
            gridletId = data[0];
            userId = data[1];

            status = policy_.gridletStatus(gridletId, userId);
        }

        // if a sender using normal send() methods
        catch (ClassCastException c)
        {
            try
            {
                Gridlet gl = (Gridlet) ev.get_data();
                gridletId = gl.getGridletID();
                userId = gl.getUserID();

                status = policy_.gridletStatus(gridletId, userId);
            }
            catch (Exception e)
            {
                System.out.println(super.get_name() +
                        ": Error in processing GridSimTags.GRIDLET_STATUS");
                System.out.println( e.getMessage() );
                return;
            }
        }
        catch (Exception e)
        {
            System.out.println(super.get_name() +
                    ": Error in processing GridSimTags.GRIDLET_STATUS");
            System.out.println( e.getMessage() );
            return;
        }

        int[] array = new int[2];
        array[0] = gridletId;
        array[1] = status;

        int tag = GridSimTags.GRIDLET_STATUS;
        super.send( super.output, GridSimTags.SCHEDULE_NOW, tag,
                    new IO_data(array, SIZE, userId) );
    }

    /**
     * Processes a Gridlet based on the event type
     * @param ev   a Sim_event object
     * @param type event type
     * @pre ev != null
     * @pre type > 0
     * @post $none
     */
    private void processGridlet(Sim_event ev, int type)
    {
        int gridletId = 0;
        int userId = 0;

        try
        {
            // if a sender using gridletXXX() methods
            int data[] = (int[]) ev.get_data();
            gridletId = data[0];
            userId = data[1];
        }

        // if a sender using normal send() methods
        catch (ClassCastException c)
        {
            try
            {
                Gridlet gl = (Gridlet) ev.get_data();
                gridletId = gl.getGridletID();
                userId = gl.getUserID();
            }
            catch (Exception e)
            {
                System.out.println(super.get_name() +
                        ": Error in processing Gridlet");
                System.out.println( e.getMessage() );
                return;
            }
        }
        catch (Exception e)
        {
            System.out.println(super.get_name() +
                    ": Error in processing a Gridlet.");
            System.out.println( e.getMessage() );
            return;
        }

        // begins executing ....
        switch (type)
        {
            case GridSimTags.GRIDLET_CANCEL:
                policy_.gridletCancel(gridletId, userId);
                break;

            case GridSimTags.GRIDLET_PAUSE:
                policy_.gridletPause(gridletId, userId, false);
                break;

            case GridSimTags.GRIDLET_PAUSE_ACK:
                policy_.gridletPause(gridletId, userId, true);
                break;

            case GridSimTags.GRIDLET_RESUME:
                policy_.gridletResume(gridletId, userId, false);
                break;

            case GridSimTags.GRIDLET_RESUME_ACK:
                policy_.gridletResume(gridletId, userId, true);
                break;

            default:
                break;
        }

    }

    /**
     * Process the event for an User who wants to know the move of a Gridlet.
     * @param ev   a Sim_event object
     * @param type  event tag
     * @pre ev != null
     * @pre type > 0
     * @post $none
     */
    private void processGridletMove(Sim_event ev, int type)
    {
        boolean ack = false;
        if (type == GridSimTags.GRIDLET_MOVE_ACK) {
            ack = true;
        }

        try
        {
            // if a sender using gridletMove() methods
            int data[] = (int[]) ev.get_data();
            int gridletId = data[0];
            int userId = data[1];
            int destId = data[2];

            policy_.gridletMove(gridletId, userId, destId, ack);
        }
        catch (Exception e)
        {
            System.out.println(super.get_name()+": Error in moving a Gridlet.");
            System.out.println( e.getMessage() );
        }
    }

    /**
     * Processes a Gridlet submission
     * @param ev  a Sim_event object
     * @param ack  an acknowledgement
     * @pre ev != null
     * @post $none
     */
    private void processGridletSubmit(Sim_event ev, boolean ack)
    {
        try
        {
            // gets the Gridlet object
            Gridlet gl = (Gridlet) ev.get_data();

            // checks whether this Gridlet has finished or not
            if (gl.isFinished())
            {
                String name = GridSim.getEntityName( gl.getUserID() );
                System.out.println(super.get_name() + ": Warning - Gridlet #" +
                        gl.getGridletID() + " owned by " + name +
                        " is already completed/finished.");
                System.out.println("Therefore, it is not being executed again");
                System.out.println();

                // NOTE: If a Gridlet has finished, then it won't be processed.
                // So, if ack is required, this method sends back a result.
                // If ack is not required, this method don't send back a result.
                // Hence, this might cause GridSim to be hanged since waiting
                // for this Gridlet back.
                if (ack)
                {
                    int[] array = new int[2];
                    array[0] = gl.getGridletID();
                    array[1] = GridSimTags.FALSE;

                    // unique tag = operation tag
                    int tag = GridSimTags.GRIDLET_SUBMIT_ACK;
                    super.send(super.output, GridSimTags.SCHEDULE_NOW, tag,
                            new IO_data(array, SIZE, gl.getUserID()) );
                }

                super.send(super.output, 0, GridSimTags.GRIDLET_RETURN,
                    new IO_data(gl,gl.getGridletOutputSize(),gl.getUserID()) );

                return;
            }

            // process this Gridlet to this GridResource
            gl.setResourceParameter(super.get_id(), resource_.getCostPerSec());
            policy_.gridletSubmit(gl, ack);
        }
        catch (ClassCastException c)
        {
            System.out.println(super.get_name() + ".processGridletSubmit(): " +
                    "ClassCastException error.");
            System.out.println( c.getMessage() );
        }
        catch (Exception e)
        {
            System.out.println(super.get_name() + ".processGridletSubmit(): " +
                    "Exception error.");
            System.out.println( e.getMessage() );
        }
    }

    /**
     * Processes a ping request.
     * @param ev  a Sim_event object
     * @pre ev != null
     * @post $none
     */
    private void processPingRequest(Sim_event ev)
    {
        InfoPacket pkt = (InfoPacket) ev.get_data();
        pkt.setTag(GridSimTags.INFOPKT_RETURN);
        pkt.setDestID( pkt.getSrcID() );

        // sends back to the sender
        super.send( super.output, 0.0, GridSimTags.INFOPKT_RETURN,
                    new IO_data(pkt, pkt.getSize(), pkt.getSrcID()) );
    }

}


text:
Set of Notepad++ plugins for Touhou Danmakufu ph3 (東方弾幕風) scripting language. Includes auto completion config and syntax highlighting configs.
##Features
- Syntax highlighting for Danmakufu ph3 scripts (.dnh)
- Default and Bespin color themes
- Code completion for ph3 engine library functions and constants
- Calltip function documentation

![Alt text](/screenshot/dmf-auto.png?raw=true "Autocomplete")
![Alt text](/screenshot/dmf-doc.png?raw=true "Calltip")
![Alt text](/screenshot/dmf-default.png?raw=true "Default theme")
![Alt text](/screenshot/dmf-bespin.png?raw=true "Bespin theme")

##Installation
To install auto completion config copy Danmakufu.ph3.xml to your Nodepad++ installation directory \plugins\APIs.
To enable auto completion go to Settings → Preferences... → Auto-Completion and select "Function completion" or "Function and word completion". For calltips check "Function parameters hint on input".

To install syntax highlighting go to Language → Define your language..., press Import... button and select the xml file.

For default theme use dmf.default.xml, and for Bespin theme use dmf.bespin.xml.

##Known limitations
- Windows-1252 encoding used for calltip documentation. Not sure but this seems to be Notepad++ limitation (utf-8 config doesn't work).
- Autocomplete window doesn't appear when a calltip is shown. Notepad++ limitation.
- Calltips only work for function and not for constants. Scintilla limitation.
- Cannot change calltip background or text color. Scintilla limitation.


text:
using System;
using System.Threading.Tasks;
using System.Threading;
using log4net;

namespace Merlion.Server.RoomFramework
{
	public class Client: IDisposable
	{
		static readonly ILog log = LogManager.GetLogger(typeof(Client));
		object sync = new object();

		readonly SemaphoreSlim moveSem = new SemaphoreSlim (1);

		static long nextId = 0;
		public long Id { get; private set; }

		public MerlionClient MerlionClient { get; internal set; }

		public Room Room { get; internal set; }

		public async Task MoveToRoom(Room newRoom)
		{
			// Leave the current room.
			Room oldRoom;
			lock (sync) {
				if (Room == newRoom) {
					return;
				}
				if (Room == null) {
					throw new InvalidOperationException ("Cannot add an orphaned client to a room. " +
						"(This might be caused by the ongoing move operation or the disposed client.)");
				}
				oldRoom = Room;
				Room = null;
			}

			await oldRoom.Strand.InvokeAsync (() => {
				oldRoom.InternalRemoveClient (this);
			});

			if (newRoom == null) {
				return;
			}

			// Add to the new room.
			try {
				await newRoom.Strand.InvokeAsync (() => {
					lock (sync) {
						Room = newRoom;
					}
					newRoom.InternalAddClient(this);
				});
			} catch (Exception ex) {
				// Adding failed.
				// Try to rollback.
				try {
					await oldRoom.Strand.InvokeAsync (() => {
						lock (sync) {
							Room = oldRoom;
						}
						oldRoom.InternalAddClient(this);
					});
				} catch (Exception ex2) {
					lock (sync) {
						Room = null;
					}
					Close ();
					throw new ClientMoveRollbackException (ex, ex2);
				}
				throw new ClientMoveException (ex);
			}
		}

		public event EventHandler<RoomChangedEventArgs> RoomChanged;
		protected virtual void OnRoomChanged(RoomChangedEventArgs args)
		{
			var handler = RoomChanged;
			if (handler != null)
				handler (this, args);
		}

		internal void InternalRaiseRoomChanged(Room room)
		{
			try {
				OnRoomChanged(new RoomChangedEventArgs(room));
			} catch (Exception ex) {
				log.Error ("Exception was thrown in RoomChanged.", ex);
			}
		}

		public event EventHandler Disconnected;
		protected virtual void OnDisconnected(EventArgs args)
		{
			var handler = Disconnected;
			if (handler != null)
				handler (this, args);
		}

		public Client ()
		{
			Id = Interlocked.Increment(ref nextId);
		}

		public void Dispose ()
		{

		}

		public void Close()
		{
			var cli = MerlionClient;
			if (cli != null) {
				cli.Close ();
			}
		}

		internal void InitializeClient(MerlionClient client, Room room)
		{
			lock (sync) {
				if (this.MerlionClient != null) {
					throw new InvalidOperationException ();
				}
				this.MerlionClient = client;
				this.Room = room;
				client.Closed += HandleClosed;
				client.Received += HandleReceived;
			}
			room.Strand.Dispatch (() => {
				room.InternalAddClient(this);
			});
		}

		void HandleReceived (object sender, ReceiveEventArgs e)
		{
			var r = Room;
			if (r != null)
				r.InternalReceived (this, e.Data);
		}

		async void HandleClosed (object sender, EventArgs e)
		{
			MerlionClient = null;
			try {
				await MoveToRoom(null);
			} catch (Exception ex) {
				log.Error ("Removing client from the room after it being closed has failed.", ex);
			}
			try {
				OnDisconnected(EventArgs.Empty);
			} catch (Exception ex) {
				log.Error ("Exception thrown in Disconnected.", ex);
			}
		}

		public async void Send(byte[] data, int start, int length)
		{
			// FIXME: check bounds safely
			try {
				await MerlionClient.SendAsync (data, start, length);
			} catch (Exception ex) {
				; // just ignore...

				// Even if Send succeeds we cannot guarantee that client can receive the
				// sent packet.
			}
		}

		public void Send(byte[] data)
		{
			Send (data, 0, data.Length);
		}
	}

	[Serializable]
	public class RoomChangedEventArgs: EventArgs
	{
		public Room Room { get; set; }
		public RoomChangedEventArgs(Room room)
		{
			this.Room = room;
		}
	}

	[Serializable]
	public class ClientMoveException: Exception
	{
		public ClientMoveException(Exception ex):
		base("Moving the client to another room failed.", ex)
		{ }
		public ClientMoveException(string message, Exception ex):
		base(message, ex)
		{ }
	}

	[Serializable]
	public class ClientMoveRollbackException: AggregateException
	{
		public ClientMoveRollbackException(Exception ex, Exception ex2):
		base("Moving the client to another room failed, and rolling back has failed too.", ex, ex2)
		{ }
	}
}


text:
import tweepy
import d

consumer_key = d.consumer_key
consumer_secret = d.consumer_secret
access_token = d.access_token
access_token_secret = d.access_token_secret

bot = d.bot
human = d.human
giris = tweepy.OAuthHandler(consumer_key, consumer_secret)
giris.set_access_token(access_token, access_token_secret)
api = tweepy.API(giris)
robot_file = open("robot.txt", "w")

for i in range(len(bot)):
    twitler = api.user_timeline(screen_name = bot[i], count=100)
    for j in range(len(twitler)):
        robot_file.write(twitler[j].text+"\n")