text:
//
//
// Copyright 2014 Kii Corporation
// http://kii.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//

package com.kii.world;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.kii.cloud.storage.Kii;
import com.kii.cloud.storage.KiiBucket;
import com.kii.cloud.storage.KiiObject;
import com.kii.cloud.storage.callback.KiiQueryCallBack;
import com.kii.cloud.storage.query.KiiQuery;
import com.kii.cloud.storage.query.KiiQueryResult;
import com.kii.cloud.storage.resumabletransfer.AlreadyStartedException;
import com.kii.cloud.storage.resumabletransfer.InvalidHolderException;
import com.kii.cloud.storage.resumabletransfer.KiiDownloader;
import com.kii.cloud.storage.resumabletransfer.KiiUploader;
import com.kii.cloud.storage.resumabletransfer.StateStoreAccessException;
import com.kii.cloud.storage.resumabletransfer.SuspendedException;
import com.kii.cloud.storage.resumabletransfer.TerminatedException;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MainActivity extends Activity {

	private static final int SELECT_PHOTO = 100;

	private static final String TAG = "MainActivity";

	// define some strings used for creating objects
	private static final String BUCKET_NAME = "FileObjects1";

	// define the UI elements
	private ProgressDialog mProgress;

	// define the list
	private ListView mListView;

	// define the list manager
	private ObjectAdapter mListAdapter;

	// define a custom list adapter to handle KiiObjects
	public class ObjectAdapter extends ArrayAdapter<KiiObject> {

		// define some vars
		int resource;
		String response;
		Context context;

		// initialize the adapter
		public ObjectAdapter(Context context, int resource,
				List<KiiObject> items) {
			super(context, resource, items);

			// save the resource for later
			this.resource = resource;
		}

		@Override
		/**
		 * List row layout
		 */
		public View getView(int position, View convertView, ViewGroup parent) {

			// create the view
			LinearLayout rowView;

			// get a reference to the object
			KiiObject kiiObject = getItem(position);

			// if it's not already created
			if (convertView == null) {

				// create the view by inflating the xml resource
				// (res/layout/row.xml)
				rowView = new LinearLayout(getContext());
				String inflater = Context.LAYOUT_INFLATER_SERVICE;
				LayoutInflater vi;
				vi = (LayoutInflater) getContext().getSystemService(inflater);
				vi.inflate(resource, rowView, true);

			}

			// it's already created, reuse it
			else {
				rowView = (LinearLayout) convertView;
			}

			// get the text fields for the row
			TextView titleText = (TextView) rowView.findViewById(R.id.title);
			titleText.setText(kiiObject.getString("imageName"));

			TextView titleCreated = (TextView) rowView
					.findViewById(R.id.dateCreated);
			titleCreated.setText(new Date(kiiObject.getCreatedTime())
					.toString());

			// show scaled down image (thumbnail) instead of the full image in
			// the list view
			ImageView image = (ImageView) rowView.findViewById(R.id.list_image);

			// Download File body if does not exist
			String newFileName = "/storage/sdcard/Pictures/"
					+ kiiObject.getString("imageName");
			File localFile = new File(newFileName);
			if (!localFile.exists()) {
				try {
					downloadFile(kiiObject, newFileName);
				} catch (Exception e) {
					// Log the error
					Log.v(TAG, "Error loading image: " + e.getLocalizedMessage());
				}

			}
			if (localFile.exists()) {
				Bitmap bmp = BitmapFactory.decodeFile(localFile
						.getAbsolutePath());
				// calculate scale ratio
				final int REQUIRED_SIZE = 100;

				// Find the correct scale value. It should be the power of 2.
				int width_tmp = bmp.getWidth(), height_tmp = bmp.getHeight();
				int scale = 1;
				while (true) {
					if (width_tmp / 2 < REQUIRED_SIZE && height_tmp / 2 < REQUIRED_SIZE) {
						break;
					}
					width_tmp /= 2;
					height_tmp /= 2;
					scale *= 2;
				}
				Bitmap thumbnail = Bitmap.createScaledBitmap(bmp, bmp.getWidth()/scale, bmp.getHeight()/scale, false);
				image.setImageBitmap(thumbnail);
			}
			// return the row view
			return rowView;
		}

	}

	/**
	 * the user can add items from the options menu. create that menu here -
	 * from the res/menu/menu.xml file
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	/**
	 * Call addItem from the options menu
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		MainActivity.this.addItem(null);
		return true;
	}

	/**
	 * helper to retrieve the path of an image URI
	 */
	public String getPath(Uri uri) {
		// just some safety built in
		if (uri == null) {
			// TODO perform some logging or show user feedback
			return null;
		}
		// try to retrieve the image from the media store first
		// this will only work for images selected from gallery
		String[] filePathColumn = { MediaStore.Images.Media.DATA };

		Cursor cursor = getContentResolver().query(uri, filePathColumn, null,
				null, null);
		cursor.moveToFirst();

		int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		String filePath = cursor.getString(columnIndex);
		cursor.close();
		return filePath;
	}

	@Override
	/**
	 * image selection is done
	 */
	protected void onActivityResult(int requestCode, int resultCode,
			Intent imageReturnedIntent) {
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

		switch (requestCode) {
		case SELECT_PHOTO:
			if (resultCode == RESULT_OK) {
				Uri selectedImage = imageReturnedIntent.getData();
				// Get reference to the local file
				String selectedImagePath = getPath(selectedImage);
				File imageFile = new File(selectedImagePath);
				String imageName = selectedImagePath
						.substring(selectedImagePath.lastIndexOf("/") + 1);
				createObject(imageFile, imageName);

			}
		}
	}

	/**
	 * "Add Item" button was clicked on the front end
	 *
	 * @param v
	 *            - owner view
	 */
	public void addItem(View v) {
		// First select an image
		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, SELECT_PHOTO);
	}

	/**
	 *
	 * @param imageFile
	 *            - Local image file
	 * @param imageName
	 *            - image name to help identify the image
	 *
	 */
	private void createObject(File imageFile, String imageName) {
		// show a progress dialog to the user
		mProgress = ProgressDialog.show(MainActivity.this, "",
				"Creating Object...", true);

		// Create an object
		KiiObject object = Kii.bucket(BUCKET_NAME).object();

		// Set key-value pairs.
		object.set("imageName", imageName);
		// Upload the file.
		KiiUploader uploader = object.uploader(getApplicationContext(),
				imageFile);
		try {
			uploader.transfer(null);
		} catch (Exception e) {
			// Can be different exceptions - see
			// http://documentation.kii.com/en/guides/android/managing-data/object-storages/uploading/
			Toast.makeText(MainActivity.this, "Error uploading file",
					Toast.LENGTH_SHORT).show();
			Log.d(TAG, "Error uploading file: " + e.getLocalizedMessage());
			mProgress.dismiss();
			return;
		}

		// tell the console and the user it was a success!
		Toast.makeText(MainActivity.this, "Image file saved",
				Toast.LENGTH_SHORT).show();
		Log.d(TAG, "Image file saved: " + imageName);

		// insert this object into the beginning of the list adapter
		MainActivity.this.mListAdapter.insert(object, 0);

		mProgress.dismiss();
	}

	/**
	 * Load all existing objects in this bucket from the server. This is done on
	 * view creation
	 */
	private void loadObjects() {

		// default to an empty adapter
		mListAdapter.clear();

		// show a progress dialog to the user
		mProgress = ProgressDialog.show(MainActivity.this, "", "Loading...",
				true);

		// create an empty KiiQuery (will retrieve all results)
		KiiQuery query = new KiiQuery();

		// define the bucket to query
		KiiBucket bucket = Kii.bucket(BUCKET_NAME);

		// perform the query
		bucket.query(new KiiQueryCallBack<KiiObject>() {

			// catch the callback's "done" feedback
			public void onQueryCompleted(int token,
					KiiQueryResult<KiiObject> result, Exception e) {

				// hide our progress UI element
				mProgress.dismiss();

				// check for an exception (successful request if e==null)
				if (e == null) {

					// add the objects to the adapter (adding to the listview)
					List<KiiObject> fileLists = result.getResult();
					for (KiiObject kiiObject : fileLists) {
						mListAdapter.add(kiiObject);
					}

					// tell the console and the user it was a success!
					Log.v(TAG, "Images loaded: " + result.getResult().size());
					Toast.makeText(MainActivity.this, "Images loaded",
							Toast.LENGTH_SHORT).show();

				}

				// otherwise, something bad happened in the request
				else {

					// tell the console and the user there was a failure
					Log.v(TAG,
							"Error loading objects: " + e.getLocalizedMessage());
					Toast.makeText(
							MainActivity.this,
							"Error loading objects: " + e.getLocalizedMessage(),
							Toast.LENGTH_SHORT).show();
				}
			}
		}, query);

	}

	/**
	 * Delete button was pressed on the front-end
	 *
	 * @param position
	 *            - object position in the list
	 */
	void performDelete(int position) {

		// show a progress dialog to the user
		mProgress = ProgressDialog.show(MainActivity.this, "",
				"Deleting object...", true);

		// get the object to delete based on the position of the row in the list
		final KiiObject kiiObject = MainActivity.this.mListAdapter
				.getItem(position);

		// delete the object including object body
		// Alternatively, object body can be deleted using
		// kiiObject.deleteBody() - this will leave the object itself intact
		//

		try {
			kiiObject.delete();
		} catch (Exception e) {
			// tell the console and the user there was a failure
			Toast.makeText(MainActivity.this, "Error deleting image",
					Toast.LENGTH_SHORT).show();
			Log.d(TAG, "Error deleting image: " + e.getLocalizedMessage());
			mProgress.dismiss();
			return;
		}

		// tell the console and the user it was a success!
		Toast.makeText(MainActivity.this, "Deleted image", Toast.LENGTH_SHORT)
				.show();
		Log.d(TAG, "Deleted image.");

		// remove the object from the list adapter
		MainActivity.this.mListAdapter.remove(kiiObject);
		mProgress.dismiss();
	}

	/**
	 * Called when the user clicks "Full Screen" button on a selected image row
	 *
	 * @param v
	 *            - owner view
	 */
	public void fullScreenImage(View v) {
		// identify row in the list
		final int position = MainActivity.this.mListView
				.getPositionForView((View) v.getParent());

		// get the image
		final KiiObject kiiObject = MainActivity.this.mListAdapter
				.getItem(position);

		// Retrieve the Object from Kii Cloud with an URI.
		Log.e(TAG, "new object " +kiiObject);
		String newFileName = "";
		try {
			// Download File body if does not exist
			newFileName = "/storage/sdcard/Pictures/"
					+ kiiObject.getString("imageName");
			File localFile  = new File(newFileName);
			if (!localFile.exists()) {
				downloadFile(kiiObject, newFileName);
			}
		} catch (Exception e) {
			// tell the console and the user there was a failure
			Toast.makeText(MainActivity.this, "Error downloading file",
					Toast.LENGTH_SHORT).show();
			Log.d(TAG, "Error downloading file: " + e.getLocalizedMessage());
			return;
		}
		// go to the image screen
		Intent myIntent = new Intent(MainActivity.this, ImageActivity.class);
		myIntent.putExtra("filePath", newFileName);
		MainActivity.this.startActivity(myIntent);

	}

	private void downloadFile(final KiiObject kiiObject, String newFileName)
			throws InvalidHolderException, AlreadyStartedException,
			SuspendedException, TerminatedException, StateStoreAccessException {
		// Create a KiiDownloader.
		KiiDownloader downloader = null;
		try {
			downloader = kiiObject.downloader(getApplicationContext(),
					new File(Environment.getExternalStorageDirectory(),
							newFileName));
		} catch (InvalidHolderException e) {
			// Target Object has not been saved or is deleted - log for
			// debugging
			Log.d(TAG,
					"Error when trying to download file: "
							+ e.getLocalizedMessage());
			throw e;
		}
		downloader.transfer(null);
	}

	/**
	 * Called when the user clicks "Delete" button on a selected image row
	 *
	 * @param v
	 *            - owner view
	 */
	public void deleteImage(View v) {

		// identify row in the list
		final int position = MainActivity.this.mListView
				.getPositionForView((View) v.getParent());

		// build the alert
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Would you like to remove this item? ")
				.setCancelable(true)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {

							// if the user chooses 'yes',
							public void onClick(DialogInterface dialog, int id) {

								// perform the delete action on the selected
								// image
								MainActivity.this.performDelete(position);
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {

					// if the user chooses 'no'
					public void onClick(DialogInterface dialog, int id) {

						// simply dismiss the dialog
						dialog.cancel();
					}
				});

		// show the dialog
		builder.create().show();

	}

	@Override
	/**
	 * Screen initialization
	 */
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		// set our view to the xml in res/layout/main.xml
		setContentView(R.layout.main);

		// create an empty list adapter
		mListAdapter = new ObjectAdapter(this, R.layout.row,
				new ArrayList<KiiObject>());

		mListView = (ListView) this.findViewById(R.id.list);

		// set it to our view's list
		mListView.setAdapter(mListAdapter);

		// query for any previously-created objects
		this.loadObjects();

	}

}


