text:
[![Build Status](https://secure.travis-ci.org/markdalgleish/bespoke.js.png)](http://travis-ci.org/markdalgleish/bespoke.js)

# Bespoke.js

### DIY Presentation Micro-Framework

Less than 1KB minified and gzipped, with no dependencies.

Bespoke.js provides the foundation, then gets out of your way so you can focus on uniquely crafting your own personal deck style.

Using keyboard and touch events, Bespoke.js adds classes to your slides, while you provide the CSS transitions.

With its robust plugin system, new functionality can be added to Bespoke.js easily.

## Download

Download the [production version][min] or the [development version][max].

[min]: https://raw.github.com/markdalgleish/bespoke.js/master/dist/bespoke.min.js
[max]: https://raw.github.com/markdalgleish/bespoke.js/master/dist/bespoke.js

Bespoke.js requires a modern browser with [ES5 support](http://kangax.github.com/es5-compat-table/). If supporting old IE is your thing, there's always [es5-shim](https://github.com/kriskowal/es5-shim) and [classList.js](https://github.com/eligrey/classList.js).

## Getting Started

To create a Bespoke.js presentation, follow these 3 simple steps:

 * Create a page with [required slide markup](#markup) and resources
 * Activate your deck via the [JavaScript API](#javascript)
 * Create a custom style sheet using the [Bespoke.js classes](#css)

Need more functionality? [Use an existing plugin](#plugins), or [create a new one](#creating-plugins).

## Basic Usage

### Markup

The tags you use are completely optional. Once a parent element is selected, the child elements become slides.

```html
<link rel="stylesheet" href="path/to/my/theme.css">

<article>
  <section>Slide 1</section>
  <section>Slide 2</section>
  <section>Slide 3</section>
</article>

<script src="bespoke.min.js"></script>
<script src="path/to/my/script.js"></script>
```

### JavaScript

Decks are created by selecting the parent element with the `from(selector)` method, with optional 'horizontal' or 'vertical' event handlers.

##### Horizontal Deck

Uses space bar, horizontal arrows and swipes for navigation.

```js
bespoke.horizontal.from('article');
```

##### Vertical Deck

Uses space bar, vertical arrows and swipes for navigation.

```js
bespoke.vertical.from('article');
```

##### Minimal Deck

*For the absolute purist only.* Minimal decks provide a [simple control API](#control-api) with *zero default event handlers*. Key presses and swipes have no effect, it's up to you to implement your own interactions from scratch.

```js
bespoke.from('article');
```

### CSS

To create your own custom deck styles, Bespoke.js provides the necessary classes to your elements.

    bespoke-parent
    The deck's containing element

    bespoke-slide
    Every slide element

    bespoke-active
    The active slide

    bespoke-inactive
    All inactive slides

    bespoke-before
    All slides before the active slide

    bespoke-before-n
    All slides before the active slive, with n value incrementing

    bespoke-after
    All slides after the active slide

    bespoke-after-n
    All slides after the active slive, with n value incrementing

If you've created an awesome theme you'd like me to share, [let me know](http://twitter.com/markdalgleish).

## Plugins

The following plugins are available for Bespoke.js.

 - [bespoke-vcr](https://github.com/markdalgleish/bespoke-vcr) for recording and playback.
 - [bespoke-bullets](https://github.com/markdalgleish/bespoke-bullets) for animated bullet lists.
 - [bespoke-hash](https://github.com/markdalgleish/bespoke-hash) for hash routing.
 - [bespoke-loop](https://github.com/markdalgleish/bespoke-loop) for looped presentations.

If you'd like your plugin added to this list, [let me know](http://twitter.com/markdalgleish).

## Advanced Usage

### Control API

Programmatically control your presentation, or implement a custom interface when using a [minimal deck](#minimal-deck).

```js
// Next slide
bespoke.next();

// Previous slide
bespoke.prev();

// Go to a specific slide
bespoke.slide(0);
```

### Events

Bespoke.js provides the following events which can be handled with the `on(event, callback)` method.

    activate
    A slide has been activated

    deactivate
    A slide has been deactivated

    next
    The next slide has been requested, even if last slide is active. Return false to cancel event.

    prev
    The previous slide has been requested, even if first slide is active. Return false to cancel event.

    slide
    A specific slide has been requested. Return false to cancel event.

##### Binding Events

Each event is passed an event object containing a reference to the current slide and its index.

```js
bespoke.on('next', function(event) {
  event.slide; // Activated slide
  event.index; // Index of activated slide

  // Prevent default functionality and stop propagation
  return false;
});
```

If you need more information about the presentation, you may need to retain a reference to the individual [deck instance](deck-instances).

*Note: Returning false from a 'next', 'prev' or 'slide' event handler will prevent default functionality and stop the event from propagating to subsequent event handlers. This allows you to intercept the standard navigation events and manage state within individual slides, allowing [plugins](#plugins) for bullet lists, in-slide animations, etc.*

##### Unbinding events

Events handlers can be removed with the `off(event, callback)` method.

*Note: To remove an event handler, you must retain a reference to the original function.*

```js
var myEventHandler = function() {
  // Do something...
};

// Bind event
bespoke.on('activate', myEventHandler);

// Unbind event
bespoke.off('activate', myEventHandler);
```

### Deck Instances

##### Creating Deck Instances

Individual deck instances can be created and controlled separately.

```js
// First deck instance
var one = bespoke.horizontal.from('#deck-one');
one.next();
one.prev();
one.slide(0);

// Second deck instance
var two = bespoke.horizontal.from('#deck-two');
two.next();
two.prev();
two.slide(0);
```

The global `bespoke` API interacts with all deck instances. For example, calling `bespoke.next()` is actually calling `next()` on all decks.

##### Deck Instance Properties

The following properties are available on each instance:

    next()
    Next slide

    prev()
    Previous slide

    slide(index)
    Activate a specific slide by index

    on(event, callback)
    Attach event handlers

    off(event, callback)
    Remove event handlers

    fire(event[, payload])
    Fire custom events. This method is primarily designed for plugin authors.

    parent
    The deck's parent element

    slides
    An array of slide elements

## Creating Plugins

If you need to expand upon the core Bespoke.js feature set, additional functionality can be packaged up as plugins.

If you'd like to learn by example, check out the [list of existing plugins](#plugins).

### Basic Plugins

Plugins are simply functions that are called when presentations are created.

They are passed a [deck instance](#deck-instance-properties) which allows you to interact with the deck's state, bind events and modify its elements.

```js
// Creating the plugin
bespoke.plugins.myPlugin = function(deck) {
  deck.on('activate', function(e) {
    console.log('Activated slide ' + (e.index + 1) + ' of ' + deck.slides.length);
  });
};
```

The plugin can now be provided to the second parameter of the `from(selector[, plugins])` method.

```js
// Using the plugin
bespoke.horizontal.from('article', { myPlugin: true });
```

*Note: If the value provided is `false` instead of `true`, your plugin won't run.*

### Plugins with Options

If your plugin needs some configurability, options can be passed through as the second parameter.

*Note: The 'options' parameter is an empty object if no options are provided.*

```js
// Creating the plugin with options
bespoke.plugins.myPlugin = function(deck, options) {
  options.showTotal = options.showTotal || true;

  deck.on('activate', function(e) {
    console.log('Activated slide ' + (e.index + 1) +
      (options.showTotal ? ' of ' + deck.slides.length : ''));
  });
};

// Using the plugin with options
bespoke.from('article', {
  myPlugin: {
    showTotal: true
  }
});
```

## Questions?

Contact me on GitHub or Twitter: [@markdalgleish](http://twitter.com/markdalgleish)

## License

Copyright 2013, Mark Dalgleish
This content is released under the MIT license
http://markdalgleish.mit-license.org


text:
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render });

function preload() {

    game.load.image('atari', 'assets/sprites/atari130xe.png');

}

var sprite;

function create() {

    game.world.setBounds(0, 0, 1600, 1200);

    game.physics.startSystem(Phaser.Physics.ARCADE);

    sprite = game.make.sprite(500, 200, 'atari');

    game.physics.arcade.enable(sprite);

    game.camera.x = 100;

    game.add.existing(sprite);

    cursors = game.input.keyboard.createCursorKeys();

}

function update() {

    if (cursors.up.isDown)
    {
        game.camera.y -= 4;
    }
    else if (cursors.down.isDown)
    {
        game.camera.y += 4;
    }

    if (cursors.left.isDown)
    {
        game.camera.x -= 4;
    }
    else if (cursors.right.isDown)
    {
        game.camera.x += 4;
    }

}

function render() {
}

redpajama_set_name: RedPajamaGithub


text:
var id: number = 10000;
var name: string = "my name";

var person: { b: string; id: number } = { name, id };  // error
var person1: { name, id };  // error: can't use short-hand property assignment in type position
function foo(name: string, id: number): { id: string, name: number } { return { name, id }; }  // error
function bar(obj: { name: string; id: boolean }) { }
bar({ name, id });  // error

//// [objectLiteralShorthandPropertiesAssignmentError.js]
var id = 10000;
var name = "my name";
var person = {
    name: name,
    id: id
}; // error
var person1 = name, id;
; // error: can't use short-hand property assignment in type position
function foo(name, id) {
    return {
        name: name,
        id: id
    };
} // error
function bar(obj) {
}
bar({
    name: name,
    id: id
}); // error


text:
<!--# 介绍-->
<!--------->

<!--[![npm version](https://badge.fury.io/js/stencil.svg)](https://badge.fury.io/js/stencil)-->
<!--[![Build Status](https://travis-ci.org/lsliangshan/stencil.svg?branch=master)](https://travis-ci.org/lsliangshan/stencil)-->
<!--[![Dependency Status](https://david-dm.org/lsliangshan/stencil.svg)](https://david-dm.org/lsliangshan/stencil)-->

# stencil

> A Vue.js project

## Build Setup

``` bash
# install dependencies
npm install

# serve with hot reload at localhost:8080
npm run dev

# build for production with minification
npm run build

# run unit tests
npm run unit

# run e2e tests
npm run e2e

# run all tests
npm test
```

For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).


text:
class ExtensionIconSet;
class Profile;

namespace extensions {
class Extension;
}

// ExtensionIconSource serves extension icons through network level chrome:
// requests. Icons can be retrieved for any installed extension or app.
//
// The format for requesting an icon is as follows:
//   chrome://extension-icon/<extension_id>/<icon_size>/<match_type>?[options]
//
//   Parameters (<> required, [] optional):
//    <extension_id>  = the id of the extension
//    <icon_size>     = the size of the icon, as the integer value of the
//                      corresponding Extension:Icons enum.
//    <match_type>    = the fallback matching policy, as the integer value of
//                      the corresponding ExtensionIconSet::MatchType enum.
//    [options]       = Optional transformations to apply. Supported options:
//                        grayscale=true to desaturate the image.
//
// Examples:
//   chrome-extension://gbmgkahjioeacddebbnengilkgbkhodg/32/1?grayscale=true
//     (ICON_SMALL, MATCH_BIGGER, grayscale)
//   chrome-extension://gbmgkahjioeacddebbnengilkgbkhodg/128/0
//     (ICON_LARGE, MATCH_EXACTLY)
//
// We attempt to load icons from the following sources in order:
//  1) The icons as listed in the extension / app manifests.
//  2) If a 16px icon was requested, the favicon for extension's launch URL.
//  3) The default extension / application icon if there are still no matches.
//
class ExtensionIconSource : public ChromeURLDataManager::DataSource {
 public:
  explicit ExtensionIconSource(Profile* profile);

  // Gets the URL of the |extension| icon in the given |icon_size|, falling back
  // based on the |match| type. If |grayscale|, the URL will be for the
  // desaturated version of the icon. |exists|, if non-NULL, will be set to true
  // if the icon exists; false if it will lead to a default or not-present
  // image.
  static GURL GetIconURL(const extensions::Extension* extension,
                         int icon_size,
                         ExtensionIconSet::MatchType match,
                         bool grayscale,
                         bool* exists);

  // A public utility function for accessing the bitmap of the image specified
  // by |resource_id|.
  static SkBitmap* LoadImageByResourceId(int resource_id);

  // ChromeURLDataManager::DataSource

  virtual std::string GetMimeType(const std::string&) const OVERRIDE;

  virtual void StartDataRequest(const std::string& path,
                                bool is_incognito,
                                int request_id) OVERRIDE;

 private:
  // Encapsulates the request parameters for |request_id|.
  struct ExtensionIconRequest;

  virtual ~ExtensionIconSource();

  // Returns the bitmap for the default app image.
  const SkBitmap* GetDefaultAppImage();

  // Returns the bitmap for the default extension.
  const SkBitmap* GetDefaultExtensionImage();

  // Performs any remaining transformations (like desaturating the |image|),
  // then returns the |image| to the client and clears up any temporary data
  // associated with the |request_id|.
  void FinalizeImage(const SkBitmap* image, int request_id);

  // Loads the default image for |request_id| and returns to the client.
  void LoadDefaultImage(int request_id);

  // Loads the extension's |icon| for the given |request_id| and returns the
  // image to the client.
  void LoadExtensionImage(const ExtensionResource& icon, int request_id);

  // Loads the favicon image for the app associated with the |request_id|. If
  // the image does not exist, we fall back to the default image.
  void LoadFaviconImage(int request_id);

  // FaviconService callback
  void OnFaviconDataAvailable(
      FaviconService::Handle request_handle,
      const history::FaviconBitmapResult& bitmap_result);

  // ImageLoader callback
  void OnImageLoaded(int request_id, const gfx::Image& image);

  // Called when the extension doesn't have an icon. We fall back to multiple
  // sources, using the following order:
  //  1) The icons as listed in the extension / app manifests.
  //  2) If a 16px icon and the extension has a launch URL, see if Chrome
  //     has a corresponding favicon.
  //  3) If still no matches, load the default extension / application icon.
  void LoadIconFailed(int request_id);

  // Parses and savse an ExtensionIconRequest for the URL |path| for the
  // specified |request_id|.
  bool ParseData(const std::string& path, int request_id);

  // Sends the default response to |request_id|, used for invalid requests.
  void SendDefaultResponse(int request_id);

  // Stores the parameters associated with the |request_id|, making them
  // as an ExtensionIconRequest via GetData.
  void SetData(int request_id,
               const extensions::Extension* extension,
               bool grayscale,
               int size,
               ExtensionIconSet::MatchType match);

  // Returns the ExtensionIconRequest for the given |request_id|.
  ExtensionIconRequest* GetData(int request_id);

  // Removes temporary data associated with |request_id|.
  void ClearData(int request_id);

  Profile* profile_;

  // Maps tracker ids to request ids.
  std::map<int, int> tracker_map_;

  // Maps request_ids to ExtensionIconRequests.
  std::map<int, ExtensionIconRequest*> request_map_;

  scoped_ptr<SkBitmap> default_app_data_;

  scoped_ptr<SkBitmap> default_extension_data_;

  CancelableRequestConsumerT<int, 0> cancelable_consumer_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionIconSource);
};

#endif  // CHROME_BROWSER_UI_WEBUI_EXTENSIONS_EXTENSION_ICON_SOURCE_H_


text:
using std::unique_ptr;

unique_ptr<Params> CreateGameParams(void) {
  unique_ptr<Params> params(new Params());
  params->AddParam("GameName", P_STRING);
  params->AddParam("NumRanks", P_INT);
  params->AddParam("NumSuits", P_INT);
  params->AddParam("StackSize", P_INT);
  params->AddParam("MaxStreet", P_INT);
  params->AddParam("NumHoleCards", P_INT);
  params->AddParam("NumFlopCards", P_INT);
  params->AddParam("Ante", P_INT);
  params->AddParam("SmallBlind", P_INT);
  params->AddParam("FirstToAct", P_STRING);
  params->AddParam("BigBlind", P_INT);
  params->AddParam("NumPlayers", P_INT);
  return params;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class jade.content.onto.BeanOntologyException (JADE v4.3.1 API)</title>
<meta name="date" content="2013-12-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
jade.content.onto.BeanOntologyException

Packages that use BeanOntologyException

Package
Description

jade.content.onto

Uses of BeanOntologyException in jade.content.onto

Methods in jade.content.onto that throw BeanOntologyException

Modifier and Type
Method and Description

void
BeanOntology.add(java.lang.Class clazz)

Adds to the ontology the schema built from the class clazz.

void
BeanOntology.add(java.lang.Class clazz,
   boolean buildHierarchy)

Adds to the ontology the schema built from the class clazz.

void
BeanOntology.add(java.lang.String pkgname)

Adds all the ontological beans (the ones which implement either
 Concept or Predicate) found in the
 specified package.

void
BeanOntology.add(java.lang.String pkgname,
   boolean buildHierarchy)

Adds all the ontological beans (the ones which implement either
 Concept or Predicate) found in the
 specified package.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

These are the official JADE API. For these API backward compatibility is guaranteed accross JADE versions


text:
"use strict";

module.exports = function (grunt) {
	// load all npm grunt tasks
	require("load-grunt-tasks")(grunt);

	// Project configuration.
	grunt.initConfig({
		jshint: {
			all: [
				"Gruntfile.js",
				"tasks/*.js",
				"<%= nodeunit.tests %>"
			],
			options: {
				jshintrc: ".jshintrc",
				reporter: require("jshint-stylish")
			}
		},

		// Before generating any new files, remove any previously-created files.
		clean: {
			tests: ["tmp"]
		},

		// Configuration to be run (and then tested).
		genticsCSS: {
			options: {
				css: [
					"./test/styles/test.css",
					"./test/styles/ie.css"
				],
				project: "emc"
			}
		},

		// Unit tests.
		nodeunit: {
			tests: ["test/*_test.js"]
		}

	});

	// Actually load this plugin's task(s).
	grunt.loadTasks("tasks");

	// Whenever the "test" task is run, first clean the "tmp" dir, then run this
	// plugin's task(s), then test the result.
	grunt.registerTask("test", ["clean", "genticsCSS", "nodeunit"]);

	grunt.registerTask("css", ["genticsCSS"]);

	// By default, lint and run all tests.
	grunt.registerTask("default", ["jshint", "test"]);

	grunt.registerTask("up", ["node-inspector"]);

};


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE section PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
 "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd">
<section id="ja_JP.UTF-8">
<title>Xlib Compose Keys for ja_JP.UTF-8</title>
<para>Applications using Xlib input handling should recognize
 these compose key sequences in locales using the
 ja_JP.UTF-8 compose table.</para>

<para>This compose table includes the non-conflicting entries from: /home/kzv/e51/depends/i686-pc-linux-gnu/share/X11/locale/en_US.UTF-8/Compose.  Those entries are not shown here - see those charts for the included key sequences.</para>
<para><emphasis>This compose table defines no sequences of its own.</emphasis></para>
</section>


text:
package xhsun.gw2app.steve.view.fragment.vault.storage;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.annimon.stream.Stream;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import timber.log.Timber;
import xhsun.gw2app.steve.MainApplication;
import xhsun.gw2app.steve.R;
import xhsun.gw2app.steve.backend.data.model.AccountModel;
import xhsun.gw2app.steve.backend.data.model.dialog.SelectAccountModel;
import xhsun.gw2app.steve.backend.data.model.vault.WardrobeModel;
import xhsun.gw2app.steve.backend.data.wrapper.account.AccountWrapper;
import xhsun.gw2app.steve.backend.data.wrapper.storage.BankWrapper;
import xhsun.gw2app.steve.backend.data.wrapper.storage.MaterialWrapper;
import xhsun.gw2app.steve.backend.data.wrapper.storage.WardrobeWrapper;
import xhsun.gw2app.steve.backend.util.Utility;
import xhsun.gw2app.steve.backend.util.support.dialog.AddAccountListener;
import xhsun.gw2app.steve.backend.util.support.vault.QueryTextCallback;
import xhsun.gw2app.steve.backend.util.support.vault.QueryTextListener;
import xhsun.gw2app.steve.backend.util.support.vault.VaultType;
import xhsun.gw2app.steve.backend.util.support.vault.preference.OnPreferenceChangeListener;
import xhsun.gw2app.steve.backend.util.support.vault.storage.StoragePagerAdapter;
import xhsun.gw2app.steve.backend.util.support.vault.storage.StorageTabFragment;
import xhsun.gw2app.steve.backend.util.support.vault.storage.StorageTabHelper;
import xhsun.gw2app.steve.backend.util.task.CancellableAsyncTask;
import xhsun.gw2app.steve.view.dialog.DialogManager;

import static android.content.Context.MODE_PRIVATE;

/**
 * A simple {@link Fragment} subclass.
 *
 * @author xhsun
 * @since 2017-05-01
 */
public class StorageFragment extends Fragment implements OnPreferenceChangeListener<SelectAccountModel>,
		AddAccountListener, StorageTabHelper, QueryTextListener {
	private String[] titles = new String[]{"Bank", "Material", "Wardrobe"};
	private static final String PREFERENCE_NAME = "storageDisplay";
	private SharedPreferences preferences;
	private List<AccountModel> accounts;
	private List<StorageTabFragment> tabs;
	private InitializeAccounts task;

	@Inject
	AccountWrapper accountWrapper;
	@Inject
	BankWrapper bankWrapper;
	@Inject
	MaterialWrapper materialWrapper;
	@Inject
	WardrobeWrapper wardrobeWrapper;

	private SearchView search;
	@BindView(R.id.storage_tab)
	TabLayout tabLayout;
	@BindView(R.id.storage_viewpager)
	ViewPager viewPager;
	@BindView(R.id.storage_fab)
	FloatingActionButton fab;
	@BindView(R.id.storage_progress)
	ProgressBar progressBar;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	                         Bundle savedInstanceState) {
		((MainApplication) getActivity().getApplication()).getServiceComponent().inject(this);//injection
		View view = inflater.inflate(R.layout.fragment_storage, container, false);
		ButterKnife.bind(this, view);

		Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
		toolbar.setTitle("Storage");
		setHasOptionsMenu(true);

		accounts = new ArrayList<>();

		//load shared preference
		preferences = getActivity().getSharedPreferences(PREFERENCE_NAME, MODE_PRIVATE);

		//init tabs
		setupTabFragments();
		viewPager.setAdapter(new StoragePagerAdapter(getChildFragmentManager(), tabs, titles));
		tabLayout.setupWithViewPager(viewPager);
		tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
			@Override
			public void onTabSelected(TabLayout.Tab tab) {
				//move fab, so that its above bottom bar
				if (tab.getText() != null && tab.getText().equals("Wardrobe")) {
					CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) getFAB().getLayoutParams();
					params.bottomMargin = Utility.getDiP(66, view);
					getFAB().setLayoutParams(params);
				}
			}

			@Override
			public void onTabUnselected(TabLayout.Tab tab) {
				//move fab, so that it at correct location when there isn't a bottom bar
				if (tab.getText() != null && tab.getText().equals("Wardrobe")) {
					CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) getFAB().getLayoutParams();
					params.bottomMargin = Utility.getDiP(16, view);
					getFAB().setLayoutParams(params);
				}
				search.clearFocus();
				search.setIconified(true);
			}

			@Override
			public void onTabReselected(TabLayout.Tab tab) {
				tabs.get(tab.getPosition()).snapToTop();
			}
		});

		fab.setOnClickListener(v -> {
			VaultType type = tabs.get(tabLayout.getSelectedTabPosition()).getType();
			new DialogManager(getFragmentManager())
					.selectAccounts(StorageFragment.this, accounts, type, getPreference(type));
		});

		task = new InitializeAccounts();
		task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		Timber.i("Initialization complete");
		return view;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		menu.clear();//prevent constantly adding stuff to toolbar
		inflater.inflate(R.menu.fragment_search_toolbar, menu);
		setupSearchView(menu);//set up search box
		super.onCreateOptionsMenu(menu, inflater);
		Timber.i("Toolbar setup finished");
	}

	@Override
	public void onPause() {
		super.onPause();
		cancelTask();
	}

	@Override
	public void addAccountCallback(AccountModel account) {
		task = new InitializeAccounts();
		task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	@Override
	public void notifyQueryTest(String query) {
		tabs.get(viewPager.getCurrentItem()).filter(query);
	}

	@Override
	public void notifyPreferenceChange(VaultType type, Set<SelectAccountModel> result) {
		Set<String> pref = new HashSet<>();
		Set<AccountModel> preference = new HashSet<>();
		for (SelectAccountModel r : result) {
			if (r.isSelected()) continue;
			AccountModel temp = new AccountModel(r.getApi());
			preference.add(temp);
			pref.add(temp.getAPI());
		}

		setPreference(type.name(), pref);
		Stream.of(tabs).filter(f -> f.getType() == type).distinct().forEach(r -> r.processChange(preference));
	}

	//update preference in file
	private boolean setPreference(String type, Set<String> value) {
		Timber.i("Set preference for %s to %s", type, value);
		Set<String> temp = preferences.getStringSet(type, null);
		if (temp == null) temp = new HashSet<>();
		if (temp.equals(value)) return false;
		SharedPreferences.Editor editor;
		editor = preferences.edit();
		editor.putStringSet(type, value);
		editor.apply();
		return true;
	}

	@Override
	public Set<String> getPreference(VaultType type) {
		Set<String> result = preferences.getStringSet(type.name(), null);
		return (result == null) ? new HashSet<>() : result;
	}

	@Override
	public List<AccountModel> getData() {
		return accounts;
	}

	@Override
	public FloatingActionButton getFAB() {
		return fab;
	}

	@Override
	public ViewPager getViewPager() {
		return viewPager;
	}

	@Override
	public SearchView getSearchView() {
		return search;
	}

	//show content
	private void showContent() {
		progressBar.setVisibility(View.GONE);
		fab.setVisibility(View.VISIBLE);
		viewPager.setVisibility(View.VISIBLE);
	}

	//hide content
	private void hideContent() {
		progressBar.setVisibility(View.VISIBLE);
		fab.setVisibility(View.GONE);
		viewPager.setVisibility(View.GONE);
	}

	private void setupTabFragments() {
		StorageTabFragment fragment;
		tabs = new ArrayList<>();
		fragment = new BankFragment();
		fragment.setHelper(this);
		tabs.add(fragment);
		fragment = new MaterialFragment();
		fragment.setHelper(this);
		tabs.add(fragment);
		fragment = new WardrobeFragment();
		fragment.setHelper(this);
		tabs.add(fragment);
	}

	//setup search with with search hint and listener
	private void setupSearchView(Menu menu) {
		search = (SearchView) menu.findItem(R.id.toolbar_search).getActionView();
		search.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER);
		search.setIconified(true);
		search.setQueryHint("Search Storage");
		search.setOnQueryTextListener(new QueryTextCallback(this));
		Timber.i("SearchView setup finished");
	}

	//cancel task
	private void cancelTask() {
		if (task != null && task.getStatus() != AsyncTask.Status.FINISHED)
			task.cancel(true);
	}

	//get all account info
	private class InitializeAccounts extends CancellableAsyncTask<Void, Void, List<AccountModel>> {

		@Override
		protected void onCancelled() {
			Timber.i("Initialize account info cancelled");
			accountWrapper.setCancelled(true);
			bankWrapper.setCancelled(true);
			materialWrapper.setCancelled(true);
			wardrobeWrapper.setCancelled(true);
			showContent();
		}

		@Override
		protected void onPreExecute() {
			accountWrapper.setCancelled(false);
			bankWrapper.setCancelled(false);
			materialWrapper.setCancelled(false);
			wardrobeWrapper.setCancelled(false);
			hideContent();
		}

		@Override
		protected List<AccountModel> doInBackground(Void... params) {
			Timber.i("Start initialize account infos");
			List<AccountModel> info = accountWrapper.getAll(true);
			List<AccountModel> banks = bankWrapper.getAll();
			List<AccountModel> materials = materialWrapper.getAll();
			List<AccountModel> wardrobes = wardrobeWrapper.getAll();
			Set<String> preferBank = getPreference(VaultType.BANK);
			Set<String> preferMaterial = getPreference(VaultType.MATERIAL);
			Set<String> preferWardrobe = getPreference(VaultType.WARDROBE);
			for (AccountModel a : info) {
				String api = a.getAPI();
				if (banks.contains(a) && !preferBank.contains(api))
					a.setBank(banks.get(banks.indexOf(a)).getBank());

				if (materials.contains(a) && !preferMaterial.contains(api))
					a.setMaterial(materials.get(materials.indexOf(a)).getMaterial());

				if (wardrobes.contains(a) && !preferWardrobe.contains(api)) {
					a.setWardrobe(wardrobes.get(wardrobes.indexOf(a)).getWardrobe());
					Stream.of(a.getWardrobe()).forEach(w -> a.getSearched().add(WardrobeModel.WardrobeType.convert(w.getType())));
				}
			}
			return info;
		}

		@Override
		protected void onPostExecute(List<AccountModel> result) {
			Timber.i("initialized all account info");
			if (isCancelled() || isCancelled) return;
			if (result.size() == 0) {
				new DialogManager((StorageFragment.this.getFragmentManager())).promptAdd(StorageFragment.this);
				return;
			}

			accounts = result;
			showContent();
			//notify current tab
			tabs.get(tabLayout.getSelectedTabPosition()).onDataUpdate();
		}
	}
}


text:
require('./test.gif');
require('./test.jpg');
require('./test.png');
require('./test.svg');


text:
from configparser import SafeConfigParser
import os

config = SafeConfigParser()
config.read(os.path.join(os.path.dirname(__file__), os.pardir, 'alembic.ini'))


text:
using NCmdLiner.SolutionCreator.Library.ViewModels;

namespace NCmdLiner.SolutionCreator.Library.Services
{
    public interface IFileResolver
    {
        void Resolve(string sourceFile, string targetFile);
    }
}


text:
namespace content {

static const char* kFakeOrigin = "http://foo.com";
static const char* kFakeIdentityName1 = "name1";
static const char* kFakeIdentityName2 = "name2";
static const char* kFakeCommonName1 = "cname1";
static const char* kFakeCommonName2 = "cname2";

static void OnRequestCompleted(bool* completed,
                               std::string* out_cert,
                               std::string* out_key,
                               int error,
                               const std::string& certificate,
                               const std::string& private_key) {
  ASSERT_EQ(net::OK, error);
  ASSERT_NE("", certificate);
  ASSERT_NE("", private_key);
  *completed = true;
  *out_cert = certificate;
  *out_key = private_key;
}

class WebRTCIdentityStoreTest : public testing::Test {
 public:
  WebRTCIdentityStoreTest()
      : browser_thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP |
                               TestBrowserThreadBundle::REAL_DB_THREAD),
        pool_owner_(
            new base::SequencedWorkerPoolOwner(3, "WebRTCIdentityStoreTest")),
        webrtc_identity_store_(
            new WebRTCIdentityStore(base::FilePath(), NULL)) {
    webrtc_identity_store_->SetTaskRunnerForTesting(pool_owner_->pool());
  }

  virtual ~WebRTCIdentityStoreTest() {
    pool_owner_->pool()->Shutdown();
  }

  void SetValidityPeriod(base::TimeDelta validity_period) {
    webrtc_identity_store_->SetValidityPeriodForTesting(validity_period);
  }

  void RunUntilIdle() {
    RunAllPendingInMessageLoop(BrowserThread::DB);
    RunAllPendingInMessageLoop(BrowserThread::IO);
    pool_owner_->pool()->FlushForTesting();
    base::RunLoop().RunUntilIdle();
  }

  base::Closure RequestIdentityAndRunUtilIdle(const std::string& origin,
                                              const std::string& identity_name,
                                              const std::string& common_name,
                                              bool* completed,
                                              std::string* certificate,
                                              std::string* private_key) {
    base::Closure cancel_callback = webrtc_identity_store_->RequestIdentity(
        GURL(origin),
        identity_name,
        common_name,
        base::Bind(&OnRequestCompleted, completed, certificate, private_key));
    EXPECT_FALSE(cancel_callback.is_null());
    RunUntilIdle();
    return cancel_callback;
  }

  void Restart(const base::FilePath& path) {
    webrtc_identity_store_ = new WebRTCIdentityStore(path, NULL);
    webrtc_identity_store_->SetTaskRunnerForTesting(pool_owner_->pool());
  }

 protected:
  TestBrowserThreadBundle browser_thread_bundle_;
  scoped_ptr<base::SequencedWorkerPoolOwner> pool_owner_;
  scoped_refptr<WebRTCIdentityStore> webrtc_identity_store_;
};

TEST_F(WebRTCIdentityStoreTest, RequestIdentity) {
  bool completed = false;
  std::string dummy;
  base::Closure cancel_callback =
      RequestIdentityAndRunUtilIdle(kFakeOrigin,
                                    kFakeIdentityName1,
                                    kFakeCommonName1,
                                    &completed,
                                    &dummy,
                                    &dummy);
  EXPECT_TRUE(completed);
}

TEST_F(WebRTCIdentityStoreTest, CancelRequest) {
  bool completed = false;
  std::string dummy;
  base::Closure cancel_callback = webrtc_identity_store_->RequestIdentity(
      GURL(kFakeOrigin),
      kFakeIdentityName1,
      kFakeCommonName1,
      base::Bind(&OnRequestCompleted, &completed, &dummy, &dummy));
  ASSERT_FALSE(cancel_callback.is_null());
  cancel_callback.Run();

  RunUntilIdle();
  EXPECT_FALSE(completed);
}

TEST_F(WebRTCIdentityStoreTest, ConcurrentUniqueRequests) {
  bool completed_1 = false;
  bool completed_2 = false;
  std::string dummy;
  base::Closure cancel_callback_1 = webrtc_identity_store_->RequestIdentity(
      GURL(kFakeOrigin),
      kFakeIdentityName1,
      kFakeCommonName1,
      base::Bind(&OnRequestCompleted, &completed_1, &dummy, &dummy));
  ASSERT_FALSE(cancel_callback_1.is_null());

  base::Closure cancel_callback_2 = webrtc_identity_store_->RequestIdentity(
      GURL(kFakeOrigin),
      kFakeIdentityName2,
      kFakeCommonName1,
      base::Bind(&OnRequestCompleted, &completed_2, &dummy, &dummy));
  ASSERT_FALSE(cancel_callback_2.is_null());

  RunUntilIdle();
  EXPECT_TRUE(completed_1);
  EXPECT_TRUE(completed_2);
}

TEST_F(WebRTCIdentityStoreTest, DifferentCommonNameReturnNewIdentity) {
  bool completed_1 = false;
  bool completed_2 = false;
  std::string cert_1, cert_2, key_1, key_2;

  base::Closure cancel_callback_1 =
      RequestIdentityAndRunUtilIdle(kFakeOrigin,
                                    kFakeIdentityName1,
                                    kFakeCommonName1,
                                    &completed_1,
                                    &cert_1,
                                    &key_1);

  base::Closure cancel_callback_2 =
      RequestIdentityAndRunUtilIdle(kFakeOrigin,
                                    kFakeIdentityName1,
                                    kFakeCommonName2,
                                    &completed_2,
                                    &cert_2,
                                    &key_2);

  EXPECT_TRUE(completed_1);
  EXPECT_TRUE(completed_2);
  EXPECT_NE(cert_1, cert_2);
  EXPECT_NE(key_1, key_2);
}

TEST_F(WebRTCIdentityStoreTest, SerialIdenticalRequests) {
  bool completed_1 = false;
  bool completed_2 = false;
  std::string cert_1, cert_2, key_1, key_2;

  base::Closure cancel_callback_1 =
      RequestIdentityAndRunUtilIdle(kFakeOrigin,
                                    kFakeIdentityName1,
                                    kFakeCommonName1,
                                    &completed_1,
                                    &cert_1,
                                    &key_1);

  base::Closure cancel_callback_2 =
      RequestIdentityAndRunUtilIdle(kFakeOrigin,
                                    kFakeIdentityName1,
                                    kFakeCommonName1,
                                    &completed_2,
                                    &cert_2,
                                    &key_2);

  EXPECT_TRUE(completed_1);
  EXPECT_TRUE(completed_2);
  EXPECT_EQ(cert_1, cert_2);
  EXPECT_EQ(key_1, key_2);
}

TEST_F(WebRTCIdentityStoreTest, ConcurrentIdenticalRequestsJoined) {
  bool completed_1 = false;
  bool completed_2 = false;
  std::string cert_1, cert_2, key_1, key_2;

  base::Closure cancel_callback_1 = webrtc_identity_store_->RequestIdentity(
      GURL(kFakeOrigin),
      kFakeIdentityName1,
      kFakeCommonName1,
      base::Bind(&OnRequestCompleted, &completed_1, &cert_1, &key_1));
  ASSERT_FALSE(cancel_callback_1.is_null());

  base::Closure cancel_callback_2 = webrtc_identity_store_->RequestIdentity(
      GURL(kFakeOrigin),
      kFakeIdentityName1,
      kFakeCommonName1,
      base::Bind(&OnRequestCompleted, &completed_2, &cert_2, &key_2));
  ASSERT_FALSE(cancel_callback_2.is_null());

  RunUntilIdle();
  EXPECT_TRUE(completed_1);
  EXPECT_TRUE(completed_2);
  EXPECT_EQ(cert_1, cert_2);
  EXPECT_EQ(key_1, key_2);
}

TEST_F(WebRTCIdentityStoreTest, CancelOneOfIdenticalRequests) {
  bool completed_1 = false;
  bool completed_2 = false;
  std::string cert_1, cert_2, key_1, key_2;

  base::Closure cancel_callback_1 = webrtc_identity_store_->RequestIdentity(
      GURL(kFakeOrigin),
      kFakeIdentityName1,
      kFakeCommonName1,
      base::Bind(&OnRequestCompleted, &completed_1, &cert_1, &key_1));
  ASSERT_FALSE(cancel_callback_1.is_null());

  base::Closure cancel_callback_2 = webrtc_identity_store_->RequestIdentity(
      GURL(kFakeOrigin),
      kFakeIdentityName1,
      kFakeCommonName1,
      base::Bind(&OnRequestCompleted, &completed_2, &cert_2, &key_2));
  ASSERT_FALSE(cancel_callback_2.is_null());

  cancel_callback_1.Run();

  RunUntilIdle();
  EXPECT_FALSE(completed_1);
  EXPECT_TRUE(completed_2);
}

TEST_F(WebRTCIdentityStoreTest, DeleteDataAndGenerateNewIdentity) {
  bool completed_1 = false;
  bool completed_2 = false;
  std::string cert_1, cert_2, key_1, key_2;

  // Generate the first identity.
  base::Closure cancel_callback_1 =
      RequestIdentityAndRunUtilIdle(kFakeOrigin,
                                    kFakeIdentityName1,
                                    kFakeCommonName1,
                                    &completed_1,
                                    &cert_1,
                                    &key_1);

  // Clear the data and the second request should return a new identity.
  webrtc_identity_store_->DeleteBetween(
      base::Time(), base::Time::Now(), base::Bind(&base::DoNothing));
  RunUntilIdle();

  base::Closure cancel_callback_2 =
      RequestIdentityAndRunUtilIdle(kFakeOrigin,
                                    kFakeIdentityName1,
                                    kFakeCommonName1,
                                    &completed_2,
                                    &cert_2,
                                    &key_2);

  EXPECT_TRUE(completed_1);
  EXPECT_TRUE(completed_2);
  EXPECT_NE(cert_1, cert_2);
  EXPECT_NE(key_1, key_2);
}

TEST_F(WebRTCIdentityStoreTest, ExpiredIdentityDeleted) {
  // The identities will expire immediately after creation.
  SetValidityPeriod(base::TimeDelta::FromMilliseconds(0));

  bool completed_1 = false;
  bool completed_2 = false;
  std::string cert_1, cert_2, key_1, key_2;

  base::Closure cancel_callback_1 =
      RequestIdentityAndRunUtilIdle(kFakeOrigin,
                                    kFakeIdentityName1,
                                    kFakeCommonName1,
                                    &completed_1,
                                    &cert_1,
                                    &key_1);
  EXPECT_TRUE(completed_1);

  // Check that the old identity is not returned.
  base::Closure cancel_callback_2 =
      RequestIdentityAndRunUtilIdle(kFakeOrigin,
                                    kFakeIdentityName1,
                                    kFakeCommonName1,
                                    &completed_2,
                                    &cert_2,
                                    &key_2);
  EXPECT_TRUE(completed_2);
  EXPECT_NE(cert_1, cert_2);
  EXPECT_NE(key_1, key_2);
}

TEST_F(WebRTCIdentityStoreTest, IdentityPersistentAcrossRestart) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  Restart(temp_dir.path());

  bool completed_1 = false;
  bool completed_2 = false;
  std::string cert_1, cert_2, key_1, key_2;

  // Creates an identity.
  base::Closure cancel_callback_1 =
      RequestIdentityAndRunUtilIdle(kFakeOrigin,
                                    kFakeIdentityName1,
                                    kFakeCommonName1,
                                    &completed_1,
                                    &cert_1,
                                    &key_1);
  EXPECT_TRUE(completed_1);

  Restart(temp_dir.path());

  // Check that the same identity is returned after the restart.
  base::Closure cancel_callback_2 =
      RequestIdentityAndRunUtilIdle(kFakeOrigin,
                                    kFakeIdentityName1,
                                    kFakeCommonName1,
                                    &completed_2,
                                    &cert_2,
                                    &key_2);
  EXPECT_TRUE(completed_2);
  EXPECT_EQ(cert_1, cert_2);
  EXPECT_EQ(key_1, key_2);
}

}  // namespace content


text:
import init_path
import numpy as np
from util import logger
import os
from graph_util import structure_mapper
init_path.bypass_frost_warning()

def save_tf_model(sess, model_path, tf_var_list=[]):
    '''
        @brief: save the tensorflow variables into a numpy npy file
    '''
    is_file_valid(model_path, save_file=True)
    logger.info('\tSAVING tensorflow variables')

    # get the tf weights one by one
    output_save_list = dict()
    for var in tf_var_list:
        weights = sess.run(var)
        output_save_list[var.name] = weights
        logger.info('\t\t[Checkpoint] saving tf parameter {}'.format(var.name))

    # save the model
    np.save(model_path, output_save_list)

def save_numpy_model(model_path, numpy_var_list=[]):
    '''
        @brief: save the numpy variables into a numpy npy file
    '''
    is_file_valid(model_path, save_file=True)

    logger.info('\tSAVING numpy variables')

    # get the numpy weights one by one
    output_save_list = dict()
    for key, var in numpy_var_list.items():
        output_save_list[key] = var
        logger.info('\t\t[Checkpoint] saving numpy parameter {}'.format(key))

    # save the model
    np.save(model_path, output_save_list)

def load_tf_model(sess, model_path, tf_var_list=[], ignore_prefix='INVALID',
                  transfer_env='Nothing2Nothing', logstd_option='load',
                  gnn_option_list=None, mlp_raw_transfer=False):
    '''
        @brief: load the tensorflow variables from a numpy npy files
    '''
    is_file_valid(model_path)
    logger.info('\tLOADING tensorflow variables')

    # load the parameters
    output_save_list = np.load(model_path, encoding='latin1').item()
    tf_name_list = [var.name for var in tf_var_list]

    # get the weights one by one
    for name, val in output_save_list.items():
        if name in tf_name_list:
            logger.info('\t\tloading TF pretrained parameters {}'.format(name))
            tf_name_list.remove(name)  # just for sanity check

            # pick up the variable that has the name
            var = [var for var in tf_var_list if var.name == name][0]

            # NOTE: this is important part
            if np.prod(var.get_shape().as_list()) != np.prod(val.shape):
                # if there is an unmatch, then we must be doing a transfer
                # learning
                # from util import fpdb; fpdb = fpdb.fpdb(); fpdb.set_trace()
                if transfer_env == 'Nothing2Nothing' or mlp_raw_transfer == 2:
                    # for the baseline, no one is preloading!
                    logger.warning('Skipping variable: {}'.format(var.name))
                else:
                    # load the policy logstd, happens for the gnn, mlpr and mlpt
                    if 'policy_logstd' in var.name:
                        if 'fix' in logstd_option:
                            single_value = float(logstd_option.split('_')[1])
                            assign_op = var.assign(
                                np.ones(var.get_shape().as_list()) *
                                single_value
                            )
                        else:
                            if '_' in logstd_option:
                                added_constant = float(
                                    logstd_option.split('_')[1]
                                )
                            else:
                                added_constant = 0.0

                            new_value = structure_mapper.map_output(
                                transfer_env,
                                val,
                                added_constant,
                                gnn_option_list
                            )
                            assign_op = var.assign(new_value)

                        sess.run(assign_op)  # or `assign_op.op.run()`
                    elif 'policy_0/w:0' in var.name:
                        new_value = structure_mapper.map_input(
                            transfer_env, val, 0.0, gnn_option_list
                        )
                        assign_op = var.assign(new_value)
                        sess.run(assign_op)  # or `assign_op.op.run()`
                    elif 'policy_output' in var.name:
                        new_value = structure_mapper.map_output(
                            transfer_env, val, 0.0, gnn_option_list
                        )
                        assign_op = var.assign(new_value)
                        sess.run(assign_op)  # or `assign_op.op.run()`
                    else:
                        logger.warning('Skipping variable: {}'.format(var.name))

            else:
                assign_op = var.assign(val)
                sess.run(assign_op)  # or `assign_op.op.run()`
        else:
            logger.warning('\t\t**** Parameters Not Exist **** {}'.format(name))

    if len(tf_name_list) > 0:
        logger.warning(
            'Some parameters are not load from the checkpoint: {}'.format(
                tf_name_list
            )
        )

def load_numpy_model(model_path, numpy_var_list={}):
    '''
        @brief: load numpy variables from npy files. The variables could be
            from baseline or from ob_normalizer
        @output:
            It is worth mentioning that this function only returns the value,
            but won't load the value (while the tf variables will be loaded at
            the same time)
    '''
    is_file_valid(model_path)
    logger.info('LOADING numpy variables')

    output_save_list = np.load(model_path, encoding='latin1').item()
    numpy_name_list = [key for key, val in numpy_var_list.items()]

    # get the weights one by one
    for name, val in output_save_list.items():
        if name in numpy_name_list:
            logger.info(
                '\t\tloading numpy pretrained parameters {}'.format(name))
            numpy_name_list.remove(name)  # just for sanity check
            numpy_var_list[name] = val
        else:
            logger.warning('\t\t**** Parameters Not Exist **** {}'.format(name))

    if len(numpy_name_list) > 0:
        logger.warning(
            'Some parameters are not load from the checkpoint: {}'.format(
                numpy_name_list))
    return numpy_var_list

'''
    @brief:
        The following variables might be a little bit of out-dated
'''

def model_save_from_list(sess, model_path, tf_var_list=[], numpy_var_list={}):
    '''
        @brief:
            if the var list is given, we just save them
    '''
    if not model_path.endswith('.npy'):
        model_path = model_path + '.npy'

    logger.info('saving checkpoint to {}'.format(model_path))
    output_save_list = dict()

    # get the tf weights one by one
    for var in tf_var_list:
        weights = sess.run(var)
        output_save_list[var.name] = weights
        logger.info('[checkpoint] saving tf parameter {}'.format(var.name))

    # get the numpy weights one by one
    for key, var in numpy_var_list.items():
        output_save_list[key] = var
        logger.info('[checkpoint] saving numpy parameter {}'.format(key))

    # save the model
    np.save(model_path, output_save_list)

    return

def model_load_from_list(sess, model_path, tf_var_list=[], numpy_var_list={},
                         target_scope_switch='trpo_agent_policy'):
    '''
        @brief:
            if the var list is given, we just save them
        @input:
            @target_scope_switch:
    '''
    if not model_path.endswith('.npy'):
        model_path = model_path + '.npy'
        logger.warning('[checkpoint] adding the ".npy" to the path name')
    logger.info('[checkpoint] loading checkpoint from {}'.format(model_path))

    output_save_list = np.load(model_path, encoding='latin1').item()
    tf_name_list = [var.name for var in tf_var_list]
    numpy_name_list = [key for key, val in numpy_var_list.items()]

    # get the weights one by one
    for name, val in output_save_list.items():
        name = name.replace('trpo_agent_policy', target_scope_switch)
        if name not in tf_name_list and name not in numpy_var_list:
            logger.info('**** Parameters Not Exist **** {}'.format(name))
            continue
        elif name in tf_name_list:
            logger.info('loading TF pretrained parameters {}'.format(name))
            tf_name_list.remove(name)  # just for sanity check

            # pick up the variable that has the name
            var = [var for var in tf_var_list if var.name == name][0]
            assign_op = var.assign(val)
            sess.run(assign_op)  # or `assign_op.op.run()`
        else:
            logger.info('loading numpy pretrained parameters {}'.format(name))
            numpy_name_list.remove(name)  # just for sanity check

            # pick up the variable that has the name
            numpy_var_list[name] = val

    if len(tf_name_list) or len(numpy_name_list) > 0:
        logger.warning(
            'Some parameters are not load from the checkpoint: {}\n {}'.format(
                tf_name_list, numpy_name_list))
    return numpy_var_list

def is_file_valid(model_path, save_file=False):
    assert model_path.endswith('.npy'), logger.error(
        'Invalid file provided {}'.format(model_path))
    if not save_file:
        assert os.path.exists(model_path), logger.error(
            'file not found: {}'.format(model_path))
    logger.info('[LOAD/SAVE] checkpoint path is {}'.format(model_path))


text:
const s32 GAF_IDVERSION=0x00010100;
const int PIXELS_PER_SQUARE_SIDE = 8;

//3DO
const s32 TranslationXAxisModModel = 1;
const s32 TranslationYAxisModModel = 1;
const s32 TranslationZAxisModModel = -1;

const s32 TranslationXAxisModScript = -1;
const s32 TranslationYAxisModScript = 1;
const s32 TranslationZAxisModScript = 1;

const s32 RotationXAxisMod = 1;
const s32 RotationYAxisMod = 1;
const s32 RotationZAxisMod = -1;

const u32 OBJECT3D_FLAG_HIDE = 1;
const u32 OBJECT3D_FLAG_CACHE = 2;
const u32 OBJECT3D_FLAG_DONT_SHADE = 4;

const s32 MAX_3DO_NAME_LENGTH = 32;

enum
{
    TA_AXIS_X,
    TA_AXIS_Y,
    TA_AXIS_Z,
    TA_AXIS_NUM
};

//FBI
const s32 MAX_UNIT_DETAILS = 128;

enum UnitSide
{
    SIDE_ARM,
    SIDE_CORE,
    SIDE_UNKNOWN
};

enum
{
    UNIT_CATEGORY_ARM=0,
    UNIT_CATEGORY_KBOT,
    UNIT_CATEGORY_LEVEL2,
    UNIT_CATEGORY_CONSTRUCTOR,
    UNIT_CATEGORY_NO_WEAPON,//4
    UNIT_CATEGORY_NOT_AIR,
    UNIT_CATEGORY_NOT_SUB,
    UNIT_CATEGORY_CTRL_B,
    UNIT_CATEGORY_SHIP,//8
    UNIT_CATEGORY_LEVEL1,
    UNIT_CATEGORY_LEVEL3,
    UNIT_CATEGORY_TANK,
    UNIT_CATEGORY_WEAPON,//12
    UNIT_CATEGORY_CTRL_W,
    UNIT_CATEGORY_SPECIAL,
    UNIT_CATEGORY_SONAR,
    UNIT_CATEGORY_CORE,//16
    UNIT_CATEGORY_LEVEL10,
    UNIT_CATEGORY_CTRL_C,
    UNIT_CATEGORY_ENERGY,
    UNIT_CATEGORY_METAL, //20
    UNIT_CATEGORY_PARAL,
    UNIT_CATEGORY_COMMANDER,
    UNIT_CATEGORY_CARRY,
    UNIT_CATEGORY_CTRL_F,//24
    UNIT_CATEGORY_PLANT,
    UNIT_CATEGORY_RAD,
    UNIT_CATEGORY_TORP,
    UNIT_CATEGORY_CTRL_V,//28
    UNIT_CATEGORY_VTOL,
    UNIT_CATEGORY_STRATEGIC,
    UNIT_CATEGORY_DEFENSIVE,//32
    UNIT_CATEGORY_JAM,
    UNIT_CATEGORY_REPAIR_PAD,
    UNIT_CATEGORY_ANTI_SUB,
    UNIT_CATEGORY_STEALTH,//36
    UNIT_CATEGORY_BOMB,
    UNIT_CATEGORY_PHIB,
    UNIT_CATEGORY_UNDERWATER,
    UNIT_CATEGORY_KAMIKAZE//40
};

//HPI
const s32 SAVE_MARKER= 'B' << 0 | 'A' <<8 | 'N' << 16 | 'K' <<24;
const s32 HPI_MARKER= 'H' << 0 | 'A' <<8 | 'P' <<16 | 'I' << 24;
const s32 CHUNK_MARKER = 'S' << 0 | 'Q' <<8 | 'S' <<16 | 'H' << 24;
const s32 CHUNK_SIZE = 65536;

const s32 MAX_HPI_FILE_NAME = 32;

enum Compression_Type
{
    COMPRESSION_NONE=0,
    COMPRESSION_LZ77,
    COMPRESSION_ZLIB
};

//Font

//TAUI
enum TagType
{
    TAG_UI_CONTAINER =0,
    TAG_BUTTON,
    TAG_LISTBOX,//No extra details
    TAG_TEXTFIELD,
    TAG_SCROLLBAR,
    TAG_LABEL,
    TAG_DYNAMIC_IMAGE,
    TAG_LABEL_FONT,
    TAG_IMAGE = 12//No extra details
};

const int TAUI_ATTRIBUTE_SCROLLBAR_HORIZONTAL = 1;
const int TAUI_ATTRIBUTE_SCROLLBAR_VERTICAL = 2;
const int LIST_ITEM_HEIGHT = 16;

//TDF
const int TDF_MAX_STRING_LENGTH  = 64;

//UnitScripts
enum Block
{
    BLOCK_INIT,
    BLOCK_NOT_BLOCKED,
    BLOCK_MOVE,
    BLOCK_TURN,
    BLOCK_SLEEP,
    BLOCK_DONE,
    BLOCK_SCRIPT
};

const int SCRIPT_NAME_STORAGE_SIZE=64;
const int UNIT_SCRIPT_MAX_STACK_SIZE = 128;
const int UNIT_SCRIPT_MAX_LOCAL_VARS = 64;
const int MAX_INSTRUCTIONS_PER_FRAME = 10000;
const int SCRIPT_POOL_SIZE = 64;

enum UnitVariable
{
    UNIT_VAR_ACTIVATION =1,
    UNIT_VAR_STANDING_MOVE_ORDERS,
    UNIT_VAR_STANDING_FIRE_ORDERS,
    UNIT_VAR_HEALTH,
    UNIT_VAR_IN_BUILD_STANCE,
    UNIT_VAR_BUSY,
    UNIT_VAR_PIECE_XZ,
    UNIT_VAR_PIECE_Y,
    UNIT_VAR_UNIT_XZ,
    UNIT_VAR_UNIT_Y,
    UNIT_VAR_UNIT_HEIGHT,
    UNIT_VAR_XZ_ATAN,
    UNIT_VAR_XZ_HYPOT,
    UNIT_VAR_ATAN,
    UNIT_VAR_HYPOT,
    UNIT_VAR_GROUND_HEIGHT,
    UNIT_VAR_BUILD_PERCENT_LEFT,
    UNIT_VAR_YARD_OPEN,
    UNIT_VAR_BUGGER_OFF,
    UNIT_VAR_ARMORED
};

internal const char * UnitVariableNames[]=
{
    "NONE",
    "UNIT_VAR_ACTIVATION",
    "UNIT_VAR_STANDING_MOVE_ORDERS",
    "UNIT_VAR_STANDING_FIRE_ORDERS",
    "UNIT_VAR_HEALTH",
    "UNIT_VAR_IN_BUILD_STANCE",
    "UNIT_VAR_BUSY",
    "UNIT_VAR_PIECE_XZ",
    "UNIT_VAR_PIECE_Y",
    "UNIT_VAR_UNIT_XZ",
    "UNIT_VAR_UNIT_Y",
    "UNIT_VAR_UNIT_HEIGHT",
    "UNIT_VAR_XZ_ATAN",
    "UNIT_VAR_XZ_HYPOT",
    "UNIT_VAR_ATAN",
    "UNIT_VAR_HYPOT",
    "UNIT_VAR_GROUND_HEIGHT",
    "UNIT_VAR_BUILD_PERCENT_LEFT",
    "UNIT_VAR_YARD_OPEN",
    "UNIT_VAR_BUGGER_OFF",
    "UNIT_VAR_ARMORED"};

//TNT
const int TNT_HEADER_ID=0x2000;
const r32 GL_UNIT_PER_MAP_TILE = 6;

////////// Structs ////////
//MMAP STUFF
struct MemoryMappedFile
{
    unsigned char * MMapBuffer;
    u64  FileSize;
    u64  ModifiedTime;
#ifdef __WINDOWS__
    HANDLE MMFile;
    HANDLE File;
#else
    s32 File;
    s32 PAD;
#endif
};

//Textures
struct TexturePosition
{
    int X;
    int Y;
};

struct Texture
{
    char Name[32];
    s32 FrameNumber;
    r32 U,V;
    r32 Width,Height;
    s32 X, Y;
    s32 NumberOfFrames;
};

struct TextureContainer
{
    Texture * Textures;
    int MaximumTextures;
    int NumberOfTextures;
    u8 * FreeSquares;
    s32 TextureWidth, TextureHeight, HeightInSquares, WidthInSquares;
    s32 RequestedHeight, RequestedWidth;
    GLuint Texture;
    TexturePosition FirstFreeTexture;
    s32 PAD;
};

//3DO
struct Position3d
{
    float X,Y,Z;
};

struct Object3d
{
    struct Object3dPrimitive * Primitives;
    char Name[MAX_3DO_NAME_LENGTH];
    Object3d * Children;
    int NumberOfChildren;
    Position3d Position;
    int NumberOfPrimitives;

    int NumberOfVertices;
    GLfloat * Vertices;
    GLuint VertexBuffer;
    int NumTriangles;
    int NumLines;
    GLuint LineBuffer;
    b32 Animates;
    s32 SelectionPrimitive;
    GLuint LineVertexBuffer;
    GLuint TriangleVertexBuffer;
};

struct Object3dPrimitive
{
    Texture * Texture;
    int NumberOfVertices;
    int ColorIndex;
    int * VertexIndexes;
};

struct RotationDetails
{
    float Heading;
    float Speed;
};

struct MovementDetails
{
    float Destination;
    float Speed;
};

struct SpinDetails
{
    float Speed;//NOTE(Christof): Docs on this are unclear, from docs it seems like this is the initial not target speed, I recall that in game stuff spins up to a target speed though (e.g. metal extractor, radar ) - this may need some investigation.
    float Acceleration;//NOTE(Christof): Always positive, i.e. |a|
};

struct Object3dTransformationDetails
{
    Object3dTransformationDetails * Children;
    RotationDetails RotationTarget[TA_AXIS_NUM];
    MovementDetails MovementTarget[TA_AXIS_NUM];
    SpinDetails SpinTarget[TA_AXIS_NUM];

    r32 Rotation[TA_AXIS_NUM];
    r32 Movement[TA_AXIS_NUM];
    r32 Spin[TA_AXIS_NUM];

    int TextureOffset;
    GLuint TextureCoordBuffer;

    u32 Flags;
};

//FBI
struct UnitKeyValue
{
    char * Name, *Value;
};

struct UnitDetails
{
    UnitKeyValue Details[MAX_UNIT_DETAILS];
    int DetailsSize;
    int GetInt(const char * Name);

    float GetFloat(const char * Name);
    char * GetString(const char * Name);
    s64  GetUnitCategories();
    UnitSide GetSide();
    s32 PAD;
};

//HPI
struct HPIFileEntry
{
    int Offset;
    int FileSize;
    Compression_Type Compression;
};

struct HPIDirectoryEntry
{
    struct HPIEntry * Entries;
    s32 NumberOfEntries;
    s32 PAD;
};

struct HPIEntry
{
    char * Name;
    struct HPIFile * ContainedInFile;
    union
    {
	HPIFileEntry File;
	HPIDirectoryEntry Directory;
    };
    b32 IsDirectory;
    s32 PAD;
};

struct HPIFile
{
    MemoryMappedFile MMFile;
    HPIDirectoryEntry Root;
    char Name[MAX_HPI_FILE_NAME];
    s32 DecryptionKey;
    s32 PAD;
};

struct HPIFileCollection
{
    //TODO(Christof): track directory(s?) as well
    HPIFile * Files;
    s32 NumberOfFiles;
    s32 PAD;
};

//Font
struct FNTGlyph
{
    int Width;
    float U;
    float TextureWidth;
};

struct FNTFont
{
    int Height;
    GLuint Texture;
    FNTGlyph Characters[256];
    char Name[64];
};

struct FontContainer
{
    FNTFont Fonts[MAX_TA_FONT_NUMBER];
    s32 NumberOfFonts;
    char FontNames[MAX_TA_FONT_NUMBER][64];
};

struct FontShaderDetails
{
    ShaderProgram * Program;
    GLint ColorLocation, AlphaLocation, PositionLocation, SizeLocation, TextureOffsetLocation;
    s32 PAD;
};

//TAUI

struct TAUIContainer
{
    Texture * Background;//Name is in Panel
    struct TAUIElement * DefaultFocus;
    TAUIElement * Elements;
    s32 NumberOfElements;
    s32 PAD;
};

struct TAUIButton
{
    int StartingFrame;//pulls from status
    int Stages;
    char * Text;// | seperator for multistage buttons, center aligned for simple (single stage) buttons, right aligned otherwise
    b32 Disabled;//pulls from grayedout
    b32 Pressed;
    s32 CurrentStage;
    s32 PAD;
};

struct TAUITextBox
{
    int MaximumCharacters;
};

struct TAUIListBox
{
    char ** ItemStrings;
    s32 NumberOfDisplayableItems, NumberOfItems, DisplayItemIndex;
    s32 SelectedIndex;
};

struct TAUIScrollbar
{
    r32 KnobPosition;
    r32 KnobSize;
    TAUIListBox * ListBox;
    b32 Pressed;
    s32 PAD;
};

struct TAUILabel
{
    char * Text;
    TAUIButton * Link;
};

struct TAUIDynamicImage
{
    b8 DisplaySelectionRectangle;//Puller from hotornot
};

struct TAUILabelFont
{
    FNTFont * Font;//from filename
};

enum TAUIElementName
{
    ELEMENT_NAME_UNKNOWN,
    ELEMENT_NAME_SINGLEPLAYER,
    ELEMENT_NAME_MULTIPLAYER,
    ELEMENT_NAME_DEBUGSTRING,
    ELEMENT_NAME_EXIT,
    ELEMENT_NAME_NEW_CAMPAIGN,
    ELEMENT_NAME_LOAD_GAME,
    ELEMENT_NAME_SKIRMISH,
    ELEMENT_NAME_PREVIOUS_MENU,
    ELEMENT_NAME_OPTIONS,
    ELEMENT_NAME_OK,
    ELEMENT_NAME_CANCEL,
    ELEMENT_NAME_LOAD,

    ELEMENT_NAME_INTRO,
    ELEMENT_NAME_CREDITS,
    ELEMENT_NAME_START,
    ELEMENT_NAME_CAMPAIGN,
    ELEMENT_NAME_CAMPAIGN_KNOB,
    ELEMENT_NAME_MISSIONS_KNOB,
    ELEMENT_NAME_MISSIONS,
    ELEMENT_NAME_SIDE_0,
    ELEMENT_NAME_SIDE_1,
    ELEMENT_NAME_SIDE_NAME,
    ELEMENT_NAME_DIFFICULTY,
    ELEMENT_NAME_ARM,
    ELEMENT_NAME_CORE,

    ELEMENT_NAME_GAMES,
    ELEMENT_NAME_SLIDER,
    ELEMENT_NAME_GAME_NAME,
    ELEMENT_NAME_GAME_TYPE,
    ELEMENT_NAME_MISSION,
    ELEMENT_NAME_TIME,
    ELEMENT_NAME_SIDE,
    ELEMENT_NAME_RADAR,
    ELEMENT_NAME_DIFF,
    ELEMENT_NAME_DELETE,
    ELEMENT_NAME_SAVE,
    ELEMENT_NAME_SKIRMISH_GUI,
    ELEMENT_NAME_HEADER,
    ELEMENT_NAME_TEXT,
    ELEMENT_NAME_SELECT_MAP,
    ELEMENT_NAME_START_LOCATION,
    ELEMENT_NAME_COMMANDER_DEATH,
    ELEMENT_NAME_MAPPING,
    ELEMENT_NAME_MAP_NAME,
    ELEMENT_NAME_LINE_OF_SIGHT,
    ELEMENT_NAME_HELP_TEXT,
    ELEMENT_NAME_SOUND,
    ELEMENT_NAME_SPEEDS,
    ELEMENT_NAME_VISUALS,
    ELEMENT_NAME_MUSIC,
    ELEMENT_NAME_RESTORE,
    ELEMENT_NAME_UNDO,
    ELEMENT_NAME_MAIN_MENU_GUI,
    ELEMENT_NAME_ANY_MISSION,
};

struct TAUIElement
{
    char * Name;
    char * Help;
    TAUIElementName ElementName;
    TagType ElementType;
    int Association,X,Y,Width,Height,ColorFore,ColorBack,TextureNumber,FontNumber;
    int Attributes, CommonAttributes;

    b32 Visible;//Pulls from active
    TextureContainer * Textures;
    union
    {
	TAUIButton Button;
	TAUIContainer Container;
	TAUITextBox TextBox;
	TAUIListBox ListBox;
	TAUIScrollbar ScrollBar;
	TAUILabel Label;
	TAUIDynamicImage DynamicImage;
	TAUILabelFont LabelFont;
    } ;
};

//TDF

struct TDFNameValue
{
    char Name[TDF_MAX_STRING_LENGTH];
    char Value[TDF_MAX_STRING_LENGTH];
    TDFNameValue * Next;
};

struct TDFElement
{
    TDFElement * Next;
    TDFElement * Child;
    TDFNameValue * Value;
    char Name[TDF_MAX_STRING_LENGTH];
};

//UnitScripts
struct UnitScript
{
    s32 * ScriptData;
    s32 * FunctionOffsets;
    int NumberOfFunctions;
    int NumberOfPieces;
    char ** FunctionNames;
    char ** PieceNames;
    int ScriptDataSize;

    s32 NumberOfStatics;
    //TODO(Christof): Make this part of the unit struct?
};

struct ScriptState
{
    //TODO(Christof): determine if stack can contain floats? some docs seem to indicate they should?
    s32 StackSize;
    s32 NumberOfLocalVariables;
    s32 * StackData;
    s32 StackStorage[UNIT_SCRIPT_MAX_STACK_SIZE];
    s32 LocalVariables[UNIT_SCRIPT_MAX_STACK_SIZE];//NOTE(Christof): function parameters go at the beginning
    s32 NumberOfStaticVariables;
    s32 ProgramCounter;
    s32 * StaticVariables;
    Block BlockedOn;
    s32 BlockTime;//NOTE(Christof): this is in milliseconds
    s32 BlockedOnPiece;
    s32 BlockedOnAxis;
    s32 SignalMask;
    s32 ScriptNumber;
    ScriptState * ReturnTo;
    struct Object3dTransformationDetails * TransformationDetails;
    s32 NumberOfParameters;
    s32 PAD;
};

struct ScriptStatePool
{
    ScriptState Scripts[SCRIPT_POOL_SIZE];
    int NumberOfScripts;
    s32 StaticVariables[UNIT_SCRIPT_MAX_STACK_SIZE];
    s32 PAD;
};

//Units
enum UnitCommandType
{
    UNIT_COMMAND_MOVE,
    UNIT_COMMAND_PATROL,
    UNIT_COMMAND_ATTACK,
    UNIT_COMMAND_WAIT,
    UNIT_COMMAND_BUILD,
    UNIT_COMMAND_WAIT_ATTACKED
};

struct UnitType
{
    Object3d Model;
    UnitScript Script;
    UnitDetails Details;
};

const s32 MAX_UNIT_TYPES = 1024;
struct UnitTypeList
{
    UnitType Types[MAX_UNIT_TYPES];
    s32 NumberOfUnitTypes;
    s32 PAD;
};

struct PatrolArguments
{
    s32 X,Y,NextOffset;
};

struct MoveArguments
{
    s32 X,Y;
};

const s32 MAX_IDENT=16;
struct AttackArguments
{
    char Name[MAX_IDENT];
};

struct WaitArguments
{
    r32 Seconds;
};

struct Position
{
    r32 X,Y;
};

struct BuildArguments
{
    UnitType * Type;
    union
    {
	Position Position;
	s32 Number;
    };
};

struct WaitAttackedArguments
{
    char Name[MAX_IDENT];
};

struct UnitCommand
{
    union
    {
	PatrolArguments PatrolArguments;
	MoveArguments MoveArguments;
	AttackArguments AttackArguments;
	WaitArguments WaitArguments;
	WaitAttackedArguments WaitAttackedArguments;
	BuildArguments BuildArguments;
    };
    UnitCommandType Command;
    s32 PAD;
};

const s32 MAX_UNIT_COMMANDS = 32;
struct Unit
{
    UnitType * Type;
    ScriptStatePool ScriptPool;
    s32 Side;
    r32 Health, BuildPercent;
    s32 NumberOfCommands;
    r32 X, Y, Z;
    r32 Rotation[3];
    UnitCommand Commands[MAX_UNIT_COMMANDS];
    char Name[MAX_IDENT];
    Object3dTransformationDetails TransformationDetails;
};

//TNT

const s32 MAX_INITIAL_UNITS = 128;
struct TAMap
{
    GLuint MapVertexBuffer, MapTexture, MinimapTexture,VertexBuffer;
    int NumTriangles;
    s32 MinimapHeight,MinimapWidth,Width,Height;
    s32 TidalStrength, SolarStrength, MinWindSpeed, MaxWindSpeed, Gravity, WaterDamage;
    r32 SeaLevel;
    r32 * HeightMap;
};

//Campaigns

struct Mission
{
    char * MissionFile;
    char * MissionName;
};

struct Campaign
{
    char * CampaignName;
    Mission * Missions;
    s32 NumberOfMissions;
    s32 PAD;
};

const s32 MAX_CAMPAIGNS = 16;

struct CampaignList
{
    s32 NumberOfARMCampaigns;
    s32 NumberOfCORECampaigns;
    Campaign ARMCampaigns[MAX_CAMPAIGNS];
    Campaign CORECampaigns[MAX_CAMPAIGNS];
};


text:
VER=0.0

# determine FreeBSD 4.11 or 8.x
REL=`uname -r`
case "$REL" in
    9.*)
	echo "Using FreeBSD 9.x..."
	KERN=9.x
	SCRIPTVER=8.x
	;;
    8.*)
	echo "Using FreeBSD 8.x..."
	KERN=8.x
	SCRIPTVER=8.x
	;;
    4.11-RELEASE)
	echo "Using FreeBSD 4.11..."
	KERN=4.11
	SCRIPTVER=4.11
	;;
    *)
	echo "What version of FreeBSD are you running (4.11/8.x) ?"
	exit 1
esac

if [ "a$1" = "a" ]
then
	echo "usage: ./core-kernel-release.sh 20080228 [clean]"
	echo a version number is required
	exit 1;
else
VER=$1
fi;

if [ "a$2" = "aclean" ]
then
	echo Cleaning up...
	rm -f core-kernel.pkglist.tmp
	rm -f core-kernel.pkglist
	rm -f core-kernel-${KERN}-${VER}.tbz
	exit
fi;

# check for /kernel.new on 4.11
if [ ${KERN} = "4.11" ]
then

if [ -e "/kernel.new" ]
then
  echo Note: proceeding using this kernel...
  ls -al /kernel.new
else
  echo "error: first copy the desired kernel to /kernel.new"
  exit
fi;

fi;

#
# build the packing list
#
echo @comment ORIGIN:net/core-kernel > core-kernel.pkglist
if [ ${KERN} = "4.11" ]
# FreeBSD 4.11
then
echo @cwd / >> core-kernel.pkglist
echo kernel.new >> core-kernel.pkglist
find /modules \! -type d > core-kernel.pkglist.tmp
find /sbin/vimage >> core-kernel.pkglist.tmp
find /usr/share/man/man8/vimage.8.gz >> core-kernel.pkglist.tmp
find /sbin/ngctl >> core-kernel.pkglist.tmp
find /usr/share/man/man8/ngctl.8.gz >> core-kernel.pkglist.tmp
# FreeBSD 8.x
else
echo @cwd /boot >> core-kernel.pkglist
PWDOLD=${PWD}
cd /boot
find kernel \! -type d > ${PWDOLD}/core-kernel.pkglist.tmp
cd ${PWDOLD}
echo @cwd / >> core-kernel.pkglist.tmp
find /usr/sbin/vimage >> core-kernel.pkglist.tmp
find /usr/share/man/man8/vimage.8.gz >> core-kernel.pkglist.tmp
fi;

# remove leading '/' from lines
sed -e "s,^/,," core-kernel.pkglist.tmp >> core-kernel.pkglist

#
# build the package
#
pkg_create -c core-kernel.pkgdesc -d core-kernel.pkgdesclong -f core-kernel.pkglist -i core-kernel-preinstall-${SCRIPTVER}.sh -K core-kernel-deinstall-${SCRIPTVER}.sh -v core-kernel-${KERN}-${VER}.tbz


text:
package com.gooddata.dataload.processes;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

class ProcessIdMatcher extends TypeSafeMatcher<DataloadProcess> {

    private final DataloadProcess process;

    public ProcessIdMatcher(final DataloadProcess process) {
        this.process = process;
    }

    @Override
    public void describeTo(final Description description) {
        description.appendText("Process id " + process.getId());
    }

    public static ProcessIdMatcher hasSameProcessIdAs(final DataloadProcess process) {
        return new ProcessIdMatcher(process);
    }

    @Override
    protected boolean matchesSafely(DataloadProcess item) {
        return process.getId().equals(item.getId());
    }
}


text:
package org.apache.jena.sparql.serializer;

import org.apache.jena.shared.PrefixMapping ;
import org.apache.jena.sparql.core.Prologue ;
import org.apache.jena.sparql.util.NodeToLabelMap ;

/** Information needed to serialize things */

public class SerializationContext
{
    // ?? Interface : WriterContext

    private Prologue prologue ;
    private NodeToLabelMap bNodeMap ;
    private boolean usePlainLiterals = true;

    public SerializationContext(SerializationContext cxt)
    {
        prologue = cxt.prologue ;
        bNodeMap = cxt.bNodeMap ;
    }

    public SerializationContext(Prologue prologue)
    {
        this(prologue, null) ;
    }

    public SerializationContext(PrefixMapping prefixMap)
    {
        this(new Prologue(prefixMap)) ;
    }

    public SerializationContext()
    {
        this((Prologue)null, null) ;
    }

    public SerializationContext(PrefixMapping prefixMap, NodeToLabelMap bMap)
    {
        this(new Prologue(prefixMap), bMap) ;
    }

    public SerializationContext(Prologue prologue, NodeToLabelMap bMap)
    {
        this.prologue = prologue ;
        if ( this.prologue == null )
            this.prologue = new Prologue() ;

        bNodeMap = bMap ;
        if ( bMap == null )
            bNodeMap = new NodeToLabelMap("b", false) ;
    }

    public SerializationContext(boolean usePlainLiterals)
    {
    	this((Prologue)null, null, usePlainLiterals);
    }

    public SerializationContext(PrefixMapping prefixMap, boolean usePlainLiterals)
    {
    	this(new Prologue(prefixMap), null);
    	this.usePlainLiterals = usePlainLiterals;
    }

    public SerializationContext(PrefixMapping prefixMap, NodeToLabelMap bMap, boolean usePlainLiterals)
    {
    	this(new Prologue(prefixMap), bMap);
    	this.usePlainLiterals = usePlainLiterals;
    }

    public SerializationContext(Prologue prologue, boolean usePlainLiterals)
    {
    	this(prologue, null, usePlainLiterals);
    }

    public SerializationContext(Prologue prologue, NodeToLabelMap bMap, boolean usePlainLiterals)
    {
    	this(prologue, bMap);
    	this.usePlainLiterals = usePlainLiterals;
    }

    /**
     * @return Returns the bNodeMap.
     */
    public NodeToLabelMap getBNodeMap()
    {
        return bNodeMap;
    }

    /**
     * @param nodeMap The bNodeMap to set.
     */
    public void setBNodeMap(NodeToLabelMap nodeMap)
    {
        bNodeMap = nodeMap;
    }

    /**
     * @return Returns the prefixMap.
     */
    public PrefixMapping getPrefixMapping()
    {
        return prologue.getPrefixMapping();
    }

    /**
     * @param prefixMap The prefixMap to set.
     */
    public void setPrefixMapping(PrefixMapping prefixMap)
    {
        prologue.setPrefixMapping(prefixMap) ;
    }

    /** @param baseIRI Set the base IRI */
    public void setBaseIRI(String baseIRI) { prologue.setBaseURI(baseIRI) ; }

    public String getBaseIRI() { return prologue.getBaseURI() ; }

    public Prologue getPrologue()
    {
        return prologue ;
    }

    /**
     * Gets whether Plain Literal forms should be used for appropriate typed literals (booleans, integers, decimals and doubles)
     */
    public boolean getUsePlainLiterals()
    {
    	return usePlainLiterals;
    }

    /**
     * Sets whether Plain Literal forms should be used for appropriate typed literals (booleans, integers, decimals and doubles)
     */
    public void setUsePlainLiterals(boolean usePlainLiterals)
    {
    	this.usePlainLiterals = usePlainLiterals;
    }
}


text:
package dk.brics.tajs.flowgraph.nodes;

import dk.brics.tajs.flowgraph.Node;
import dk.brics.tajs.flowgraph.NodeVisitor;
import dk.brics.tajs.flowgraph.SourceLocation;

/**
 * Return exception node.
 * <p>
 * Must be the only node in its block.
 */
public class ExceptionalReturnNode extends Node {

	/**
	 * Constructs a new exceptional return node.
	 */
	public ExceptionalReturnNode(SourceLocation location) {
		super(location);
	}

	@Override
	public String toString() {
		return "exceptional-return";
	}

	@Override
	public <Arg> void visitBy(NodeVisitor<Arg> v, Arg a) {
		v.visit(this, a);
	}

	@Override
	public boolean canThrowExceptions() {
		return false;
	}
}


text:
<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines contain the default error messages used by
    | the validator class. Some of these rules have multiple versions such
    | as the size rules. Feel free to tweak each of these messages here.
    |
    */

    'accepted'        => 'Câmpul :attribute trebuie să fie acceptat.',
    'active_url'      => 'Câmpul :attribute nu este un URL valid.',
    'after'           => 'Câmpul :attribute trebuie să fie o dată după :date.',
    'after_or_equal'  => 'Câmpul :attribute trebuie să fie o dată ulterioară sau egală cu :date.',
    'alpha'           => 'Câmpul :attribute poate conține doar litere.',
    'alpha_dash'      => 'Câmpul :attribute poate conține doar litere, numere și cratime.',
    'alpha_num'       => 'Câmpul :attribute poate conține doar litere și numere.',
    'array'           => 'Câmpul :attribute trebuie să fie un array.',
    'before'          => 'Câmpul :attribute trebuie să fie o dată înainte de :date.',
    'before_or_equal' => 'Câmpul :attribute trebuie să fie o dată înainte sau egală cu :date.',
    'between'         => [
        'numeric' => 'Câmpul :attribute trebuie să fie între :min și :max.',
        'file'    => 'Câmpul :attribute trebuie să fie între :min și :max kiloocteți.',
        'string'  => 'Câmpul :attribute trebuie să fie între :min și :max caractere.',
        'array'   => 'Câmpul :attribute trebuie să aibă între :min și :max elemente.',
    ],
    'boolean'        => 'Câmpul :attribute trebuie să fie adevărat sau fals.',
    'confirmed'      => 'Confirmarea :attribute nu se potrivește.',
    'date'           => 'Câmpul :attribute nu este o dată validă.',
    'date_equals'    => 'Aceasta :attribute trebuie să fie o dată egală cu :date.',
    'date_format'    => 'Câmpul :attribute trebuie să fie în formatul :format.',
    'different'      => 'Câmpurile :attribute și :other trebuie să fie diferite.',
    'digits'         => 'Câmpul :attribute trebuie să aibă :digits cifre.',
    'digits_between' => 'Câmpul :attribute trebuie să aibă între :min și :max cifre.',
    'dimensions'     => 'Câmpul :attribute are dimensiuni de imagine nevalide.',
    'distinct'       => 'Câmpul :attribute are o valoare duplicat.',
    'email'          => 'Câmpul :attribute trebuie să fie o adresă de e-mail validă.',
    'ends_with'      => 'Câmpul :attribute trebuie să se încheie cu una din următoarele valori: :values',
    'exists'         => 'Câmpul :attribute selectat nu este valid.',
    'file'           => 'Câmpul :attribute trebuie să fie un fișier.',
    'filled'         => 'Câmpul :attribute trebuie completat.',
    'gt'             => [
        'numeric' => 'Câmpul :attribute trebuie să fie mai mare de :value.',
        'file'    => 'Câmpul :attribute trebuie să fie mai mare de :value kilobyți.',
        'string'  => 'Câmpul :attribute trebuie să fie mai mare de :value caractere.',
        'array'   => 'Câmpul :attribute trebuie să aibă mai multe de :value elemente.',
    ],
    'gte' => [
        'numeric' => 'Câmpul :attribute trebuie să fie mai mare sau egal cu :value.',
        'file'    => 'Câmpul :attribute trebuie să fie mai mare sau egal cu :value kilobyți.',
        'string'  => 'Câmpul :attribute trebuie să fie mai mare sau egal cu :value caractere.',
        'array'   => 'Câmpul :attribute trebuie să aibă :value elemente sau mai multe.',
    ],
    'image'    => 'Câmpul :attribute trebuie să fie o imagine.',
    'in'       => 'Câmpul :attribute selectat nu este valid.',
    'in_array' => 'Câmpul :attribute nu există în :other.',
    'integer'  => 'Câmpul :attribute trebuie să fie un număr întreg.',
    'ip'       => 'Câmpul :attribute trebuie să fie o adresă IP validă.',
    'ipv4'     => 'Câmpul :attribute trebuie să fie o adresă IPv4 validă.',
    'ipv6'     => 'Câmpul :attribute trebuie să fie o adresă IPv6 validă.',
    'json'     => 'Câmpul :attribute trebuie să fie un string JSON valid.',
    'lt'       => [
        'numeric' => 'Câmpul :attribute trebuie să fie mai mic de :value.',
        'file'    => 'Câmpul :attribute trebuie să fie mai mic de :value kilobyți.',
        'string'  => 'Câmpul :attribute trebuie să fie mai mic de :value caractere.',
        'array'   => 'Câmpul :attribute trebuie să aibă mai puțin de :value elemente.',
    ],
    'lte' => [
        'numeric' => 'Câmpul :attribute trebuie să fie mai mic sau egal cu :value.',
        'file'    => 'Câmpul :attribute trebuie să fie mai mic sau egal cu :value kilobyți.',
        'string'  => 'Câmpul :attribute trebuie să fie mai mic sau egal cu :value caractere.',
        'array'   => 'Câmpul :attribute trebuie să aibă :value elemente sau mai puține.',
    ],
    'max' => [
        'numeric' => 'Câmpul :attribute nu poate fi mai mare de :max.',
        'file'    => 'Câmpul :attribute nu poate avea mai mult de :max kiloocteți.',
        'string'  => 'Câmpul :attribute nu poate avea mai mult de :max caractere.',
        'array'   => 'Câmpul :attribute nu poate avea mai mult de :max elemente.',
    ],
    'mimes'     => 'Câmpul :attribute trebuie să fie un fișier de tipul: :values.',
    'mimetypes' => 'Câmpul :attribute trebuie să fie un fișier de tipul: :values.',
    'min'       => [
        'numeric' => 'Câmpul :attribute nu poate fi mai mic de :min.',
        'file'    => 'Câmpul :attribute trebuie să aibă cel puțin :min kiloocteți.',
        'string'  => 'Câmpul :attribute trebuie să aibă cel puțin :min caractere.',
        'array'   => 'Câmpul :attribute trebuie să aibă cel puțin :min elemente.',
    ],
    'not_in'               => 'Câmpul :attribute selectat nu este valid.',
    'not_regex'            => 'Câmpul :attribute nu are un format valid.',
    'numeric'              => 'Câmpul :attribute trebuie să fie un număr.',
    'password'             => 'Parola este greșită.',
    'present'              => 'Câmpul :attribute trebuie să fie prezent.',
    'regex'                => 'Câmpul :attribute nu are un format valid.',
    'required'             => 'Câmpul :attribute este obligatoriu.',
    'required_if'          => 'Câmpul :attribute este necesar când :other este :value.',
    'required_unless'      => 'Câmpul :attribute este necesar, cu excepția cazului :other este in :values.',
    'required_with'        => 'Câmpul :attribute este necesar când există :values.',
    'required_with_all'    => 'Câmpul :attribute este necesar când există :values.',
    'required_without'     => 'Câmpul :attribute este necesar când nu există :values.',
    'required_without_all' => 'Câmpul :attribute este necesar când niciunul(una) dintre :values nu există.',
    'same'                 => 'Câmpul :attribute și :other trebuie să fie identice.',
    'size'                 => [
        'numeric' => 'Câmpul :attribute trebuie să fie :size.',
        'file'    => 'Câmpul :attribute trebuie să aibă :size kiloocteți.',
        'string'  => 'Câmpul :attribute trebuie să aibă :size caractere.',
        'array'   => 'Câmpul :attribute trebuie să aibă :size elemente.',
    ],
    'starts_with' => 'Acesta :attribute trebuie să înceapă cu una din următoarele: :values',
    'string'      => 'Câmpul :attribute trebuie să fie string.',
    'timezone'    => 'Câmpul :attribute trebuie să fie un fus orar valid.',
    'unique'      => 'Câmpul :attribute a fost deja folosit.',
    'uploaded'    => 'Câmpul :attribute nu a reușit încărcarea.',
    'url'         => 'Câmpul :attribute nu este un URL valid.',
    'uuid'        => 'Acesta :attribute trebuie să fie un cod UUID valid.',

    /*
    |--------------------------------------------------------------------------
    | Custom Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | Here you may specify custom validation messages for attributes using the
    | convention "attribute.rule" to name the lines. This makes it quick to
    | specify a specific custom language line for a given attribute rule.
    |
    */

    'custom' => [
        'attribute-name' => [
            'rule-name' => 'custom-message',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Custom Validation Attributes
    |--------------------------------------------------------------------------
    |
    | The following language lines are used to swap attribute place-holders
    | with something more reader friendly such as E-Mail Address instead
    | of "email". This simply helps us make messages a little cleaner.
    |
    */

    'attributes' => [
    ],
];


text:
define([
  '../core',
  '../method',
  '../regex'
], function( Han, $ ) {

var hws = '<<hws>>'

var $hws = $.create( 'h-hws' )
$hws.setAttribute( 'hidden', '' )
$hws.innerHTML = ' '

function sharingSameParent( $a, $b ) {
  return $a && $b && $a.parentNode === $b.parentNode
}

function properlyPlaceHWSBehind( $node, text ) {
  var $elmt = $node
  var text  = text || ''

  if (
    $.isElmt( $node.nextSibling ) ||
    sharingSameParent( $node, $node.nextSibling )
  ) {
    return text + hws
  } else {
    // One of the parental elements of the current text
    // node would definitely have a next sibling, since
    // it is of the first portion and not `isEnd`.
    while ( !$elmt.nextSibling ) {
      $elmt = $elmt.parentNode
    }
    if ( $node !== $elmt ) {
      $elmt.insertAdjacentHTML( 'afterEnd', '<h-hws hidden> </h-hws>' )
    }
  }
  return text
}

function firstStepLabel( portion, mat ) {
  return portion.isEnd && portion.index === 0
    ? mat[1] + hws + mat[2]
    : portion.index === 0
    ? properlyPlaceHWSBehind( portion.node, portion.text )
    : portion.text
}

function real$hwsElmt( portion ) {
  return portion.index === 0
    ? $.clone( $hws )
    : ''
}

var last$hwsIdx

function apostrophe( portion ) {
  var $elmt = portion.node.parentNode

  if ( portion.index === 0 ) {
    last$hwsIdx = portion.endIndexInNode-2
  }

  if (
    $elmt.nodeName.toLowerCase() === 'h-hws' && (
    portion.index === 1 || portion.indexInMatch === last$hwsIdx
  )) {
    $elmt.classList.add( 'quote-inner' )
  }
  return portion.text
}

function curveQuote( portion ) {
  var $elmt = portion.node.parentNode

  if ( $elmt.nodeName.toLowerCase() === 'h-hws' ) {
    $elmt.classList.add( 'quote-outer' )
  }
  return portion.text
}

$.extend( Han, {
  renderHWS: function( context, strict ) {
    // Elements to be filtered according to the
    // HWS rendering mode.
    var AVOID = strict
    ? 'textarea, code, kbd, samp, pre'
    : 'textarea'

    var mode = strict ? 'strict' : 'base'
    var context = context || document
    var finder = Han.find( context )

    finder
    .avoid( AVOID )

    // Basic situations:
    // - 字a => 字<hws/>a
    // - A字 => A<hws/>字
    .replace( Han.TYPESET.hws[ mode ][0], firstStepLabel )
    .replace( Han.TYPESET.hws[ mode ][1], firstStepLabel )

    // Convert text nodes `<hws/>` into real element nodes:
    .replace( new RegExp( '(' + hws + ')+', 'g' ), real$hwsElmt )

    // Deal with:
    // - '<hws/>字<hws/>' => '字'
    // - "<hws/>字<hws/>" => "字"
    .replace( /([\'"])\s(.+?)\s\1/g, apostrophe )

    // Deal with:
    // - <hws/>"字"<hws/>
    // - <hws/>'字'<hws/>
    .replace( /\s['"]/g, curveQuote )
    .replace( /['"]\s/g, curveQuote )
    .normalize()

    // Return the finder instance for future usage
    return finder
  }
})

$.extend( Han.fn, {
  renderHWS: function( strict ) {
    Han.renderHWS( this.context, strict )
    return this
  },

  revertHWS: function() {
    $.tag( 'h-hws', this.context )
    .forEach(function( hws ) {
      $.remove( hws )
    })
    this.HWS = []
    return this
  }
})

return Han
})


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * java mavlink generator tool. It should not be modified by hand.
 */

// MESSAGE GLOBAL_VISION_POSITION_ESTIMATE PACKING
package com.MAVLink.packer\common;
import com.MAVLink.MAVLinkPacket;
import com.MAVLink.Messages.MAVLinkMessage;
import com.MAVLink.Messages.MAVLinkPayload;

/**
*
*/
public class msg_global_vision_position_estimate extends MAVLinkMessage{

    public static final int MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE = 101;
    public static final int MAVLINK_MSG_LENGTH = 32;
    private static final long serialVersionUID = MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE;

    /**
    * Timestamp (microseconds, synced to UNIX time or since system boot)
    */
    public long usec;

    /**
    * Global X position
    */
    public float x;

    /**
    * Global Y position
    */
    public float y;

    /**
    * Global Z position
    */
    public float z;

    /**
    * Roll angle in rad
    */
    public float roll;

    /**
    * Pitch angle in rad
    */
    public float pitch;

    /**
    * Yaw angle in rad
    */
    public float yaw;

    /**
    * Generates the payload for a mavlink message for a message of this type
    * @return
    */
    public MAVLinkPacket pack(){
        MAVLinkPacket packet = new MAVLinkPacket();
        packet.len = MAVLINK_MSG_LENGTH;
        packet.sysid = 255;
        packet.compid = 190;
        packet.msgid = MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE;

        packet.payload.putUnsignedLong(usec);

        packet.payload.putFloat(x);

        packet.payload.putFloat(y);

        packet.payload.putFloat(z);

        packet.payload.putFloat(roll);

        packet.payload.putFloat(pitch);

        packet.payload.putFloat(yaw);

        return packet;
    }

    /**
    * Decode a global_vision_position_estimate message into this class fields
    *
    * @param payload The message to decode
    */
    public void unpack(MAVLinkPayload payload) {
        payload.resetIndex();

        this.usec = payload.getUnsignedLong();

        this.x = payload.getFloat();

        this.y = payload.getFloat();

        this.z = payload.getFloat();

        this.roll = payload.getFloat();

        this.pitch = payload.getFloat();

        this.yaw = payload.getFloat();

    }

    /**
    * Constructor for a new message, just initializes the msgid
    */
    public msg_global_vision_position_estimate(){
        msgid = MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE;
    }

    /**
    * Constructor for a new message, initializes the message with the payload
    * from a mavlink packet
    *
    */
    public msg_global_vision_position_estimate(MAVLinkPacket mavLinkPacket){
        this.sysid = mavLinkPacket.sysid;
        this.compid = mavLinkPacket.compid;
        this.msgid = MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE;
        unpack(mavLinkPacket.payload);
    }

    /**
    * Returns a string with the MSG name and data
    */
    public String toString(){
        return "MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE -"+" usec:"+usec+" x:"+x+" y:"+y+" z:"+z+" roll:"+roll+" pitch:"+pitch+" yaw:"+yaw+"";
    }
}


text:
module Vision
  module Generators
    class ViewsGenerator < Rails::Generators::Base
      source_root File.expand_path("../../templates", __FILE__)
      argument :resource_name, :type => :string
      desc "Creates a vision resource_controller"
      def copy_view_files
        directory 'resource', "app/views/vision/#{resource_name.tableize}"
      end
    end
  end
end


text:
'use strict';
define([
    "rebar"
],
function(
    Rebar
) {
	return Backbone.Rebar.CompositeView.extend({
		render: function(callback){
			this.$el.html(_.template($("#footer-template").html()));
		}
	});
});


text:
<?php
namespace trifs\jsonrpc;

use Yii;
use trifs\jsonrpc\Server\Request\RequestInterface;
use trifs\jsonrpc\Server\Request\Batch;
use trifs\jsonrpc\Server\Request\Notification;
use trifs\jsonrpc\Server\Request\Request;
use trifs\jsonrpc\JSONRPCError;
use yii\base\UnknownClassException;

class Server
{
    const ERROR_PARSE_CODE       = -32700;
    const ERROR_INVALID_REQUEST  = -32600;
    const ERROR_METHOD_NOT_FOUND = -32601;
    const ERROR_INVALID_PARAMS   = -32602;
    const ERROR_INTERNAL_ERROR   = -32603;

    const MESSAGE_ERROR_PARSE_CODE       = 'Parse error';
    const MESSAGE_ERROR_INVALID_REQUEST  = 'Invalid Request';
    const MESSAGE_ERROR_METHOD_NOT_FOUND = 'Method not found';
    const MESSAGE_ERROR_INVALID_PARAMS   = 'Invalid params';
    const MESSAGE_ERROR_INTERNAL_ERROR   = 'Internal error';

    /**
     * Holds JSON input.
     *
     * @var string
     */
    private $input;

    /**
     * Holds callback invoker.
     *
     * @var callable
     */
    private $invoker;

    /**
     * Constructor, sets input and invoker.
     *
     * @param  string   $input
     * @param  callable $invoker
     * @throws \InvalidArgumentException if $input is not a string
     */
    public function __construct($input, $invoker)
    {
        // should assert() be used instead?
        if (false === is_string($input)) {
            throw new \InvalidArgumentException('$input has to be a string.');
        }

        $this->input   = (string)$input;
        $this->invoker = $invoker;
    }

    /**
     * Run and invoke the request.
     *
     * @return string
     */
    public function run()
    {
        $json = json_decode($this->input, true);

        if (empty($json)) {
            $result = $this->getErrorResponse(null, self::ERROR_PARSE_CODE, self::MESSAGE_ERROR_PARSE_CODE);
        } else {
            $request = $this->getRequest($json);

            if ($request->isBatch()) {
                $result = [];
                foreach ($request->getRequests() as $request) {
                    $result[] = $this->invoke($request);
                }
                // remove notifications
                $result = array_values(array_filter($result));
            } else {
                $result = $this->invoke($request);
            }
        }

        if (empty($result)) {
            return null;
        }

        return json_encode($result);
    }

    /**
     * Returns a RequestInterface object.
     *
     * @param  array $json
     * @return RequestInterface
     */
    private function getRequest(array $json)
    {
        // more than one
        if (isset($json[0])) {
            $request = new Batch($json);
        } elseif (false === isset($json['id'])) {
            $request = new Notification($json);
        } else {
            $request = new Request($json);
        }
        return $request;
    }

    /**
     * Returns an error response array.
     *
     * @param  mixed   $id
     * @param  integer $code
     * @param  string  $message
     * @return array
     */
    private function getErrorResponse($id, $code, $message)
    {
        return [
            'jsonrpc' => '2.0',
            'id'      => $id,
            'error'   => [
                'code'    => $code,
                'message' => $message,
            ],
        ];
    }

    /**
     *
     * @param $e \Exception
     * @return exception message
     */
    private function formatErrorMessage($e){
        return "Exception at " . $e->getFile() . "(" . $e->getLine() . ":" . $e->getCode() . ") " . $e->getMessage() ;
    }
    /**
     * Invokes the request.
     *
     * @param  RequestInterface $request
     * @return array
     */
    private function invoke(RequestInterface $request)
    {
        if (defined('YII_DEBUG') && YII_DEBUG == true){
            try {
                $request->validate();

                $result = [
                    'jsonrpc' => '2.0',
                    'id'      => $request->getId(),
                    'result'  => call_user_func(
                        $this->invoker,
                        $request->getMethod(),
                        $request->getParameters()
                    ),
                ];
            } catch (\ReflectionException $e) { // on class not found
                Yii::error($this->formatErrorMessage($e), __METHOD__);
                $result = $this->getErrorResponse(
                    $request->getId(),
                    self::ERROR_METHOD_NOT_FOUND,
                    self::MESSAGE_ERROR_METHOD_NOT_FOUND
                );
            } catch (UnknownClassException $e){
                Yii::error($this->formatErrorMessage($e), __METHOD__);
                $result = $this->getErrorResponse(
                    $request->getId(),
                    self::ERROR_METHOD_NOT_FOUND,
                    self::MESSAGE_ERROR_METHOD_NOT_FOUND
                );
            } catch (JSONRPCError $e) { // A "NORMAL" error message display to user
                $result = $this->getErrorResponse(
                    $request->getId(),
                    $e->getCode(),
                    $e->getMessage()
                );
            } // Don't catch regular PHP regular \Exception in development mode
        } else {
            try {
                $request->validate();

                $result = [
                    'jsonrpc' => '2.0',
                    'id'      => $request->getId(),
                    'result'  => call_user_func(
                        $this->invoker,
                        $request->getMethod(),
                        $request->getParameters()
                    ),
                ];
            } catch (\ReflectionException $e) { // on class not found
                Yii::error($this->formatErrorMessage($e), __METHOD__);
                $result = $this->getErrorResponse(
                    $request->getId(),
                    self::ERROR_METHOD_NOT_FOUND,
                    self::MESSAGE_ERROR_METHOD_NOT_FOUND
                );
            } catch (UnknownClassException $e){
                Yii::error($this->formatErrorMessage($e), __METHOD__);
                $result = $this->getErrorResponse(
                    $request->getId(),
                    self::ERROR_METHOD_NOT_FOUND,
                    self::MESSAGE_ERROR_METHOD_NOT_FOUND
                );
            } catch (JSONRPCError $e) { // A "NORMAL" error message display to user
                $result = $this->getErrorResponse(
                    $request->getId(),
                    $e->getCode(),
                    $e->getMessage()
                );
            } catch (\Exception $e) { // unexpected exception occured at non-dev mode
                Yii::error($this->formatErrorMessage($e), __METHOD__);
                $result = $this->getErrorResponse(
                    $request->getId(),
                    $e->getCode(),
                    $e->getMessage()
                );
            }
        }

        if ($request->isNotification() && empty($result['error'])) {
            $result = null;
        }

        return $result;
    }
}


text:
package de.darwinspl.preferences.resource.dwprofile.mopp;

import org.eclipse.emf.common.util.URI;

/**
 * <p>
 * A basic implementation of the
 * de.darwinspl.preferences.resource.dwprofile.IDwprofileURIMapping interface that
 * can map identifiers to URIs.
 * </p>
 *
 * @param <ReferenceType> unused type parameter which is needed to implement
 * de.darwinspl.preferences.resource.dwprofile.IDwprofileURIMapping.
 */
public class DwprofileURIMapping<ReferenceType> implements de.darwinspl.preferences.resource.dwprofile.IDwprofileURIMapping<ReferenceType> {

	private URI uri;
	private String identifier;
	private String warning;

	public DwprofileURIMapping(String identifier, URI newIdentifier, String warning) {
		super();
		this.uri = newIdentifier;
		this.identifier = identifier;
		this.warning = warning;
	}

	public URI getTargetIdentifier() {
		return uri;
	}

	public String getIdentifier() {
		return identifier;
	}

	public String getWarning() {
		return warning;
	}

}