text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os, sys, six
import importlib
from enum import Enum

import tensorflow as tf
import numpy as np

import tensorflow_datasets as tf_data
from tensorflow_datasets.utils.list import wrap
import tensorflow_models.optimizers
import tensorflow_models.contexts
import tensorflow_models.layers

class GraphKeys(object):
	INPUTS = 'inputs'
	PRIOR = 'prior'
	PLACEHOLDERS = 'placeholders'
	OUTPUTS = 'outputs'
	ENCODERS = 'encoders'
	DECODERS = 'decoders'
	LOSSES = 'losses'
	INFERENCE = 'inference'

# Flatten out the HWC dimensions of a tensor
def flatten(x):
	if len(x.shape) > 2:
		x = tf.reshape(x, [int(x.shape[0]), -1])
	return x

# Sum out the HWC dimensions of a tensor
def reduce_sum(x):
	return tf.reduce_sum(flatten(x), 1)

# Return the scale of samples (which is [0, 1] unless transformations have been applied)
def sample_scale(settings):
	scale = [0, 1]
	if 'transformations' in settings:
		for k, v in six.viewitems(settings['transformations']):
			if k == 'rescale':
				scale = list(v)
	return scale

# Gets the shape of the tensor holding an unflattened minibatch => (batch x channels x height x width)
def unflattened_batchshape(settings):
	return [settings['batch_size']] + tf_data.unflattened_sample_shape(settings)

def flattened_shape(settings):
	return [int(np.prod(tf_data.unflattened_sample_shape(settings)))]

def flattened_batchshape(settings):
	return [settings['batch_size']] + flattened_shape(settings)

def batchshape(settings):
	if 'flatten' in settings['transformations']:
		return flattened_batchshape(settings)
	else:
		return unflattened_batchshape(settings)

def safe_log(x, **kwargs):
	#return tf.log(x + 1e-16, **kwargs)
	return tf.log(x + 1e-8, **kwargs)

def count_batches(settings, subset=None):
	if not subset is None:
		return tf_data.count(settings['dataset'], subset) // settings['batch_size']
	else:
		train_batches = count_batches(settings, tf_data.Subset.TRAIN)
		test_batches = count_batches(settings, tf_data.Subset.TEST)
		return train_batches, test_batches

def global_step():
	return tf.contrib.framework.get_or_create_global_step()

def local_step(settings, name='local_step', start=0):
	with cpu_device(settings):
		step = tf.Variable(start, name=name, trainable=False)

def host():
	return tf.device("/cpu:0")

def device(settings):
	return tf.device("/" + settings['device'])

def create(settings, placeholders=False):
	with host():
		if not placeholders:
			input_ops(settings)
		else:
			input_placeholders(settings)

	with device(settings):
		model_ops(settings)
		loss_ops(settings)
		inference_ops(settings)

def trainer(settings):
	lib = importlib.import_module('tensorflow_models.trainers.' + settings['trainer'])
	return lib.Trainer

# TODO: Would it be better to expand the settings dictionary when it is called and have named arguments?
def input_ops(settings):
	with tf.name_scope('inputs/train'):
		train_samples = tf_data.inputs(
			name=settings['dataset'],
			subset=tf_data.Subset.TRAIN,
			return_labels=settings['labels'],
			batch_size=settings['batch_size'],
			num_threads=settings['num_threads'],
			transformations=settings['transformations'])

	for x in wrap(train_samples):
		tf.add_to_collection(GraphKeys.INPUTS, x)

	if not settings['model'] == 'gan':
		with tf.name_scope('inputs/test'):
			test_samples = tf_data.inputs(
				name=settings['dataset'],
				subset=tf_data.Subset.TEST,
				return_labels=settings['labels'],
				batch_size=settings['batch_size'],
				num_threads=settings['num_threads'],
				transformations=settings['transformations'])

		for x in wrap(test_samples):
			tf.add_to_collection(GraphKeys.INPUTS, x)

	#return train_samples, test_samples

def input_placeholders(settings):
	#count_train = settings['count'][tf_data.Subset.TRAIN]
	#count_test = settings['count'][tf_data.Subset.TEST]

	with tf.name_scope('inputs/train'):
		#print('sample_shape', sample_shape(settings), unflattened_sample_shape(settings))

		train = tf.placeholder(dtype=tf.float32, shape=np.concatenate(([settings['batch_size']], tf_data.sample_shape(settings))), name='samples')
		if settings['labels']:
			train = [train, tf.placeholder(dtype=tf.float32, shape=[settings['batch_size'], 1], name='labels')]

	for x in wrap(train):
		tf.add_to_collection(GraphKeys.INPUTS, x)

	with tf.name_scope('inputs/test'):
		test = tf.placeholder(dtype=tf.float32, shape=np.concatenate(([settings['batch_size']], tf_data.sample_shape(settings))), name='samples')
		if settings['labels']:
			test = [test, tf.placeholder(dtype=tf.float32, shape=[settings['batch_size'], 1], name='labels')]

	for x in wrap(test):
		tf.add_to_collection(GraphKeys.INPUTS, x)

	#print('train.shape', train.shape, 'test.shape', test.shape)
	#print('train', train, 'test', test)
	#raise Exception()

	return train, test

def samples(subset=tf_data.Subset.TRAIN):
	inputs = tf.get_collection(GraphKeys.INPUTS)
	for op in inputs:
		if tf_data.subset_suffix[subset] + '/samples' in op.name:
			return op
	return None

def labels(subset=tf_data.Subset.TRAIN):
	inputs = tf.get_collection(GraphKeys.INPUTS)
	for op in inputs:
		if tf_data.subset_suffix[subset] + '/labels' in op.name:
			return op
	return None

# Get trainable variables with a given substring
def get_vars(name):
	variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
	selected = []
	for v in variables:
		if name in v.name:
			selected.append(v)
	return v

def get_prior():
	ops = tf.get_collection(GraphKeys.PRIOR)
	if not ops is []:
		return ops[0]
	else:
		raise ValueError('No prior sampling operation exists')

def lg_likelihood(settings):
	model = importlib.import_module('tensorflow_models.models.' + settings['model'])
	if 'lg_likelihood' in dir(model):
		return model.lg_likelihood
	else:
		raise ValueError('No log-likelihood function exists')

def model(settings):
	model_module = importlib.import_module('tensorflow_models.models.' + settings['model'])
	return model_module

def lg_prior(settings):
	model = importlib.import_module('tensorflow_models.models.' + settings['model'])
	if 'lg_prior' in dir(model):
		return model.lg_prior
	else:
		raise ValueError('No log-prior function exists')

def get_decoder():
	ops = tf.get_collection(GraphKeys.DECODERS)
	if not ops is []:
		return ops[0]
	else:
		return None
		#raise ValueError('No decoder sampling operation exists')

def get_encoder():
	ops = tf.get_collection(GraphKeys.ENCODERS)
	if not ops is []:
		return ops[0]
	else:
		return None
		#raise ValueError('No encoder sampling operation exists')

def get_output(name):
	ops = tf.get_collection(GraphKeys.OUTPUTS)
	for op in ops:
		if name in op.name:
			return op
	raise ValueError('No output operation with substring "{}" exists'.format(name))

def get_loss(name):
	ops = tf.get_collection(GraphKeys.LOSSES)
	for op in ops:
		if name in op.name:
			return op
	raise ValueError('No loss operation with substring "{}" exists'.format(name))

def get_inference(name):
	ops = tf.get_collection(GraphKeys.INFERENCE)
	for op in ops:
		if name in op.name:
			return op
	raise ValueError('No inference operation with substring "{}" exists'.format(name))

def samples_placeholder():
	placeholders = tf.get_collection(GraphKeys.PLACEHOLDERS)
	for p in placeholders:
		if 'samples' in p.name:
			return p
	return None

def train_placeholder():
	placeholders = tf.get_collection(GraphKeys.INPUTS)
	for p in placeholders:
		if 'train/samples' in p.name:
			return p
	return None

def test_placeholder():
	placeholders = tf.get_collection(GraphKeys.INPUTS)
	for p in placeholders:
		if 'test/samples' in p.name:
			return p
	return None

def codes_placeholder():
	placeholders = tf.get_collection(GraphKeys.PLACEHOLDERS)
	for p in placeholders:
		if 'codes' in p.name:
			return p
	return None

def model_ops(settings):
	model = importlib.import_module('tensorflow_models.models.' + settings['model'])

	with tf.variable_scope('model'):
		# Create and store an operation to sample from the prior
		if 'create_prior' in dir(model):
			with tf.name_scope('prior'):
				tf.add_to_collection(GraphKeys.PRIOR, model.create_prior(settings))

		if 'create_placeholders' in dir(model):
			with tf.name_scope('placeholders'):
				placeholders = model.create_placeholders(settings)
				for p in wrap(placeholders):
					tf.add_to_collection(GraphKeys.PLACEHOLDERS, p)

		with tf.name_scope('train'):
			probs = model.create_probs(settings, samples(tf_data.Subset.TRAIN), is_training=True)
			for p in wrap(probs):
				tf.add_to_collection(GraphKeys.OUTPUTS, p)

		if not settings['model'] == 'gan':
			with tf.name_scope('test'):
				probs = model.create_probs(settings, samples(tf_data.Subset.TEST), is_training=False, reuse=True)
				for p in wrap(probs):
					tf.add_to_collection(GraphKeys.OUTPUTS, p)

		if 'create_encoder' in dir(model):
			tf.add_to_collection(GraphKeys.ENCODERS, model.create_encoder(settings, reuse=True))
		if 'create_decoder' in dir(model):
			tf.add_to_collection(GraphKeys.DECODERS, model.create_decoder(settings, reuse=True))

def loss_ops(settings):
	loss_lib = importlib.import_module('tensorflow_models.losses.' + settings['loss'])
	with tf.name_scope('losses'):
		if not settings['model'] == 'gan':
			ls = wrap(loss_lib.create('train', settings)) + wrap(loss_lib.create('test', settings))
		else:
			ls = wrap(loss_lib.create('train', settings))
		for l in ls:
			tf.add_to_collection(GraphKeys.LOSSES, l)

def inference_ops(settings):
	inference_lib = importlib.import_module('tensorflow_models.inference.' + settings['inference'])
	with tf.name_scope('inference'):
		ops = wrap(inference_lib.create(settings))
		for op in ops:
			tf.add_to_collection(GraphKeys.INFERENCE, op)

def latentshape(settings):
	return [settings['batch_size'], settings['latent_dimension']]

def noiseshape(settings):
	return [settings['batch_size'], settings['noise_dimension']]

def standard_normal(shape, name='MultivariateNormalDiag'):
	return tf.contrib.distributions.MultivariateNormalDiag(tf.zeros(shape), tf.ones(shape), name=name)

def standard_uniform(name='Uniform'):
	return tf.contrib.distributions.Uniform(name=name)

def gan_uniform(name='Uniform'):
	try:
		return tf.contrib.distributions.Uniform(a=-1., b=1., name=name)
	except:
		return tf.contrib.distributions.Uniform(low=-1., high=1., name=name)


text:
class CreateEveAgents < ActiveRecord::Migration[6.0]
  def change
    create_table :eve_agents do |t|
      t.bigint :agent_id
      t.bigint :agent_type_id
      t.bigint :corporation_id
      t.bigint :division_id
      t.boolean :is_locator
      t.integer :level
      t.bigint :location_id
      t.integer :quality

      t.timestamps
    end

    add_index :eve_agents, :agent_id, unique: true
    add_index :eve_agents, :corporation_id
  end
