text:
PLOTTER='matplotlib'
#PLOTTER='gnuplot'

COLORS = {"broken": "#FF3F3F",
          "good": "#7FFF7F",
          "---": "#CFCFCF",
          "test": "#FFFF7F",
          "missing1": "#FFFF7F",
          "missing2": "#FFFF7F",
          "failed": "#FF3F3F",
          "succeeded": "#7FFF7F",
          "NIY": "#CFCFCF",
          "undefined": "#CFCFCF",
          "default": "#FFFFFF",
          True:"#FFFFFF",
          False:"#FF3F3F"}

# The format of simulators is a dict of dictionaries.
# The keys are the simulator identification's name. This is a unique
# name that is displayed as headline in the index table.
# The simulator references the simulator type required by the parttest.
# The command tells how to invoke it and the spice file syntax
# The values are either full paths or just the executable that is in
# the PATH.
# The command can contain spaces to facilitate the use of wrapper scripts
# e.g. '/usr/local/bin/spice-wrapper gnucap'
# The folder value defines the storage of the result files
# e.g. [PARTNAME]/[folder]/index.html
SIMULATORS = {
    'ngspice_25': {'simulator':'ngspice',
                   'command': 'ngspice',
                   'options': '-r X -b',  ## -r X suppresses the "no plot" error
                   'folder': 'ng25'},
    'gnucap_0.35': {'simulator':'gnucap',
                    'command': '/usr/bin/gnucap',
                    'options': '-b',
                    'folder': 'gc0.35'}
    }


text:
class RedactorRailsDocumentUploader < CarrierWave::Uploader::Base
  include RedactorRails::Backend::CarrierWave

  use_file = Rails.env.test? || Rails.env.development?
  storage use_file ? :file : :fog

  def store_dir
    "system/redactor_assets/documents/#{model.id}"
  end

  def extension_white_list
    RedactorRails.document_file_types
  end
end

redpajama_set_name: RedPajamaGithub


text:
package unstructured_test

import (
	"math/rand"
	"reflect"
	"testing"

	"github.com/stretchr/testify/assert"

	"k8s.io/apimachinery/pkg/api/apitesting/fuzzer"
	"k8s.io/apimachinery/pkg/api/equality"
	metafuzzer "k8s.io/apimachinery/pkg/apis/meta/fuzzer"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	"k8s.io/apimachinery/pkg/util/diff"
)

func TestNilUnstructuredContent(t *testing.T) {
	var u unstructured.Unstructured
	uCopy := u.DeepCopy()
	content := u.UnstructuredContent()
	expContent := make(map[string]interface{})
	assert.EqualValues(t, expContent, content)
	assert.Equal(t, uCopy, &u)
}

// TestUnstructuredMetadataRoundTrip checks that metadata accessors
// correctly set the metadata for unstructured objects.
// First, it fuzzes an empty ObjectMeta and sets this value as the metadata for an unstructured object.
// Next, it uses metadata accessor methods to set these fuzzed values to another unstructured object.
// Finally, it checks that both the unstructured objects are equal.
func TestUnstructuredMetadataRoundTrip(t *testing.T) {
	scheme := runtime.NewScheme()
	codecs := serializer.NewCodecFactory(scheme)
	seed := rand.Int63()
	fuzzer := fuzzer.FuzzerFor(metafuzzer.Funcs, rand.NewSource(seed), codecs)

	N := 1000
	for i := 0; i < N; i++ {
		u := &unstructured.Unstructured{Object: map[string]interface{}{}}
		uCopy := u.DeepCopy()
		metadata := &metav1.ObjectMeta{}
		fuzzer.Fuzz(metadata)

		if err := setObjectMeta(u, metadata); err != nil {
			t.Fatalf("unexpected error setting fuzzed ObjectMeta: %v", err)
		}
		setObjectMetaUsingAccessors(u, uCopy)

		// TODO: remove this special casing when creationTimestamp becomes a pointer.
		// Right now, creationTimestamp is a struct (metav1.Time) so omitempty holds no meaning for it.
		// However, the current behaviour is to remove the field if it holds an empty struct.
		// This special casing exists here because custom marshallers for metav1.Time marshal
		// an empty value to "null", which gets converted to nil when converting to an unstructured map by "ToUnstructured".
		if err := unstructured.SetNestedField(uCopy.UnstructuredContent(), nil, "metadata", "creationTimestamp"); err != nil {
			t.Fatalf("unexpected error setting creationTimestamp as nil: %v", err)
		}

		if !equality.Semantic.DeepEqual(u, uCopy) {
			t.Errorf("diff: %v", diff.ObjectReflectDiff(u, uCopy))
		}
	}
}

// TestUnstructuredMetadataOmitempty checks that ObjectMeta omitempty
// semantics are enforced for unstructured objects.
// The fuzzing test above should catch these cases but this is here just to be safe.
// Example: the metadata.clusterName field has the omitempty json tag
// so if it is set to it's zero value (""), it should be removed from the metadata map.
func TestUnstructuredMetadataOmitempty(t *testing.T) {
	scheme := runtime.NewScheme()
	codecs := serializer.NewCodecFactory(scheme)
	seed := rand.Int63()
	fuzzer := fuzzer.FuzzerFor(metafuzzer.Funcs, rand.NewSource(seed), codecs)

	// fuzz to make sure we don't miss any function calls below
	u := &unstructured.Unstructured{Object: map[string]interface{}{}}
	metadata := &metav1.ObjectMeta{}
	fuzzer.Fuzz(metadata)
	if err := setObjectMeta(u, metadata); err != nil {
		t.Fatalf("unexpected error setting fuzzed ObjectMeta: %v", err)
	}

	// set zero values for all fields in metadata explicitly
	// to check that omitempty fields having zero values are never set
	u.SetName("")
	u.SetGenerateName("")
	u.SetNamespace("")
	u.SetSelfLink("")
	u.SetUID("")
	u.SetResourceVersion("")
	u.SetGeneration(0)
	u.SetCreationTimestamp(metav1.Time{})
	u.SetDeletionTimestamp(nil)
	u.SetDeletionGracePeriodSeconds(nil)
	u.SetLabels(nil)
	u.SetAnnotations(nil)
	u.SetOwnerReferences(nil)
	u.SetInitializers(nil)
	u.SetFinalizers(nil)
	u.SetClusterName("")

	gotMetadata, _, err := unstructured.NestedFieldNoCopy(u.UnstructuredContent(), "metadata")
	if err != nil {
		t.Error(err)
	}
	emptyMetadata := make(map[string]interface{})

	if !reflect.DeepEqual(gotMetadata, emptyMetadata) {
		t.Errorf("expected %v, got %v", emptyMetadata, gotMetadata)
	}
}

func setObjectMeta(u *unstructured.Unstructured, objectMeta *metav1.ObjectMeta) error {
	if objectMeta == nil {
		unstructured.RemoveNestedField(u.UnstructuredContent(), "metadata")
		return nil
	}
	metadata, err := runtime.DefaultUnstructuredConverter.ToUnstructured(objectMeta)
	if err != nil {
		return err
	}
	u.UnstructuredContent()["metadata"] = metadata
	return nil
}

func setObjectMetaUsingAccessors(u, uCopy *unstructured.Unstructured) {
	uCopy.SetName(u.GetName())
	uCopy.SetGenerateName(u.GetGenerateName())
	uCopy.SetNamespace(u.GetNamespace())
	uCopy.SetSelfLink(u.GetSelfLink())
	uCopy.SetUID(u.GetUID())
	uCopy.SetResourceVersion(u.GetResourceVersion())
	uCopy.SetGeneration(u.GetGeneration())
	uCopy.SetCreationTimestamp(u.GetCreationTimestamp())
	uCopy.SetDeletionTimestamp(u.GetDeletionTimestamp())
	uCopy.SetDeletionGracePeriodSeconds(u.GetDeletionGracePeriodSeconds())
	uCopy.SetLabels(u.GetLabels())
	uCopy.SetAnnotations(u.GetAnnotations())
	uCopy.SetOwnerReferences(u.GetOwnerReferences())
	uCopy.SetInitializers(u.GetInitializers())
	uCopy.SetFinalizers(u.GetFinalizers())
	uCopy.SetClusterName(u.GetClusterName())
}


text:
package cherry.foundation.db.gen.query;

import static com.mysema.query.types.PathMetadataFactory.*;

import com.mysema.query.types.path.*;

import com.mysema.query.types.PathMetadata;
import javax.annotation.Generated;
import com.mysema.query.types.Path;

import com.mysema.query.sql.ColumnMetadata;
import java.sql.Types;

/**
 * QVerifyFlag is a Querydsl query type for BVerifyFlag
 */
@Generated("com.mysema.query.sql.codegen.MetaDataSerializer")
public class QVerifyFlag extends com.mysema.query.sql.RelationalPathBase<BVerifyFlag> {

    private static final long serialVersionUID = -715695175;

    public static final QVerifyFlag verifyFlag = new QVerifyFlag("VERIFY_FLAG");

    public final NumberPath<Integer> deletedFlg = createNumber("deletedFlg", Integer.class);

    public final NumberPath<Integer> flagCode = createNumber("flagCode", Integer.class);

    public final NumberPath<Long> id = createNumber("id", Long.class);

    public final com.mysema.query.sql.PrimaryKey<BVerifyFlag> verifyFlagPkc = createPrimaryKey(id);

    public QVerifyFlag(String variable) {
        super(BVerifyFlag.class, forVariable(variable), "PUBLIC", "VERIFY_FLAG");
        addMetadata();
    }

    public QVerifyFlag(String variable, String schema, String table) {
        super(BVerifyFlag.class, forVariable(variable), schema, table);
        addMetadata();
    }

    public QVerifyFlag(Path<? extends BVerifyFlag> path) {
        super(path.getType(), path.getMetadata(), "PUBLIC", "VERIFY_FLAG");
        addMetadata();
    }

    public QVerifyFlag(PathMetadata<?> metadata) {
        super(BVerifyFlag.class, metadata, "PUBLIC", "VERIFY_FLAG");
        addMetadata();
    }

    public void addMetadata() {
        addMetadata(deletedFlg, ColumnMetadata.named("DELETED_FLG").withIndex(3).ofType(Types.INTEGER).withSize(10));
        addMetadata(flagCode, ColumnMetadata.named("FLAG_CODE").withIndex(2).ofType(Types.INTEGER).withSize(10));
        addMetadata(id, ColumnMetadata.named("ID").withIndex(1).ofType(Types.BIGINT).withSize(19).notNull());
    }

}


text:
// +build !linux,!windows

package cm

import (
	"fmt"

	"k8s.io/api/core/v1"
	"k8s.io/client-go/tools/record"
	"k8s.io/kubernetes/pkg/kubelet/cadvisor"
	kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
	"k8s.io/kubernetes/pkg/util/mount"
)

type unsupportedContainerManager struct {
}

var _ ContainerManager = &unsupportedContainerManager{}

func (unsupportedContainerManager) Start(_ *v1.Node, _ ActivePodsFunc) error {
	return fmt.Errorf("Container Manager is unsupported in this build")
}

func (unsupportedContainerManager) SystemCgroupsLimit() v1.ResourceList {
	return v1.ResourceList{}
}

func (unsupportedContainerManager) GetNodeConfig() NodeConfig {
	return NodeConfig{}
}

func (unsupportedContainerManager) GetMountedSubsystems() *CgroupSubsystems {
	return &CgroupSubsystems{}
}

func (unsupportedContainerManager) GetQOSContainersInfo() QOSContainersInfo {
	return QOSContainersInfo{}
}

func (unsupportedContainerManager) UpdateQOSCgroups() error {
	return nil
}

func (cm *unsupportedContainerManager) Status() Status {
	return Status{}
}

func (cm *unsupportedContainerManager) GetNodeAllocatableReservation() v1.ResourceList {
	return nil
}

func (cm *unsupportedContainerManager) GetCapacity() v1.ResourceList {
	return nil
}