text:
/** @author Jia Pan */

#include "fcl/narrowphase/distance_result-inl.h"

namespace fcl
{

template
struct DistanceResult<double>;

} // namespace fcl

redpajama_set_name: RedPajamaGithub


text:
package instructions

import (
	"strings"

	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/api/types/strslice"
	"github.com/moby/buildkit/frontend/dockerfile/parser"
	digest "github.com/opencontainers/go-digest"
	"github.com/pkg/errors"
)

// KeyValuePair represent an arbitrary named value (useful in slice instead of map[string] string to preserve ordering)
type KeyValuePair struct {
	Key   string
	Value string
}

func (kvp *KeyValuePair) String() string {
	return kvp.Key + "=" + kvp.Value
}

// KeyValuePairOptional is the same as KeyValuePair but Value is optional
type KeyValuePairOptional struct {
	Key     string
	Value   *string
	Comment string
}

func (kvpo *KeyValuePairOptional) ValueString() string {
	v := ""
	if kvpo.Value != nil {
		v = *kvpo.Value
	}
	return v
}

// Command is implemented by every command present in a dockerfile
type Command interface {
	Name() string
	Location() []parser.Range
}

// KeyValuePairs is a slice of KeyValuePair
type KeyValuePairs []KeyValuePair

// withNameAndCode is the base of every command in a Dockerfile (String() returns its source code)
type withNameAndCode struct {
	code     string
	name     string
	location []parser.Range
}

func (c *withNameAndCode) String() string {
	return c.code
}

// Name of the command
func (c *withNameAndCode) Name() string {
	return c.name
}

// Location of the command in source
func (c *withNameAndCode) Location() []parser.Range {
	return c.location
}

func newWithNameAndCode(req parseRequest) withNameAndCode {
	return withNameAndCode{code: strings.TrimSpace(req.original), name: req.command, location: req.location}
}

// SingleWordExpander is a provider for variable expansion where 1 word => 1 output
type SingleWordExpander func(word string) (string, error)

// SupportsSingleWordExpansion interface marks a command as supporting variable
// expansion
type SupportsSingleWordExpansion interface {
	Expand(expander SingleWordExpander) error
}

// SupportsSingleWordExpansionRaw interface marks a command as supporting
// variable expansion, while ensuring that quotes are preserved
type SupportsSingleWordExpansionRaw interface {
	ExpandRaw(expander SingleWordExpander) error
}

// PlatformSpecific adds platform checks to a command
type PlatformSpecific interface {
	CheckPlatform(platform string) error
}

func expandKvp(kvp KeyValuePair, expander SingleWordExpander) (KeyValuePair, error) {
	key, err := expander(kvp.Key)
	if err != nil {
		return KeyValuePair{}, err
	}
	value, err := expander(kvp.Value)
	if err != nil {
		return KeyValuePair{}, err
	}
	return KeyValuePair{Key: key, Value: value}, nil
}
func expandKvpsInPlace(kvps KeyValuePairs, expander SingleWordExpander) error {
	for i, kvp := range kvps {
		newKvp, err := expandKvp(kvp, expander)
		if err != nil {
			return err
		}
		kvps[i] = newKvp
	}
	return nil
}

func expandSliceInPlace(values []string, expander SingleWordExpander) error {
	for i, v := range values {
		newValue, err := expander(v)
		if err != nil {
			return err
		}
		values[i] = newValue
	}
	return nil
}

// EnvCommand : ENV key1 value1 [keyN valueN...]
type EnvCommand struct {
	withNameAndCode
	Env KeyValuePairs // kvp slice instead of map to preserve ordering
}

// Expand variables
func (c *EnvCommand) Expand(expander SingleWordExpander) error {
	return expandKvpsInPlace(c.Env, expander)
}

// MaintainerCommand : MAINTAINER maintainer_name
type MaintainerCommand struct {
	withNameAndCode
	Maintainer string
}

// NewLabelCommand creates a new 'LABEL' command
func NewLabelCommand(k string, v string, NoExp bool) *LabelCommand {
	kvp := KeyValuePair{Key: k, Value: v}
	c := "LABEL "
	c += kvp.String()
	nc := withNameAndCode{code: c, name: "label"}
	cmd := &LabelCommand{
		withNameAndCode: nc,
		Labels: KeyValuePairs{
			kvp,
		},
		noExpand: NoExp,
	}
	return cmd
}

// LabelCommand : LABEL some json data describing the image
//
// Sets the Label variable foo to bar,
type LabelCommand struct {
	withNameAndCode
	Labels   KeyValuePairs // kvp slice instead of map to preserve ordering
	noExpand bool
}

// Expand variables
func (c *LabelCommand) Expand(expander SingleWordExpander) error {
	if c.noExpand {
		return nil
	}
	return expandKvpsInPlace(c.Labels, expander)
}

// SourceContent represents an anonymous file object
type SourceContent struct {
	Path   string
	Data   string
	Expand bool
}

// SourcesAndDest represent a collection of sources and a destination
type SourcesAndDest struct {
	DestPath       string
	SourcePaths    []string
	SourceContents []SourceContent
}

func (s *SourcesAndDest) Expand(expander SingleWordExpander) error {
	err := expandSliceInPlace(s.SourcePaths, expander)
	if err != nil {
		return err
	}

	expandedDestPath, err := expander(s.DestPath)
	if err != nil {
		return err
	}
	s.DestPath = expandedDestPath

	return nil
}

func (s *SourcesAndDest) ExpandRaw(expander SingleWordExpander) error {
	for i, content := range s.SourceContents {
		if !content.Expand {
			continue
		}

		expandedData, err := expander(content.Data)
		if err != nil {
			return err
		}
		s.SourceContents[i].Data = expandedData
	}
	return nil
}

// AddCommand : ADD foo /path
//
// Add the file 'foo' to '/path'. Tarball and Remote URL (http, https) handling
// exist here. If you do not wish to have this automatic handling, use COPY.
type AddCommand struct {
	withNameAndCode
	SourcesAndDest
	Chown      string
	Chmod      string
	Link       bool
	KeepGitDir bool // whether to keep .git dir, only meaningful for git sources
	Checksum   digest.Digest
}