end

redpajama_set_name: RedPajamaGithub


text:
/*This file was created for Terratap-Technologies-Inc by Cody Clattenburg, Sam Collins, Martin Suryadi, and Sergio Josue Villegas. This file is under the protection of the Apache 2.0 License.*/
/*NEW WESTMINSTER - PUBLIC ART*/

/*Declare Variables*/
var fs = require('fs');
var obj;
var inputPath = 'in.json';
var outputPath = 'out.json';
var prettyPrint = 0; /*Setting this to 1 or TRUE formats the output with indentation.*/
var ppNL = '';
var ppTB = '';

/*Read the file and send to the callback*/
fs.readFile(inputPath, handleFile)

/*Write the callback function*/
function handleFile(err, data) {

  if (err) throw err
  obj = JSON.parse(data);
  obj = obj.features;

  if (prettyPrint == 1) {
    ppNL = '\n';
    ppTB = '\t';
  }

  /*Default Override*/
  for (var i = 0; i < obj.length; i++) {
    if (obj[i].properties.Name == "")
      obj[i].properties.Name = "Name Unavailable";
  }
  for (var i = 0; i < obj.length; i++) {
    //if (obj[i].properties.ARTIST_NAME == "")
      obj[i].properties.ARTIST_NAME = "Artist Name Unavailable";
  }
  for (var i = 0; i < obj.length; i++) {
    //if (obj[i].properties.MEDIUM == "")
      obj[i].properties.MEDIUM = "Art Type Unavailable";
  }
  for (var i = 0; i < obj.length; i++) {
    if (obj[i].properties.summary == "")
      obj[i].properties.summary = obj[i].properties.Descriptn;
    if (obj[i].properties.summary == "")
      obj[i].properties.summary = "Summary Unavailable";
    while(obj[i].properties.summary.search('\"') != -1)
      obj[i].properties.summary = obj[i].properties.summary.slice(0, obj[i].properties.summary.search('\"')) + '\'' + obj[i].properties.summary.slice(obj[i].properties.summary.search('\"') + 1, obj[i].properties.summary.length);
  }
  for (var i = 0; i < obj.length; i++) {
    if (obj[i].properties.Descriptn == "")
      obj[i].properties.Descriptn = "Description Unavailable";
      while(obj[i].properties.Descriptn.search('\"') != -1)
        obj[i].properties.Descriptn = obj[i].properties.Descriptn.slice(0, obj[i].properties.Descriptn.search('\"')) + '\'' + obj[i].properties.Descriptn.slice(obj[i].properties.Descriptn.search('\"') + 1, obj[i].properties.Descriptn.length);
      while(obj[i].properties.Descriptn.search('\n') != -1)
        obj[i].properties.Descriptn = obj[i].properties.Descriptn.slice(0, obj[i].properties.Descriptn.search('\n')) + ' ' + obj[i].properties.Descriptn.slice(obj[i].properties.Descriptn.search('\n') + 1, obj[i].properties.Descriptn.length);
      while(obj[i].properties.Descriptn.search('\r') != -1)
        obj[i].properties.Descriptn = obj[i].properties.Descriptn.slice(0, obj[i].properties.Descriptn.search('\r')) + obj[i].properties.Descriptn.slice(obj[i].properties.Descriptn.search('\r') + 1, obj[i].properties.Descriptn.length);
  }

  for (var i = 0; i < obj.length; i++) {
    if (obj[i].properties.Address == "")
    obj[i].properties.Address = "Address Unavailable";
  }

  /*Writing Loop*/
  var content = '[' + ppNL;
  for (var i = 0; i < obj.length; i++) {

    /*CSV Newline Fix*/
    if (obj[i].properties.X == undefined) {
      while (content.slice(-1) == '\n' || content.slice(-1) == ',') {
        content = content.slice(0, -1);
      }
      continue;
    }

    /*Write to out.json*/
    content += '{'
    + ppNL + ppTB + '"type": "Feature"'
    + ppNL + ppTB + ',"geometry": {'
    + ppNL + ppTB + ppTB + '"type": "Point"'
    + ppNL + ppTB + ppTB + ',"coordinates": ' + '[' + obj[i].properties.Y + ', ' + obj[i].properties.X + ']'
    + ppNL + ppTB + '}'
    + ppNL + ppTB + ',"properties": ';

    content += '{'
    + ppNL + ppTB + ppTB + '"nm": "' + obj[i].properties.Name + '"'
    + ppNL + ppTB + ppTB + ',' + '"aNm": "' + obj[i].properties.ARTIST_NAME + '"'
    + ppNL + ppTB + ppTB + ',' + '"type": "' + obj[i].properties.MEDIUM + '"'
    + ppNL + ppTB + ppTB + ',' + '"summ": "' + obj[i].properties.summary + '"'
    + ppNL + ppTB + ppTB + ',' + '"desc": "' + obj[i].properties.Descriptn + '"'
    + ppNL + ppTB + ppTB + ',' + '"adr": "' + obj[i].properties.Address + '"'
    + ppNL + ppTB + '}'
    + ppNL + '}';

    if (i < obj.length - 1) {
      content += ppNL + ',';
    }
  }
  content += ppNL + ']';

  /*Save File*/
  fs.writeFile(outputPath, content, 'utf8', function (err) {
    if (err) {
      return console.log(err);
    }

    /*Print File Status*/
    console.log("The file was converted!");
  });
}


text:
<?php

final class NuanceQueueQuery
  extends NuanceQuery {

  private $ids;
  private $phids;

  public function withIDs(array $ids) {
    $this->ids = $ids;
    return $this;
  }

  public function withPHIDs(array $phids) {
    $this->phids = $phids;
    return $this;
  }

  public function newResultObject() {
    return new NuanceQueue();
  }

  protected function loadPage() {
    return $this->loadStandardPage($this->newResultObject());
  }

  protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
    $where = parent::buildWhereClauseParts($conn);

    if ($this->ids !== null) {
      $where[] = qsprintf(
        $conn,
        'id IN (%Ld)',
        $this->ids);
    }

    if ($this->phids !== null) {
      $where[] = qsprintf(
        $conn,
        'phid IN (%Ls)',
        $this->phids);
    }

    return $where;
  }

}


text:
using System.ComponentModel.DataAnnotations;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using EPiServerDemoSite.Models.ViewModels;

namespace EPiServerDemoSite.Models.Pages
{
    [ContentType(DisplayName = "TwoColumnPage", GUID = "898b6aad-fed4-4496-9c35-c64aa6cbd647", Description = "")]
    public class TwoColumnPage : EPiPageData, IHasRelatedContent
    {
        [Display(
            GroupName = SystemTabNames.Content,
            Order = 310)]
        [CultureSpecific]
        [AllowedTypes(new[] { typeof(IContentData) })]
        public virtual ContentArea RelatedContentArea { get; set; }
    }
}


text:
package com.btmura.android.reddit.app;

import java.util.ArrayList;
import java.util.Arrays;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

/**
 * A version of FragmentStatePagerAdapter that supports reorderable fragments.
 *
 * Copied from the support library and merged with modifications describe from the following issue
 * to support reordering of fragments:
 *
 * http://code.google.com/p/android/issues/detail?id=37990
 */
public abstract class FragmentStateItemPagerAdapter extends PagerAdapter {
    private static final String TAG = "FSIPagerAdapter";
    private static final boolean DEBUG = false;

    private final FragmentManager mFragmentManager;
    private FragmentTransaction mCurTransaction = null;

    private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>();
    private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
    private long[] mItemIds;
    private Fragment mCurrentPrimaryItem = null;

    public FragmentStateItemPagerAdapter(FragmentManager fm) {
        mFragmentManager = fm;
    }

    /**
     * Return the Fragment associated with a specified position.
     */
    public abstract Fragment getItem(int position);

    /**
     * Return a unique identifier for the item at the given position.
     */
    public long getItemId(int position) {
        return position;
    }

    @Override
    public void notifyDataSetChanged() {
        long[] newItemIds = new long[getCount()];
        for (int i = 0; i < newItemIds.length; i++) {
            newItemIds[i] = getItemId(i);
        }

        if (!Arrays.equals(mItemIds, newItemIds)) {
            ArrayList<Fragment.SavedState> newSavedState = new ArrayList<Fragment.SavedState>();
            ArrayList<Fragment> newFragments = new ArrayList<Fragment>();
            int numItemIds = mItemIds != null ? mItemIds.length : 0;
            for (int oldPosition = 0; oldPosition < numItemIds; oldPosition++) {
                int newPosition = POSITION_NONE;
                for (int i = 0; i < newItemIds.length; i++) {
                    if (mItemIds[oldPosition] == newItemIds[i]) {
                        newPosition = i;
                        break;
                    }
                }
                if (newPosition >= 0) {
                    if (oldPosition < mSavedState.size()) {
                        Fragment.SavedState savedState = mSavedState.get(oldPosition);
                        if (savedState != null) {
                            while (newSavedState.size() <= newPosition) {
                                newSavedState.add(null);
                            }
                            newSavedState.set(newPosition, savedState);
                        }
                    }
                    if (oldPosition < mFragments.size()) {
                        Fragment fragment = mFragments.get(oldPosition);
                        if (fragment != null) {
                            while (newFragments.size() <= newPosition) {
                                newFragments.add(null);
                            }
                            newFragments.set(newPosition, fragment);
                        }
                    }
                }
            }

            mItemIds = newItemIds;
            mSavedState = newSavedState;
            mFragments = newFragments;
        }

        super.notifyDataSetChanged();
    }

    @Override
    public void startUpdate(ViewGroup container) {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // If we already have this item instantiated, there is nothing
        // to do. This can happen when we are restoring the entire pager
        // from its saved state, where the fragment manager has already
        // taken care of restoring the fragments we previously had instantiated.
        if (mFragments.size() > position) {
            Fragment f = mFragments.get(position);
            if (f != null) {
                return f;
            }
        }

        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        Fragment fragment = getItem(position);
        if (DEBUG) {
            Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
        }
        if (mSavedState.size() > position) {
            Fragment.SavedState fss = mSavedState.get(position);
            if (fss != null) {
                fragment.setInitialSavedState(fss);
            }
        }
        while (mFragments.size() <= position) {
            mFragments.add(null);
        }
        fragment.setMenuVisibility(false);
        fragment.setUserVisibleHint(false);
        mFragments.set(position, fragment);
        mCurTransaction.add(container.getId(), fragment);

        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment) object;

        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        position = getItemPosition(object);
        if (DEBUG) {
            Log.v(TAG, "Removing item #" + position + ": f=" + object
                    + " v=" + ((Fragment) object).getView());
        }
        if (position >= 0) {
            while (mSavedState.size() <= position) {
                mSavedState.add(null);
            }
            mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
            mFragments.set(position, null);
        }
        mCurTransaction.remove(fragment);
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment) object;
        if (fragment != mCurrentPrimaryItem) {
            if (mCurrentPrimaryItem != null) {
                mCurrentPrimaryItem.setMenuVisibility(false);
                mCurrentPrimaryItem.setUserVisibleHint(false);
            }
            if (fragment != null) {
                fragment.setMenuVisibility(true);
                fragment.setUserVisibleHint(true);
            }
            mCurrentPrimaryItem = fragment;
        }
    }

    @Override
    public void finishUpdate(ViewGroup container) {
        if (mCurTransaction != null) {
            mCurTransaction.commitAllowingStateLoss();
            mCurTransaction = null;
            mFragmentManager.executePendingTransactions();
        }
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return ((Fragment) object).getView() == view;
    }

    @Override
    public Parcelable saveState() {
        Bundle state = null;
        if (mItemIds != null && mItemIds.length > 0) {
            state = new Bundle();
            state.putLongArray("itemIds", mItemIds);
        }
        if (mSavedState.size() > 0) {
            if (state == null) {
                state = new Bundle();
            }
            Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
            mSavedState.toArray(fss);
            state.putParcelableArray("states", fss);
        }
        for (int i = 0; i < mFragments.size(); i++) {
            Fragment f = mFragments.get(i);
            if (f != null) {
                if (state == null) {
                    state = new Bundle();
                }
                String key = "f" + i;
                mFragmentManager.putFragment(state, key, f);
            }
        }
        return state;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
        if (state != null) {
            Bundle bundle = (Bundle) state;
            bundle.setClassLoader(loader);
            mItemIds = bundle.getLongArray("itemIds");
            Parcelable[] fss = bundle.getParcelableArray("states");
            mSavedState.clear();
            mFragments.clear();
            if (fss != null) {
                for (int i = 0; i < fss.length; i++) {
                    mSavedState.add((Fragment.SavedState) fss[i]);
                }
            }
            Iterable<String> keys = bundle.keySet();
            for (String key : keys) {
                if (key.startsWith("f")) {
                    int index = Integer.parseInt(key.substring(1));
                    Fragment f = mFragmentManager.getFragment(bundle, key);
                    if (f != null) {
                        while (mFragments.size() <= index) {
                            mFragments.add(null);
                        }
                        f.setMenuVisibility(false);
                        mFragments.set(index, f);
                    } else {
                        Log.w(TAG, "Bad fragment at key " + key);
                    }
                }
            }
        }
    }
}