func (cm *unsupportedContainerManager) NewPodContainerManager() PodContainerManager {
	return &unsupportedPodContainerManager{}
}

func (cm *unsupportedContainerManager) GetResources(pod *v1.Pod, container *v1.Container, activePods []*v1.Pod) (*kubecontainer.RunContainerOptions, error) {
	return &kubecontainer.RunContainerOptions{}, nil
}

func NewContainerManager(_ mount.Interface, _ cadvisor.Interface, _ NodeConfig, failSwapOn bool, devicePluginEnabled bool, recorder record.EventRecorder) (ContainerManager, error) {
	return &unsupportedContainerManager{}, nil
}


text:
@implementation WMCommentSectionHeaderView

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
        self.textLabel.textColor = [UIColor darkGrayColor];

        //        UISwitch *s = [[UISwitch alloc] init];
        //        s.xmg_x = 200;
        //        [self.contentView addSubview:s];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    // 在layoutSubviews方法中覆盖对子控件的一些设置
    self.textLabel.font = [UIFont systemFontOfSize:15];

    // 设置label的x值
    self.textLabel.wm_x = 5;
}

@end


text:
package com.badlogic.sol.command;

import com.badlogic.sol.Command;
import com.badlogic.sol.Game;

public class Remove implements Command {
	String name;

	public Remove(String name) {
		this.name = name;
	}

	@Override
	public void update (float delta) {
		Game.ctx.removeDrawable(name);
	}

	@Override
	public boolean isDone () {
		return true;
	}

	@Override
	public Command copy () {
		return this;
	}
}


text:
<?php

Yii::import('bootstrap.widgets.BootWidget');

/**
 * Bootstrap alert widget.
 * @todo Fix event support. http://twitter.github.com/bootstrap/javascript.html#alerts
 */
class BootAlert extends BootWidget
{
	/**
	 * @var array the keys for which to get flash messages.
	 */
	public $keys = array('success', 'info', 'warning', 'error', /* or */'danger');
	/**
	 * @var string the template to use for displaying flash messages.
	 */
	public $template = '
×{message}
';
	/**
	 * @var array the html options.
	 */
	public $htmlOptions = array();

	/**
	 * Initializes the widget.
	 */
	public function init()
	{
		parent::init();

		Yii::app()->bootstrap->registerAlert();

		if (!isset($this->htmlOptions['id']))
			$this->htmlOptions['id'] = $this->getId();
	}

	/**
	 * Runs the widget.
	 */
	public function run()
	{
		if (is_string($this->keys))
			$this->keys = array($this->keys);

		echo CHtml::openTag('div', $this->htmlOptions);

		$transitions = Yii::app()->bootstrap->isPluginRegistered(Bootstrap::PLUGIN_TRANSITION);

		foreach ($this->keys as $key)
		{
			if (Yii::app()->user->hasFlash($key))
			{
				echo strtr($this->template, array(
					'{class}'=>$transitions ? ' fade in' : '',
					'{key}'=>$key,
					'{message}'=>Yii::app()->user->getFlash($key),
				));
			}
		}

		echo '
';

		$selector = "#{$this->id} .alert";
		Yii::app()->clientScript->registerScript(__CLASS__.'#'.$this->id, "jQuery('{$selector}').alert();");

		/*
		// Register the "close" event-handler.
		if (isset($this->events['close']))
		{
			$fn = CJavaScript::encode($this->events['close']);
			Yii::app()->clientScript->registerScript(__CLASS__.'#'.$this->id.'.close', "jQuery('{$selector}').bind('close', {$fn});");
		}

		// Register the "closed" event-handler.
		if (isset($this->events['closed']))
		{
			$fn = CJavaScript::encode($this->events['closed']);
			Yii::app()->clientScript->registerScript(__CLASS__.'#'.$this->id.'.closed', "jQuery('{$selector}').bind('closed', {$fn});");
		}
		*/
	}
}


text:
const stylelint = require('stylelint')
const path = require('path')
const slash = require('slash')

const processor = path.join(__dirname, '../src/index.js')
const rules = {
  'block-no-empty': true,
  'declaration-block-no-duplicate-properties': true,
  'no-duplicate-selectors': true,
  indentation: 2
}

describe('interpolation-tagging', () => {
  let fixture
  let data

  beforeEach(done => {
    stylelint
      .lint({
        files: [fixture],
        config: {
          processors: [processor],
          rules
        }
      })
      .then(result => {
        data = result
        done()
      })
      .catch(err => {
        data = err
        done()
      })
  })

  describe('valid', () => {
    beforeAll(() => {
      fixture = slash(path.join(__dirname, './fixtures/interpolation-tagging/valid.js'))
    })

    it('should have one result', () => {
      expect(data.results.length).toEqual(1)
    })

    it('should use the right file', () => {
      expect(slash(data.results[0].source)).toEqual(fixture)
    })

    it('should not have errored', () => {
      expect(data.errored).toEqual(false)
    })

    it('should not have any warnings', () => {
      expect(data.results[0].warnings.length).toEqual(0)
    })
  })

  describe('invalid tag', () => {
    beforeAll(() => {
      fixture = slash(path.join(__dirname, './fixtures/interpolation-tagging/invalid-tag.js'))
    })

    it('should return error', () => {
      expect(data.errored).toEqual(true)
    })

    it('should have exactly one warning', () => {
      expect(data.results[0].warnings.length).toBe(1)
    })

    it('should throw correct error', () => {
      const warning = data.results[0].warnings[0]
      expect(warning.line).toBe(5)
      expect(warning.column).toBe(4)
      expect(warning.severity).toBe('error')
      expect(warning.text).toMatch(/Styled Components.*invalid sc- tag/)
    })
  })

  describe('invalid custom tag', () => {
    beforeAll(() => {
      fixture = slash(path.join(__dirname, './fixtures/interpolation-tagging/invalid-custom.js'))
    })

    it('should return error', () => {
      expect(data.errored).toEqual(true)
    })

    it('should have exactly one warning', () => {
      expect(data.results[0].warnings.length).toBe(1)
    })

    it('should throw correct error', () => {
      const warning = data.results[0].warnings[0]
      expect(warning.line).toBe(5)
      expect(warning.column).toBe(4)
      expect(warning.severity).toBe('error')
      expect(warning.text).toMatch(/We were unable to parse.*Styled Components/)
    })
  })
})


text:
/*

205. Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters.
No two characters may map to the same character but a character may map to itself.

For example,
Given "egg", "add", return true.

Given "foo", "bar", return false.

Given "paper", "title", return true.

Note:
You may assume both s and t have the same length.

*/

class Solution {

public:

    bool isIsomorphic(string s, string t) {
        if (s.size() != t.size())
            return false;

        // 127 is the size of ASCII
	    vector<char> mapStoT(127, 0);
	    vector<char> mapTtoS(127, 0);

    	for (int i = 0; i < s.size(); ++i)
    	{
    		char s_char = s[i], t_char = t[i];
    		if (mapStoT[s[i]] == 0 && mapTtoS[t[i]] == 0)
    		{
    			mapStoT[s[i]] = t[i];
    			mapTtoS[t[i]] = s[i];
    		}
    		else if (mapTtoS[t[i]] != s[i] || mapStoT[s[i]] != t[i])
    			return false;
    	}
    	return true;
    }
};


text:
<?php

namespace WebLoader\Nette;

use Nette\Configurator;
use Nette\DI\Compiler;
use Nette\DI\CompilerExtension;
use Nette\DI\Config\Helpers;
use Nette\DI\ContainerBuilder;
use Nette\Utils\Finder;
use Nette;
use WebLoader\FileNotFoundException;

/**
 * @author Jan Marek
 */
class Extension extends CompilerExtension
{

	const DEFAULT_TEMP_PATH = 'webtemp';
	const EXTENSION_NAME = 'webloader';

	public function getDefaultConfig()
	{
		return array(
			'jsDefaults' => array(
				'checkLastModified' => TRUE,
				'debug' => FALSE,
				'sourceDir' => '%wwwDir%/js',
				'tempDir' => '%wwwDir%/' . self::DEFAULT_TEMP_PATH,
				'tempPath' => self::DEFAULT_TEMP_PATH,
				'files' => array(),
				'watchFiles' => array(),
				'remoteFiles' => array(),
				'filters' => array(),
				'fileFilters' => array(),
				'joinFiles' => TRUE,
				'namingConvention' => '@' . $this->prefix('jsNamingConvention'),
			),
			'cssDefaults' => array(
				'checkLastModified' => TRUE,
				'debug' => FALSE,
				'sourceDir' => '%wwwDir%/css',
				'tempDir' => '%wwwDir%/' . self::DEFAULT_TEMP_PATH,
				'tempPath' => self::DEFAULT_TEMP_PATH,
				'files' => array(),
				'watchFiles' => array(),
				'remoteFiles' => array(),
				'filters' => array(),
				'fileFilters' => array(),
				'joinFiles' => TRUE,
				'namingConvention' => '@' . $this->prefix('cssNamingConvention'),
			),
			'js' => array(

			),
			'css' => array(

			),
			'debugger' => '%debugMode%'
		);
	}

	public function loadConfiguration()
	{
		$builder = $this->getContainerBuilder();
		$config = $this->getConfig($this->getDefaultConfig());

		$builder->addDefinition($this->prefix('cssNamingConvention'))
			->setFactory('WebLoader\DefaultOutputNamingConvention::createCssConvention');

		$builder->addDefinition($this->prefix('jsNamingConvention'))
			->setFactory('WebLoader\DefaultOutputNamingConvention::createJsConvention');

		if ($config['debugger']) {
			$builder->addDefinition($this->prefix('tracyPanel'))
				->setClass('WebLoader\Nette\Diagnostics\Panel')
				->setArguments(array($builder->expand('%appDir%')));
		}

		$builder->parameters['webloader'] = $config;

		$loaderFactoryTempPaths = array();

		foreach (array('css', 'js') as $type) {
			foreach ($config[$type] as $name => $wlConfig) {
				$wlConfig = Helpers::merge($wlConfig, $config[$type . 'Defaults']);
				$this->addWebLoader($builder, $type . ucfirst($name), $wlConfig);
				$loaderFactoryTempPaths[strtolower($name)] = $wlConfig['tempPath'];

				if (!is_dir($wlConfig['tempDir']) || !is_writable($wlConfig['tempDir'])) {
					throw new CompilationException(sprintf("You must create a writable directory '%s'", $wlConfig['tempDir']));
				}
			}
		}

		$builder->addDefinition($this->prefix('factory'))
			->setClass('WebLoader\Nette\LoaderFactory', array($loaderFactoryTempPaths));
	}

	private function addWebLoader(ContainerBuilder $builder, $name, $config)
	{
		$filesServiceName = $this->prefix($name . 'Files');

		$files = $builder->addDefinition($filesServiceName)
			->setClass('WebLoader\FileCollection')
			->setArguments(array($config['sourceDir']));

		foreach ($this->findFiles($config['files'], $config['sourceDir']) as $file) {
			$files->addSetup('addFile', array($file));
		}

		foreach ($this->findFiles($config['watchFiles'], $config['sourceDir']) as $file) {
			$files->addSetup('addWatchFile', array($file));
		}

		$files->addSetup('addRemoteFiles', array($config['remoteFiles']));

		$compiler = $builder->addDefinition($this->prefix($name . 'Compiler'))
			->setClass('WebLoader\Compiler')
			->setArguments(array(
				'@' . $filesServiceName,
				$config['namingConvention'],
				$config['tempDir'],
			));

		$compiler->addSetup('setJoinFiles', array($config['joinFiles']));

		if ($builder->parameters['webloader']['debugger']) {
			$compiler->addSetup('@' . $this->prefix('tracyPanel') . '::addLoader', array(
				$name,
				'@' . $this->prefix($name . 'Compiler')
			));
		}

		foreach ($config['filters'] as $filter) {
			$compiler->addSetup('addFilter', array($filter));
		}

		foreach ($config['fileFilters'] as $filter) {
			$compiler->addSetup('addFileFilter', array($filter));
		}

		if (isset($config['debug']) && $config['debug']) {
			$compiler->addSetup('enableDebugging');
		}

		$compiler->addSetup('setCheckLastModified', array($config['checkLastModified']));

		// todo css media
	}