// Expand variables
func (c *AddCommand) Expand(expander SingleWordExpander) error {
	expandedChown, err := expander(c.Chown)
	if err != nil {
		return err
	}
	c.Chown = expandedChown

	return c.SourcesAndDest.Expand(expander)
}

// CopyCommand : COPY foo /path
//
// Same as 'ADD' but without the tar and remote url handling.
type CopyCommand struct {
	withNameAndCode
	SourcesAndDest
	From  string
	Chown string
	Chmod string
	Link  bool
}

// Expand variables
func (c *CopyCommand) Expand(expander SingleWordExpander) error {
	expandedChown, err := expander(c.Chown)
	if err != nil {
		return err
	}
	c.Chown = expandedChown

	return c.SourcesAndDest.Expand(expander)
}

// OnbuildCommand : ONBUILD <some other command>
type OnbuildCommand struct {
	withNameAndCode
	Expression string
}

// WorkdirCommand : WORKDIR /tmp
//
// Set the working directory for future RUN/CMD/etc statements.
type WorkdirCommand struct {
	withNameAndCode
	Path string
}

// Expand variables
func (c *WorkdirCommand) Expand(expander SingleWordExpander) error {
	p, err := expander(c.Path)
	if err != nil {
		return err
	}
	c.Path = p
	return nil
}

// ShellInlineFile represents an inline file created for a shell command
type ShellInlineFile struct {
	Name  string
	Data  string
	Chomp bool
}

// ShellDependantCmdLine represents a cmdline optionally prepended with the shell
type ShellDependantCmdLine struct {
	CmdLine      strslice.StrSlice
	Files        []ShellInlineFile
	PrependShell bool
}

// RunCommand : RUN some command yo
//
// run a command and commit the image. Args are automatically prepended with
// the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under
// Windows, in the event there is only one argument The difference in processing:
//
// RUN echo hi          # sh -c echo hi       (Linux)
// RUN echo hi          # cmd /S /C echo hi   (Windows)
// RUN [ "echo", "hi" ] # echo hi
type RunCommand struct {
	withNameAndCode
	withExternalData
	ShellDependantCmdLine
	FlagsUsed []string
}

func (c *RunCommand) Expand(expander SingleWordExpander) error {
	if err := setMountState(c, expander); err != nil {
		return err
	}
	return nil
}

// CmdCommand : CMD foo
//
// Set the default command to run in the container (which may be empty).
// Argument handling is the same as RUN.
type CmdCommand struct {
	withNameAndCode
	ShellDependantCmdLine
}

// HealthCheckCommand : HEALTHCHECK foo
//
// Set the default healthcheck command to run in the container (which may be empty).
// Argument handling is the same as RUN.
type HealthCheckCommand struct {
	withNameAndCode
	Health *container.HealthConfig
}

// EntrypointCommand : ENTRYPOINT /usr/sbin/nginx
//
// Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
// to /usr/sbin/nginx. Uses the default shell if not in JSON format.
//
// Handles command processing similar to CMD and RUN, only req.runConfig.Entrypoint
// is initialized at newBuilder time instead of through argument parsing.
type EntrypointCommand struct {
	withNameAndCode
	ShellDependantCmdLine
}

// ExposeCommand : EXPOSE 6667/tcp 7000/tcp
//
// Expose ports for links and port mappings. This all ends up in
// req.runConfig.ExposedPorts for runconfig.
type ExposeCommand struct {
	withNameAndCode
	Ports []string
}

// UserCommand : USER foo
//
// Set the user to 'foo' for future commands and when running the
// ENTRYPOINT/CMD at container run time.
type UserCommand struct {
	withNameAndCode
	User string
}

// Expand variables
func (c *UserCommand) Expand(expander SingleWordExpander) error {
	p, err := expander(c.User)
	if err != nil {
		return err
	}
	c.User = p
	return nil
}

// VolumeCommand : VOLUME /foo
//
// Expose the volume /foo for use. Will also accept the JSON array form.
type VolumeCommand struct {
	withNameAndCode
	Volumes []string
}

// Expand variables
func (c *VolumeCommand) Expand(expander SingleWordExpander) error {
	return expandSliceInPlace(c.Volumes, expander)
}

// StopSignalCommand : STOPSIGNAL signal
//
// Set the signal that will be used to kill the container.
type StopSignalCommand struct {
	withNameAndCode
	Signal string
}

// Expand variables
func (c *StopSignalCommand) Expand(expander SingleWordExpander) error {
	p, err := expander(c.Signal)
	if err != nil {
		return err
	}
	c.Signal = p
	return nil
}

// CheckPlatform checks that the command is supported in the target platform
func (c *StopSignalCommand) CheckPlatform(platform string) error {
	if platform == "windows" {
		return errors.New("The daemon on this platform does not support the command stopsignal")
	}
	return nil
}

// ArgCommand : ARG name[=value]
//
// Adds the variable foo to the trusted list of variables that can be passed
// to builder using the --build-arg flag for expansion/substitution or passing to 'run'.
// Dockerfile author may optionally set a default value of this variable.
type ArgCommand struct {
	withNameAndCode
	Args []KeyValuePairOptional
}

// Expand variables
func (c *ArgCommand) Expand(expander SingleWordExpander) error {
	for i, v := range c.Args {
		p, err := expander(v.Key)
		if err != nil {
			return err
		}
		v.Key = p
		if v.Value != nil {
			p, err = expander(*v.Value)
			if err != nil {
				return err
			}
			v.Value = &p
		}
		c.Args[i] = v
	}
	return nil
}

// ShellCommand : SHELL powershell -command
//
// Set the non-default shell to use.
type ShellCommand struct {
	withNameAndCode
	Shell strslice.StrSlice
}

// Stage represents a single stage in a multi-stage build
type Stage struct {
	Name       string
	Commands   []Command
	BaseName   string
	SourceCode string
	Platform   string
	Location   []parser.Range
	Comment    string
}

// AddCommand to the stage
func (s *Stage) AddCommand(cmd Command) {
	// todo: validate cmd type
	s.Commands = append(s.Commands, cmd)
}

// IsCurrentStage check if the stage name is the current stage
func IsCurrentStage(s []Stage, name string) bool {
	if len(s) == 0 {
		return false
	}
	return s[len(s)-1].Name == name
}

// CurrentStage return the last stage in a slice
func CurrentStage(s []Stage) (*Stage, error) {
	if len(s) == 0 {
		return nil, errors.New("no build stage in current context")
	}
	return &s[len(s)-1], nil
}

// HasStage looks for the presence of a given stage name
func HasStage(s []Stage, name string) (int, bool) {
	for i, stage := range s {
		// Stage name is case-insensitive by design
		if strings.EqualFold(stage.Name, name) {
			return i, true
		}
	}
	return -1, false
}

type withExternalData struct {
	m map[interface{}]interface{}
}

func (c *withExternalData) getExternalValue(k interface{}) interface{} {
	return c.m[k]
}

func (c *withExternalData) setExternalValue(k, v interface{}) {
	if c.m == nil {
		c.m = map[interface{}]interface{}{}
	}
	c.m[k] = v
}


text:
package com.github.anba.es6draft.runtime.internal;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.Function;

import com.github.anba.es6draft.runtime.objects.atomics.SharedByteBuffer;

/**
 *
Shared Memory and Atomics

 *
The Atomics Object

 *

 *
Runtime semantics
 *

 */
public final class Futex {
    private static final class FutexWaiter {
        private static final ScheduledThreadPoolExecutor INSTANCE;
        static {
            ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new ThreadFactoryImpl());
            executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
            executor.setRemoveOnCancelPolicy(true);
            INSTANCE = executor;
        }

        static ScheduledFuture<?> wait(Runnable command, long timeout, TimeUnit timeUnit) {
            return INSTANCE.schedule(command, timeout, timeUnit);
        }

        private static final class ThreadFactoryImpl implements ThreadFactory {
            private final ThreadGroup group;

            private ThreadFactoryImpl() {
                SecurityManager sec = System.getSecurityManager();
                group = sec != null ? sec.getThreadGroup() : Thread.currentThread().getThreadGroup();
            }