text:
from abc import ABC, abstractmethod

class BaseUpgradeHelper(ABC):
    """Base UpgradeHelper abstract class"""

    @abstractmethod
    def manual_steps_required(self) -> None:
        pass

    @abstractmethod
    def get_upgrade_overview(self) -> None:
        pass

    @abstractmethod
    def upgrade_project(self) -> None:
        pass

    @abstractmethod
    def _generate_upgrade_report(self) -> None:
        pass

    @abstractmethod
    def _save_upgrade_log(self) -> None:
        pass


text:
OCRP_Buddies = OCRP_Buddies or {}

net.Receive("OCRP_UpdateBuddies", function()
    OCRP_Buddies = net.ReadTable(OCRP_Buddies)
end)

function GetSpecCL( um )
	SpecEnt = um:ReadEntity()
	LocalPlayer().Spec = tostring(um:ReadBool())
end
usermessage.Hook("Spec", GetSpecCL)

function GetSpecEndCL( um )
	SpecEnt = nil
	LocalPlayer().Spec = nil
end
usermessage.Hook("SpecEnd", GetSpecEndCL)

LocalPlayer().Energy = 100
LocalPlayer().ChargeInt = 0

function CL_GetChargeInt()
	if LocalPlayer().ChargeInt == nil then
		LocalPlayer().ChargeInt = 0
	end
	return LocalPlayer().ChargeInt or 0
end

function CL_GetEnergy()
	LocalPlayer().Energy = LocalPlayer():GetNWInt("Energy")
	return LocalPlayer().Energy
end

function CL_SetEnergy( ZeAmt )
	LocalPlayer().Energy = ZeAmt
	LocalPlayer():SetNWInt("Energy", ZeAmt)
end

function UM_GetForceWalkCL( umsg )
	LocalPlayer().ForceWalk = umsg:ReadBool()
end
usermessage.Hook("inhib_forcewalk", UM_GetForceWalkCL)

function GetForceWalk()
	return LocalPlayer().ForceWalk or false
end

function CL_ResetEnergy( umsg )
	LocalPlayer().Energy = umsg:ReadLong()
end
usermessage.Hook("spawning_energy", CL_ResetEnergy)

function CL_GetSodaCL( umsg )
	CL_SetEnergy( umsg:ReadLong() )
end
usermessage.Hook("soda_energy", CL_GetSodaCL)

function CL_SprintDecay(ply, data)
	if ply:KeyPressed(IN_JUMP) && ply:OnGround() then
		if CL_GetEnergy() > 10 then
			if CL_HasSkill("skill_acro",2) then
				CL_SetEnergy(CL_GetEnergy() - 5)
			else
				CL_SetEnergy(CL_GetEnergy() - 10)
			end
		else
			CL_SetEnergy(0)
		end
	end
	if GetForceWalk() == true then
		return
	end
	if ply:KeyDown(IN_SPEED) && ply:OnGround() && !GetForceWalk() then
		if math.abs(data:GetForwardSpeed()) > 0 || math.abs(data:GetSideSpeed()) > 0 then
		--	data:SetMoveAngles(data:GetMoveAngles())
		--	data:SetSideSpeed(data:GetSideSpeed()* 0.1)
		--	data:SetForwardSpeed(data:GetForwardSpeed())
			if CL_GetEnergy() > 0 && CL_GetChargeInt() <= CurTime()  then
				CL_SetEnergy(CL_GetEnergy() - 1)
				LocalPlayer().ChargeInt = CurTime() + 0.05
			end
		end
	else
		if CL_GetEnergy() < 100 && CL_GetChargeInt() <= CurTime() then
			CL_SetEnergy(CL_GetEnergy() + 1)
			LocalPlayer().ChargeInt = CurTime() + 1
		end
	end
	if CL_GetEnergy() > 0 && !LocalPlayer().CanSprint then
		LocalPlayer().CanSprint = true
	elseif CL_GetEnergy() <= 0 && LocalPlayer().CanSprint  then
		LocalPlayer().CanSprint = false
		LocalPlayer().ChargeInt = CurTime() + 5
	end
end
hook.Add("Move", "CL_SprintDecay",  CL_SprintDecay)


text:
using System;
using NUnit.Framework;

namespace ZXing.Client.Result.Test
{
   [TestFixture]
   public class VINParsedResultTestCase
   {

      [Test]
      public void testNotVIN()
      {
         var fakeResult = new ZXing.Result("1M8GDM9A1KP042788", null, null, BarcodeFormat.CODE_39);
         var result = ResultParser.parseResult(fakeResult);
         Assert.AreEqual(ParsedResultType.TEXT, result.Type);
         fakeResult = new ZXing.Result("1M8GDM9AXKP042788", null, null, BarcodeFormat.CODE_128);
         result = ResultParser.parseResult(fakeResult);
         Assert.AreEqual(ParsedResultType.TEXT, result.Type);
      }

      [Test]
      public void testVIN()
      {
         doTest("1M8GDM9AXKP042788", "1M8", "GDM9AX", "KP042788", "US", "GDM9A", 1989, 'P', "042788");
         doTest("I1M8GDM9AXKP042788", "1M8", "GDM9AX", "KP042788", "US", "GDM9A", 1989, 'P', "042788");
         doTest("LJCPCBLCX11000237", "LJC", "PCBLCX", "11000237", "CN", "PCBLC", 2001, '1', "000237");
      }

      private static void doTest(String contents,
                                 String wmi,
                                 String vds,
                                 String vis,
                                 String country,
                                 String attributes,
                                 int year,
                                 char plant,
                                 String sequential)
      {
         var fakeResult = new ZXing.Result(contents, null, null, BarcodeFormat.CODE_39);
         var result = ResultParser.parseResult(fakeResult);
         Assert.AreEqual(ParsedResultType.VIN, result.Type);
         var vinResult = (VINParsedResult) result;
         Assert.AreEqual(wmi, vinResult.WorldManufacturerID);
         Assert.AreEqual(vds, vinResult.VehicleDescriptorSection);
         Assert.AreEqual(vis, vinResult.VehicleIdentifierSection);
         Assert.AreEqual(country, vinResult.CountryCode);
         Assert.AreEqual(attributes, vinResult.VehicleAttributes);
         Assert.AreEqual(year, vinResult.ModelYear);
         Assert.AreEqual(plant, vinResult.PlantCode);
         Assert.AreEqual(sequential, vinResult.SequentialNumber);
      }
   }
}


text:
package com.mace.runner.util;

import java.io.*;
import java.net.URL;

public class ResourceFile {

	private String fileName;

	public ResourceFile(String fileName) {
		this.fileName = fileName;
	}

	public String getContent() {

		String line;
		StringBuffer sb = new StringBuffer();
		try (FileReader reader = new FileReader(openFile());
		     BufferedReader br = new BufferedReader(reader)) {

			while ((line = br.readLine()) != null) {
				sb.append(line);
				sb.append(System.lineSeparator());
			}
			return sb.toString();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private File openFile() {

		URL resource = ClassLoader.getSystemClassLoader().getResource(fileName);
		if (resource == null) {
			throw new IllegalArgumentException("file is not found!");
		} else {
			return new File(resource.getFile());
		}

	}
}


text:
(function() {
  "use strict";

  angular.module("paginate", ["paginate.buttons"]);

}());


text:
layout: page
title: Mayer Vision Research Trade Fair
date: 2016-05-24
author: Victoria Webb
tags: weekly links, java
status: published
summary: Mauris pretium mauris sed mi faucibus semper. Morbi ultrices sem.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 08/07/2016
  endDate: 08/09/2016
  ctyhocn: CHIFFHX
  groupCode: MVRTF
published: true
---
Aenean quis massa nulla. Nunc et eros non arcu ultricies tincidunt. In hac habitasse platea dictumst. Pellentesque commodo gravida metus, a accumsan nulla ultrices id. Vestibulum vel diam neque. Proin maximus ex id felis semper lobortis. Aliquam ultrices lectus in ligula mattis rutrum. Nam convallis ex eget est ornare, eget dictum eros elementum. Maecenas ut metus sit amet nulla accumsan accumsan. Aenean lectus mi, mattis non euismod a, eleifend a velit. Curabitur sed consequat justo. Aliquam eu auctor ipsum. Aliquam faucibus sem nec condimentum rhoncus. Integer condimentum arcu a quam mollis, in efficitur neque egestas.
Vestibulum sagittis faucibus nisi non tristique. Phasellus tempus, tellus vel dignissim tincidunt, dolor tortor finibus libero, in faucibus enim tortor eu velit. Nam ac ex interdum, ornare sem pharetra, porta lectus. Nullam nunc felis, efficitur ut dolor at, placerat aliquet ligula. Suspendisse nunc leo, vulputate nec turpis sed, dignissim volutpat mi. Quisque vitae gravida sapien. Phasellus elementum consectetur felis ac ornare.

* Proin ultrices ipsum eu urna gravida tincidunt
* Quisque pellentesque velit in velit euismod venenatis
* Maecenas at justo feugiat, faucibus mi non, eleifend est
* Integer venenatis sapien eget tortor cursus consectetur
* Nulla sit amet urna quis mauris ultrices cursus at a sapien.

Phasellus arcu ex, maximus sit amet feugiat sit amet, faucibus id tellus. Praesent purus turpis, faucibus vitae tristique et, accumsan sagittis est. Suspendisse potenti. Etiam volutpat ligula ex, quis pellentesque ligula rhoncus eget. Suspendisse et ullamcorper leo, vitae scelerisque ipsum. Aenean eu neque a nunc tincidunt tristique eu in leo. Aenean id aliquet nulla, quis pulvinar metus. Sed at arcu urna. Nulla tristique lacus lorem, eget aliquet leo eleifend at.


text:
package org.apache.geode.rest.internal.web.security;

import java.util.Properties;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;

import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.security.SecurityService;
import org.apache.geode.internal.security.SecurityServiceFactory;
import org.apache.geode.management.internal.security.ResourceConstants;
import org.apache.geode.security.GemFireSecurityException;

@Component
public class GeodeAuthenticationProvider implements AuthenticationProvider {

  private final SecurityService securityService;

  public GeodeAuthenticationProvider() {
    // TODO: can we pass SecurityService in?
    this.securityService = findSecurityService();
  }

  private static SecurityService findSecurityService() {
    InternalCache cache = GemFireCacheImpl.getInstance();
    if (cache != null) {
      return cache.getSecurityService();
    } else {
      return SecurityServiceFactory.create();
    }
  }

  public SecurityService getSecurityService() {
    return this.securityService;
  }

  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = authentication.getCredentials().toString();
    Properties credentials = new Properties();
    if (username != null)
      credentials.put(ResourceConstants.USER_NAME, username);
    if (password != null)
      credentials.put(ResourceConstants.PASSWORD, password);

    try {
      securityService.login(credentials);
      return new UsernamePasswordAuthenticationToken(username, password,
          AuthorityUtils.NO_AUTHORITIES);
    } catch (GemFireSecurityException e) {
      throw new BadCredentialsException(e.getLocalizedMessage(), e);
    }
  }

  @Override
  public boolean supports(Class<?> authentication) {
    return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
  }
}


text:
package guildPlugin.georgep.pokuit.regiusCraft;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.bukkit.ChatColor;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;

public class ConfigManager {
	ArrayList<customConfig> fileStorage = new ArrayList<customConfig>();