	public function afterCompile(Nette\PhpGenerator\ClassType $class)
	{
		$meta = $class->properties['meta'];
		if (array_key_exists('webloader\\nette\\loaderfactory', $meta->value['types'])) {
			$meta->value['types']['webloader\\loaderfactory'] = $meta->value['types']['webloader\\nette\\loaderfactory'];
		}
		if (array_key_exists('WebLoader\\Nette\\LoaderFactory', $meta->value['types'])) {
			$meta->value['types']['WebLoader\\LoaderFactory'] = $meta->value['types']['WebLoader\\Nette\\LoaderFactory'];
		}

		$init = $class->methods['initialize'];
		$init->addBody('if (!class_exists(?, ?)) class_alias(?, ?);', array('WebLoader\\LoaderFactory', FALSE, 'WebLoader\\Nette\\LoaderFactory', 'WebLoader\\LoaderFactory'));
	}

	public function install(Configurator $configurator)
	{
		$self = $this;
		$configurator->onCompile[] = function ($configurator, Compiler $compiler) use ($self) {
			$compiler->addExtension($self::EXTENSION_NAME, $self);
		};
	}

	/**
	 * @param array $filesConfig
	 * @param string $sourceDir
	 * @return array
	 */
	private function findFiles(array $filesConfig, $sourceDir)
	{
		$normalizedFiles = array();

		foreach ($filesConfig as $file) {
			// finder support
			if (is_array($file) && isset($file['files']) && (isset($file['in']) || isset($file['from']))) {
				$finder = Finder::findFiles($file['files']);

				if (isset($file['exclude'])) {
					$finder->exclude($file['exclude']);
				}

				if (isset($file['in'])) {
					$finder->in(is_dir($file['in']) ? $file['in'] : $sourceDir . DIRECTORY_SEPARATOR . $file['in']);
				} else {
					$finder->from(is_dir($file['from']) ? $file['from'] : $sourceDir . DIRECTORY_SEPARATOR . $file['from']);
				}

				$foundFilesList = array();
				foreach ($finder as $foundFile) {
					/** @var \SplFileInfo $foundFile */
					$foundFilesList[] = $foundFile->getPathname();
				}

				natsort($foundFilesList);

				foreach ($foundFilesList as $foundFilePathname) {
					$normalizedFiles[] = $foundFilePathname;
				}

			} else {
				$this->checkFileExists($file, $sourceDir);
				$normalizedFiles[] = $file;
			}
		}

		return $normalizedFiles;
	}

	/**
	 * @param string $file
	 * @param string $sourceDir
	 * @throws FileNotFoundException
	 */
	protected function checkFileExists($file, $sourceDir)
	{
		if (!file_exists($file)) {
			$tmp = rtrim($sourceDir, '/\\') . DIRECTORY_SEPARATOR . $file;
			if (!file_exists($tmp)) {
				throw new FileNotFoundException(sprintf("Neither '%s' or '%s' was found", $file, $tmp));
			}
		}
	}

}


text:
namespace Treenumerable
{
    public partial struct VirtualTree<T>
    {
        /// <summary>
        /// Gets the ancestors, starting with its parent node and ending with the root node.
        /// </summary>
        /// <returns>
        /// An <see cref="Treenumerable.VirtualTreeEnumerable<T&gt"/> that contains all of
        /// the VirtualTree's ancestors, up to and including the root.
        /// </returns>
        public VirtualTreeEnumerable<T> GetAncestors()
        {
            return
                this
                .TreeWalker
                .GetAncestors(this.Root)
                .ToVirtualTrees(this)
                .AsVirtualTreeEnumerable();
        }
    }
}


text:
function Character () {
  this.initialized = false;
  this.color = 0xffffff;
  this.name = '';
}

Character.prototype.init = function (name, color) {
  this.initialized = true;
  this.name = name;
  this.color = color;
};

module.exports = Character;


text:
'use strict';

// The user controller.
var UserController = {
    index: function(req, res) {
        res.status(200).json({ message: 'Welcome to the users area ' + req.user.username + '!' });
    }
};

module.exports = UserController;


text:
<?php
//----------------------------------------------------------------------------------------------------------------------
namespace SetBased\ErdConcepts\Test;

use PHPUnit\Framework\TestCase;
use SetBased\ErdConcepts\MySqlFix;

/**
 * Unit test for class MySqlFix.
 */