            @Override
            public Thread newThread(Runnable r) {
                Thread newThread = new Thread(group, r, "futex-waiter");
                if (!newThread.isDaemon()) {
                    newThread.setDaemon(true);
                }
                if (newThread.getPriority() != Thread.NORM_PRIORITY) {
                    newThread.setPriority(Thread.NORM_PRIORITY);
                }
                return newThread;
            }
        }
    }

    private static final class Entry {
        private final Runnable onWake;
        private final SharedByteBuffer buffer;
        private final int index;

        Entry(Condition condition, SharedByteBuffer buffer, int index) {
            this.onWake = () -> condition.signal();
            this.buffer = buffer;
            this.index = index;
        }

        Entry(Function<Entry, Runnable> schedule, SharedByteBuffer buffer, int index) {
            this.onWake = schedule.apply(this);
            this.buffer = buffer;
            this.index = index;
        }

        void wake() {
            onWake.run();
        }

        boolean matches(SharedByteBuffer buffer, int index) {
            return this.buffer.sameData(buffer) && this.index == index;
        }
    }

    // FIXME: spec issue - define fairness property for 'futex critical section'?
    private final ReentrantLock lock = new ReentrantLock(true);
    private final LinkedList<Futex.Entry> queue = new LinkedList<>();

    /**
     * Result enumeration for {@link Futex#wait(SharedByteBuffer, int, int, long, TimeUnit)}.
     */
    public enum State {
        OK, NotEqual, Timedout;
    }

    private Futex.State enqueueAndWait(SharedByteBuffer buffer, int index, long timeout, TimeUnit timeUnit)
            throws InterruptedException {
        assert lock.isHeldByCurrentThread();

        Condition condition = lock.newCondition();
        Futex.Entry entry = new Entry(condition, buffer, index);
        queue.add(entry);
        if (condition.await(timeout, timeUnit)) {
            return State.OK;
        }
        queue.remove(entry);
        return State.Timedout;
    }

    private void enqueueAndWait(SharedByteBuffer buffer, int index, long timeout, TimeUnit timeUnit,
            BiConsumer<Futex.State, ? super Throwable> action) throws InterruptedException {
        assert lock.isHeldByCurrentThread();

        queue.add(new Entry(entry -> {
            ScheduledFuture<?> sf = FutexWaiter.wait(() -> {
                lock.lock();
                try {
                    queue.remove(entry);
                } finally {
                    lock.unlock();
                }
                action.accept(State.Timedout, null);
            }, timeout, timeUnit);

            return () -> {
                sf.cancel(false);
                action.accept(State.OK, null);
            };
        }, buffer, index));
    }

    /**
     * Causes the current agent to wait until it is waken or the timeout elapses.
     *
     * @param buffer
     *            the byte buffer
     * @param index
     *            the byte buffer index
     * @param value
     *            the expected byte buffer value
     * @param timeout
     *            the timeout in milli-seconds
     * @param timeUnit
     *            the time unit of the timeout parameter
     * @return the result value
     * @throws InterruptedException
     *             if interrupted while waiting
     */
    public Futex.State wait(SharedByteBuffer buffer, int index, int value, long timeout, TimeUnit timeUnit)
            throws InterruptedException {
        lock.lock();
        try {
            int w = UnsafeHolder.getIntVolatile(buffer.get(), index);
            if (w != value) {
                return State.NotEqual;
            }
            return enqueueAndWait(buffer, index, timeout, timeUnit);
        } finally {
            lock.unlock();
        }
    }

    /**
     * Causes the current agent to wait until it is waken or the timeout elapses.
     *
     * @param buffer
     *            the byte buffer
     * @param index
     *            the byte buffer index
     * @param value
     *            the expected byte buffer value
     * @param timeout
     *            the timeout in milli-seconds
     * @param timeUnit
     *            the time unit of the timeout parameter
     * @return the result value
     * @throws InterruptedException
     *             if interrupted while waiting
     */
    public Futex.State wait(SharedByteBuffer buffer, int index, long value, long timeout, TimeUnit timeUnit)
            throws InterruptedException {
        lock.lock();
        try {
            long w = UnsafeHolder.getLongVolatile(buffer.get(), index);
            if (w != value) {
                return State.NotEqual;
            }
            return enqueueAndWait(buffer, index, timeout, timeUnit);
        } finally {
            lock.unlock();
        }
    }

    /**
     * Causes the current agent to wait asynchronously until it is waken or the timeout elapses.
     *
     * @param buffer
     *            the byte buffer
     * @param index
     *            the byte buffer index
     * @param value
     *            the expected byte buffer value
     * @param timeout
     *            the timeout in milli-seconds
     * @param timeUnit
     *            the time unit of the timeout parameter
     * @param action
     * @return
     * @throws InterruptedException
     *             if interrupted while waiting
     */
    public Futex.State waitAsync(SharedByteBuffer buffer, int index, int value, long timeout, TimeUnit timeUnit,
            BiConsumer<Futex.State, ? super Throwable> action) throws InterruptedException {
        lock.lock();
        try {
            int w = UnsafeHolder.getIntVolatile(buffer.get(), index);
            if (w != value) {
                return State.NotEqual;
            }
            enqueueAndWait(buffer, index, timeout, timeUnit, action);
            return State.OK;
        } finally {
            lock.unlock();
        }
    }

    /**
     * Causes the current agent to wait asynchronously until it is waken or the timeout elapses.
     *
     * @param buffer
     *            the byte buffer
     * @param index
     *            the byte buffer index
     * @param value
     *            the expected byte buffer value
     * @param timeout
     *            the timeout in milli-seconds
     * @param timeUnit
     *            the time unit of the timeout parameter
     * @param action
     * @return
     * @throws InterruptedException
     *             if interrupted while waiting
     */
    public Futex.State waitAsync(SharedByteBuffer buffer, int index, long value, long timeout, TimeUnit timeUnit,
            BiConsumer<Futex.State, ? super Throwable> action) throws InterruptedException {
        lock.lock();
        try {
            long w = UnsafeHolder.getLongVolatile(buffer.get(), index);
            if (w != value) {
                return State.NotEqual;
            }
            enqueueAndWait(buffer, index, timeout, timeUnit, action);
            return State.OK;
        } finally {
            lock.unlock();
        }
    }

    /**
     * Wakes up a number of currently waiting agents.
     *
     * @param buffer
     *            the byte buffer
     * @param index
     *            the byte buffer index
     * @param count
     *            the maximum number of agents to wake
     * @return the actual number of agents awoken
     */
    public int wake(SharedByteBuffer buffer, int index, int count) {
        lock.lock();
        try {
            int n = 0;
            for (Iterator<Futex.Entry> it = queue.iterator(); count > 0 && it.hasNext();) {
                Futex.Entry entry = it.next();
                if (entry.matches(buffer, index)) {
                    it.remove();
                    entry.wake();
                    count -= 1;
                    n += 1;
                }
            }
            return n;
        } finally {
            lock.unlock();
        }
    }
}


text:
This project removes manual steps from the bundle installation process and aims
at shrinking it into a single command.

To do so, it provides two commands to register a bundle into the application's
kernel:

* `wizard:register:bundle` which takes the bundle's fully qualified classname
  (e.g. `Acme\DemoBundle\AcmeDemoBundle`)
* `wizard:register:package` which takes the bundle's composer package name
  (e.g. `acme/demo-bundle`)

See the [usage documentation](03-usage.md) to learn more about them.