	private Plugin plugin;

	public ConfigManager(Plugin plugin) {
		this.plugin = plugin;
	}
	/**
	 * Add a new Custom Config
	 * @param String - Name of config you wish to create
	 * @return boolean - True if created config file, false if file already by that name
	 */
	public boolean newConfig(String name) {
		if(!configByName(name)) {

			customConfig cc = new customConfig(name);

			fileStorage.add(cc);

			this.saveDefaultConfig(name);

			return true;
		} else {
			return false;
		}
	}
	/**
	 * Reloads the config with the name passed in
	 * @param name
	 * @return boolean true if file with that name false if file not with that name
	 */
	public boolean reloadCustomConfig(String name) {
		customConfig cc = getConfigFromName(name);
		if(cc != null) {
			if (cc.getFile() == null) {
			    cc.setFile(new File(plugin.getDataFolder(), cc.getName()+".yml"));
			}
			cc.setConfig(YamlConfiguration.loadConfiguration(cc.getFile()));

		    // Look for defaults in the jar
		    InputStream defConfigStream = plugin.getResource(cc.getName()+".yml");
		    if (defConfigStream != null) {
		        YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
		        cc.getConfig().setDefaults(defConfig);
		    }
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Gets custom config
	 * @param name of Custom configuration
	 * @return FileConfiguration
	 */
	public FileConfiguration getCustomConfig(String name) {
		customConfig cc = getConfigFromName(name);
		if(cc != null) {
			if (cc.getConfig() == null) {
				if(!this.reloadCustomConfig(cc.getName())) {
					return null;
				}
		    }
		    return cc.getConfig();
		} else {
			return null;
		}
	}
	/**
	 * Saves custom Config
	 * @param name - Name of Config to Save
	 * @return boolean - true if could save false if could not
	 */
	public boolean saveCustomConfig(String name) {
		customConfig cc = getConfigFromName(name);
		if(cc != null) {
		    if (cc.getConfig() == null || cc.getFile()== null) {
		    	return false;
		    }
		    try {
		        getCustomConfig(cc.getName()).save(cc.getFile());
		    } catch (IOException ex) {
		       log(ChatColor.RED+"Could not save config to " + cc.getFile()+"  \n"+ex.toString());
		        return false;
		    }
		    return true;
		} else {
			return false;
		}
	}
	/**
	 * Save Default Config
	 *
	 * @param Name of config to save
	 * @return
	 */
	public boolean saveDefaultConfig(String name) {
		customConfig cc = getConfigFromName(name);
		if(cc != null) {
			if (cc.getConfig() == null) {
		        cc.setFile(new File(plugin.getDataFolder(), cc.getName()+".yml"));
		    }
		    if (!cc.getFile().exists()) {
		         this.plugin.saveResource(cc.getName()+".yml", false);
		     }
		    return true;
		} else {
			return false;
		}
	}
	/**
	 * Checks if theres a config by that name
	 * @param String - Name of config you wish to find
	 * @return boolean - True if there is a config by that name. False otherwise
	 */
	public boolean configByName(String name) {
		for(customConfig cc:fileStorage){
			if(cc.getName() == name) {
				return true;
			}
		}
		return false;
	}
	/**
	 * Gets the config from a name
	 * @param String - Name of config you wish to find
	 * @return customConfig - The Config || returns null if no config by that name
	 */
	public customConfig getConfigFromName(String Name) {
		for(customConfig cc:fileStorage){
			if(cc.getName() == Name) {
				return cc;
			}
		}
		return null;
	}
	/**
	 * Reload all Configs, except default bukkit config
	 */
	public void reloadAllConfigs() {
		for(customConfig cc:fileStorage) {
			this.reloadCustomConfig(cc.getName());
		}
	}
	private void log(Object o) {
		ConsoleCommandSender console = plugin.getServer().getConsoleSender();
		console.sendMessage(o+"");
	}
}


text:
layout: post
title:  "This is a post!"
date:   2017-04-03
author: Marianna Brady
---

Hello.

[Facebook is a website](http://facebook.com).


text:
ifconfig
/bin/bash


text:
package com.example.ubuntu.activitylifecycletest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        setContentView(R.layout.activity_main);
        if(savedInstanceState != null){
            String tempData = savedInstanceState.getString("data_key");
            Log.d(TAG, tempData);
        }
        Button startNormalActivity = (Button)findViewById(R.id.start_normal_activity);
        Button startDialogActivity = (Button)findViewById(R.id.start_dialog_activity);
        startNormalActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,NormalActivity.class);
                startActivity(intent);
            }
        });
        startDialogActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,DialogActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        String tempData = "Something you just typed";
        outState.putString("data_key",tempData);
    }
}


text:
CMAKE_PROJECT_VERSION
---------------------

The version of the top level project.

This variable holds the version of the project as specified in the top
level CMakeLists.txt file by a :command:`project` command.  In the event that
the top level CMakeLists.txt contains multiple :command:`project` calls,
the most recently called one from that top level CMakeLists.txt will determine
the value that ``CMAKE_PROJECT_VERSION`` contains.  For example, consider
the following top level CMakeLists.txt:

.. code-block:: cmake

  cmake_minimum_required(VERSION 3.0)
  project(First VERSION 1.2.3)
  project(Second VERSION 3.4.5)
  add_subdirectory(sub)
  project(Third VERSION 6.7.8)

And ``sub/CMakeLists.txt`` with the following contents:

.. code-block:: cmake

  project(SubProj VERSION 1)
  message("CMAKE_PROJECT_VERSION = ${CMAKE_PROJECT_VERSION}")

The most recently seen :command:`project` command from the top level
CMakeLists.txt would be ``project(Second ...)``, so this will print::

  CMAKE_PROJECT_VERSION = 3.4.5

To obtain the version from the most recent call to :command:`project` in
the current directory scope or above, see the :variable:`PROJECT_VERSION`
variable.


text:
from cli import verify
from cli import verify_within
import cli

# -----------------------------------------------------------------------------------------------------------------------
# Test description: forming a Thread network

test_name = __file__[:-3] if __file__.endswith('.py') else __file__
print('-' * 120)
print('Starting \'{}\''.format(test_name))

# -----------------------------------------------------------------------------------------------------------------------
# Creating `Nodes` instances

speedup = 4
cli.Node.set_time_speedup_factor(speedup)

node = cli.Node()

# -----------------------------------------------------------------------------------------------------------------------
# Test implementation

WAIT_TIME = 5

verify(node.get_state() == 'disabled')
node.form('test')

verify(node.get_network_name() == 'test')

node.interface_down()
verify(node.get_state() == 'disabled')

node.form('form-test',
          channel=21,
          panid=0x5678,
          xpanid='1020031510006016',
          network_key='0123456789abcdeffecdba9876543210')

verify(node.get_network_name() == 'form-test')
verify(node.get_channel() == '21')
verify(node.get_panid() == '0x5678')
verify(node.get_ext_panid() == '1020031510006016')
verify(node.get_network_key() == '0123456789abcdeffecdba9876543210')

# -----------------------------------------------------------------------------------------------------------------------
# Test finished

cli.Node.finalize_all_nodes()

print('\'{}\' passed.'.format(test_name))


text:
package com.facebook.buck.cxx;

import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.model.Flavored;
import com.facebook.buck.model.MacroException;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.ImplicitDepsInferringDescription;
import com.facebook.buck.rules.ImplicitFlavorsInferringDescription;
import com.facebook.buck.rules.MetadataProvidingDescription;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.versions.VersionRoot;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;

import java.util.Optional;
import java.util.Set;