class ErdConceptMySQLTest extends TestCase
{
  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Test column comments with quoted identifiers.
   */
  public function testColumns1()
  {
    $source   = file_get_contents(realpath(__DIR__).'/source/quoted/php-erd-concepts-create.ddl');
    $expected = file_get_contents(realpath(__DIR__).'/template/quoted/column.ddl');

    $result = MySqlFix::fixColumnComments($source);
    self::assertEquals($expected, $result);
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Test column comments without quoted identifiers.
   */
  public function testColumns2()
  {
    $source   = file_get_contents(realpath(__DIR__).'/source/unquoted/php-erd-concepts-create.ddl');
    $expected = file_get_contents(realpath(__DIR__).'/template/unquoted/column.ddl');

    $result = MySqlFix::fixColumnComments($source);
    self::assertEquals($expected, $result);
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Test index comments with quoted identifiers.
   */
  public function testIndex1()
  {
    $source   = file_get_contents(realpath(__DIR__).'/source/quoted/php-erd-concepts-create.ddl');
    $expected = file_get_contents(realpath(__DIR__).'/template/quoted/index.ddl');

    $result = MySqlFix::fixIndexComments($source);
    self::assertEquals($expected, $result);
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Test index comments without quoted identifiers.
   */
  public function testIndex2()
  {
    $source   = file_get_contents(realpath(__DIR__).'/source/unquoted/php-erd-concepts-create.ddl');
    $expected = file_get_contents(realpath(__DIR__).'/template/unquoted/index.ddl');

    $result = MySqlFix::fixIndexComments($source);
    self::assertEquals($expected, $result);
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Test table comments with quoted identifiers.
   */
  public function testTables1()
  {
    $source   = file_get_contents(realpath(__DIR__).'/source/quoted/php-erd-concepts-create.ddl');
    $expected = file_get_contents(realpath(__DIR__).'/template/quoted/table.ddl');

    $result = MySqlFix::fixTableComments($source);
    self::assertEquals($expected, $result);
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Test table comments without quoted identifiers.
   */
  public function testTables2()
  {
    $source   = file_get_contents(realpath(__DIR__).'/source/unquoted/php-erd-concepts-create.ddl');
    $expected = file_get_contents(realpath(__DIR__).'/template/unquoted/table.ddl');

    $result = MySqlFix::fixTableComments($source);
    self::assertEquals($expected, $result);
  }

  //--------------------------------------------------------------------------------------------------------------------
}

//----------------------------------------------------------------------------------------------------------------------


text:
require_relative 'query_tracker'

# Tracks a channel and a query on a collection.  Alerts
# the listener when the data in the query changes.
class LiveQuery
  attr_reader :current_ids, :collection, :query

  def initialize(pool, data_store, collection, query)
    @pool = pool
    @collection = collection
    @query = query

    @channels = []
    @data_store = data_store

    @query_tracker = QueryTracker.new(self, @data_store)

    run
  end

  def run(skip_channel = nil)
    @query_tracker.run(skip_channel)
  end

  def notify_removed(ids, skip_channel)
    # puts "Removed: #{ids.inspect}"
    notify! do |channel|
      channel.send_message('removed', nil, @collection, @query, ids)
    end
  end

  def notify_added(index, data, skip_channel)
    # puts "Added: #{index} - #{data.inspect}"
    notify! do |channel|
      channel.send_message('added', nil, @collection, @query, index, data)
    end
  end

  def notify_moved(id, new_position, skip_channel)
    # puts "Moved: #{id}, #{new_position}"
    notify! do |channel|
      channel.send_message('moved', nil, @collection, @query, id, new_position)
    end
  end

  def notify_changed(id, data, skip_channel)
    notify!(skip_channel) do |channel|
      # puts "Changed: #{id}, #{data} to #{channel.inspect}"
      channel.send_message('changed', nil, @collection, @query, id, data)
    end
  end

  # return the query results the first time a channel connects
  def initial_data
    @query_tracker.results.map.with_index do |data, index|
      data = data.dup
      data['_id'] = data['_id'].to_s
      [index, data]
    end
  end

  def add_channel(channel)
    @channels << channel
  end

  def remove_channel(channel)
    @channels.delete(channel)

    # remove this query, no one is listening anymore
    @pool.remove(@collection, @query) if @channels.empty?
  end

  def notify!(skip_channel = nil, only_channel = nil)
    if only_channel
      channels = [only_channel]
    else
      channels = @channels
    end

    channels = channels.reject { |c| c == skip_channel }

    channels.each do |channel|
      yield(channel)
    end
  end
end


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

	public class MessageActivityExecutor<TInstance, TBody> :
		Activity<TInstance>
		where TInstance : class
	{
		readonly ActivityList<TInstance> _activities;
		readonly Event _event;
		readonly EventExceptionHandler<TInstance, TBody> _exceptionHandler;
		readonly State _state;

		public MessageActivityExecutor(State state, Event eevent, EventExceptionHandler<TInstance, TBody> exceptionHandler)
		{
			_exceptionHandler = exceptionHandler;
			_state = state;
			_event = eevent;
			_activities = new ActivityList<TInstance>();
		}

		public void Execute(TInstance instance)
		{
			try
			{
				_activities.Execute(instance);
			}
			catch (Exception innerException)
			{
				string message = "{0} occurred while handling {1} during {2}"
					.FormatWith(innerException.GetType().ToShortTypeName(), _event.Name, _state.Name);

				throw new StateMachineWorkflowException(message, innerException);
			}
		}

		public void Execute<T>(TInstance instance, T bodyT)
		{
			if (typeof(TBody) != typeof(T))
				throw new StateMachineWorkflowException("Body type mismatch for message event: " + Event.Name);

			var body = (TBody)((object)bodyT);

			while (true)
			{
				try
				{
					_activities.Execute(instance, body);
					return;
				}
				catch (Exception ex)
				{
					try
					{
						ExceptionHandlerResult result = _exceptionHandler.Handle(instance, _event, body, ex);
						if (result == ExceptionHandlerResult.Unhandled)
							throw;

						if (result == ExceptionHandlerResult.Return)
							return;
					}
					catch (Exception innerException)
					{
						string message = "{0} occurred while handling {1} during {2}"
							.FormatWith(innerException.GetType().ToShortTypeName(), _event.Name, _state.Name);

						throw new StateMachineWorkflowException(message, innerException);
					}
				}
			}
		}

		public void Accept(StateMachineVisitor visitor)
		{
			_activities.Each(x => x.Accept(visitor));
		}

		public State State
		{
			get { return _state; }
		}

		public Event Event
		{
			get { return _event; }
		}

		public void Add(Activity<TInstance> activity)
		{
			_activities.Add(activity);
		}
	}
}


text:
import * as React from 'react';
import useSiteToken from '../../../../hooks/useSiteToken';
import { COLOR_IMAGES, DEFAULT_COLOR, getClosetColor } from './colorUtil';

export interface BackgroundImageProps {
  colorPrimary?: string;
  isLight?: boolean;
}

export default function BackgroundImage({ colorPrimary, isLight }: BackgroundImageProps) {
  const { token } = useSiteToken();

  const activeColor = React.useMemo(() => getClosetColor(colorPrimary), [colorPrimary]);

  const sharedStyle: React.CSSProperties = {
    transition: `all ${token.motionDurationSlow}`,
    position: 'absolute',
    left: 0,
    top: 0,
    height: '100%',
    width: '100%',
  };

  return (
    <>
      {COLOR_IMAGES.map(({ color, url }) => {
        if (!url) {
          return null;
        }

        return (
          <img
            key={color}
            style={{
              ...sharedStyle,
              opacity: isLight && activeColor === color ? 1 : 0,
              objectFit: 'cover',
              objectPosition: 'right top',
            }}
            src={url}
          />
        );
      })}

      {/* <div
        style={{
          ...sharedStyle,
          opacity: isLight || !activeColor || activeColor === DEFAULT_COLOR ? 0 : 1,
          background: 'rgba(0,0,0,0.79)',
        }}
      /> */}
    </>
  );
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Tagging;

namespace MonoDevelop.AddinMaker.Pads
{
	class ClassificationTagDescriptor : DesignerSupport.CustomDescriptor
	{
		public ClassificationTagDescriptor (IClassificationTag classificationTag)
		{
			ClassificationType = classificationTag.ClassificationType;
		}

		[Category ("Classification")]
		[TypeConverter (typeof (ClassificationTypeConverter))]
		public IClassificationType ClassificationType { get; }
	}

	class ClassificationTypeConverter : TypeConverter
	{
		public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
		{
			return false;
		}

		public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if (destinationType == typeof (string)) {
				return ((IClassificationType)value).Classification;
			}
			return base.ConvertTo (context, culture, value, destinationType);
		}

		public override bool GetPropertiesSupported (ITypeDescriptorContext context)
		{
			return true;
		}

		public override PropertyDescriptorCollection GetProperties (ITypeDescriptorContext context, object value, Attribute [] attributes)
		{
			var props = new List<PropertyDescriptor> ();
			int n = 0;
			foreach (var bt in ((IClassificationType)value).BaseTypes) {
				props.Add (new BaseTypePropertyDescriptor ($"Base{n++}", bt));
			}
			return new PropertyDescriptorCollection (props.ToArray (), true);
		}

		class BaseTypePropertyDescriptor : PropertyDescriptor
		{
			readonly IClassificationType value;

			public BaseTypePropertyDescriptor (string name, IClassificationType value)
				: base (name, new Attribute [] { new TypeConverterAttribute (typeof (ClassificationTypeConverter)) })
			{
				this.value = value;
			}

			public override Type ComponentType => PropertyType;
			public override bool IsReadOnly => true;
			public override Type PropertyType => typeof (IClassificationType);
			public override bool CanResetValue (object component) => false;
			public override object GetValue (object component) => value;
			public override void ResetValue (object component) => throw new NotSupportedException ();
			public override void SetValue (object component, object value) => throw new NotSupportedException ();
			public override bool ShouldSerializeValue (object component) => false;
		}
	}
}


text:
/*
 * sensor.c
 *
 * Created: 11/19/2015 8:59:23 PM
 *  Authors: Bryce Carter, Nigil Lee, Tim Rupprecht
 */

#include "sensor.h"

#include "asf.h"
//#include "tc.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"

#include "ms5607_02ba_dev.h"
// #include "hmc5883l.h"
// #include "fxls8471qr1.h"
// #include "l3g4200d.h"
#include "Si7021-A20.h"
#include "nrf24l01p.h"
#include "hmc5883l.h"
#include "message_types.h"
#include "transceiver.h"
#include "twi_interface.h"

/* Constant Variables */
#define SENSOR_TIMER TCE2

#define SESNORCOLLECTION_100Hz TCC2
#define SESNORCOLLECTION_400Hz TCD2
#define SESNORCOLLECTION_800Hz TCE2

#define EVENT_DATA_SIZE_MAX 25
#define EVENT_QUEUE_DEPTH 8
#define BASE_HERTZ_MODIFIER 40000

enum sensor_queue_state_type {
	SENSOR_ENTRY_50Hz,
	SENSOR_ENTRY_100Hz,
	SENSOR_ENTRY_400Hz,
	SENSOR_ENTRY_800Hz,
	SENSOR_ENTRY_NONE,
	SENSOR_CHECK_TWI_3200Hz
};

typedef struct {
	enum sensor_queue_state_type type;
	uint8_t data[EVENT_DATA_SIZE_MAX];
} sensor_timer_t;

extern twi_interface_t twie;
extern ms5607_02ba_dev_t ms5607_02ba;

static QueueHandle_t sensor_queue;

/* Private Prototypes */
static void sensor_task_loop(void * pvParameters);
static void sensor_initialize(void);
static void startup_timer(void);
// static void send_to_tranceiver(void);

static void protocol_timer_overflow_handler(void);

static inline void add_priority_event(enum sensor_queue_state_type event_type, void *data);

TaskHandle_t sensor_task_handle;
static QueueHandle_t sensor_queue;
sensors_message_t current_sensor_readings;

int8_t get_ms5607_data_countdown = -1; // number of 3.2kHz ticks remaining

void sensor_start_task(void) {
  xTaskCreate(sensor_task_loop, "sensor", 1024, NULL, 2, &sensor_task_handle);
  sensor_queue = xQueueCreate(EVENT_QUEUE_DEPTH, sizeof(sensor_timer_t));
}

/* Private Functions */
static void sensor_task_loop(void * pvParameters)
{
  sensor_timer_t timer_update;
  MS5607_02BA_POLL_MODE_T altimeter_poll_mode = START_UP;

  memset(&current_sensor_readings, 0, sizeof(sensors_message_t));

  // Setup hardware interfaces
  // ============================
  twi_init();
  // ============================

  //Setup sensor drivers
  // ============================
  sensor_initialize();
  startup_timer();
  ms5607_02ba_reset();
  ms5607_02ba_load_prom();

  int temp_debug_variable_breakpoint = 10;

  for(;;) {
	// Wait until a timed event occurs. This is when other tasks get to execute
    xQueueReceive(sensor_queue, &timer_update, portMAX_DELAY);

	// Operate on sensors based on what timed event occurred
    switch(timer_update.type) {
	  case SENSOR_CHECK_TWI_3200Hz:
		  // If the event was a 3.2khz tick, update the get data countdowns
		  if (get_ms5607_data_countdown >= 0)
		  {
			  get_ms5607_data_countdown -= 1;
			  if(get_ms5607_data_countdown == 0)
			  {
				  xQueueSendToBack(twie.twi_todo_queue, &ms5607_02ba.prepareADC, NULL);
				  if (altimeter_poll_mode == PRESSURE || altimeter_poll_mode == START_UP) {
					xQueueSendToBack(twie.twi_todo_queue, &ms5607_02ba.getADC_pressure, NULL);
				  }
				  else {
					  xQueueSendToBack(twie.twi_todo_queue, &ms5607_02ba.getADC_temperature, NULL);
				  }
			  }
		  }
			// Add more countdowns here
		break;
      case SENSOR_ENTRY_800Hz:
		temp_debug_variable_breakpoint += 1;
        break;
	  case SENSOR_ENTRY_400Hz:
		ms5607_02ba_convert_d2();
	  	get_ms5607_data_countdown = 26;
	    break;
      case SENSOR_ENTRY_100Hz:
		    temp_debug_variable_breakpoint += 3;
        //hmc5883l_read_data_single(&magnetometer_data);
        break;
	  case SENSOR_ENTRY_50Hz:
		  Si7021_A20_issue_rh_read_holds();
		  // Si7021_A20_issue_rh_read_noholds();
		  Si7021_A20_receive_rh_read();
      hmc5883l_read_data();
		  break;
	  case SENSOR_ENTRY_NONE:
	    break;
    }
    timer_update.type = SENSOR_ENTRY_NONE;

	ms5607_02ba_fetch_queue_press(&current_sensor_readings);
	ms5607_02ba_fetch_queue_temp(&current_sensor_readings);

    Si7021_A20_fetch_queue_rh(&current_sensor_readings);

    hmc5883l_fetch_queue_data(&current_sensor_readings);

	// send_to_tranceiver();
	twi_process_queue();
  }
}

static void sensor_initialize() {
	ms5607_02ba_init();
	// nrf24l01p_init();
    ms5607_02ba_reset();
    twi_process_queue();
    ms5607_02ba_load_prom();
		Si7021_A20_init();
    // hmc5883l_init();
    // hmc5883l_configure();
    // startup_timer();
}

// NOTE: send_to_transceiver not yet used
// ======================
//static void send_to_tranceiver() {
//	transceiver_message_t created_message;
//
//	// format message from struct based on message
//	created_message = transceiver_message_create(TRANSCEIVER_MSG_TYPE_GENERAL, &current_sensor_readings);
//
//	// transceiver_send_message/transceiver_message_create
//	transceiver_send_message(created_message, 0);
//}

// ================================================================================================
// ======================== Sensor loop timer handling ============================================
// ================================================================================================

static void startup_timer()
{
	tc_enable(&SENSOR_TIMER);
	tc_set_wgm(&SENSOR_TIMER, TC_WG_NORMAL);
	tc_write_period(&SENSOR_TIMER, F_CPU / (32 * BASE_HERTZ_MODIFIER));

	tc_set_overflow_interrupt_callback(&SENSOR_TIMER, protocol_timer_overflow_handler);
	tc_set_overflow_interrupt_level(&SENSOR_TIMER, TC_INT_LVL_LO);

	tc_write_clock_source(&SENSOR_TIMER, TC_CLKSEL_DIV1_gc);
}

static void protocol_timer_overflow_handler() {
	static uint8_t hertz_state = 0;
	static uint8_t fifty_hertz_state = 0;

	if (hertz_state == 0) {
		add_priority_event(SENSOR_ENTRY_100Hz, NULL);
		add_priority_event(SENSOR_ENTRY_400Hz, NULL);
		add_priority_event(SENSOR_ENTRY_800Hz, NULL);
		if (fifty_hertz_state == 0) {
			add_priority_event(SENSOR_ENTRY_50Hz,NULL);
		}
	}
	else if ((hertz_state & 7) == 0) {
		add_priority_event(SENSOR_ENTRY_400Hz, NULL);
	}
	else if ((hertz_state & 3) == 0)
	{
		add_priority_event(SENSOR_ENTRY_800Hz, NULL);
	}
	add_priority_event(SENSOR_CHECK_TWI_3200Hz, NULL);

	if (hertz_state == 31)
	{
		hertz_state = 0;

		if (fifty_hertz_state == 0)
			fifty_hertz_state+=1;
		else
			fifty_hertz_state = 0;
	}
	else{
		hertz_state+=1;
	}
}

// Is the one we need, or the one before this?
//static void protocol_timer_overflow_handler() {
	//static uint8_t hertz_state = 0;
//
	//if (hertz_state == 0) {
		//add_priority_event(SENSOR_ENTRY_100Hz, NULL);
	//}
	//else if (!(hertz_state & 1)) {
		//add_priority_event(SENSOR_ENTRY_400Hz, NULL);
	//}
	//add_priority_event(SENSOR_ENTRY_800Hz, NULL);
//
	//if (hertz_state == 7)
	//{
		//hertz_state = 0;
	//}
	//else{
		//hertz_state+=1;
	//}
//}

static inline void add_priority_event(enum sensor_queue_state_type event_type, void *data) {
	sensor_timer_t event = {
		.type = event_type
	};
	memcpy(event.data, data, EVENT_DATA_SIZE_MAX);
	xQueueSendToFront(sensor_queue, &event, portMAX_DELAY);
};

// ================================================================================================
// ================================================================================================
// ================================================================================================


text:
The Computer Graphics Club is a student organization at San José State University, in San Jose, CA. Formed out of a need to represent students with an interest in computer graphics, the CG Club aims to be an asset to student life by connecting the SJSU community to the CG industry.

See the site live at [sjsucg.org](http://sjsucg.org).

## Installation & Usage
    bundle install
    jekyll serve --watch

_Note: Requires Ruby version 1.9.3 =>. For example use [rbenv](https://github.com/sstephenson/rbenv)_

Run rake task. **NOTE: It will deploy the generated site to _gh-pages_ branch overwriting it**
```
rake site:publish
```

## Authors

Jekyll theme originally built by [sendtoinc.com](https://sendtoinc.com), modified by [Justin Tennant](http://justintennant.me), Karl Lapuz, and Shelley Wu.

## Todo:

+ Fix mobile version
+ Add blog category for `news`, update index to show `news` posts instead of static content


text:
layout: post-index
title: Questions, tips, and topics to consider when building your website
description: "Describe this nonsense."
tags: [web, application, tips, issues, suggestions]
comments: false
image:
  feature: stardust.png
  credit: Atle Mo
  creditlink: http://www.atlemo.com/
---

  {% assign sorted_posts = site.posts | sort:"title" %}
  {% for post in sorted_posts %}

        {% if post.link %}

 {{ post.title }}

        {% else %}

{{ post.title }}

        {% endif %}

          {% if site.reading_time %}

            {% assign readtime = post.content | number_of_words | divided_by:site.words_per_minute %}
            Reading time ~{% if readtime <= 1 %}1 minute{% else %}{{ readtime }} minutes{% endif %}

          {% endif %}

  {% endfor %}


text:
Automation scripts

```

BatchRunGVKI
takes 1 command line argument: the path of the exectables
and reads from stdin the names of the executables to launch.
By running LD_PRELOAD=[path_to_gvki_preload.so] ./automate <PathToExecutables> < input_list.txt
will batch run all the executables in the list and create appropriately named gvki folders.

```


text:
          {{ site.title }}

{{ site.description }}

      Home

      {% comment %}
        The code below dynamically generates a sidebar nav of pages with
        `layout: page` in the front-matter. See readme for usage.
      {% endcomment %}

      {% assign pages_list = site.pages %}
      {% for node in pages_list %}
        {% if node.title != null %}
          {% if node.layout == "page" %}
            {{ node.title }}
          {% endif %}
        {% endif %}
      {% endfor %}

      GitHub
      Currently v{{ site.version }}

Copyright © 2013-{{ site.time | date: '%Y' }}


text:
"""
Tests for ACL. Checks whether certain kinds of requests
are blocked or allowed to be processed.
"""

import mock

# NOTE(deva): import auth_token so we can override a config option
from keystonemiddleware import auth_token  # noqa

from oslo.config import cfg

from ironic.db import api as db_api
from ironic.tests.api import base
from ironic.tests.api import utils
from ironic.tests.db import utils as db_utils

class TestACL(base.FunctionalTest):

    def setUp(self):
        super(TestACL, self).setUp()

        self.environ = {'fake.cache': utils.FakeMemcache()}
        self.fake_db_node = db_utils.get_test_node(chassis_id=None)
        self.dbapi = db_api.get_instance()
        self.node_path = '/nodes/%s' % self.fake_db_node['uuid']

    def get_json(self, path, expect_errors=False, headers=None, q=[], **param):
        return super(TestACL, self).get_json(path,
                                                expect_errors=expect_errors,
                                                headers=headers,
                                                q=q,
                                                extra_environ=self.environ,
                                                **param)

    def _make_app(self):
        cfg.CONF.set_override('cache', 'fake.cache',
                              group='keystone_authtoken')
        return super(TestACL, self)._make_app(enable_acl=True)

    def test_non_authenticated(self):
        response = self.get_json(self.node_path, expect_errors=True)
        self.assertEqual(401, response.status_int)

    def test_authenticated(self):
        with mock.patch.object(self.dbapi, 'get_node_by_uuid',
                               autospec=True) as mock_get_node:
            mock_get_node.return_value = self.fake_db_node

            response = self.get_json(self.node_path,
                                 headers={'X-Auth-Token': utils.ADMIN_TOKEN})

            self.assertEqual(self.fake_db_node['uuid'], response['uuid'])
            mock_get_node.assert_called_once_with(self.fake_db_node['uuid'])

    def test_non_admin(self):
        response = self.get_json(self.node_path,
                                 headers={'X-Auth-Token': utils.MEMBER_TOKEN},
                                 expect_errors=True)

        self.assertEqual(403, response.status_int)

    def test_non_admin_with_admin_header(self):
        response = self.get_json(self.node_path,
                                 headers={'X-Auth-Token': utils.MEMBER_TOKEN,
                                          'X-Roles': 'admin'},
                                 expect_errors=True)

        self.assertEqual(403, response.status_int)

    def test_public_api(self):
        # expect_errors should be set to True: If expect_errors is set to False
        # the response gets converted to JSON and we cannot read the response
        # code so easy.
        for route in ('/', '/v1'):
            response = self.get_json(route,
                                     path_prefix='', expect_errors=True)
            self.assertEqual(200, response.status_int)

    def test_public_api_with_path_extensions(self):
        for route in ('/v1/', '/v1.json', '/v1.xml'):
            response = self.get_json(route,
                                     path_prefix='', expect_errors=True)
            self.assertEqual(200, response.status_int)


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var path_title_component_1 = require('./path-title.component');
var index_pipe_1 = require('./pipes/index.pipe');
var path_service_1 = require('./path/path.service');
var step_row_component_1 = require('./step-row.component');
var PathDetailComponent = (function () {
    function PathDetailComponent(_pathService) {
        this._pathService = _pathService;
        this.stepChunks = [];
    }
    PathDetailComponent.prototype.routerOnActivate = function (curr) {
        var _this = this;
        console.log('id is ' + curr.getParam('id'));
        this._pathService.getPath(curr.getParam('id'))
            .subscribe(function (steps) {
            _this.stepChunks = steps;
            console.log("from dBB", _this.stepChunks);
        });
        //this.path is data to display for the title Jumbotron
        this.path = JSON.parse(localStorage.getItem('path'));
    };
    PathDetailComponent.prototype.ngOnInit = function () {
        var _this = this;
        this._pathService.updatePath.subscribe(function (stepChunks) {
            _this.stepChunks = stepChunks;
        });
    };
    PathDetailComponent.prototype.getChunks = function () {
        //console.log("from here", this.stepChunks);
        return this.stepChunks;
    };
    PathDetailComponent = __decorate([
        core_1.Component({
            selector: 'path-detail',
            templateUrl: 'views/path-grid.component.html',
            styleUrls: ['stylesheets/detail.component.css'],
            pipes: [index_pipe_1.ExcludeFirst],
            directives: [path_title_component_1.PathTitleComponent, step_row_component_1.StepRowComponent],
            encapsulation: core_1.ViewEncapsulation.None
        }),
        __metadata('design:paramtypes', [path_service_1.PathService])
    ], PathDetailComponent);
    return PathDetailComponent;
}());
exports.PathDetailComponent = PathDetailComponent;
//# sourceMappingURL=path-detail.component.js.map


text:
FROM openshift/origin-base

RUN mkdir -p /var/lib/openshift

ADD bin/openshift        /usr/bin/openshift
RUN ln -s /usr/bin/openshift /usr/bin/osc && \
    ln -s /usr/bin/openshift /usr/bin/openshift-deploy && \
    ln -s /usr/bin/openshift /usr/bin/openshift-docker-build && \
    ln -s /usr/bin/openshift /usr/bin/openshift-sti-build && \
    ln -s /usr/bin/openshift /usr/bin/osadm && \
    ln -s /usr/bin/openshift /usr/bin/openshift-router

ENV HOME /root
ENV OPENSHIFTCONFIG /var/lib/openshift/openshift.local.config/master/admin.kubeconfig
WORKDIR /var/lib/openshift
ENTRYPOINT ["/usr/bin/openshift"]


text:
package net.notanothercraft.mintcraft.item;

import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.notanothercraft.mintcraft.MintCraftMod;

import java.util.List;
import java.util.UUID;

/**
 * Created by KJ4IPS on 11/16/2014.
 */
public class ItemKey extends Item implements IUnlocker {

    public ItemKey() {
        super();
        this.setMaxStackSize(4);
        this.setUnlocalizedName("gkey");
        this.setTextureName("mintcraft:goldenkey");
    }

    public void registerRecipies(){
        GameRegistry.addShapedRecipe(new ItemStack(this),
                "i ",
                "p ",
                "pn",
                'i',new ItemStack(Items.gold_ingot),
                'p',new ItemStack(MintCraftMod.instance.itemPin),
                'n',new ItemStack(Items.gold_nugget));
    }

    @Override
    public String getSecret(ItemStack is) {
        return (is.hasTagCompound() && is.getTagCompound().hasKey("bitting")) ? is.getTagCompound().getString("bitting") : null;
    }

    @Override
    public void onCreated(ItemStack stack, World world, EntityPlayer player) {
        super.onCreated(stack, world, player);
        String secret = UUID.randomUUID().toString();
        NBTTagCompound tag = new NBTTagCompound();
        tag.setString("bitting", secret);
        stack.setTagCompound(tag);
    }

    @Override
    public void addInformation(ItemStack stack, EntityPlayer player, List entries, boolean someBoolean) {
        super.addInformation(stack, player, entries, someBoolean);
        if(Minecraft.getMinecraft().gameSettings.advancedItemTooltips){
            entries.add("Bitting: " + (getSecret(stack) != null ? getSecret(stack) : "NONE"));
        }
    }
}


text:
from xpybuild.buildcommon import enableLegacyXpybuildModuleNames
enableLegacyXpybuildModuleNames()

import os, logging
from propertysupport import *
from buildcommon import *
from pathsets import *
from targets.copy import Copy

defineOutputDirProperty('OUTPUT_DIR', None)
defineBooleanProperty('CUSTOM_GLOBAL_EXCLUDES', False)
if getPropertyValue('CUSTOM_GLOBAL_EXCLUDES'):
	def customExcludesFunction(name):
		assert name, name
		assert '\\' not in name, name
		assert '/' not in name.rstrip('/'), name
		return name in ['exclude-file', 'exclude-dir']

	setGlobalOption('FindPaths.globalExcludesFunction', customExcludesFunction)

Copy('${OUTPUT_DIR}/CopyOutput/', FindPaths('${OUTPUT_DIR}/../input/', includes=['**', '**/']))


text:
/**
 * Custom auth system for demostrative purposes.
 *
 * To login, do a GET to /login.  Pass the name query parameter to control your name, or leave blank for anonymous
 * Use /logout to log out
 * All routes will require you to be logged in or else you'll get a 401.
 * @param app
 */
exports.init = function (app) {

    app.get('/login', function (req, res) {
        var username = req.query.name || 'anonymous';
        req.session.auth = {
            id: username
        };
        res.status(200).send('You logged in as ' + username);
    });

    app.get('/logout', function (req, res) {
        var username = 'anonymous';
        if (req.session.auth) {
            username = req.session.auth.id;
        }

        delete req.session.auth;

        res.status(200).send('You logged out as ' + username);
    });
};

exports.authenticate = function (req, res, next) {
    if (req.session.auth) {
        req.user = {
            id: req.session.auth.id
        };
    } else {
        return res.status(401).send('Log in first at /login');
    }
    next();
};


text:
package codeine.model;

public class ExitStatus {
	public final static int SUCCESS = 0;
	public final static int TIMEOUT = -1;
	public final static int INTERRUPTED = -2;
	public final static int EXCEPTION = -3;
	public static final int IO_ERROR = -4;

	public static String fromInt(int exitStatus) {
		switch (exitStatus)	{
		case ExitStatus.TIMEOUT: {
			return "timeout";
		}
		case ExitStatus.INTERRUPTED: {
			return "interrupted";
		}
		case ExitStatus.EXCEPTION: {
			return "internal error";
		}
		case ExitStatus.IO_ERROR: {
			return "IO Error";
		}
		default:
			return "Definition Missing for ExitStatus";
		}
	}
}


text:
package sri.web.examples.styles

object Colors {

  val blue = "#0B8AA9"

  val darkBlue = "#126884"

  val transparent = "transparent"
}


text:
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!

#ifndef V8RelatedEventInit_h
#define V8RelatedEventInit_h

#include "bindings/core/v8/ToV8.h"
#include "bindings/core/v8/V8Binding.h"
#include "core/CoreExport.h"
#include "core/events/RelatedEventInit.h"
#include "platform/heap/Handle.h"

namespace blink {

class ExceptionState;

class V8RelatedEventInit {
public:
    CORE_EXPORT static void toImpl(v8::Isolate*, v8::Local<v8::Value>, RelatedEventInit&, ExceptionState&);
};

v8::Local<v8::Value> toV8(const RelatedEventInit&, v8::Local<v8::Object>, v8::Isolate*);
CORE_EXPORT bool toV8RelatedEventInit(const RelatedEventInit&, v8::Local<v8::Object> dictionary, v8::Local<v8::Object> creationContext, v8::Isolate*);

template<class CallbackInfo>
inline void v8SetReturnValue(const CallbackInfo& callbackInfo, RelatedEventInit& impl)
{
    v8SetReturnValue(callbackInfo, toV8(impl, callbackInfo.Holder(), callbackInfo.GetIsolate()));
}

template <>
struct NativeValueTraits<RelatedEventInit> {
    static RelatedEventInit nativeValue(v8::Isolate*, v8::Local<v8::Value>, ExceptionState&);
};

} // namespace blink

#endif // V8RelatedEventInit_h


text:
@interface MineFavorProductsTopTableViewCell : UITableViewCell
{
    UIView  * _backView;
    UIImageView * _titleImgView;

    CAShapeLayer * _maskLayer;
}

-(void)setCell;

@end


text:
from mockito import mock, verify
from pyfix import test

from helloworld import helloworld

@test
def should_issue_hello_world_message():
    out = mock()

    helloworld(out)

    verify(out).write("Hello world of Python\n")


text:
from argparse import ArgumentParser
import sqlite3

from volttron.platform.agent.utils import parse_timestamp_string, format_timestamp

def main(database_name):
    db = sqlite3.connect(database_name)
    c = db.cursor()
    c.execute("select max(rowid) from data;")
    count = c.fetchone()[0]

    #Batches of 1000
    #We do this because of a bug in the sqlite implementation in python
    #which causes problems with nested cursors.
    for i in xrange(0, count, 1000):
        c.execute("select rowid, ts from data where rowid > ? order by rowid asc limit 1000;", (i,))
        rows = c.fetchall()
        print "processing rowid:", i+1, "to", i+len(rows)

        for rowid, ts in rows:
            #Skip already converted rows.
            if "T" in ts:
                continue

            new_ts = format_timestamp(parse_timestamp_string(ts))
            c.execute("update data set ts = ? where rowid = ?;", (new_ts, rowid))

        db.commit()

if __name__ == "__main__":
    parser = ArgumentParser(description="Update the timestamp format in a Sqlite Historians database in place. "
                            "This script corrects a problem comparing dates introduced by a format change in "
                            "VOLTTRON 4.1. Running this is only needed for SqliteHistorians data created in versions "
                            " of VOLTTRON prior to 4.1. It is recommended that the historian is not running while "
                            "this script is. It is recommended that you backup your database file before running this.")

    parser.add_argument('database',
                        help='The path to the database file.')

    args = parser.parse_args()
    main(args.database)


text:
/**
 *  \file SDL_bits.h
 *
 *  Functions for fiddling with bits and bitmasks.
 */

#ifndef _SDL_bits_h
#define _SDL_bits_h

#include "SDL_stdinc.h"

#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif

/**
 *  \file SDL_bits.h
 */

/**
 *  Get the index of the most significant bit. Result is undefined when called
 *  with 0. This operation can also be stated as "count leading zeroes" and
 *  "log base 2".
 *
 *  \return Index of the most significant bit.
 */
SDL_FORCE_INLINE Sint8
SDL_MostSignificantBitIndex32(Uint32 x)
{
#if defined(__GNUC__) && __GNUC__ >= 4
    /* Count Leading Zeroes builtin in GCC.
     * http://gcc.gnu.org/onlinedocs/gcc-4.3.4/gcc/Other-Builtins.html
     */
    return 31 - __builtin_clz(x);
#else
    /* Based off of Bit Twiddling Hacks by Sean Eron Anderson
     * <seander@cs.stanford.edu>, released in the public domain.
     * http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog
     */
    const Uint32 b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000};
    const Uint8  S[] = {1, 2, 4, 8, 16};

    Uint8 msbIndex = 0;
    int i;

    for (i = 4; i >= 0; i--)
    {
        if (x & b[i])
        {
            x >>= S[i];
            msbIndex |= S[i];
        }
    }

    return msbIndex;
#endif
}

/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"

#endif /* _SDL_bits_h */

/* vi: set ts=4 sw=4 expandtab: */


text:
<?php

  $_title = "Home";
  require_once "header.php";
  require_once "app/classes/DB.php";

  $db = new DB();

  class featuredSubjects{

    private $featuredSubQuery;
    private $db;

    public function __construct($grade){
      $this->db = new DB();
      $this->featuredSubQuery = $this->db->query("SELECT * FROM subjects WHERE grade={$grade} AND featured=1");
    }
    public function featuredSubjects_count(){
      return $this->featuredSubQuery->num_rows;
    }
    public function echoAllSubjects(){
      while($subject = $this->featuredSubQuery->fetch_assoc()){
        echo "
".$subject['name']."
";
      }
    }
  }

 ?>
 <link rel="stylesheet" href="css/home.css" media="screen" title="no title" charset="utf-8">

            Class XI Featured Subjects

            <?php
              $featured11 = new featuredSubjects(11);
              if($featured11->featuredSubjects_count() == 0){
                echo "
No featured Subjects
";
              }else{
                $featured11->echoAllSubjects();
              }
            ?>

            Class XII Featured Subjects

            <?php
              $featured12 = new featuredSubjects(12);
              if($featured12->featuredSubjects_count() == 0){
                echo "
No featured Subjects
";
              }else{
                $featured12->echoAllSubjects();
              }
            ?>

<?php

  require_once "footer.php";

 ?>


text:
table {
    border-collapse: collapse;
}

th, td {
    border: 1px solid black;
    padding: 0.5rem 1rem;
    text-align: center;
    vertical-align: middle;
}

th {
    color: white;
    background-color: gray;
}

button {
    margin: 0 0.5rem;
}


text:
import * as request from 'request';
import * as Consts from './consts';
import SkypeAccount from './skype_account';
import Utils from './utils';
import * as http from 'http';
import {CookieJar} from "request";
import {EventEmitter} from "./utils";

export class ContactsService {
    public contacts:Array<{}>;
    private requestWithJar: any;
    private eventEmitter: EventEmitter;

    constructor(cookieJar:CookieJar, eventEmitter: EventEmitter) {
        this.requestWithJar = request.defaults({jar: cookieJar});
        this.eventEmitter = eventEmitter;
    }

    public loadContacts(skypeAccount:SkypeAccount, resolve:(skypeAccount:SkypeAccount, contacts:Array<{}>)=>{}, reject: any):void {
        this.requestWithJar.get(Consts.SKYPEWEB_HTTPS + Consts.SKYPEWEB_CONTACTS_HOST + '/contacts/v1/users/' + skypeAccount.selfInfo.username + '/contacts', {
            headers: {
                'X-Skypetoken': skypeAccount.skypeToken
            }
        }, (error:any, response:http.IncomingMessage, body:any) => {
            if (!error && response.statusCode === 200) {
                this.contacts = JSON.parse(body).contacts;
                resolve(skypeAccount, this.contacts);
            } else {
                this.eventEmitter.fire('error', 'Failed to load contacts.');
            }
        });
    }
}

export default ContactsService;


text:
package zipkin2.storage.cassandra;

import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.ResultSetFuture;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.google.auto.value.AutoValue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import zipkin2.Call;
import zipkin2.internal.Nullable;
import zipkin2.storage.cassandra.CassandraSpanStore.TimestampRange;
import zipkin2.storage.cassandra.internal.call.AccumulateTraceIdTsUuid;
import zipkin2.storage.cassandra.internal.call.AggregateIntoMap;
import zipkin2.storage.cassandra.internal.call.ResultSetFutureCall;

import static zipkin2.storage.cassandra.Schema.TABLE_TRACE_BY_SERVICE_SPAN;

final class SelectTraceIdsFromServiceSpan extends ResultSetFutureCall<ResultSet> {
  @AutoValue
  abstract static class Input {
    abstract String service();

    abstract String span();

    abstract int bucket();

    @Nullable
    abstract Long start_duration();

    @Nullable
    abstract Long end_duration();

    abstract UUID start_ts();

    abstract UUID end_ts();

    abstract int limit_();

    Input withService(String service) {
      return new AutoValue_SelectTraceIdsFromServiceSpan_Input(
          service,
          span(),
          bucket(),
          start_duration(),
          end_duration(),
          start_ts(),
          end_ts(),
          limit_());
    }
  }

  static class Factory {
    final Session session;
    final PreparedStatement selectTraceIdsByServiceSpanName;
    final PreparedStatement selectTraceIdsByServiceSpanNameAndDuration;

    Factory(Session session) {
      this.session = session;
      // separate to avoid: "Unsupported unset value for column duration" maybe SASI related
      // TODO: revisit on next driver update
      this.selectTraceIdsByServiceSpanName =
          session.prepare(
              QueryBuilder.select("ts", "trace_id")
                  .from(TABLE_TRACE_BY_SERVICE_SPAN)
                  .where(QueryBuilder.eq("service", QueryBuilder.bindMarker("service")))
                  .and(QueryBuilder.eq("span", QueryBuilder.bindMarker("span")))
                  .and(QueryBuilder.eq("bucket", QueryBuilder.bindMarker("bucket")))
                  .and(QueryBuilder.gte("ts", QueryBuilder.bindMarker("start_ts")))
                  .and(QueryBuilder.lte("ts", QueryBuilder.bindMarker("end_ts")))
                  .limit(QueryBuilder.bindMarker("limit_")));
      this.selectTraceIdsByServiceSpanNameAndDuration =
          session.prepare(
              QueryBuilder.select("ts", "trace_id")
                  .from(TABLE_TRACE_BY_SERVICE_SPAN)
                  .where(QueryBuilder.eq("service", QueryBuilder.bindMarker("service")))
                  .and(QueryBuilder.eq("span", QueryBuilder.bindMarker("span")))
                  .and(QueryBuilder.eq("bucket", QueryBuilder.bindMarker("bucket")))
                  .and(QueryBuilder.gte("ts", QueryBuilder.bindMarker("start_ts")))
                  .and(QueryBuilder.lte("ts", QueryBuilder.bindMarker("end_ts")))
                  .and(QueryBuilder.gte("duration", QueryBuilder.bindMarker("start_duration")))
                  .and(QueryBuilder.lte("duration", QueryBuilder.bindMarker("end_duration")))
                  .limit(QueryBuilder.bindMarker("limit_")));
    }

    Input newInput(
        String serviceName,
        String spanName,
        int bucket,
        @Nullable Long minDurationMicros,
        @Nullable Long maxDurationMicros,
        TimestampRange timestampRange,
        int limit) {
      Long start_duration = null, end_duration = null;
      if (minDurationMicros != null) {
        start_duration = minDurationMicros / 1000L;
        end_duration = maxDurationMicros != null ? maxDurationMicros / 1000L : Long.MAX_VALUE;
      }
      return new AutoValue_SelectTraceIdsFromServiceSpan_Input(
          serviceName,
          spanName,
          bucket,
          start_duration,
          end_duration,
          timestampRange.startUUID,
          timestampRange.endUUID,
          limit);
    }

    Call<Map<String, Long>> newCall(List<Input> inputs) {
      if (inputs.isEmpty()) return Call.create(Collections.emptyMap());
      if (inputs.size() == 1) return newCall(inputs.get(0));

      List<Call<Map<String, Long>>> bucketedTraceIdCalls = new ArrayList<>();
      for (SelectTraceIdsFromServiceSpan.Input input : inputs) {
        bucketedTraceIdCalls.add(newCall(input));
      }
      return new AggregateIntoMap<>(bucketedTraceIdCalls);
    }

    Call<Map<String, Long>> newCall(Input input) {
      return new SelectTraceIdsFromServiceSpan(
              this,
              input.start_duration() != null
                  ? selectTraceIdsByServiceSpanNameAndDuration
                  : selectTraceIdsByServiceSpanName,
              input)
          .flatMap(new AccumulateTraceIdTsUuid());
    }

    /** Applies all deferred service names to all input templates */
    FlatMapper<List<String>, Map<String, Long>> newFlatMapper(List<Input> inputTemplates) {
      return new FlatMapServicesToInputs(inputTemplates);
    }

    class FlatMapServicesToInputs implements FlatMapper<List<String>, Map<String, Long>> {
      final List<SelectTraceIdsFromServiceSpan.Input> inputTemplates;

      FlatMapServicesToInputs(List<SelectTraceIdsFromServiceSpan.Input> inputTemplates) {
        this.inputTemplates = inputTemplates;
      }

      @Override public Call<Map<String, Long>> map(List<String> serviceNames) {
        List<Call<Map<String, Long>>> bucketedTraceIdCalls = new ArrayList<>();

        for (String service : serviceNames) { // fan out every input for each service name
          List<SelectTraceIdsFromServiceSpan.Input> scopedInputs = new ArrayList<>();
          for (SelectTraceIdsFromServiceSpan.Input input : inputTemplates) {
            scopedInputs.add(input.withService(service));
          }
          bucketedTraceIdCalls.add(newCall(scopedInputs));
        }

        if (bucketedTraceIdCalls.isEmpty()) return Call.create(Collections.emptyMap());
        if (bucketedTraceIdCalls.size() == 1) return bucketedTraceIdCalls.get(0);
        return new AggregateIntoMap<>(bucketedTraceIdCalls);
      }

      @Override public String toString() {
        List<String> inputs = new ArrayList<>();
        for (Input input : inputTemplates) {
          inputs.add(input.toString().replace("Input", "SelectTraceIdsFromServiceSpan"));
        }
        return "FlatMapServicesToInputs{" + inputs + "}";
      }
    }
  }

  final Factory factory;
  final PreparedStatement preparedStatement;
  final Input input;

  SelectTraceIdsFromServiceSpan(Factory factory, PreparedStatement preparedStatement, Input input) {
    this.factory = factory;
    this.preparedStatement = preparedStatement;
    this.input = input;
  }

  @Override
  protected ResultSetFuture newFuture() {
    BoundStatement bound = preparedStatement.bind()
      .setString("service", input.service())
      .setString("span", input.span())
      .setInt("bucket", input.bucket());
    if (input.start_duration() != null) {
      bound.setLong("start_duration", input.start_duration());
      bound.setLong("end_duration", input.end_duration());
    }
    bound
        .setUUID("start_ts", input.start_ts())
        .setUUID("end_ts", input.end_ts())
        .setInt("limit_", input.limit_())
        .setFetchSize(input.limit_());
    return factory.session.executeAsync(bound);
  }

  @Override public ResultSet map(ResultSet input) {
    return input;
  }

  @Override
  public String toString() {
    return input.toString().replace("Input", "SelectTraceIdsFromServiceSpan");
  }

  @Override
  public SelectTraceIdsFromServiceSpan clone() {
    return new SelectTraceIdsFromServiceSpan(factory, preparedStatement, input);
  }
}


text:
\documentclass{article} %[11pt]{amsart}
\usepackage{geometry}
\geometry{letterpaper}
\usepackage{graphicx}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{siunitx}
\usepackage{tikz}
\usepackage{lscape}
\usepackage{pgfplots}
\usetikzlibrary{
  arrows,
  calc,
  decorations.markings,
  decorations.pathreplacing,
  dsp,
  fit,
  positioning
}
\input{../util/airfoils.tex}
\input{../util/wing.tex}
\input{../util/coordinate_systems.tex}
\input{../util/control.tex}

\pgfplotsset{grid style={dashed,gray!25}}

\newcommand{\qhat}{\hat{q}}
\newcommand{\cbar}{\bar{c}}
\newcommand{\qbar}{\bar{q}}
\newcommand{\cmd}{\mathrm{cmd}}
\newcommand{\ff}{\mathrm{ff}}
\newcommand{\eff}{\mathrm{eff}}
\newcommand{\app}{\mathrm{app}}
\newcommand{\wind}{\mathrm{wind}}
\newcommand{\grav}{\mathrm{grav}}
\newcommand{\kite}{\mathrm{kite}}
\newcommand{\nom}{\mathrm{nom}}
\newcommand{\aero}{\mathrm{aero}}
\newcommand{\geom}{\mathrm{geom}}
\newcommand{\cw}{\mathrm{cw}}

\begin{document}

\section{Curvature from force balance}

\begin{figure}[h]
\begin{center}
  \begin{tikzpicture}[scale=0.75]
    \begin{scope}[shift={(-5, 0)}, scale=0.3, rotate=-10]
      \DrawWingFront[]
      \draw[line width=1.5pt, -latex] (4, 1) -- (9, 1) node[midway, above] {$-Y$};
      \draw[line width=1.5pt, -latex] (0, 5) -- (0, 12) node[midway, right] {$L$};
      \draw (-5.86, -0.13) -- (0, -4.92);
      \draw (5.86, -0.13) -- (0, -4.92);
      \draw[dashed] (0, -4.92) -- (0, -15);
    \end{scope}
    \node at (-5, -3) {$\phi_t$};
    \draw[line width=1.5pt, -latex] (-5.25, -1.45) --
    (-3.5, -4.3) node[midway, above right] {$t$};
    \draw[line width=1.5pt, -latex] (-3.5, -1) -- (-2, -2)
    node[midway, below left] {$W$};
    \draw (-5.25, -1.45) -- (0, -10) node[midway, above right] {$l_t$};
    %\draw[dashed] (-5.25, -1.45) -- (-0.975, 1.175);
    \node at (-0.5, -8.5) {$\gamma$};
    \draw[dashed] (0, -10) -- (0, -5);
    %\draw[dashed] (-5, 0) -- (-10, 0) node[near end, above] {$-\phi$};
    %\draw[line width=1.5pt, -latex] (-7, 0) -- (-9, 0) node[midway, below]
    %{$mv^2/R$};
    \DrawCoordinateSystem{shift={(0, -10)}, scale=1}
                         {$x_{\cw}$}{$y_{\cw}$}{$z_{\cw}$}
  \end{tikzpicture}
  \caption{Diagram of force balance in the stability axes' y-z plane.}
\end{center}
\end{figure}

By balancing forces in the stability axes' y-z plane, it is possible
to relate the curvature of a kite's flight path to a few known
parameters of the kite (e.g. lift coefficient, wing area, and mass)
and the easily measured roll angle between the kite and the tether.
This implies that it is possible to steer the kite simply by
controlling the tether roll angle.  Indeed, this is the approach taken
in the current flight controller.  Here an appoximate relationship
between tether roll angle and curvature is derived.  To simplify the
relationship, the tether is appoximated as a straight line from the
ground-station to the bridle point.  Other effects on the tether such
as the catenary from gravity are ignored.

It is easiest to conduct the force balance along axes that are
parallel and perpendicular to the tether.  Because the wing is forced
to fly on the surface of a sphere with radius equal to the tether
length, $l_t$, the acceleration parallel to the tether is
$a_{\parallel} = v_i^2/l_t$.  The lift, pylon side force, and weight
each have components along the direction perpendicular to the tether.
Together, these create an acceleration perpendicular to the tether
given by
\begin{equation}
m_{\eff} a_{\bot} = L \sin \phi_t - Y \cos \phi_t -
W_{\cw, x} \cos \gamma - W_{\cw, z} \sin \gamma
\end{equation}
Here $m_{\eff}$ is the effective mass of the kite, which is given by
$m_{\eff} = m_{\kite} + m_{\mathrm{tether}} / 3$.  The extra term from
the tether mass comes from calculating the acceleration of a point
mass at the end of a rigid rod due to a force applied at the point
mass.  Also, a few small approximations were made such as ignoring
forces from motor thrust, ignoring the component of drag along the
stability z-axis, and ignoring the cosine term from projecting the
lift vector onto the stability z-axis.

The curvature and thus acceleration that is relevant for control is
that in the crosswind flight plane.  The parallel and perpendicular
accelerations can be combined, projected onto the crosswind $x$-axis,
and converted to a curvature as follows:
\begin{equation}
\kappa_{\cw} = \frac{1}{l_t} \sin \gamma +
\frac{\rho A v_{\app}^2}{2 m_{\eff} v_i^2}
\left(C_L \sin \phi_t - C_Y \cos \phi_t \right) \cos \gamma -
\frac{m}{m_{\eff} v_i^2}
(g_{\cw,x} \cos \gamma + g_{\cw,z} \sin \gamma) \cos \gamma
\end{equation}
%
It is somtimes useful to decompose this total, in-plane curvature into
components caused by the tether sphere, aerodynamic angles, wind, and
gravity:
\begin{equation}
\kappa_{\cw} = \kappa_0 + \kappa_{\aero} + \kappa_{\wind} + \kappa_{\grav}
\end{equation}
%
where
%
\begin{eqnarray}
\kappa_0 &=& \frac{1}{l_t} \sin \gamma \\
\kappa_{\aero} &=&
\frac{\rho A}{2 m_{\eff}} \left(C_L \sin \phi_t - C_Y \cos \phi_t \right) \cos \gamma \\
\kappa_{\wind} &=&
\left( \frac{v_w^2 - 2 \vec{v}_i \cdot \vec{v}_w}{v_i^2} \right) \kappa_{\aero} \\
\kappa_{\grav} &=&
-\frac{m}{m_{\eff} v_i^2}
(g_{\cw,x} \cos \gamma + g_{\cw,z} \sin \gamma) \cos \gamma
\end{eqnarray}

\section{Curvature mixer}

The curvature mixer takes as input the curvature command,
$\kappa_{\cmd}$, and a component of the curvature command due to lift
and tether roll, $\kappa^{\aero}_{\cmd}$.  It returns the inner loop
incidence and tether angle commands and angular rate commands that
will generate these curvatures.

\begin{equation}
[\alpha_{\cmd},\; \Delta {C_L}_{\cmd},\; \beta_{\cmd},\; {\phi_t}_{\cmd}]^T
= F(\kappa_{\cmd}^{\aero})
\end{equation}

\begin{equation}
\kappa_{\cw} \approx v \cdot |\vec{\omega}|
\end{equation}

\begin{equation}
\kappa^{\cw} = \frac{|\vec{a}_b \times \vec{v}_b|}{|\vec{v}_b|^3}
\end{equation}

\begin{equation}
[p_{\cmd},\; r_{\cmd}]^T = G(\kappa_{\cmd}^{\geom})
\end{equation}

\begin{eqnarray}
\alpha_{\cmd} &=& \alpha_{\nom} \\
\Delta {C_L}_{\cmd} &=& 0 \\
\beta_{\cmd} &=& 0 \\
{\phi_t}_{\cmd} &=& \sin^{-1} \left(
\frac{2 m \kappa_{\cmd}^{\aero}}{\rho A {C_L}_{\nom}} +
\frac{C_{Y_0}}{{C_L}_{\nom}} \right)
\end{eqnarray}

\end{document}


text:
here you can:
- try a different theme by adding to the url:
  - `?theme=<any bootswatch theme>`
  - [bootswatch](https://bootswatch.com)
  - default theme for the demo is `paper`
- try with a different markdown file by adding to the url:
  - showdown's readme `?src=https://raw.githubusercontent.com/showdownjs/showdown/master/README.md`
  - bootstrap's readme `?src=https://raw.githubusercontent.com/twbs/bootstrap/master/README.md`
- try joining markdown files
	- `?src=docs/example-chapters/1.md docs/example-chapters/2.md`
- define a join string when using multiple files
	- `?join=any markdown string`
- try without a table of contents by adding to the url:
  - `?toc=false`
- limit which headers are used for the toc
  - `?tocLimit=2`
- change the default code formatting theme
  - `?prettifyTheme=github`


text:
package org.rapidpm.proxybuilder.objectadapter.testusage.v002;

import org.rapidpm.proxybuilder.objectadapter.annotations.dynamicobjectadapter.DynamicObjectAdapterBuilder;
import org.rapidpm.proxybuilder.objectadapter.annotations.staticobjectadapter.StaticObjectAdapter;

@DynamicObjectAdapterBuilder
@StaticObjectAdapter
public interface LevelA {
  String dowWorkA();
}


text:
City,State, Country latitude  longitude location,  google map,

* https://postindustria.com/postgresql-geo-queries-made-easy/
* http://download.geonames.org/export/dump/ dump of location in csv format world wide


text:
import datetime
import logging
from celery.task import task
from sqlalchemy.exc import DataError
from casexml.apps.case.models import CommCareCase
from corehq.apps.domain.utils import get_doc_ids
from corehq.apps.userreports.models import DataSourceConfiguration, CustomDataSourceConfiguration
from corehq.apps.userreports.sql import IndicatorSqlAdapter, create_engine
from couchforms.models import XFormInstance
from dimagi.utils.couch.database import iter_docs

@task(queue='background_queue', ignore_result=True, acks_late=True)
def rebuild_indicators(indicator_config_id):
    is_static = indicator_config_id.startswith(CustomDataSourceConfiguration._datasource_id_prefix)
    if is_static:
        config = CustomDataSourceConfiguration.by_id(indicator_config_id)
    else:
        config = DataSourceConfiguration.get(indicator_config_id)
        # Save the start time now in case anything goes wrong. This way we'll be
        # able to see if the rebuild started a long time ago without finishing.
        config.meta.build.initiated = datetime.datetime.utcnow()
        config.save()

    adapter = IndicatorSqlAdapter(config, engine=create_engine())
    adapter.rebuild_table()

    couchdb = _get_db(config.referenced_doc_type)
    relevant_ids = get_doc_ids(config.domain, config.referenced_doc_type,
                               database=couchdb)

    for doc in iter_docs(couchdb, relevant_ids, chunksize=500):
        try:
            # save is a noop if the filter doesn't match
            adapter.save(doc)
        except DataError as e:
            logging.exception('problem saving document {} to table. {}'.format(doc['_id'], e))
    adapter.engine.dispose()

    if not is_static:
        config.meta.build.finished = True
        config.save()

def _get_db(doc_type):
    return _DOC_TYPE_MAPPING.get(doc_type, CommCareCase).get_db()

# This is intentionally not using magic to introspect the class from the name, though it could
_DOC_TYPE_MAPPING = {
    'XFormInstance': XFormInstance,
    'CommCareCase': CommCareCase,
}


text:
var auth = require('./auth');

module.exports = function TokenCache() {
	var self = this;
	this._cache = {};

	TokenCache.prototype.get = function (options, callback) {
		var key = options.email + ':' + options.scopes.join(',');

		if (!self._cache[key]) {
			self._cache[key] = new TokenRequest(options);
		}

		self._cache[key].get(callback);
	};

	TokenCache.prototype.clear = function () {
		self._cache = {};
	};
};

function TokenRequest(options) {
	var self = this;
	this.status = 'expired';
	this.pendingCallbacks = [];

	this.get = function (callback) {
		if (this.status == 'expired') {
			this.status = 'pending';
			this.pendingCallbacks.push(callback);

			auth.authenticate(options, function (err, token, body) {
				var expires_in = null;

				if (err) {
					return fireCallbacks(err, null);
				}

				if (body && body.hasOwnProperty('expires_in')) {
					expires_in = parseInt(body.expires_in);
				}

				self.issued = new Date().getTime();
				self.duration = expires_in || options.expiration || 60 * 60 * 1000;
				self.token = token;

				self.status = 'completed';
				return fireCallbacks(null, token);
			});

		}
		else if (this.status == 'pending') {
			this.pendingCallbacks.push(callback);
		}
		else if (this.status == 'completed') {
			if (this.issued + this.duration < new Date().getTime()) {
				this.status = 'expired';
				this.get(callback);
			}
			else {
				callback(null, this.token);
			}
		}
	};

	function fireCallbacks(err, token) {
		self.pendingCallbacks.forEach(function (callback) {
			callback(err, token);
		});
		self.pendingCallbacks = [];
	}
}


text:
:mod:`pymunk.examples` Module
------------------------------------

.. container:: custom-index

    .. raw:: html

        <script type="text/javascript" src='_static/pymunk.js'></script>

.. automodule:: pymunk.examples
    :members:
    :undoc-members:
    :special-members: __init__


text:
require "brew_dependency_graph/version"

module BrewDependencyGraph
  def self.run()
  	brew_available = `which brew`

		if !brew_available
			puts "Homebrew was not found!"
			return
		end

		Formula = Struct.new(:name)
		Dependency = Struct.new(:package, :dependency)

		puts "Constructing dependency tree..."

		formulas = {}

		brew_packages = `brew list`.split("\n")
		brew_packages.each do |package|
			formulas[package] = []
		end

		for package, dependencies in formulas
			package_dependants = `brew uses --installed #{package}`.split("\n")
			package_dependants.each do |package_dependant|
				dependencies.push(package_dependant)
			end
		end

		puts JSON.pretty_generate(formulas)

  end
end


text:
/**
 * Created by Marco on 17/05/2014.
 */
"use strict";

var karmaLauncherTesterAdapter = function(launcher){
    var key,
        launcherName = 'not defined',
        browserAdapter = {};

    if(!launcher) { return ;}

    for (key in launcher) {
        if (key.indexOf('launcher:') >= 0) {
            launcherName = key.split(':')[1];
            browserAdapter = launcher[key][1];
        }
    }

    return {
        name:launcherName,
        adapter:browserAdapter
    };
};

module.exports = karmaLauncherTesterAdapter;


text:
#include <babylon/postprocesses/pass_cube_post_process.h>

namespace BABYLON {

PassCubePostProcess::PassCubePostProcess(const std::string& iName,
                                         const std::variant<float, PostProcessOptions>& options,
                                         const CameraPtr& camera,
                                         const std::optional<unsigned int>& samplingMode,
                                         Engine* engine, bool reusable, unsigned int textureType,
                                         bool blockCompilation)
    : PostProcess{iName,        "passCube",
                  {},           {},
                  options,      camera,
                  samplingMode, engine,
                  reusable,     "#define POSITIVEX",
                  textureType,  "",
                  {},           blockCompilation}
    , face{this, &PassCubePostProcess::get_face, &PassCubePostProcess::set_face}
    , _face{}
{
}

PassCubePostProcess::~PassCubePostProcess() = default;

unsigned int PassCubePostProcess::get_face() const
{
  return _face;
}

void PassCubePostProcess::set_face(unsigned int value)
{
  if (value > 5) {
    return;
  }

  _face = value;
  switch (_face) {
    case 0:
      updateEffect("#define POSITIVEX");
      break;
    case 1:
      updateEffect("#define NEGATIVEX");
      break;
    case 2:
      updateEffect("#define POSITIVEY");
      break;
    case 3:
      updateEffect("#define NEGATIVEY");
      break;
    case 4:
      updateEffect("#define POSITIVEZ");
      break;
    case 5:
      updateEffect("#define NEGATIVEZ");
      break;
  }
}

std::string PassCubePostProcess::getClassName() const
{
  return "PassCubePostProcess";
}

PassCubePostProcessPtr PassCubePostProcess::_Parse(const json& /*parsedPostProcess*/,
                                                   const CameraPtr& /*targetCamera*/,
                                                   Scene* /*scene*/, const std::string& /*rootUrl*/)
{
  return nullptr;
}

} // end of namespace BABYLON


text:
#ifndef	K2HASHFUNC_H
#define	K2HASHFUNC_H

#include "k2hash.h"
#include "k2hcommon.h"

//---------------------------------------------------------
// Readme about HASH functions
//---------------------------------------------------------
// K2Hash library has three type functions for HASHING.
// 1) k2h_hash         - convert binary array to hash value(unsigned long)
// 3) k2h_second_hash  - secondary hash function like k2h_hash
// 3) k2h_hash_version - returns hash function version string
//
// You can overwrite these three functions by follow two way.
// 1) Built'in these function in your source codes(binary)
//    You must make completely same prototype functions in your
//    codes. Thereby, your functions is given priority to over-
//    write these functions in the library, In other words you
//    can overwrite these.
//
// 2) Load your library
//    You can load your library(so) which has these functions by
//    calling Load() member function in K2HashDynLib class.
//
// If you use these functions for example: making hash code,
// checking function version. You can call below macros which is
// defined in this header file, so you call rightly function
// regardless of overwriting functions.
//
//    K2H_HASH_FUNC(unsigned char* ptr, size_t length)
//    K2H_2ND_HASH_FUNC(unsigned char* ptr, size_t length)
//    K2H_HASH_VER_FUNC(void)
//

//---------------------------------------------------------
// Global Hash function
//---------------------------------------------------------
//
// weak function for over loading same name function.
//
DECL_EXTERN_C_START		// extern "C" - start

// First hash value returns, the value is used Key Index
extern k2h_hash_t k2h_hash(const void* ptr, size_t length) K2HASH_ATTR_WEAK;

// Second hash value returns, the value is used the Element in collision keys.
extern k2h_hash_t k2h_second_hash(const void* ptr, size_t length) K2HASH_ATTR_WEAK;

// Hash function(library) version string, the value is stamped into SHM file.
// This retuned value length must be under 32 byte.
extern const char* k2h_hash_version(void) K2HASH_ATTR_WEAK;

DECL_EXTERN_C_END		// extern "C" - end

//---------------------------------------------------------
// Prototype Hash function
//---------------------------------------------------------
DECL_EXTERN_C_START		// extern "C" - start

typedef k2h_hash_t (*Tfp_k2h_hash)(const void* ptr, size_t length);
typedef k2h_hash_t (*Tfp_k2h_second_hash)(const void* ptr, size_t length);
typedef const char* (*Tfp_k2h_hash_version)(void);

DECL_EXTERN_C_END		// extern "C" - end

//---------------------------------------------------------
// Macros
//---------------------------------------------------------
#define	CALL_K2H_HASH_FUNCTION(type, ...)	(reinterpret_cast<K2HSTRJOIN(Tfp_, type)>(NULL != K2HashDynLib::get()->K2HSTRJOIN(get_, type)() ? K2HashDynLib::get()->K2HSTRJOIN(get_, type)() : type))(__VA_ARGS__)
#define	K2H_HASH_FUNC(...)					CALL_K2H_HASH_FUNCTION(k2h_hash, __VA_ARGS__)
#define	K2H_2ND_HASH_FUNC(...)				CALL_K2H_HASH_FUNCTION(k2h_second_hash, __VA_ARGS__)
#define	K2H_HASH_VER_FUNC()					CALL_K2H_HASH_FUNCTION(k2h_hash_version)

//---------------------------------------------------------
// Load library
//---------------------------------------------------------
class K2HashDynLib
{
	private:
		void*					hDynLib;
		Tfp_k2h_hash			fp_k2h_hash;
		Tfp_k2h_second_hash		fp_k2h_second_hash;
		Tfp_k2h_hash_version	fp_k2h_hash_version;

	public:
		static K2HashDynLib* get(void);

		K2HashDynLib();
		virtual ~K2HashDynLib();

		bool Unload(void);
		bool Load(const char* path);

		Tfp_k2h_hash get_k2h_hash(void) { return fp_k2h_hash; }
		Tfp_k2h_second_hash get_k2h_second_hash(void) { return fp_k2h_second_hash; }
		Tfp_k2h_hash_version get_k2h_hash_version(void) { return fp_k2h_hash_version; }
};

#endif	// K2HASHFUNC_H

/*
 * VIM modelines
 *
 * vim:set ts=4 fenc=utf-8:
 */