**Note**: By using the composer plugin
([gnugat/wizard-plugin](https://github.com/gnugat/wizard-plugin)), the only
command you need to run is `composer require <package>`.

## What's the point?

Bundle installation is currently too tedious: In order to install a bundle
into a Symfony2 application, you need to follow at least the 2 following steps:

1. downloading it
2. registering it

While the first step is achievable by running a command thanks to Composer, the
second one requires a manual edition of the application's kernel.

In the worst case scenario, the following steps can be added:

* creating a bundle (which can extends the installed one)
* creating some classes
* configuring the bundle
* importing its routes

##  Next readings

* [installation](02-installation.md)
* [usage](03-usage.md)
* [tests](04-tests.md)


text:
package com.microsoft.azure.management.dns.implementation;

import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.dns.RecordType;
import com.microsoft.azure.management.dns.TxtRecord;
import com.microsoft.azure.management.dns.TxtRecordSet;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Implementation of TxtRecordSet.
 */
@LangDefinition
class TxtRecordSetImpl
        extends DnsRecordSetImpl
        implements TxtRecordSet {
    TxtRecordSetImpl(final DnsZoneImpl parent, final RecordSetInner innerModel) {
        super(parent, innerModel);
    }

    static TxtRecordSetImpl newRecordSet(final String name, final DnsZoneImpl parent) {
        return new TxtRecordSetImpl(parent,
                new RecordSetInner()
                        .withName(name)
                        .withType(RecordType.TXT.toString())
                        .withTxtRecords(new ArrayList<TxtRecord>()));
    }

    @Override
    public List<TxtRecord> records() {
        if (this.inner().txtRecords() != null) {
            return Collections.unmodifiableList(this.inner().txtRecords());
        }
        return Collections.unmodifiableList(new ArrayList<TxtRecord>());
    }

    @Override
    protected RecordSetInner prepareForUpdate(RecordSetInner resource) {
        if (this.inner().txtRecords() != null && this.inner().txtRecords().size() > 0) {
            if (resource.txtRecords() == null) {
                resource.withTxtRecords(new ArrayList<TxtRecord>());
            }

            resource.txtRecords().addAll(this.inner().txtRecords());
            this.inner().txtRecords().clear();
        }

        if (this.recordSetRemoveInfo.txtRecords().size() > 0) {
            if (resource.txtRecords() != null) {
                for (TxtRecord recordToRemove : this.recordSetRemoveInfo.txtRecords()) {
                    for (TxtRecord record : resource.txtRecords()) {
                        if (record.value().size() != 0 && record.value().get(0).equalsIgnoreCase(recordToRemove.value().get(0))) {
                            resource.txtRecords().remove(record);
                            break;
                        }
                    }
                }
            }
            this.recordSetRemoveInfo.txtRecords().clear();
        }
        return resource;
    }
}


text:
simple_nanoc_blog
=================

Simple nanoc blog site. First version 2014-12-22


text:
#ifndef OSTAP_HISTODUMP_H
#define OSTAP_HISTODUMP_H 1
// ============================================================================
// Include files
// ============================================================================
// STD & STL
// ============================================================================
#include <string>
// ============================================================================
/// forward declarations:
// ============================================================================
class TH1      ;                                                        // ROOT
class TProfile ;                                                        // ROOT
// ============================================================================
/** @file Ostap/HistoDump.h
 *  dump the histogtams
 */
// ============================================================================
namespace Ostap
{
  // ==========================================================================
  namespace Utils
  {
    // ========================================================================
    namespace Histos
    {
      // ======================================================================
      /** dump the text representation of the Profile
       *  @param histo  (INPUT) the histogram
       *  @param stream (OUTUT) the stream
       *  @param width  (INPUT) the maximal column width
       *  @param height (INPUT) the proposed coulmn height
       *  @return the stream
       *  @author Vanya BELYAEV  Ivan.BElyaev@itep.ru
       *  @date 2009-09-19
       */
      std::ostream& histoDump_
      ( const TProfile*           histo           ,
        std::ostream&             stream          ,
        const std::size_t         width   = 80    ,
        const std::size_t         height  = 50    ) ;
      // ====================================================================
      /** dump the text representation of the histogram
       *  @param histo  (INPUT) the histogram
       *  @param width  (INPUT) the maximal column width
       *  @param height (INPUT) the propsoed coulmn height
       *  @return string representation of the histogram
       *  @author Vanya BELYAEV  Ivan.Belyaev@itep.ru
       *  @date 2009-09-19
       */
      std::string   histoDump
      ( const TProfile*           histo          ,
        const std::size_t         width  = 80    ,
        const std::size_t         height = 50    ) ;
      // ====================================================================
      /** dump the text representation of the histogram
       *  @param histo  (INPUT) the histogram
       *  @param stream (OUTUT) the stream
       *  @param width  (INPUT) the maximal column width
       *  @param height (INPUT) the proposed coulmn height
       *  @param errors (INPUT) print/plot errors
       *  @return the stream
       *  @author Vanya BELYAEV  Ivan.BElyaev@itep.ru
       *  @date 2009-09-19
       */
      std::ostream& histoDump_
      ( const TH1*                histo           ,
        std::ostream&             stream          ,
        const std::size_t         width   = 80    ,
        const std::size_t         height  = 50    ,
        const bool                errors  = false ) ;
      // ====================================================================
      /** dump the text representation of the histogram
       *  @param histo  (INPUT) the histogram
       *  @param width  (INPUT) the maximal column width
       *  @param height (INPUT) the propsoed coulmn height
       *  @param errors (INPUT) print/plot errors
       *  @return string representation of the histogram
       *  @author Vanya BELYAEV  Ivan.Belyaev@itep.ru
       *  @date 2009-09-19
       */
      std::string   histoDump
      ( const TH1*                histo          ,
        const std::size_t         width  = 80    ,
        const std::size_t         height = 50    ,
        const bool                errors = false ) ;
      // ======================================================================
    } //                                  end of namespace Ostap::Utils::Histos
    // ========================================================================
  } //                                            end of namespace Ostap::Utils
  // ==========================================================================
} //                                                     end of namespace Ostap
// ============================================================================
//                                                                      The END
// ============================================================================
#endif // OSTAP_HISTODUMP_H
// ============================================================================


text:
<?php

namespace Oro\Bundle\ReminderBundle\Entity;

use Doctrine\Common\Collections\Collection;

use Oro\Bundle\ReminderBundle\Model\ReminderDataInterface;

interface RemindableInterface
{
    /**
     * @return Collection
     */
    public function getReminders();

    /**
     * @param Collection $reminders
     */
    public function setReminders(Collection $reminders);

    /**
     * @return ReminderDataInterface
     */
    public function getReminderData();
}


text:
/**
 * @file        src/client/api/client-api.cpp
 * @author      Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
 * @author      Zofia Abramowska <z.abramowska@samsung.com>
 * @version     1.0
 * @brief       Implementation of external libcynara-client API
 */

#include <new>

#include <common.h>

#include <exceptions/TryCatch.h>
#include <log/log.h>

#include <configuration/Configuration.h>
#include <cynara-client.h>
#include <cynara-error.h>
#include <api/ApiInterface.h>
#include <logic/Logic.h>

struct cynara {
    Cynara::ApiInterface *impl;

    cynara(Cynara::ApiInterface *_impl) : impl(_impl) {
    }
    ~cynara() {
        delete impl;
    }
};

struct cynara_configuration {
    Cynara::Configuration* impl;

    cynara_configuration(Cynara::Configuration *_impl) : impl(_impl) {}

    ~cynara_configuration() {
        delete impl;
    }
};

CYNARA_API
int cynara_configuration_create(cynara_configuration **pp_conf) {
    if (!pp_conf)
        return CYNARA_API_INVALID_PARAM;

    return Cynara::tryCatch([&]() {
        Cynara::ConfigurationUniquePtr ptr(new Cynara::Configuration());
        *pp_conf = new cynara_configuration(ptr.get());
        ptr.release();
        LOGD("Cynara configuration initialized");
        return CYNARA_API_SUCCESS;
    });
}

CYNARA_API
void cynara_configuration_destroy(cynara_configuration *p_conf) {
    delete p_conf;
}

CYNARA_API
int cynara_configuration_set_cache_size(cynara_configuration *p_conf, size_t cache_size) {
    if (!p_conf || !p_conf->impl)
        return CYNARA_API_INVALID_PARAM;

    return Cynara::tryCatch([&]() {
        p_conf->impl->setCacheSize(cache_size);
        return CYNARA_API_SUCCESS;
    });
}

CYNARA_API
int cynara_initialize(cynara **pp_cynara, const cynara_configuration *p_conf)
{
    if (!pp_cynara)
        return CYNARA_API_INVALID_PARAM;

    init_log();

    return Cynara::tryCatch([&]() {
        Cynara::LogicUniquePtr ptr;
        if (p_conf && p_conf->impl) {
            ptr.reset(new Cynara::Logic(*(p_conf->impl)));
        } else {
            ptr.reset(new Cynara::Logic());
        }
        *pp_cynara = new cynara(ptr.get());
        ptr.release();

        LOGD("Cynara client initialized");

        return CYNARA_API_SUCCESS;
    });
}

CYNARA_API
int cynara_finish(cynara *p_cynara)
{
    delete p_cynara;

    return CYNARA_API_SUCCESS;
}

CYNARA_API
int cynara_check(cynara *p_cynara, const char *client, const char *client_session, const char *user,
    const char *privilege)
{
    if(!p_cynara || !p_cynara->impl)
        return CYNARA_API_INVALID_PARAM;
    if(!client || !client_session || !user || !privilege)
        return CYNARA_API_INVALID_PARAM;

    return Cynara::tryCatch([&]() {
        std::string clientStr;
        std::string clientSessionStr;
        std::string userStr;
        std::string privilegeStr;

        try {
            clientStr = client;
            clientSessionStr = client_session;
            userStr = user;
            privilegeStr = privilege;
        } catch (const std::length_error &e) {
            LOGE("%s", e.what());
            return CYNARA_API_INVALID_PARAM;
        }
        return p_cynara->impl->check(clientStr, clientSessionStr, userStr, privilegeStr);
    });
}

CYNARA_API
int cynara_simple_check(cynara *p_cynara, const char *client, const char *client_session,
                        const char *user, const char *privilege) {
    if (!p_cynara || !p_cynara->impl)
        return CYNARA_API_INVALID_PARAM;
    if (!client || !client_session || !user || !privilege)
        return CYNARA_API_INVALID_PARAM;

    return Cynara::tryCatch([&]() {
        std::string clientStr;
        std::string clientSessionStr;
        std::string userStr;
        std::string privilegeStr;

        try {
            clientStr = client;
            clientSessionStr = client_session;
            userStr = user;
            privilegeStr = privilege;
        } catch (const std::length_error &e) {
            LOGE("%s", e.what());
            return CYNARA_API_INVALID_PARAM;
        }
        return p_cynara->impl->simpleCheck(clientStr, clientSessionStr, userStr, privilegeStr);
    });
}


text:
(function(){module.exports = require('./wrapperCommit');

})();


text:
module Azure::ARM::ServerManagement
  module Models
    #
    # A collection of results from a PowerShell command.
    #
    class PowerShellCommandResults

      include MsRestAzure

      # @return [Array<PowerShellCommandResult>]
      attr_accessor :results

      # @return [String]
      attr_accessor :pssession

      # @return [String]
      attr_accessor :command

      # @return [Boolean]
      attr_accessor :completed

      #
      # Mapper for PowerShellCommandResults class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          required: false,
          serialized_name: 'PowerShellCommandResults',
          type: {
            name: 'Composite',
            class_name: 'PowerShellCommandResults',
            model_properties: {
              results: {
                required: false,
                serialized_name: 'results',
                type: {
                  name: 'Sequence',
                  element: {
                      required: false,
                      serialized_name: 'PowerShellCommandResultElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'PowerShellCommandResult'
                      }
                  }
                }
              },
              pssession: {
                required: false,
                serialized_name: 'pssession',
                type: {
                  name: 'String'
                }
              },
              command: {
                required: false,
                serialized_name: 'command',
                type: {
                  name: 'String'
                }
              },
              completed: {
                required: false,
                serialized_name: 'completed',
                type: {
                  name: 'Boolean'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
const fs = require('fs')
const html = fs.readFileSync(__dirname + '/../../../index.html', 'utf8')
const jsdom = require('jsdom-global')()
document.write(html)
let filter = require('../../../js/index').filter
let sorting = require('../../../js/index').sorting
let state = require('../../../js/index').state
const sinon = require('sinon')
const expect = require("chai").expect

describe('state:', () => {

  it('can setData', () => {
    const data = {some: 'some'}

    state.setData(data)

    expect(state.current._data).to.deep.equal(data)
  })

  it('can getData', () => {
    const data = {some: 'some'}
    state.current._data = data

    const result = state.getData()

    expect(result).to.deep.equal(data)
  })

  it('can getDisplayData', () => {
    const expectedData = {some: 'some'}

    const filterMock = sinon.mock(filter)
    filterMock.expects('filterByState').once()

    const sortingMock = sinon.mock(sorting)
    sortingMock.expects('sort').once().returns(expectedData)

    const result = state.getDisplayData()

    expect(result).to.deep.equal(expectedData)

    filterMock.verify()
    filterMock.restore()

    sortingMock.verify()
    sortingMock.restore()
  })

})


text:
package main

import (
	"database/sql"
	//pm "github.com/gnewton/
	"errors"
	pmx "github.com/gnewton/pubmedstruct"
	"log"
)

const P_KW = "insert into keywords (id, owner, major_topic, name) values (?,?,?,?)"

func (kw *Keyword) Save(s *sql.Stmt) {
	//log.Println("Inserting keyword", kw.ID, kw.Owner, kw.MajorTopic, kw.Name)
	_, err := s.Exec(kw.ID, kw.Owner, kw.MajorTopic, kw.Name)
	if err != nil {
		log.Fatal(kw.ID, kw.Owner, kw.MajorTopic, kw.Name)
		log.Fatal(err)
	}
}

func (kw Keyword) MakePreparedStatement(tx *sql.Tx) (*sql.Stmt, error) {
	if tx == nil {
		log.Println(errors.New("Database is nil"))
	}
	return tx.Prepare(P_KW)
}

func ExtractKeywords(owner string, keywords []*pmx.Keyword) []*Keyword {
	newKeywords := make([]*Keyword, len(keywords))

	for i, _ := range keywords {
		keyword := keywords[i]
		newKeywords[i] = findKeyword(owner, keyword)
	}

	return newKeywords
}


text:
<?php

namespace phpManufaktur\Contact\Data\Contact;

use Silex\Application;

class Title
{

    protected $app = null;
    protected static $table_name = null;

    /**
     * Constructor
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
        self::$table_name = FRAMEWORK_TABLE_PREFIX.'contact_title';
    }

    /**
     * Create the TITLE table
     *
     * @throws \Exception
     */
    public function createTable()
    {
        $table = self::$table_name;
        $SQL = <<<EOD
    CREATE TABLE IF NOT EXISTS `$table` (
        `title_id` INT(11) NOT NULL AUTO_INCREMENT,
        `title_identifier` VARCHAR(32) NOT NULL DEFAULT 'NO_TITLE',
        `title_short` VARCHAR(32) NOT NULL DEFAULT '',
        `title_long` VARCHAR(64) NOT NULL DEFAULT '',
        PRIMARY KEY (`title_id`),
        UNIQUE INDEX `title_identifier` (`title_identifier` ASC)
        )
    COMMENT='The person title definition table'
    ENGINE=InnoDB
    AUTO_INCREMENT=1
    DEFAULT CHARSET=utf8
    COLLATE='utf8_general_ci'
EOD;
        try {
            $this->app['db']->query($SQL);
            $this->app['monolog']->addInfo("Created table 'contact_title'", array(__METHOD__, __LINE__));
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }

    /**
     * Drop table - switching check for foreign keys off before executing
     *
     * @throws \Exception
     */
    public function dropTable()
    {
        try {
            $table = self::$table_name;
            $SQL = <<<EOD
    SET foreign_key_checks = 0;
    DROP TABLE IF EXISTS `$table`;
    SET foreign_key_checks = 1;
EOD;
            $this->app['db']->query($SQL);
            $this->app['monolog']->addInfo("Drop table 'contact_tag'", array(__METHOD__, __LINE__));
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }
    /**
     * Initialize the title list with the defaults from /titles.json
     *
     * @throws \Exception
     */
    public function initTitleList()
    {
        try {
            // get the number of titles in the list
            $count = $this->app['db']->fetchColumn("SELECT COUNT(`title_id`) FROM `".self::$table_name."`");
            if ($count < 1) {
                // no entries!
                $json_import = MANUFAKTUR_PATH.'/Contact/Data/Setup/Import/titles.json';
                if (!file_exists($json_import)) {
                    throw new \Exception("Can't read the title definition list: $json_import");
                }
                $titles = $this->app['utils']->readJSON($json_import);
                foreach ($titles as $title) {
                    $this->app['db']->insert(self::$table_name, array(
                        'title_identifier' => $title['identifier'],
                        'title_short' => $this->app['utils']->sanitizeText($title['short']),
                        'title_long' => $this->app['utils']->sanitizeText($title['long'])
                    ));
                }
            }
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }

    /**
     * Return a array with all titles, prepared for usage with TWIG
     *
     * @throws \Exception
     * @return array
     */
    public function getArrayForTwig()
    {
        try {
            $SQL = "SELECT * FROM `".self::$table_name."` ORDER BY `title_short` ASC";
            $titles = $this->app['db']->fetchAll($SQL);
            $result = array();
            foreach ($titles as $title) {
                if ($title['title_identifier'] == 'NO_TITLE') {
                    // skip the NO_TITLE entry
                    continue;
                }
                $result[$title['title_identifier']] = $this->app['utils']->unsanitizeText($title['title_short']);
            }
            return $result;
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }

    /**
     * Select all titles and return a ascending orderd list by identifier
     *
     * @throws \Exception
     * @return Ambigous <multitype:, unknown>
     */
    public function selectAll()
    {
        try {
            $SQL = "SELECT * FROM `".self::$table_name."` ORDER BY `title_identifier` ASC";
            $results = $this->app['db']->fetchAll($SQL);
            $titles = array();
            $level = 0;
            foreach ($results as $result) {
                foreach ($result as $key => $value) {
                    $titles[$level][$key] = is_string($value) ? $this->app['utils']->unsanitizeText($value) : $value;
                }
                $level++;
            }
            return $titles;
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }

    /**
     * Select the desired title ID and return the record
     *
     * @param integer $title_id
     * @throws \Exception
     * @return array|boolean array on success, false if ID not exists
     */
    public function select($title_id)
    {
        try {
            $SQL = "SELECT * FROM `".self::$table_name."` WHERE `title_id`='$title_id'";
            $result = $this->app['db']->fetchAssoc($SQL);
            if (is_array($result) && isset($result['title_identifier'])) {
                $title = array();
                foreach ($result as $key => $value) {
                    $title[$key] = is_string($value) ? $this->app['utils']->unsanitizeText($value) : $value;
                }
                return $title;
            }
            return false;
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }

    /**
     * Delete the title ID from the definition table and also the title
     * identifier from all PERSON records!
     *
     * @param integer $title_id
     * @throws \Exception
     * @return boolean
     */
    public function delete($title_id)
    {
        try {
            $this->app['db']->delete(self::$table_name, array('title_id' => $title_id));
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }

    /**
     * Insert a new TITLE record
     *
     * @param array $data
     * @param reference integer $title_id
     * @throws \Exception
     */
    public function insert($data, &$title_id=null)
    {
        try {
            $insert = array();
            foreach ($data as $key => $value) {
                if ($key == 'title_id') continue;
                $insert[$this->app['db']->quoteIdentifier($key)] = is_string($value) ? $this->app['utils']->unsanitizeText($value) : $value;
            }
            $this->app['db']->insert(self::$table_name, $insert);
            $title_id = $this->app['db']->lastInsertId();
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }

    /**
     * Update the TITLE for the given ID
     *
     * @param array $data
     * @param integer $title_id
     * @throws \Exception
     */
    public function update($data, $title_id)
    {
        try {
            $update = array();
            foreach ($data as $key => $value) {
                if (($key == 'title_id') || ($key == 'title_identifier')) continue;
                $update[$this->app['db']->quoteIdentifier($key)] = is_string($value) ? $this->app['utils']->sanitizeText($value) : $value;
            }
            if (!empty($update)) {
                $this->app['db']->update(self::$table_name, $update, array('title_id' => $title_id));
            }
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }

    /**
     * Check if the given $title_identifier already exists
     *
     * @param string $title_identifier
     * @throws \Exception
     * @return boolean
     */
    public function existsTitle($title_identifier)
    {
        try {
            $SQL = "SELECT `title_identifier` FROM `".self::$table_name."` WHERE `title_identifier`='$title_identifier'";
            return ($title_identifier == $this->app['db']->fetchColumn($SQL));
        } catch (\Doctrine\DBAL\DBALException $e) {
            throw new \Exception($e);
        }
    }

}


text:
package io.compgen.ngsutils.cli.fasta;

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

import io.compgen.cmdline.annotation.Command;
import io.compgen.cmdline.annotation.Exec;
import io.compgen.cmdline.annotation.Option;
import io.compgen.cmdline.annotation.UnnamedArg;
import io.compgen.cmdline.exceptions.CommandArgumentException;
import io.compgen.cmdline.impl.AbstractOutputCommand;
import io.compgen.common.IterUtils;
import io.compgen.common.StringLineReader;
import io.compgen.common.TallyValues;
import io.compgen.common.progress.ProgressMessage;
import io.compgen.ngsutils.fasta.FastaReader;
import io.compgen.ngsutils.support.SeqUtils;

@Command(name="fasta-tri", desc="Determine the trinucleotide counts for a genome (DNA)", category="fasta")
public class FastaTri extends AbstractOutputCommand {
    private String filename = null;
    private String bedFilename = null;
    private String include = null;
    private String exclude = null;

    @Option(desc="BED file containing regions to count", name="bed")
    public void setBEDFile(String bedFilename) {
        this.bedFilename = bedFilename;
    }

    @Option(desc="Only count these sequences (comma-delimited)", name="include")
    public void setInclude(String include) {
        this.include = include;
    }

    @Option(desc="Don't count these sequences (comma-delimited)", name="exclude")
    public void setExclude(String exclude) {
        this.exclude = exclude;
    }

    @UnnamedArg(name = "FILE")
    public void setFilename(String filename) throws CommandArgumentException {
        this.filename = filename;
    }

    @Exec
    public void exec() throws IOException, CommandArgumentException {
        if (filename == null) {
            throw new CommandArgumentException("Missing/invalid arguments!");
        }

        if (exclude != null && include != null) {
            throw new CommandArgumentException("You can't use both --include and --exclude at the same time!");
        }

        if (exclude != null && bedFilename != null) {
            throw new CommandArgumentException("You can't use both --exclude and --bed at the same time!");
        }

        if (include != null && bedFilename != null) {
            throw new CommandArgumentException("You can't use both --include and --bed at the same time!");
        }

        FastaReader fasta = FastaReader.open(filename);

        TallyValues<String> tally = new TallyValues<String>();

        if (bedFilename != null) {
            StringLineReader bedReader = new StringLineReader(bedFilename);
            for (String line: IterUtils.wrap(bedReader.iterator())) {
                if (line.trim().length()>0){
                    String[] spl = line.split("\t");
                    String ref = spl[0];
                    int start = Integer.parseInt(spl[1]);
                    int end = Integer.parseInt(spl[2]);

                    String seq = fasta.fetchSequence(ref, start, end);
                    for (int i=0; i < seq.length()-2; i++) {
                        String tri = seq.substring(i, i+3);
                        tally.incr(tri);
                    }
                }
            }

            bedReader.close();

        } else {

            StringLineReader reader = new StringLineReader(filename);
            String buf = null;
            boolean includeThisSeq = false;
            final String seqName[] = new String[1];

            Set<String> includeSeqs = null;
            Set<String> excludeSeqs = null;

            if (include != null) {
                includeSeqs = new HashSet<String>();
                for (String s: include.split(",")) {
                    includeSeqs.add(s);
                }
            }
            if (exclude != null) {
                excludeSeqs = new HashSet<String>();
                for (String s: exclude.split(",")) {
                    excludeSeqs.add(s);
                }
            }

            for (String line: IterUtils.wrap(reader.progress(new ProgressMessage<String>(){

                @Override
                public String msg(String current) {
                    return seqName[0];
                }}))) {
                if (line.charAt(0) == '>') {
                    buf = null;
                    String name = line.trim().split(" ")[0].substring(1);

                    if (includeSeqs == null && excludeSeqs == null) {
                        includeThisSeq = true;
                    } else if (includeSeqs != null) {
                        if (includeSeqs.contains(name)) {
                            includeThisSeq = true;
                        } else {
                            includeThisSeq = false;
                        }
                    } else if (excludeSeqs != null) {
                        if (excludeSeqs.contains(name)) {
                            includeThisSeq = false;
                        } else {
                            includeThisSeq = true;
                        }
                    }

                    if (includeThisSeq) {
                        seqName[0] = name + " *";
                    } else {
                        seqName[0] = name + " -";
                    }

                } else if (includeThisSeq) {
                    line = line.toUpperCase();
                    if (buf != null) {
                        buf += line.trim();
                    } else {
                        buf = line;
                    }

                    int i=0;
                    for (i=0; i < buf.length()-2; i++) {
                        String tri = buf.substring(i, i+3);
//                        System.err.println(tri);
                        tally.incr(tri);
                    }
                    buf = buf.substring(i);
                }
            }

            reader.close();
        }

        List<String> validTri = new ArrayList<String>();
        validTri.add("ACA");
        validTri.add("ACC");
        validTri.add("ACG");
        validTri.add("ACT");
        validTri.add("ATA");
        validTri.add("ATC");
        validTri.add("ATG");
        validTri.add("ATT");
        validTri.add("CCA");
        validTri.add("CCC");
        validTri.add("CCG");
        validTri.add("CCT");
        validTri.add("CTA");
        validTri.add("CTC");
        validTri.add("CTG");
        validTri.add("CTT");
        validTri.add("GCA");
        validTri.add("GCC");
        validTri.add("GCG");
        validTri.add("GCT");
        validTri.add("GTA");
        validTri.add("GTC");
        validTri.add("GTG");
        validTri.add("GTT");
        validTri.add("TCA");
        validTri.add("TCC");
        validTri.add("TCG");
        validTri.add("TCT");
        validTri.add("TTA");
        validTri.add("TTC");
        validTri.add("TTG");
        validTri.add("TTT");

        for (String tri: validTri) {
            long count = tally.getCount(tri) + tally.getCount(SeqUtils.revcomp(tri));
            out.write((tri+"\t"+count+"\n").getBytes());
        }
    }
}


text:
const {Rule} = require('../src')

describe('array', () => {
  test('required constraint', async () => {
    const rule = Rule.array().required()
    await expect(rule.validate(null)).resolves.toMatchSnapshot('required: null')
    await expect(rule.validate(undefined)).resolves.toMatchSnapshot(
      'required: undefined'
    )
    await expect(rule.validate([])).resolves.toMatchSnapshot(
      'required: empty array'
    )
    await expect(rule.validate(['hei'])).resolves.toMatchSnapshot(
      'required: valid'
    )
  })

  test('min length constraint', async () => {
    const rule = Rule.array().min(2)
    await expect(rule.validate(['a'])).resolves.toMatchSnapshot(
      'min length: too short'
    )
    await expect(rule.validate(['a', 'b', 'c'])).resolves.toMatchSnapshot(
      'min length: valid'
    )
  })

  test('max length constraint', async () => {
    const rule = Rule.array().max(2)
    await expect(rule.validate(['a', 'b', 'c', 'd'])).resolves.toMatchSnapshot(
      'max length: too long'
    )
    await expect(rule.validate(['a'])).resolves.toMatchSnapshot(
      'max length: valid'
    )
  })

  test('exact length constraint', async () => {
    const rule = Rule.array().length(2)
    await expect(rule.validate(['a', 'b', 'c'])).resolves.toMatchSnapshot(
      'exact length: too long'
    )
    await expect(rule.validate(['a'])).resolves.toMatchSnapshot(
      'exact length: too short'
    )
    await expect(rule.validate(['a', 'b'])).resolves.toMatchSnapshot(
      'exact length: valid'
    )
  })

  test('unique constraint (default, simple values)', async () => {
    const rule = Rule.array().unique()
    await expect(rule.validate(['a', 'b', 'c', 'd'])).resolves.toMatchSnapshot(
      'simple unique: valid'
    )
    await expect(rule.validate(['a', 'b', 'c', 'a'])).resolves.toMatchSnapshot(
      'simple unique: duplicates'
    )
  })

  test('unique constraint (default, object values)', async () => {
    const rule = Rule.array().unique()
    const ref = id => ({_ref: id, _type: 'reference'})
    await expect(
      rule.validate(['a', 'b', 'c', 'd'].map(ref))
    ).resolves.toMatchSnapshot('object unique: valid')
    await expect(
      rule.validate(['a', 'b', 'c', 'a'].map(ref))
    ).resolves.toMatchSnapshot('object unique: duplicates')
  })

  test('unique constraint (default, array values)', async () => {
    const rule = Rule.array().unique()
    const refArr = id => [{_ref: id, _type: 'reference'}]
    await expect(
      rule.validate(['a', 'b', 'c', 'd'].map(refArr))
    ).resolves.toMatchSnapshot('array unique: valid')
    await expect(
      rule.validate(['a', 'a', 'c', 'd'].map(refArr))
    ).resolves.toMatchSnapshot('array unique: duplicates')
  })

  test('unique constraint (default, bool values)', async () => {
    const rule = Rule.array().unique()
    await expect(rule.validate([true, false])).resolves.toMatchSnapshot(
      'boolean unique: valid'
    )
    await expect(rule.validate([false, true, false])).resolves.toMatchSnapshot(
      'boolean unique: duplicates'
    )
  })

  test('unique constraint (default, numeric values)', async () => {
    const rule = Rule.array().unique()
    await expect(rule.validate([1, 3])).resolves.toMatchSnapshot(
      'numeric unique: valid'
    )
    await expect(rule.validate([3, 1, 3])).resolves.toMatchSnapshot(
      'numeric unique: duplicates'
    )
  })
})


text:
package "aspell-ca"
package "myspell-ca"

package "aspell-es"
package "myspell-es"

# Virtualization support
if virtual_box?
  %w[
    virtualbox-guest-dkms
    virtualbox-guest-utils
    virtualbox-guest-x11
  ].each do |pkg|
    package pkg
  end
end


text:
namespace Microsoft.Azure.Management.Avs
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Extension methods for ScriptExecutionsOperations.
    /// </summary>
    public static partial class ScriptExecutionsOperationsExtensions
    {
            /// <summary>
            /// List script executions in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// Name of the private cloud
            /// </param>
            public static IPage<ScriptExecution> List(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName)
            {
                return operations.ListAsync(resourceGroupName, privateCloudName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// List script executions in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// Name of the private cloud
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<ScriptExecution>> ListAsync(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, privateCloudName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Get an script execution by name in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// Name of the private cloud
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            public static ScriptExecution Get(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName)
            {
                return operations.GetAsync(resourceGroupName, privateCloudName, scriptExecutionName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Get an script execution by name in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// Name of the private cloud
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<ScriptExecution> GetAsync(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, privateCloudName, scriptExecutionName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Create or update a script execution in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// The name of the private cloud.
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            /// <param name='scriptExecution'>
            /// A script running in the private cloud
            /// </param>
            public static ScriptExecution CreateOrUpdate(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName, ScriptExecution scriptExecution)
            {
                return operations.CreateOrUpdateAsync(resourceGroupName, privateCloudName, scriptExecutionName, scriptExecution).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Create or update a script execution in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// The name of the private cloud.
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            /// <param name='scriptExecution'>
            /// A script running in the private cloud
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<ScriptExecution> CreateOrUpdateAsync(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName, ScriptExecution scriptExecution, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, privateCloudName, scriptExecutionName, scriptExecution, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Cancel a ScriptExecution in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// Name of the private cloud
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            public static void Delete(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName)
            {
                operations.DeleteAsync(resourceGroupName, privateCloudName, scriptExecutionName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Cancel a ScriptExecution in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// Name of the private cloud
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task DeleteAsync(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, privateCloudName, scriptExecutionName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// Return the logs for a script execution resource
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// Name of the private cloud
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            /// <param name='scriptOutputStreamType'>
            /// Name of the desired output stream to return. If not provided, will return
            /// all. An empty array will return nothing
            /// </param>
            public static ScriptExecution GetExecutionLogs(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName, IList<string> scriptOutputStreamType = default(IList<string>))
            {
                return operations.GetExecutionLogsAsync(resourceGroupName, privateCloudName, scriptExecutionName, scriptOutputStreamType).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Return the logs for a script execution resource
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// Name of the private cloud
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            /// <param name='scriptOutputStreamType'>
            /// Name of the desired output stream to return. If not provided, will return
            /// all. An empty array will return nothing
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<ScriptExecution> GetExecutionLogsAsync(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName, IList<string> scriptOutputStreamType = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.GetExecutionLogsWithHttpMessagesAsync(resourceGroupName, privateCloudName, scriptExecutionName, scriptOutputStreamType, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Create or update a script execution in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// The name of the private cloud.
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            /// <param name='scriptExecution'>
            /// A script running in the private cloud
            /// </param>
            public static ScriptExecution BeginCreateOrUpdate(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName, ScriptExecution scriptExecution)
            {
                return operations.BeginCreateOrUpdateAsync(resourceGroupName, privateCloudName, scriptExecutionName, scriptExecution).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Create or update a script execution in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// The name of the private cloud.
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            /// <param name='scriptExecution'>
            /// A script running in the private cloud
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<ScriptExecution> BeginCreateOrUpdateAsync(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName, ScriptExecution scriptExecution, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, privateCloudName, scriptExecutionName, scriptExecution, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Cancel a ScriptExecution in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// Name of the private cloud
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            public static void BeginDelete(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName)
            {
                operations.BeginDeleteAsync(resourceGroupName, privateCloudName, scriptExecutionName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Cancel a ScriptExecution in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='privateCloudName'>
            /// Name of the private cloud
            /// </param>
            /// <param name='scriptExecutionName'>
            /// Name of the user-invoked script execution resource
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task BeginDeleteAsync(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, privateCloudName, scriptExecutionName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// List script executions in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            public static IPage<ScriptExecution> ListNext(this IScriptExecutionsOperations operations, string nextPageLink)
            {
                return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
            }

            /// <summary>
            /// List script executions in a private cloud
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<ScriptExecution>> ListNextAsync(this IScriptExecutionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.zacharee1.systemuituner.MainActivity"
    tools:showIn="@layout/app_bar_main">

</LinearLayout>


text:
namespace gpu {

RingBuffer::RingBuffer(uint32_t alignment,
                       Offset base_offset,
                       uint32_t size,
                       CommandBufferHelper* helper,
                       void* base)
    : helper_(helper),
      base_offset_(base_offset),
      size_(size),
      alignment_(alignment),
      base_(static_cast<int8_t*>(base) - base_offset) {}

RingBuffer::~RingBuffer() {
  DCHECK_EQ(num_used_blocks_, 0u);
  for (const auto& block : blocks_)
    DCHECK(block.state != IN_USE);
}

void RingBuffer::FreeOldestBlock() {
  DCHECK(!blocks_.empty()) << "no free blocks";
  Block& block = blocks_.front();
  DCHECK(block.state != IN_USE)
      << "attempt to allocate more than maximum memory";
  if (block.state == FREE_PENDING_TOKEN) {
    helper_->WaitForToken(block.token);
  }
  in_use_offset_ += block.size;
  if (in_use_offset_ == size_) {
    in_use_offset_ = 0;
  }
  // If they match then the entire buffer is free.
  if (in_use_offset_ == free_offset_) {
    in_use_offset_ = 0;
    free_offset_ = 0;
  }
  blocks_.pop_front();
}

void* RingBuffer::Alloc(uint32_t size) {
  DCHECK_LE(size, size_) << "attempt to allocate more than maximum memory";
  // Similarly to malloc, an allocation of 0 allocates at least 1 byte, to
  // return different pointers every time.
  if (size == 0) size = 1;
  // Allocate rounded to alignment size so that the offsets are always
  // memory-aligned.
  size = RoundToAlignment(size);
  DCHECK_LE(size, size_)
      << "attempt to allocate more than maximum memory after rounding";

  // Wait until there is enough room.
  while (size > GetLargestFreeSizeNoWaitingInternal()) {
    FreeOldestBlock();
  }

  if (size + free_offset_ > size_) {
    // Add padding to fill space before wrapping around
    blocks_.push_back(Block(free_offset_, size_ - free_offset_, PADDING));
    free_offset_ = 0;
  }

  Offset offset = free_offset_;
  blocks_.push_back(Block(offset, size, IN_USE));
  num_used_blocks_++;

  free_offset_ += size;
  if (free_offset_ == size_) {
    free_offset_ = 0;
  }

  return GetPointer(offset + base_offset_);
}

void RingBuffer::FreePendingToken(void* pointer, uint32_t token) {
  Offset offset = GetOffset(pointer);
  offset -= base_offset_;
  DCHECK(!blocks_.empty()) << "no allocations to free";
  for (Container::reverse_iterator it = blocks_.rbegin();
        it != blocks_.rend();
        ++it) {
    Block& block = *it;
    if (block.offset == offset) {
      DCHECK(block.state == IN_USE)
          << "block that corresponds to offset already freed";
      block.token = token;
      block.state = FREE_PENDING_TOKEN;
      num_used_blocks_--;
      return;
    }
  }

  NOTREACHED() << "attempt to free non-existant block";
}

void RingBuffer::DiscardBlock(void* pointer) {
  Offset offset = GetOffset(pointer);
  offset -= base_offset_;
  DCHECK(!blocks_.empty()) << "no allocations to discard";
  for (Container::reverse_iterator it = blocks_.rbegin();
        it != blocks_.rend();
        ++it) {
    Block& block = *it;
    if (block.offset == offset) {
      DCHECK(block.state != PADDING)
          << "block that corresponds to offset already discarded";
      if (block.state == IN_USE)
        num_used_blocks_--;
      block.state = PADDING;

      // Remove block if it were in the back along with any extra padding.
      while (!blocks_.empty() && blocks_.back().state == PADDING) {
        free_offset_= blocks_.back().offset;
        blocks_.pop_back();
      }

      // Remove blocks if it were in the front along with extra padding.
      while (!blocks_.empty() && blocks_.front().state == PADDING) {
        blocks_.pop_front();
        if (blocks_.empty())
          break;

        in_use_offset_ = blocks_.front().offset;
      }

      // In the special case when there are no blocks, we should be reset it.
      if (blocks_.empty()) {
        in_use_offset_ = 0;
        free_offset_ = 0;
      }
      return;
    }
  }
  NOTREACHED() << "attempt to discard non-existant block";
}

uint32_t RingBuffer::GetLargestFreeSizeNoWaiting() {
  uint32_t size = GetLargestFreeSizeNoWaitingInternal();
  DCHECK_EQ(size, RoundToAlignment(size));
  return size;
}

uint32_t RingBuffer::GetLargestFreeSizeNoWaitingInternal() {
  while (!blocks_.empty()) {
    Block& block = blocks_.front();
    if (!helper_->HasTokenPassed(block.token) || block.state == IN_USE) break;
    FreeOldestBlock();
  }
  if (free_offset_ == in_use_offset_) {
    if (blocks_.empty()) {
      // The entire buffer is free.
      DCHECK_EQ(free_offset_, 0u);
      return size_;
    } else {
      // The entire buffer is in use.
      return 0;
    }
  } else if (free_offset_ > in_use_offset_) {
    // It's free from free_offset_ to size_ and from 0 to in_use_offset_
    return std::max(size_ - free_offset_, in_use_offset_);
  } else {
    // It's free from free_offset_ -> in_use_offset_;
    return in_use_offset_ - free_offset_;
  }
}

uint32_t RingBuffer::GetTotalFreeSizeNoWaiting() {
  uint32_t largest_free_size = GetLargestFreeSizeNoWaitingInternal();
  if (free_offset_ > in_use_offset_) {
    // It's free from free_offset_ to size_ and from 0 to in_use_offset_.
    return size_ - free_offset_ + in_use_offset_;
  } else {
    return largest_free_size;
  }
}

void RingBuffer::ShrinkLastBlock(uint32_t new_size) {
  if (blocks_.empty())
    return;
  auto& block = blocks_.back();
  DCHECK_LT(new_size, block.size);
  DCHECK_EQ(block.state, IN_USE);

  // Can't shrink to size 0, see comments in Alloc.
  new_size = std::max(new_size, 1u);

  // Allocate rounded to alignment size so that the offsets are always
  // memory-aligned.
  new_size = RoundToAlignment(new_size);
  if (new_size == block.size)
    return;
  free_offset_ = block.offset + new_size;
  block.size = new_size;
}

}  // namespace gpu