public class CxxBinaryDescription implements
    Description<CxxBinaryDescription.Arg>,
    Flavored,
    ImplicitDepsInferringDescription<CxxBinaryDescription.Arg>,
    ImplicitFlavorsInferringDescription,
    MetadataProvidingDescription<CxxBinaryDescription.Arg>,
    VersionRoot<CxxBinaryDescription.Arg> {

  private final CxxBuckConfig cxxBuckConfig;
  private final InferBuckConfig inferBuckConfig;
  private final CxxPlatform defaultCxxPlatform;
  private final FlavorDomain<CxxPlatform> cxxPlatforms;

  public CxxBinaryDescription(
      CxxBuckConfig cxxBuckConfig,
      InferBuckConfig inferBuckConfig,
      CxxPlatform defaultCxxPlatform,
      FlavorDomain<CxxPlatform> cxxPlatforms) {
    this.cxxBuckConfig = cxxBuckConfig;
    this.inferBuckConfig = inferBuckConfig;
    this.defaultCxxPlatform = defaultCxxPlatform;
    this.cxxPlatforms = cxxPlatforms;
  }

  /**
   * @return a {@link com.facebook.buck.cxx.HeaderSymlinkTree} for the headers of this C/C++ binary.
   */
  public static <A extends Arg> HeaderSymlinkTree createHeaderSymlinkTreeBuildRule(
      BuildRuleParams params,
      BuildRuleResolver resolver,
      CxxPlatform cxxPlatform,
      A args) {
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
    return CxxDescriptionEnhancer.createHeaderSymlinkTree(
        params,
        resolver,
        pathResolver,
        cxxPlatform,
        CxxDescriptionEnhancer.parseHeaders(
            params.getBuildTarget(),
            pathResolver,
            Optional.of(cxxPlatform),
            args),
        HeaderVisibility.PRIVATE,
        true);
  }

  @Override
  public Arg createUnpopulatedConstructorArg() {
    return new Arg();
  }

  @SuppressWarnings("PMD.PrematureDeclaration")
  @Override
  public <A extends Arg> BuildRule createBuildRule(
      TargetGraph targetGraph,
      BuildRuleParams params,
      BuildRuleResolver resolver,
      A args) throws NoSuchBuildTargetException {

    // We explicitly remove some flavors below from params to make sure rule
    // has the same output regardless if we will strip or not.
    Optional<StripStyle> flavoredStripStyle =
        StripStyle.FLAVOR_DOMAIN.getValue(params.getBuildTarget());
    Optional<LinkerMapMode> flavoredLinkerMapMode =
        LinkerMapMode.FLAVOR_DOMAIN.getValue(params.getBuildTarget());
    params = CxxStrip.removeStripStyleFlavorInParams(params, flavoredStripStyle);
    params = LinkerMapMode.removeLinkerMapModeFlavorInParams(params, flavoredLinkerMapMode);

    // Extract the platform from the flavor, falling back to the default platform if none are
    // found.
    ImmutableSet<Flavor> flavors = ImmutableSet.copyOf(params.getBuildTarget().getFlavors());
    CxxPlatform cxxPlatform = cxxPlatforms
        .getValue(flavors).orElse(defaultCxxPlatform);
    if (flavors.contains(CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR)) {
      flavors = ImmutableSet.copyOf(
          Sets.difference(
              flavors,
              ImmutableSet.of(CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR)));
      BuildTarget target = BuildTarget
          .builder(params.getBuildTarget().getUnflavoredBuildTarget())
          .addAllFlavors(flavors)
          .build();
      BuildRuleParams typeParams =
          params.copyWithChanges(
              target,
              params.getDeclaredDeps(),
              params.getExtraDeps());

      return createHeaderSymlinkTreeBuildRule(
          typeParams,
          resolver,
          cxxPlatform,
          args);
    }

    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);

    if (flavors.contains(CxxCompilationDatabase.COMPILATION_DATABASE)) {
      BuildRuleParams paramsWithoutFlavor =
          params.withoutFlavor(CxxCompilationDatabase.COMPILATION_DATABASE);
      CxxLinkAndCompileRules cxxLinkAndCompileRules = CxxDescriptionEnhancer
          .createBuildRulesForCxxBinaryDescriptionArg(
              paramsWithoutFlavor,
              resolver,
              cxxBuckConfig,
              cxxPlatform,
              args,
              flavoredStripStyle,
              flavoredLinkerMapMode);
      return CxxCompilationDatabase.createCompilationDatabase(
          params,
          pathResolver,
          cxxLinkAndCompileRules.compileRules,
          CxxDescriptionEnhancer.requireTransitiveCompilationDatabaseHeaderSymlinkTreeDeps(
              paramsWithoutFlavor,
              resolver,
              pathResolver,
              cxxPlatform,
              args));
    }

    if (flavors.contains(CxxCompilationDatabase.UBER_COMPILATION_DATABASE)) {
      return CxxDescriptionEnhancer.createUberCompilationDatabase(
          cxxPlatforms.getValue(flavors).isPresent() ?
              params :
              params.withFlavor(defaultCxxPlatform.getFlavor()),
          resolver);
    }

    if (flavors.contains(CxxInferEnhancer.InferFlavors.INFER.get())) {
      return CxxInferEnhancer.requireInferAnalyzeAndReportBuildRuleForCxxDescriptionArg(
          params,
          resolver,
          pathResolver,
          cxxBuckConfig,
          cxxPlatform,
          args,
          inferBuckConfig,
          new CxxInferSourceFilter(inferBuckConfig));
    }

    if (flavors.contains(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get())) {
      return CxxInferEnhancer.requireInferAnalyzeBuildRuleForCxxDescriptionArg(
          params,
          resolver,
          pathResolver,
          cxxBuckConfig,
          cxxPlatform,
          args,
          inferBuckConfig,
          new CxxInferSourceFilter(inferBuckConfig));
    }

    if (flavors.contains(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.get())) {
      return CxxInferEnhancer.requireAllTransitiveCaptureBuildRules(
          params,
          resolver,
          cxxBuckConfig,
          cxxPlatform,
          inferBuckConfig,
          new CxxInferSourceFilter(inferBuckConfig),
          args);
    }

    if (flavors.contains(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ONLY.get())) {
      return CxxInferEnhancer.requireInferCaptureAggregatorBuildRuleForCxxDescriptionArg(
          params,
          resolver,
          pathResolver,
          cxxBuckConfig,
          cxxPlatform,
          args,
          inferBuckConfig,
          new CxxInferSourceFilter(inferBuckConfig));
    }

    if (flavors.contains(CxxDescriptionEnhancer.SANDBOX_TREE_FLAVOR)) {
      return CxxDescriptionEnhancer.createSandboxTreeBuildRule(
          resolver,
          args,
          cxxPlatform,
          params);
    }

    CxxLinkAndCompileRules cxxLinkAndCompileRules =
        CxxDescriptionEnhancer.createBuildRulesForCxxBinaryDescriptionArg(
            params,
            resolver,
            cxxBuckConfig,
            cxxPlatform,
            args,
            flavoredStripStyle,
            flavoredLinkerMapMode);

    // Return a CxxBinary rule as our representative in the action graph, rather than the CxxLink
    // rule above for a couple reasons:
    //  1) CxxBinary extends BinaryBuildRule whereas CxxLink does not, so the former can be used
    //     as executables for genrules.
    //  2) In some cases, users add dependencies from some rules onto other binary rules, typically
    //     if the binary is executed by some test or library code at test time.  These target graph
    //     deps should *not* become build time dependencies on the CxxLink step, otherwise we'd
    //     have to wait for the dependency binary to link before we could link the dependent binary.
    //     By using another BuildRule, we can keep the original target graph dependency tree while
    //     preventing it from affecting link parallelism.

    params = CxxStrip.restoreStripStyleFlavorInParams(params, flavoredStripStyle);
    params = LinkerMapMode.restoreLinkerMapModeFlavorInParams(params, flavoredLinkerMapMode);
    CxxBinary cxxBinary = new CxxBinary(
        params.appendExtraDeps(cxxLinkAndCompileRules.executable.getDeps(ruleFinder)),
        resolver,
        pathResolver,
        ruleFinder,
        cxxLinkAndCompileRules.getBinaryRule(),
        cxxLinkAndCompileRules.executable,
        args.frameworks,
        args.tests,
        params.getBuildTarget().withoutFlavors(cxxPlatforms.getFlavors()));
    resolver.addToIndex(cxxBinary);
    return cxxBinary;
  }

  @Override
  public Iterable<BuildTarget> findDepsForTargetFromConstructorArgs(
      BuildTarget buildTarget,
      CellPathResolver cellRoots,
      Arg constructorArg) {
    return findDepsForTargetFromConstructorArgs(
        buildTarget,
        cellRoots,
        constructorArg.linkerFlags,
        constructorArg.platformLinkerFlags.getValues());
  }

  public Iterable<BuildTarget> findDepsForTargetFromConstructorArgs(
      BuildTarget buildTarget,
      CellPathResolver cellRoots,
      ImmutableList<String> linkerFlags,
      ImmutableList<ImmutableList<String>> platformLinkerFlags) {
    ImmutableSet.Builder<BuildTarget> deps = ImmutableSet.builder();

    // Get any parse time deps from the C/C++ platforms.
    deps.addAll(
        CxxPlatforms.getParseTimeDeps(
            cxxPlatforms
                .getValue(buildTarget.getFlavors()).orElse(defaultCxxPlatform)));

    ImmutableList<ImmutableList<String>> macroStrings =
        ImmutableList.<ImmutableList<String>>builder()
            .add(linkerFlags)
            .addAll(platformLinkerFlags)
            .build();
    for (String macroString : Iterables.concat(macroStrings)) {
      try {
        deps.addAll(
            CxxDescriptionEnhancer.MACRO_HANDLER.extractParseTimeDeps(
                buildTarget,
                cellRoots,
                macroString));
      } catch (MacroException e) {
        throw new HumanReadableException(e, "%s: %s", buildTarget, e.getMessage());
      }
    }

    return deps.build();
  }

  @Override
  public Optional<ImmutableSet<FlavorDomain<?>>> flavorDomains() {
    return
        Optional.of(
            ImmutableSet.of(
                // Missing: CXX Compilation Database
                // Missing: CXX Description Enhancer
                // Missing: CXX Infer Enhancer
                cxxPlatforms,
                LinkerMapMode.FLAVOR_DOMAIN,
                StripStyle.FLAVOR_DOMAIN
            )
        );
  }

  @Override
  public boolean hasFlavors(ImmutableSet<Flavor> inputFlavors) {
    Set<Flavor> flavors = inputFlavors;

    Set<Flavor> platformFlavors = Sets.intersection(flavors, cxxPlatforms.getFlavors());
    if (platformFlavors.size() > 1) {
      return false;
    }
    flavors = Sets.difference(flavors, platformFlavors);

    flavors = Sets.difference(
        flavors,
        ImmutableSet.of(
            CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR,
            CxxCompilationDatabase.COMPILATION_DATABASE,
            CxxCompilationDatabase.UBER_COMPILATION_DATABASE,
            CxxInferEnhancer.InferFlavors.INFER.get(),
            CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get(),
            CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.get(),
            StripStyle.ALL_SYMBOLS.getFlavor(),
            StripStyle.DEBUGGING_SYMBOLS.getFlavor(),
            StripStyle.NON_GLOBAL_SYMBOLS.getFlavor(),
            LinkerMapMode.NO_LINKER_MAP.getFlavor()));

    return flavors.isEmpty();
  }

  public FlavorDomain<CxxPlatform> getCxxPlatforms() {
    return cxxPlatforms;
  }

  public CxxPlatform getDefaultCxxPlatform() {
    return defaultCxxPlatform;
  }

  @Override
  public <A extends Arg, U> Optional<U> createMetadata(
      BuildTarget buildTarget,
      BuildRuleResolver resolver,
      A args,
      final Class<U> metadataClass) throws NoSuchBuildTargetException {
    if (!metadataClass.isAssignableFrom(CxxCompilationDatabaseDependencies.class) ||
        !buildTarget.getFlavors().contains(CxxCompilationDatabase.COMPILATION_DATABASE)) {
      return Optional.empty();
    }
    return CxxDescriptionEnhancer
        .createCompilationDatabaseDependencies(buildTarget, cxxPlatforms, resolver, args).map(
            metadataClass::cast);
  }

  @Override
  public ImmutableSortedSet<Flavor> addImplicitFlavors(
      ImmutableSortedSet<Flavor> argDefaultFlavors) {
    return addImplicitFlavorsForRuleTypes(argDefaultFlavors, Description.getBuildRuleType(this));
  }

  public ImmutableSortedSet<Flavor> addImplicitFlavorsForRuleTypes(
      ImmutableSortedSet<Flavor> argDefaultFlavors,
      BuildRuleType... types) {
    Optional<Flavor> platformFlavor = getCxxPlatforms().getFlavor(argDefaultFlavors);

    for (BuildRuleType type : types) {
      ImmutableMap<String, Flavor> libraryDefaults =
          cxxBuckConfig.getDefaultFlavorsForRuleType(type);

      if (!platformFlavor.isPresent()) {
        platformFlavor = Optional.ofNullable(
            libraryDefaults.get(CxxBuckConfig.DEFAULT_FLAVOR_PLATFORM));
      }
    }

    if (platformFlavor.isPresent()) {
      return ImmutableSortedSet.of(platformFlavor.get());
    } else {
      // To avoid changing the output path of binaries built without a flavor,
      // we'll default to no flavor, which implicitly builds the default platform.
      return ImmutableSortedSet.of();
    }
  }

  @Override
  public boolean isVersionRoot(ImmutableSet<Flavor> flavors) {
    return true;
  }

  @SuppressFieldNotInitialized
  public static class Arg extends LinkableCxxConstructorArg {
  }

}


text:
namespace {

const int kStayOpenTimeMS = 100;
const int kOpenTimeMS = 100;
const int kAnimationDurationMS = (kOpenTimeMS * 2) + kStayOpenTimeMS;
const int kImageSize = 15;
const SkColor kTestColor = SkColorSetRGB(64, 64, 64);
const int kNumberOfSteps = 300;

class TestIconLabelBubbleView : public IconLabelBubbleView {
 public:
  enum State {
    GROWING,
    STEADY,
    SHRINKING,
  };

  explicit TestIconLabelBubbleView(const gfx::FontList& font_list)
      : IconLabelBubbleView(font_list, false), value_(0) {
    GetImageView()->SetImageSize(gfx::Size(kImageSize, kImageSize));
    SetLabel(base::ASCIIToUTF16("Label"));
  }

  void SetCurrentAnimationValue(int value) {
    value_ = value;
    SizeToPreferredSize();
  }

  int width() const { return bounds().width(); }
  bool IsLabelVisible() const { return label()->visible(); }
  void SetLabelVisible(bool visible) { label()->SetVisible(visible); }
  const gfx::Rect& GetLabelBounds() const { return label()->bounds(); }

  State state() const {
    const double kOpenFraction =
        static_cast<double>(kOpenTimeMS) / kAnimationDurationMS;
    double state = value_ / (double)kNumberOfSteps;
    if (state < kOpenFraction)
      return GROWING;
    if (state > (1.0 - kOpenFraction))
      return SHRINKING;
    return STEADY;
  }

 protected:
  // IconLabelBubbleView:
  SkColor GetTextColor() const override { return kTestColor; }

  bool ShouldShowLabel() const override {
    return !IsShrinking() ||
           (width() > (image()->GetPreferredSize().width() +
                       2 * GetLayoutConstant(LOCATION_BAR_HORIZONTAL_PADDING)));
  }

  double WidthMultiplier() const override {
    const double kOpenFraction =
        static_cast<double>(kOpenTimeMS) / kAnimationDurationMS;
    double fraction = value_ / (double)kNumberOfSteps;
    switch (state()) {
      case GROWING:
        return fraction / kOpenFraction;
      case STEADY:
        return 1.0;
      case SHRINKING:
        return (1.0 - fraction) / kOpenFraction;
    }
    NOTREACHED();
    return 1.0;
  }

  bool IsShrinking() const override { return state() == SHRINKING; }

 private:
  int value_;
  DISALLOW_COPY_AND_ASSIGN(TestIconLabelBubbleView);
};

}  // namespace

class IconLabelBubbleViewTest : public views::ViewsTestBase {
 public:
  IconLabelBubbleViewTest()
      : views::ViewsTestBase(),
        steady_reached_(false),
        shrinking_reached_(false),
        minimum_size_reached_(false),
        previous_width_(0),
        initial_image_x_(0) {}
  ~IconLabelBubbleViewTest() override {}

 protected:
  // views::ViewsTestBase:
  void SetUp() override {
    views::ViewsTestBase::SetUp();
    gfx::FontList font_list;
    view_.reset(new TestIconLabelBubbleView(font_list));
  }

  void VerifyWithAnimationStep(int step) {
    Reset();
    for (int value = 0; value < kNumberOfSteps; value += step) {
      SetValue(value);
      VerifyAnimationStep();
    }
    view_->SetLabelVisible(false);
  }

 private:
  void Reset() {
    view_->SetLabelVisible(true);
    SetValue(0);
    steady_reached_ = false;
    shrinking_reached_ = false;
    minimum_size_reached_ = false;
    previous_width_ = 0;
    initial_image_x_ = GetImageBounds().x();
    EXPECT_NE(0, initial_image_x_);
  }

  void VerifyAnimationStep() {
    switch (state()) {
      case TestIconLabelBubbleView::State::GROWING: {
        EXPECT_GE(width(), previous_width_);
        EXPECT_EQ(initial_image_x_, GetImageBounds().x());
        EXPECT_GE(GetImageBounds().x(), 0);
        if (GetImageBounds().width() > 0)
          EXPECT_LE(GetImageBounds().right(), width());
        EXPECT_TRUE(IsLabelVisible());
        if (GetLabelBounds().width() > 0) {
          EXPECT_GT(GetLabelBounds().x(), GetImageBounds().right());
          EXPECT_LT(GetLabelBounds().right(), width());
        }
        break;
      }
      case TestIconLabelBubbleView::State::STEADY: {
        if (steady_reached_)
          EXPECT_EQ(previous_width_, width());
        EXPECT_EQ(initial_image_x_, GetImageBounds().x());
        EXPECT_GT(GetImageBounds().x(), 0);
        EXPECT_LT(GetImageBounds().right(), width());
        EXPECT_TRUE(IsLabelVisible());
        EXPECT_GT(GetLabelBounds().x(), GetImageBounds().right());
        EXPECT_LT(GetLabelBounds().right(), width());
        steady_reached_ = true;
        break;
      }
      case TestIconLabelBubbleView::State::SHRINKING: {
        if (shrinking_reached_)
          EXPECT_LE(width(), previous_width_);
        if (minimum_size_reached_)
          EXPECT_EQ(previous_width_, width());

        EXPECT_GE(GetImageBounds().x(), 0);
        if (width() <= initial_image_x_ + kImageSize) {
          EXPECT_EQ(width(), GetImageBounds().right());
          EXPECT_EQ(0, GetLabelBounds().width());
        } else {
          EXPECT_EQ(initial_image_x_, GetImageBounds().x());
          EXPECT_LE(GetImageBounds().right(), width());
        }
        if (GetLabelBounds().width() > 0) {
          EXPECT_GT(GetLabelBounds().x(), GetImageBounds().right());
          EXPECT_LT(GetLabelBounds().right(), width());
        }
        shrinking_reached_ = true;
        if (width() == kImageSize)
          minimum_size_reached_ = true;
        break;
      }
    }
    previous_width_ = width();
  }

  void SetValue(int value) { view_->SetCurrentAnimationValue(value); }

  TestIconLabelBubbleView::State state() const { return view_->state(); }

  int width() { return view_->width(); }

  bool IsLabelVisible() { return view_->IsLabelVisible(); }

  const gfx::Rect& GetLabelBounds() const { return view_->GetLabelBounds(); }

  const gfx::Rect& GetImageBounds() const {
    return view_->GetImageView()->bounds();
  }

  std::unique_ptr<TestIconLabelBubbleView> view_;

  bool steady_reached_;
  bool shrinking_reached_;
  bool minimum_size_reached_;
  int previous_width_;
  int initial_image_x_;
};

// Tests layout rules for IconLabelBubbleView while simulating animation.
// The animation is first growing the bubble from zero, then keeping its size
// constant and finally shrinking it down to its minimum size which is the image
// size.
// Various step sizes during animation simulate different possible timing.
TEST_F(IconLabelBubbleViewTest, AnimateLayout) {
  VerifyWithAnimationStep(1);
  VerifyWithAnimationStep(5);
  VerifyWithAnimationStep(10);
  VerifyWithAnimationStep(25);
}

#if defined(USE_ASH)
// Verifies IconLabelBubbleView::GetPreferredSize() doesn't crash when there is
// a widget but no compositor.
using IconLabelBubbleViewCrashTest = views::ViewsTestBase;

TEST_F(IconLabelBubbleViewCrashTest,
       GetPreferredSizeDoesntCrashWhenNoCompositor) {
  gfx::FontList font_list;
  views::Widget::InitParams params =
      CreateParams(views::Widget::InitParams::TYPE_WINDOW);
  params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  views::Widget widget;
  widget.Init(params);
  IconLabelBubbleView* icon_label_bubble_view =
      new TestIconLabelBubbleView(font_list);
  icon_label_bubble_view->SetLabel(base::ASCIIToUTF16("x"));
  widget.GetContentsView()->AddChildView(icon_label_bubble_view);
  aura::Window* widget_native_view = widget.GetNativeView();
  // Remove the window from its parent. This means GetWidget() in
  // IconLabelBubbleView will return non-null, but GetWidget()->GetCompositor()
  // will return null.
  ASSERT_TRUE(widget_native_view->parent());
  widget_native_view->parent()->RemoveChild(widget_native_view);
  static_cast<views::View*>(icon_label_bubble_view)->GetPreferredSize();
}
#endif


text:
import json

from nose import tools as nt
from django.test import RequestFactory

from tests.base import AdminTestCase
from osf_tests.factories import (
    AuthUserFactory,
    PreprintProviderFactory,
    PreprintFactory,
    SubjectFactory,
)
from osf.models import PreprintProvider
from admin_tests.utilities import setup_form_view, setup_user_view
from admin.preprint_providers import views
from admin.preprint_providers.forms import PreprintProviderForm
from admin.base.forms import ImportFileForm

class TestPreprintProviderList(AdminTestCase):
    def setUp(self):
        super(TestPreprintProviderList, self).setUp()

        self.provider1 = PreprintProviderFactory()
        self.provider2 = PreprintProviderFactory()

        self.user = AuthUserFactory()

        self.request = RequestFactory().get('/fake_path')
        self.view = views.PreprintProviderList()
        self.view = setup_user_view(self.view, self.request, user=self.user)

    def test_get_list(self, *args, **kwargs):
        res = self.view.get(self.request, *args, **kwargs)
        nt.assert_equal(res.status_code, 200)

    def test_get_queryset(self):
        providers_returned = list(self.view.get_queryset())
        provider_list = [self.provider1, self.provider2]
        nt.assert_items_equal(providers_returned, provider_list)
        nt.assert_is_instance(providers_returned[0], PreprintProvider)

    def test_context_data(self):
        self.view.object_list = self.view.get_queryset()
        res = self.view.get_context_data()
        nt.assert_is_instance(res, dict)
        nt.assert_equal(len(res['preprint_providers']), 2)
        nt.assert_is_instance(res['preprint_providers'][0], PreprintProvider)

class TestPreprintProviderDisplay(AdminTestCase):
    def setUp(self):
        super(TestPreprintProviderDisplay, self).setUp()

        self.user = AuthUserFactory()

        self.preprint_provider = PreprintProviderFactory()

        self.request = RequestFactory().get('/fake_path')
        self.view = views.PreprintProviderDisplay()
        self.view = setup_user_view(self.view, self.request, user=self.user)

        self.view.kwargs = {'preprint_provider_id': self.preprint_provider.id}

    def test_get_object(self):
        obj = self.view.get_object()
        nt.assert_is_instance(obj, PreprintProvider)
        nt.assert_equal(obj.name, self.preprint_provider.name)

    def test_context_data(self):
        res = self.view.get_context_data()
        nt.assert_is_instance(res, dict)
        nt.assert_is_instance(res['preprint_provider'], dict)
        nt.assert_equal(res['preprint_provider']['name'], self.preprint_provider.name)
        nt.assert_is_instance(res['form'], PreprintProviderForm)
        nt.assert_is_instance(res['import_form'], ImportFileForm)

    def test_get(self, *args, **kwargs):
        res = self.view.get(self.request, *args, **kwargs)
        nt.assert_equal(res.status_code, 200)

class TestDeletePreprintProvider(AdminTestCase):
    def setUp(self):
        super(TestDeletePreprintProvider, self).setUp()

        self.user = AuthUserFactory()
        self.preprint_provider = PreprintProviderFactory()

        self.request = RequestFactory().get('/fake_path')
        self.view = views.DeletePreprintProvider()
        self.view = setup_user_view(self.view, self.request, user=self.user)

        self.view.kwargs = {'preprint_provider_id': self.preprint_provider.id}

    def test_cannot_delete_if_preprints_present(self):
        preprint = PreprintFactory()
        self.preprint_provider.preprint_services.add(preprint)
        self.preprint_provider.save()

        redirect = self.view.delete(self.request)
        nt.assert_equal(redirect.url, '/preprint_providers/{}/cannot_delete/'.format(self.preprint_provider.id))
        nt.assert_equal(redirect.status_code, 302)

    def test_delete_provider_with_no_preprints(self):
        redirect = self.view.delete(self.request)
        nt.assert_equal(redirect.url, '/preprint_providers/')
        nt.assert_equal(redirect.status_code, 302)

    def test_get_with_no_preprints(self):
        res = self.view.get(self.request)
        nt.assert_equal(res.status_code, 200)

    def test_cannot_get_if_preprints_present(self):
        preprint = PreprintFactory()
        self.preprint_provider.preprint_services.add(preprint)
        self.preprint_provider.save()

        redirect = self.view.get(self.request)
        nt.assert_equal(redirect.url, '/preprint_providers/{}/cannot_delete/'.format(self.preprint_provider.id))
        nt.assert_equal(redirect.status_code, 302)

class TestPreprintProviderChangeForm(AdminTestCase):
    def setUp(self):
        super(TestPreprintProviderChangeForm, self).setUp()

        self.user = AuthUserFactory()
        self.preprint_provider = PreprintProviderFactory()

        self.request = RequestFactory().get('/fake_path')
        self.request.user = self.user
        self.view = views.PreprintProviderChangeForm()
        self.view = setup_form_view(self.view, self.request, form=PreprintProviderForm())

        self.parent_1 = SubjectFactory()
        self.child_1 = SubjectFactory(parent=self.parent_1)
        self.child_2 = SubjectFactory(parent=self.parent_1)
        self.grandchild_1 = SubjectFactory(parent=self.child_1)

        self.view.kwargs = {'preprint_provider_id': self.preprint_provider.id}

    def test_get_context_data(self):
        self.view.object = self.preprint_provider
        res = self.view.get_context_data()
        nt.assert_is_instance(res, dict)
        nt.assert_is_instance(res['import_form'], ImportFileForm)

    def test_preprint_provider_form(self):
        formatted_rule = [[[self.parent_1._id], True]]

        new_data = {
            'name': 'New Name',
            'subjects_chosen': '{}, {}, {}, {}'.format(
                self.parent_1.id, self.child_1.id, self.child_2.id, self.grandchild_1.id
            ),
            'toplevel_subjects': [self.parent_1.id],
            'subjects_acceptable': '[]',
            '_id': 'newname'
        }
        form = PreprintProviderForm(data=new_data)
        nt.assert_true(form.is_valid())

        new_provider = form.save()
        nt.assert_equal(new_provider.name, new_data['name'])
        nt.assert_equal(new_provider.subjects_acceptable, formatted_rule)

class TestPreprintProviderExport(AdminTestCase):
    def setUp(self):
        super(TestPreprintProviderExport, self).setUp()

        self.user = AuthUserFactory()
        self.preprint_provider = PreprintProviderFactory()

        self.request = RequestFactory().get('/fake_path')
        self.view = views.ExportPreprintProvider()
        self.view = setup_user_view(self.view, self.request, user=self.user)

        self.view.kwargs = {'preprint_provider_id': self.preprint_provider.id}

    def test_post(self):
        res = self.view.get(self.request)
        content_dict = json.loads(res.content)
        nt.assert_equal(content_dict['model'], 'osf.preprintprovider')
        nt.assert_equal(content_dict['fields']['name'], self.preprint_provider.name)
        nt.assert_equal(res.__getitem__('content-type'), 'text/json')

    def test_certain_fields_not_included(self):
        res = self.view.get(self.request)
        content_dict = json.loads(res.content)
        for field in views.FIELDS_TO_NOT_IMPORT_EXPORT:
            nt.assert_not_in(field, content_dict['fields'].keys())

class TestCreatePreprintProvider(AdminTestCase):
    def setUp(self):
        super(TestCreatePreprintProvider, self).setUp()

        self.user = AuthUserFactory()
        self.preprint_provider = PreprintProviderFactory()

        self.request = RequestFactory().get('/fake_path')
        self.request.user = self.user
        self.view = views.CreatePreprintProvider()
        self.view = setup_form_view(self.view, self.request, form=PreprintProviderForm())

        self.view.kwargs = {'preprint_provider_id': self.preprint_provider.id}

    def test_get_context_data(self):
        self.view.object = self.preprint_provider
        res = self.view.get_context_data()
        nt.assert_is_instance(res, dict)
        nt.assert_is_instance(res['import_form'], ImportFileForm)

    def test_get_view(self):
        res = self.view.get(self.request)
        nt.assert_equal(res.status_code, 200)

class TestGetSubjectDescendants(AdminTestCase):
    def setUp(self):
        super(TestGetSubjectDescendants, self).setUp()

        self.user = AuthUserFactory()
        self.preprint_provider = PreprintProviderFactory()

        self.parent_1 = SubjectFactory()
        self.child_1 = SubjectFactory(parent=self.parent_1)
        self.child_2 = SubjectFactory(parent=self.parent_1)
        self.grandchild_1 = SubjectFactory(parent=self.child_1)

        self.request = RequestFactory().get('/?parent_id={}'.format(self.parent_1.id))
        self.view = views.GetSubjectDescendants()
        self.view = setup_user_view(self.view, self.request, user=self.user)

    def test_get_subject_descendants(self):
        res = self.view.get(self.request)
        nt.assert_equal(res.status_code, 200)
        nt.assert_equal(res.__getitem__('content-type'), 'application/json')

        content_dict = json.loads(res.content)
        nt.assert_items_equal(
            content_dict['all_descendants'],
            [self.child_1.id, self.child_2.id, self.grandchild_1.id]
        )


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

<title>MetadataPrefix</title>
<meta name="date" content="2014-10-30">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

org.grants.harvesters.pmh

Enum MetadataPrefix

java.lang.Object

java.lang.Enum<MetadataPrefix>

org.grants.harvesters.pmh.MetadataPrefix

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<MetadataPrefix>

public enum MetadataPrefix
extends java.lang.Enum<MetadataPrefix>

Enum with all supported metadata prefixes

Author:

Dmitrij Kudriavcev, dmitrij@kudriavcev.info

Enum Constant Summary

Enum Constants

Enum Constant and Description

marcxml

mets

oai_dc

ore

rdf

rif

Method Summary

Methods

Modifier and Type
Method and Description

static MetadataPrefix
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static MetadataPrefix[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

compareTo, equals, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

rif

public static final MetadataPrefix rif

marcxml

public static final MetadataPrefix marcxml

oai_dc

public static final MetadataPrefix oai_dc

rdf

public static final MetadataPrefix rdf

ore

public static final MetadataPrefix ore

mets

public static final MetadataPrefix mets

Method Detail

values

public static MetadataPrefix[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (MetadataPrefix c : MetadataPrefix.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static MetadataPrefix valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method


text:
package k8s

// Endpoints is a collection of endpoints that implement the actual service.  Example:
//   Name: "mysvc",
//   Subsets: [
//     {
//       Addresses: [{"ip": "10.10.1.1"}, {"ip": "10.10.2.2"}],
//       Ports: [{"name": "a", "port": 8675}, {"name": "b", "port": 309}]
//     },
//     {
//       Addresses: [{"ip": "10.10.3.3"}],
//       Ports: [{"name": "a", "port": 93}, {"name": "b", "port": 76}]
//     },
//  ]
type Endpoints struct {
	TypeMeta   `json:",inline"`
	ObjectMeta `json:"metadata,omitempty"`

	// The set of all endpoints is the union of all subsets.
	Subsets []EndpointSubset
}

// EndpointSubset is a group of addresses with a common set of ports.  The
// expanded set of endpoints is the Cartesian product of Addresses x Ports.
// For example, given:
//   {
//     Addresses: [{"ip": "10.10.1.1"}, {"ip": "10.10.2.2"}],
//     Ports:     [{"name": "a", "port": 8675}, {"name": "b", "port": 309}]
//   }
// The resulting set of endpoints can be viewed as:
//     a: [ 10.10.1.1:8675, 10.10.2.2:8675 ],
//     b: [ 10.10.1.1:309, 10.10.2.2:309 ]
type EndpointSubset struct {
	Addresses         []EndpointAddress
	NotReadyAddresses []EndpointAddress
	Ports             []EndpointPort
}

// EndpointAddress is a tuple that describes single IP address.
type EndpointAddress struct {
	// The IP of this endpoint.
	// IPv6 is also accepted but not fully supported on all platforms. Also, certain
	// kubernetes components, like kube-proxy, are not IPv6 ready.
	// TODO: This should allow hostname or IP, see #4447.
	IP string
	// Optional: Hostname of this endpoint
	// Meant to be used by DNS servers etc.
	Hostname string `json:"hostname,omitempty"`
	// Optional: The kubernetes object related to the entry point.
	TargetRef *ObjectReference
}

// EndpointPort is a tuple that describes a single port.
type EndpointPort struct {
	// The name of this port (corresponds to ServicePort.Name).  Optional
	// if only one port is defined.  Must be a DNS_LABEL.
	Name string

	// The port number.
	Port int32

	// The IP protocol for this port.
	Protocol Protocol
}

// ObjectReference contains enough information to let you inspect or modify the referred object.
type ObjectReference struct {
	Kind            string `json:"kind,omitempty"`
	Namespace       string `json:"namespace,omitempty"`
	Name            string `json:"name,omitempty"`
	UID             UID    `json:"uid,omitempty"`
	APIVersion      string `json:"apiVersion,omitempty"`
	ResourceVersion string `json:"resourceVersion,omitempty"`

	// Optional. If referring to a piece of an object instead of an entire object, this string
	// should contain information to identify the sub-object. For example, if the object
	// reference is to a container within a pod, this would take on a value like:
	// "spec.containers{name}" (where "name" refers to the name of the container that triggered
	// the event) or if no container name is specified "spec.containers[2]" (container with
	// index 2 in this pod). This syntax is chosen only to have some well-defined way of
	// referencing a part of an object.
	// TODO: this design is not final and this field is subject to change in the future.
	FieldPath string `json:"fieldPath,omitempty"`
}


text:
Real world TypeScript implementation of the builder pattern for building a complex http request object that provides the client with a fluent API.

If you wanted to use it inside of an Angular directive like I am in a real project...

```typescript
scope: {},
        link: function (scope:ISidebarScope) {

            scope.Utils = Utils;
            var myRequest = new scope.Utils.RequestBuilder("get").setScheme("http").setPath("mypath").setHost("localhost").setPort("9999").build();

            console.log("My Request: " + myRequest.toString());

            var a = <HTMLAnchorElement> document.getElementById("aOutput");
            a.href = myRequest.toString();
```


text:
using BeaverLeague.Data.Queries;
using Microsoft.EntityFrameworkCore;

namespace BeaverLeague.Data.Services
{
    public class LeagueData
    {
        private readonly LeagueDbContext db;

        public LeagueData(LeagueDbContext db)
        {
            this.db = db;
        }

        public TResult Execute<TSet, TResult>(IQuery<TSet, TResult> query) where TSet : class
        {
            if (query is null) throw new System.ArgumentNullException(nameof(query));

            var set = db.Set<TSet>();
            return query.Execute(set);
        }

        public void Add(object entity)
        {
            db.Add(entity);
        }

        public void Update(object entity)
        {
            var entityState = db.Entry(entity);
            entityState.State = EntityState.Modified;
        }

        public void Add(params object[] entities)
        {
            foreach(var entity in entities)
            {
                Add(entity);
            }
        }

        public int Commit()
        {
            return db.SaveChanges();
        }
    }
}


text:
export interface Theme {
  getColor():string;
}


text:
\SetAPI{J-C}
\section{database.autocleanup.recyclebin}
\label{configuration:DatabaseAutocleanupRecyclebin}
\ClearAPI
Whether the recyclebin contents should be removed during startup in databases which support them (e.g. Oracle 10g/11g). The recycle bin is conrains dropped objects or tables, from where they can be restored (undropped) or finally deleted. Valid values are "true" and "false".
%% GENERATED USAGE REFERENCE - DO NOT EDIT
\begin{longtable}{ l l } \hline \textbf{Used in bean} & \textbf{Module} \
	\endhead
	\hline
		\type{com.koch.ambeth.persistence.oracle.Oracle10gThinDialect} &
		\prettyref{module:Persistence} \\
	\hline
		\type{com.koch.ambeth.persistence.oracle.Oracle10gThinDialect} &
		\prettyref{module:Persistence} \\
	\hline
\end{longtable}
%% GENERATED USAGE REFERENCE END
\type{com.koch.ambeth.persistence.jdbc.config.PersistenceJdbcConfigurationConstants.DatabaseAutoCleanupRecycleBin}
\begin{lstlisting}[style=Props,caption={Usage example for \textit{database.autocleanup.recyclebin}}]
database.autocleanup.recyclebin=false
\end{lstlisting}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Class Hierarchy (Lightity 0.5 API)
</TITLE>

<META NAME="date" CONTENT="2011-03-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For All Packages

Package Hierarchies:
com.googlecode.lightity, com.googlecode.lightity.filter

Class Hierarchy

java.lang.Object

com.googlecode.lightity.EntityFactory
com.googlecode.lightity.EntityListFactory
com.googlecode.lightity.EntityPropertyFactory
com.googlecode.lightity.filter.Filters
com.googlecode.lightity.ForwardingEntity (implements com.googlecode.lightity.Entity)

com.googlecode.lightity.ForwardingEntityProperty<T> (implements com.googlecode.lightity.EntityProperty<T>)

com.googlecode.lightity.DateProperty
com.googlecode.lightity.NumberProperty<T>
com.googlecode.lightity.StringProperty

java.lang.Throwable (implements java.io.Serializable)

java.lang.Exception

java.lang.RuntimeException

com.googlecode.lightity.NoSuchEntityPropertyException

Interface Hierarchy

com.googlecode.lightity.EntityList.Each
com.googlecode.lightity.EntityList.Filter
com.googlecode.lightity.EntityProperty<T>
java.lang.Iterable<T>

java.util.Collection<E>

com.googlecode.lightity.EntityList
java.util.List<E>

com.googlecode.lightity.EntityList

com.googlecode.lightity.Entity
com.googlecode.lightity.EntityList
java.util.List<E>

com.googlecode.lightity.EntityList

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2011. All Rights Reserved.


text:
SET PAGESIZE 0
SET FEEDBACK OFF
SET VERIFY OFF

SPOOL temp.sql

SELECT 'ANALYZE TABLE "' || table_name || '" COMPUTE STATISTICS;'
FROM   all_tables
WHERE  owner = Upper('&1')
ORDER BY 1;

SPOOL OFF

-- Comment out following line to prevent immediate run
@temp.sql

SET PAGESIZE 14
SET FEEDBACK ON
SET VERIFY ON


text:
package com.facebook.watchman;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import com.facebook.watchman.bser.BserDeserializer;
import com.facebook.watchman.bser.BserSerializer;

import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.google.common.collect.Queues;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.immutables.value.Value;

public class WatchmanConnection {

  private final ListeningExecutorService outgoingMessageExecutor;
  private final ExecutorService incomingMessageExecutor;
  private final Supplier<Map<String, Object>> inputMessageSupplier;
  private final Optional<Socket> socket;
  private final OutputStream outputStream;
  private final Optional<Callback> unilateralCallback;
  private final Optional<Collection<String>> unilateralLabels;
  private final BlockingQueue<QueuedCommand> commandQueue;
  private final AtomicBoolean processing;
  private final BserSerializer bserSerializer;
  private final Optional<WatchmanCommandListener> commandListener;

  public WatchmanConnection(Socket socket) throws IOException {
    this(
        inputSupplierFromSocket(socket),
        socket.getOutputStream(),
        Optional.<Collection<String>>absent(),
        Optional.<Callback>absent(),
        Optional.<WatchmanCommandListener>absent(),
        Optional.<Socket>of(socket));
  }

  public WatchmanConnection(
      final Socket socket,
      Optional<Collection<String>> unilateralLabels,
      Optional<Callback> unilateralCallback) throws IOException {
    this(
        inputSupplierFromSocket(socket),
        socket.getOutputStream(),
        unilateralLabels,
        unilateralCallback,
        Optional.<WatchmanCommandListener>absent(),
        Optional.<Socket>of(socket));
  }

  public WatchmanConnection(
      final Socket socket,
      Optional<Collection<String>> unilateralLabels,
      Optional<Callback> unilateralCallback,
      Optional<WatchmanCommandListener> commandListener) throws IOException {
    this(
        inputSupplierFromSocket(socket),
        socket.getOutputStream(),
        unilateralLabels,
        unilateralCallback,
        commandListener,
        Optional.<Socket>of(socket));
  }

  public WatchmanConnection(
      Supplier<Map<String, Object>> inputStream,
      OutputStream outputStream) {
    this(
        inputStream,
        outputStream,
        Optional.<Collection<String>>absent(),
        Optional.<Callback>absent(),
        Optional.<WatchmanCommandListener>absent(),
        Optional.<Socket>absent());
  }

  public WatchmanConnection(
      Supplier<Map<String, Object>> inputStream,
      OutputStream outputStream,
      Optional<WatchmanCommandListener> commandListener) {
    this(
        inputStream,
        outputStream,
        Optional.<Collection<String>>absent(),
        Optional.<Callback>absent(),
        commandListener,
        Optional.<Socket>absent());
  }

  public WatchmanConnection(
      Supplier<Map<String, Object>> inputStream,
      OutputStream outputStream,
      Optional<Collection<String>> unilateralLabels,
      Optional<Callback> unilateralCallback) {
    this(
        inputStream,
        outputStream,
        unilateralLabels,
        unilateralCallback,
        Optional.<WatchmanCommandListener>absent(),
        Optional.<Socket>absent());
  }

  public WatchmanConnection(
      Supplier<Map<String, Object>> inputStream,
      OutputStream outputStream,
      Optional<Collection<String>> unilateralLabels,
      Optional<Callback> unilateralCallback,
      Optional<WatchmanCommandListener> commandListener,
      Optional<Socket> optionalSocket) {
    this.inputMessageSupplier = inputStream;
    this.outputStream = outputStream;
    this.unilateralLabels = unilateralLabels;
    this.unilateralCallback = unilateralCallback;
    this.socket = optionalSocket;
    this.processing = new AtomicBoolean(true);
    this.outgoingMessageExecutor = MoreExecutors.listeningDecorator(
        Executors.newSingleThreadExecutor(
            new ThreadFactoryBuilder()
                .setNameFormat("[watchman] Outgoing Message Executor")
                .build()));
    this.commandQueue = Queues.newLinkedBlockingDeque();
    this.bserSerializer = new BserSerializer();
    this.commandListener = commandListener;
    this.incomingMessageExecutor = Executors.newSingleThreadExecutor(
        new ThreadFactoryBuilder()
            .setNameFormat("[watchman] Incoming Message Executor")
            .build());
  }

  private boolean checkMessageUnilateral(Map<String, Object> response) {
    if (! unilateralLabels.isPresent()) return false;
    for (String label: unilateralLabels.get()) {
      if (response.containsKey(label)) return true;
    }
    return false;
  }

  public ListenableFuture<Map<String, Object>> run(final Object command) {
    if (! processing.get()) {
      SettableFuture<Map<String, Object>> die = SettableFuture.create();
      die.setException(new WatchmanException("connection closing down"));
      return die;
    }
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Map<String, Object>> resultRef =
        new AtomicReference<Map<String, Object>>();
    final AtomicReference<Exception> errorRef = new AtomicReference<Exception>();
    QueuedCommand queuedCommand = new QueuedCommandBuilder()
        .command(command)
        .latch(latch)
        .resultRef(resultRef)
        .errorRef(errorRef)
        .build();
    commandQueue.add(queuedCommand);
    return outgoingMessageExecutor.submit(new Callable<Map<String, Object>>() {
      @Override
      public Map<String, Object> call() throws Exception {
        if (commandListener.isPresent()) {
          commandListener.get().onStart();
        }
        if (processing.get()) {
          bserSerializer.serializeToStream(
              command,
              outputStream);
        }
        if (commandListener.isPresent()) {
          commandListener.get().onSent();
        }
        latch.await();
        if (commandListener.isPresent()) {
          commandListener.get().onReceived();
        }
        if (resultRef.get() != null) return resultRef.get();
        throw errorRef.get();
      }
    });
  }

  private void failAllCommands(Exception e) {
    processing.set(false);
    for (QueuedCommand command: commandQueue) {
      command.errorRef().set(e);
      command.latch().countDown();
    }
  }

  public void close() throws IOException {
    failAllCommands(new WatchmanException("connection closing down"));
    outputStream.close();
    incomingMessageExecutor.shutdown();
    outgoingMessageExecutor.shutdown();

    if (socket.isPresent()) {
      socket.get().close();
    }
  }

  public void start() {
    this.incomingMessageExecutor.execute(new IncomingMessageThread());
  }

  private class IncomingMessageThread implements Runnable {

    @Override
    public void run() {
      while (processing.get()) {
        try {
          Map<String, Object> deserializedResponse = inputMessageSupplier.get();
          if (deserializedResponse == null) continue;

          if (checkMessageUnilateral(deserializedResponse)) {
            if (unilateralCallback.isPresent()) {
              unilateralCallback.get().call(deserializedResponse);
            } else {
              failAllCommands(
                  new Exception("Received unilateral message without any callback registered"));
              return;
            }
            continue;
          }

          QueuedCommand lastCommand = commandQueue.take();
          if (deserializedResponse.containsKey("error")) {
            lastCommand.errorRef().set(new WatchmanException(
                String.valueOf(deserializedResponse.get("error")),
                deserializedResponse));
          } else {
            lastCommand.resultRef().set(deserializedResponse);
          }
          lastCommand.latch().countDown();
        } catch (Exception e) {
          failAllCommands(e);
          return;
        }
      }
    }
  }

  @Value.Immutable
  @Value.Style(visibility = Value.Style.ImplementationVisibility.PRIVATE)
  interface QueuedCommand {
    Object command();
    CountDownLatch latch();
    AtomicReference<Map<String, Object>> resultRef();
    AtomicReference<Exception> errorRef();
  }

  /**
   * Permits the synchronization of test classes with the thread sending messages. If the
   * WatchmanConnection has a WatchmanCommandListener attached, it will make sure that the methods
   * will be called:
   *

   *
onStart: when the thread picks up the command

   *
onSent: when the serialization to the OutputStream is done

   *
onReceived: when a response from Watchman is received

   *

   */
  public interface WatchmanCommandListener {
    void onStart();
    void onSent();
    void onReceived();
  }

  private static SerializedStreamMessageSupplier inputSupplierFromSocket(Socket socket)
      throws IOException {
    return new SerializedStreamMessageSupplier(
        socket.getInputStream(),
        new BserDeserializer(BserDeserializer.KeyOrdering.UNSORTED));
  }
}