text:
<?php

namespace Lupka\Crudder;

use Lupka\Crudder\Fields\Factory as FieldFactory;
use Lupka\Crudder\RelationshipFinder;

use Illuminate\Support\Collection;

class CrudderModel
{
    public $className;
    public $tableName;
    public $config;
    public $fields;
    public $scripts;
    public $formAttributes;
    protected $fieldFactory;
    protected $relationshipFinder;

    /**
     * Constructor
     */
    public function __construct($className)
    {
        $this->fieldFactory = new FieldFactory();
        $this->relationshipFinder = new RelationshipFinder();
        $this->className = $className;
        $this->tableName = $this->getTableName();
        $this->generateFields();
        //$this->generateRelationshipFields();
        $this->parseModelConfig();
        $this->registerScripts();
        $this->registerFormAttributes();
    }

    /**
     * Model retreival
     */

    // returns all models in collection
    public static function get()
    {
        $configModels = collect(config('crudder.models'));
        return $configModels->map(function($item, $key){
            return new self($key);
        });
    }

    public static function all()
    {
        return self::get();
    }

    public static function fromTableName($tableName)
    {
        $loadedModels = self::all();
        if($model = $loadedModels->where('tableName', $tableName)->first()){
            return $model;
        }
        else{
            // throw error?
        }
    }

    /**
     * General Configuration (names, etc)
     */
    protected function parseModelConfig()
    {
        $defaultModelConfig = [
            'name' => $this->defaultName(),
            'dashboard' => true,
            'available_actions' => ['create','update','delete'],
        ];
        $this->config = array_merge($defaultModelConfig, config('crudder.models.'.$this->className));

        // name_plural is separate so it can be derived from default OR manually set
        if(!isset($this->config['name_plural'])) $this->config['name_plural'] = str_plural($this->config['name']);
    }

    public function getConfig($key, $default = '')
    {
        return isset($this->config[$key]) ? $this->config[$key] : $default;
    }

    public function defaultName()
    {
        return ucwords(str_singular(str_replace('_', ' ', $this->tableName)));
    }

    public function actionEnabled($action)
    {
        return in_array($action, $this->getConfig('available_actions'));
    }

    /**
     * Fields
     */
    protected function generateFields()
    {
        $fields = $this->getFieldsConfig();
        $this->fields = new Collection();
        foreach($fields as $fieldName => $field)
        {
            // get type from config, otherwise use suggested default
            $type = config('crudder.models.'.$this->className.'.fields.'.$fieldName.'.type', $this->getFieldSuggestion($field['fieldType']));
            if(!in_array($fieldName, config('crudder.models.'.$this->className.'.hidden_fields', ['id','created_at','updated_at']))){
                $this->addField($type, $this->className, $fieldName);
            }
        }
    }

    public function addField($type, $className, $fieldName)
    {
        $field = $this->fieldFactory->dispenseField($type, $className, $fieldName);
        $this->fields[] = $field;
        return $field;
    }

    public function getFieldSuggestion($fieldType)
    {
        if(in_array($fieldType,['string'])){
            return 'text';
        }
        elseif(in_array($fieldType,['boolean'])){
            return 'checkbox';
        }
        elseif(in_array($fieldType,['text'])){
            return 'textarea';
        }
        else{
            return 'text';
        }
    }

    public function getFieldsConfig()
    {
        $config = [];
        $fields = \Schema::getColumnListing($this->getTableName());
        foreach($fields as $field){
            $config[$field] = [
                'fieldType' => self::getFieldType($this->getTableName(), $field)
            ];
        }
        return $config;
    }

    public function dashboardListingField()
    {
        if($fieldName = $this->getConfig('dashboard_listing_field', false)){
            return $this->fields->where('fieldName', $fieldName)->first();
        }
        else{
            return $this->fields->first();
        }
    }

    public function indexDisplayFields()
    {
        $customFields = $this->fields->whereIn('fieldName', $this->getConfig('index_display_fields'));
        if($customFields->count() == 0){
             return $this->fields->slice(0,2);
        }
        return $customFields;
    }

    /**
     * Load scripts into array
     */
    public function registerScripts()
    {
        $this->scripts = [];
        foreach($this->fields as $field){
            $this->scripts = array_merge($this->scripts, $field->scripts());
        }
    }

    /**
     * Load form attributes into array
     */
    public function registerFormAttributes()
    {
        $this->formAttributes = [];
        foreach($this->fields as $field){
            $this->formAttributes = array_merge($this->formAttributes, $field->formAttributes());
        }
    }

    public function formAttributeString()
    {
        return collect($this->formAttributes)->map(function($val, $key){
            return $key.'="'.$val.'"';
        })->implode(' ');
    }

    /**
     * Relationship Fields
     */
    protected function generateRelationshipFields()
    {
        $relationships = $this->relationshipFinder->getPropertiesFromMethods($this->dispenseModel());
        foreach($relationships as $relationship){
            $this->fields[] = $this->fieldFactory->dispenseField($relationship['type'], $this->className, $relationship['fieldName'], ['relation' => $relationship['relationObj']]);
        }
    }

    /**
     * Loading Objects
     */
     public function dispenseModel()
     {
         return new $this->className;
     }
     public function query()
     {
         $className = $this->className;
         return $className::query();
     }
     public function loadModel($id)
     {
         return $this->query()->find($id);
     }
     public function dashboardItems()
     {
         return $this->query()->orderBy('created_at','DESC')->limit(5)->get();
     }

    /**
     * Utility Methods
     */
    public static function getFieldType($tableName, $fieldName)
    {
        return \DB::connection()->getDoctrineColumn($tableName, $fieldName)->getType()->getName();
    }

    public function getTableName()
    {
        return (new $this->className)->getTable();
    }

    /**
     * URLs
     */
    public function indexUrl()
    {
        return route('crudder_index', ['tableName' => $this->getTableName()]);
    }
    public function createUrl()
    {
        return route('crudder_create', ['tableName' => $this->getTableName()]);
    }
    public function viewUrl($model)
    {
        return route('crudder_view', ['tableName' => $this->getTableName(), 'id' => $model->id]);
    }
    public function editUrl($model)
    {
        return route('crudder_edit', ['tableName' => $this->getTableName(), 'id' => $model->id]);
    }
    public function deleteUrl($model)
    {
        return route('crudder_delete', ['tableName' => $this->getTableName(), 'id' => $model->id]);
    }

}


text:
.. image:: https://travis-ci.org/cdent/gabbi.svg?branch=master
    :target: https://travis-ci.org/cdent/gabbi
.. image:: https://readthedocs.org/projects/gabbi/badge/?version=latest
    :target: http://gabbi.readthedocs.org/en/latest/
    :alt: Documentation Status

Gabbi
=====

Gabbi is a tool for running HTTP tests where requests and responses
are represented in a declarative form.

It is under active development. See the YAML files for examples of
working tests and the docs_ for more details on features and
formats. It is actively tested with Python 2.7, 3.4 and pypy and
pypy3.

There is a `gabbi-demo`_ repository which provides a tutorial via
its commit history. The demo builds a simple API using gabbi to
facilitate test driven development.

.. _docs: http://gabbi.readthedocs.org/
.. _gabbi-demo: https://github.com/cdent/gabbi-demo

Purpose
-------

Gabbi works to bridge the gap between human readable YAML files that
represent HTTP requests and expected responses and the obscured realm of
Python-based, object-oriented unit tests in the style of the unittest
module and its derivatives.

Each YAML file represents an ordered list of HTTP requests along with
the expected responses. This allows a single file to represent a
process in the API being tested. For example:

* Create a resource.
* Retrieve a resource.
* Delete a resource.
* Retrieve a resource again to confirm it is gone.

At the same time it is still possible to ask gabbi to run just one
request. If it is in a sequence of tests, those tests prior to it in
the YAML file will be run (in order). In any single process any test
will only be run once. Concurrency is handled such that one file
runs in one process.

These features mean that it is possible to create tests that are
useful for both humans (as tools for improving and developing APIs)
and automated CI systems.

Testing
-------

To run the built in tests (the YAML files are in the directories
``gabbi/gabbits_*`` and loaded by the file ``gabbi/test_*.py``),
you can use ``tox``::

    tox -epep8,py27,py34

Or if you have the dependencies installed (or a warmed up
virtualenv) you can run the tests by hand and exit on the first
failure::

    python -m subunit.run discover -f gabbi | subunit2pyunit

redpajama_set_name: RedPajamaGithub


text:
package org.qi4j.migration;

import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * The Migrator implements this interface, which is invoked by MigrationOperation implementations
 * to perform changes to EntityState during a version migration.
 */
public interface Migrator
{
    boolean addProperty( JSONObject state, String name, Object defaultValue )
        throws JSONException;

    boolean removeProperty( JSONObject state, String name )
        throws JSONException;

    boolean renameProperty( JSONObject state, String from, String to )
        throws JSONException;

    boolean addAssociation( JSONObject state, String name, String defaultReference )
        throws JSONException;

    boolean removeAssociation( JSONObject state, String name )
        throws JSONException;

    boolean renameAssociation( JSONObject state, String from, String to )
        throws JSONException;

    boolean addManyAssociation( JSONObject state, String name, String... defaultReferences )
        throws JSONException;

    boolean removeManyAssociation( JSONObject state, String name )
        throws JSONException;

    boolean renameManyAssociation( JSONObject state, String from, String to )
        throws JSONException;

    boolean addNamedAssociation( JSONObject state, String name, Map<String, String> defaultReferences )
        throws JSONException;

    boolean removeNamedAssociation( JSONObject state, String name )
        throws JSONException;

    boolean renameNamedAssociation( JSONObject state, String from, String to )
        throws JSONException;

    void changeEntityType( JSONObject state, String newEntityType )
        throws JSONException;
}


text:
{% extends 'base.html' %}
{% block content %}

Welcome to Spkrepo on Vagrant!

Spkrepo is a feature rich Synology Package Repository.

To support spkrepo developments, please

{% endblock %}


text:
import { InjectionToken } from "@angular/core";

import { IAppConfig }     from "./app-config.interface";

export let APP_CONFIG = new InjectionToken< IAppConfig >( 'app.config' );

export const APP_DI_CONFIG: IAppConfig = {

  // Endpoint to your Backend Server
  apiEndpoint: 'http://localhost:3000',

  // URL to web API
  apiUrl: '/api/v1/authenticate',
  //    '/api/v1/user/1',

  // URL to JSON file
  fileUrl: 'app/menu.json',

  OAUTH_KEY: '726fca4a820151152102cb3776cb53b7ca8de30c',

};


text:
using DragonSpark.Activation;
using DragonSpark.Testing.Objects;
using Ploeh.AutoFixture.Xunit2;
using Xunit;
using Constructor = DragonSpark.Activation.Constructor;

namespace DragonSpark.Testing.Activation
{
	public class ActivatorExtensionsTests
	{
		[Theory, AutoData]
		public void ActivateMany()
		{
			var sut = Constructor.Default;
			var items = sut.ActivateMany<IInterface>( new[] { typeof(Class), typeof(AnotherClass), typeof(YetAnotherClass) } );
			Assert.Collection( items, x => Assert.IsType<Class>( x ), x => Assert.IsType<AnotherClass>( x ), x => Assert.IsType<YetAnotherClass>( x ) );
		}
	}
}


text:
@interface BusinessVC : UIViewController<ViewControllerDemo>

@property (nonatomic, strong) UIButton *btnLoad;
@property (nonatomic, strong) UIButton *btnStart;

- (IBAction)clickStart:(id)sender;

- (IBAction)clickLoad:(id)sender;

@end


text:
package game.math;

public class GameMath {

	public final static double sqrt2=Math.sqrt(2);

}


text:
<!DOCTYPE html>

<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>

Loading...


text:
package org.elasticsearch.search.aggregations.bucket.histogram;

import org.apache.lucene.util.PriorityQueue;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation;
import org.elasticsearch.search.aggregations.KeyComparable;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class InternalVariableWidthHistogram
    extends InternalMultiBucketAggregation<InternalVariableWidthHistogram, InternalVariableWidthHistogram.Bucket>
    implements Histogram, HistogramFactory{

    public static class Bucket extends InternalMultiBucketAggregation.InternalBucket
        implements Histogram.Bucket, KeyComparable<Bucket> {

        public static class BucketBounds {
            public double min;
            public double max;

            public BucketBounds(double min, double max) {
                assert min <= max;
                this.min = min;
                this.max = max;
            }

            public BucketBounds(StreamInput in) throws IOException {
                this(in.readDouble(), in.readDouble());
            }

            public void writeTo(StreamOutput out) throws IOException {
                out.writeDouble(min);
                out.writeDouble(max);
            }

            public boolean equals(Object obj){
                if (this == obj) return true;
                if (obj == null || getClass() != obj.getClass()) return false;
                BucketBounds that = (BucketBounds) obj;
                return min == that.min && max == that.max;
            }

            @Override
            public int hashCode() {
                return Objects.hash(getClass(), min, max);
            }
        }

        private final BucketBounds bounds;
        private long docCount;
        private InternalAggregations aggregations;
        protected final transient DocValueFormat format;
        private double centroid;

        public Bucket(double centroid,
                      BucketBounds bounds,
                      long docCount,
                      DocValueFormat format,
                      InternalAggregations aggregations) {
            this.format = format;
            this.centroid = centroid;
            this.bounds = bounds;
            this.docCount = docCount;
            this.aggregations = aggregations;
        }

        /**
         * Read from a stream.
         */
        public Bucket(StreamInput in, DocValueFormat format) throws IOException {
            this.format = format;
            centroid = in.readDouble();
            docCount = in.readVLong();
            bounds = new BucketBounds(in);
            aggregations = InternalAggregations.readFrom(in);
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            out.writeDouble(centroid);
            out.writeVLong(docCount);
            bounds.writeTo(out);
            aggregations.writeTo(out);
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null || obj.getClass() != InternalVariableWidthHistogram.Bucket.class) {
                return false;
            }
            InternalVariableWidthHistogram.Bucket that = (InternalVariableWidthHistogram.Bucket) obj;
            return centroid == that.centroid
                && bounds.equals(that.bounds)
                && docCount == that.docCount
                && Objects.equals(aggregations, that.aggregations);
        }

        @Override
        public int hashCode() {
            return Objects.hash(getClass(), centroid, bounds, docCount, aggregations);
        }

        @Override
        public String getKeyAsString() {
            return format.format((double) getKey()).toString();
        }

        /**
         * Buckets are compared using their centroids. But, in the final XContent returned by the aggregation,
         * we want the bucket's key to be its min. Otherwise, it would look like the distances between centroids
         * are buckets, which is incorrect.
         */
        @Override
        public Object getKey() { return centroid; }

        public double min() { return bounds.min; }

        public double max() { return bounds.max; }

        public double centroid() { return centroid; }

        @Override
        public long getDocCount() {
            return docCount;
        }

        @Override
        public Aggregations getAggregations() {
            return aggregations;
        }

        @Override
        public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
            String keyAsString = format.format((double) getKey()).toString();
            builder.startObject();

            builder.field(CommonFields.MIN.getPreferredName(), min());
            if (format != DocValueFormat.RAW) {
                builder.field(CommonFields.MIN_AS_STRING.getPreferredName(), format.format(min()));
            }

            builder.field(CommonFields.KEY.getPreferredName(), getKey());
            if (format != DocValueFormat.RAW) {
                builder.field(CommonFields.KEY_AS_STRING.getPreferredName(), keyAsString);
            }

            builder.field(CommonFields.MAX.getPreferredName(), max());
            if (format != DocValueFormat.RAW) {
                builder.field(CommonFields.MAX_AS_STRING.getPreferredName(), format.format(max()));
            }

            builder.field(CommonFields.DOC_COUNT.getPreferredName(), docCount);
            aggregations.toXContentInternal(builder, params);
            builder.endObject();
            return builder;
        }

        @Override
        public int compareKey(InternalVariableWidthHistogram.Bucket other) {
            return Double.compare(centroid, other.centroid); // Use centroid for bucket ordering
        }

        public DocValueFormat getFormatter() {
            return format;
        }
    }

    static class EmptyBucketInfo {

        final InternalAggregations subAggregations;

        EmptyBucketInfo(InternalAggregations subAggregations) {
            this.subAggregations = subAggregations;
        }

        EmptyBucketInfo(StreamInput in) throws IOException {
            this(InternalAggregations.readFrom(in));
        }

        public void writeTo(StreamOutput out) throws IOException {
            subAggregations.writeTo(out);
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null || getClass() != obj.getClass()) {
                return false;
            }
            EmptyBucketInfo that = (EmptyBucketInfo) obj;
            return Objects.equals(subAggregations, that.subAggregations);
        }

        @Override
        public int hashCode() {
            return Objects.hash(getClass(), subAggregations);
        }
    }

    private List<Bucket> buckets;
    private final DocValueFormat format;
    private final int targetNumBuckets;
    final EmptyBucketInfo emptyBucketInfo;

    InternalVariableWidthHistogram(String name, List<Bucket> buckets, EmptyBucketInfo emptyBucketInfo, int targetNumBuckets,
                                   DocValueFormat formatter, Map<String, Object> metaData){
        super(name, metaData);
        this.buckets = buckets;
        this.emptyBucketInfo = emptyBucketInfo;
        this.format = formatter;
        this.targetNumBuckets = targetNumBuckets;
    }

    /**
     * Stream from a stream.
     */
    public InternalVariableWidthHistogram(StreamInput in) throws IOException{
        super(in);
        emptyBucketInfo = new EmptyBucketInfo(in);
        format = in.readNamedWriteable(DocValueFormat.class);
        buckets = in.readList(stream -> new Bucket(stream, format));
        targetNumBuckets = in.readVInt();
    }

    @Override
    protected void doWriteTo(StreamOutput out) throws IOException {
        emptyBucketInfo.writeTo(out);
        out.writeNamedWriteable(format);
        out.writeList(buckets);
        out.writeVInt(targetNumBuckets);
    }

    @Override
    public String getWriteableName() {
        return VariableWidthHistogramAggregationBuilder.NAME;
    }

    @Override
    public List<Bucket> getBuckets() {
        return Collections.unmodifiableList(buckets);
    }

    DocValueFormat getFormatter() {
        return format;
    }

    public int getTargetBuckets() {
        return targetNumBuckets;
    }

    public EmptyBucketInfo getEmptyBucketInfo() {
        return emptyBucketInfo;
    }

    @Override
    public InternalVariableWidthHistogram create(List<Bucket> buckets) {
        return new InternalVariableWidthHistogram(name, buckets, emptyBucketInfo, targetNumBuckets,
            format,  metadata);
    }

    @Override
    public Bucket createBucket(InternalAggregations aggregations, Bucket prototype) {
        return new Bucket(prototype.centroid, prototype.bounds, prototype.docCount, prototype.format, aggregations);
    }

    @Override
    public Bucket createBucket(Number key, long docCount, InternalAggregations aggregations) {
        return new Bucket(key.doubleValue(), new Bucket.BucketBounds(key.doubleValue(), key.doubleValue()),
            docCount, format, aggregations);
    }

    @Override
    public Number getKey(MultiBucketsAggregation.Bucket bucket) {
        return ((Bucket) bucket).centroid;
    }

    @Override
    public Number nextKey(Number key) {
        return nextKey(key.doubleValue());
    }

    /**
     * This method should not be called for this specific subclass of InternalHistogram, since there should not be
     * empty buckets when clustering.
=    */
    private double nextKey(double key){ return key + 1; }

    private static class IteratorAndCurrent {

        private final Iterator<Bucket> iterator;
        private Bucket current;

        IteratorAndCurrent(Iterator<Bucket> iterator) {
            this.iterator = iterator;
            current = iterator.next();
        }

    }

    @Override
    protected Bucket reduceBucket(List<Bucket> buckets, ReduceContext context) {
        List<InternalAggregations> aggregations = new ArrayList<>(buckets.size());
        long docCount = 0;
        double min = Double.POSITIVE_INFINITY;
        double max = Double.NEGATIVE_INFINITY;
        double sum = 0;
        for (InternalVariableWidthHistogram.Bucket bucket : buckets) {
            docCount += bucket.docCount;
            min = Math.min(min, bucket.bounds.min);
            max = Math.max(max, bucket.bounds.max);
            sum += bucket.docCount * bucket.centroid;
            aggregations.add((InternalAggregations) bucket.getAggregations());
        }
        InternalAggregations aggs = InternalAggregations.reduce(aggregations, context);
        double centroid = sum / docCount;
        Bucket.BucketBounds bounds = new Bucket.BucketBounds(min, max);
        return new Bucket(centroid, bounds, docCount, format, aggs);
    }

    public List<Bucket> reduceBuckets(List<InternalAggregation> aggregations, ReduceContext reduceContext) {
        PriorityQueue<IteratorAndCurrent> pq = new PriorityQueue<IteratorAndCurrent>(aggregations.size()) {
            @Override
            protected boolean lessThan(IteratorAndCurrent a, IteratorAndCurrent b) {
                return Double.compare(a.current.centroid, b.current.centroid) < 0;
            }
        };
        for (InternalAggregation aggregation : aggregations) {
            InternalVariableWidthHistogram histogram = (InternalVariableWidthHistogram) aggregation;
            if (histogram.buckets.isEmpty() == false) {
                pq.add(new IteratorAndCurrent(histogram.buckets.iterator()));
            }
        }

        List<Bucket> reducedBuckets = new ArrayList<>();
        if(pq.size() > 0) {
            double key = pq.top().current.centroid();
            // list of buckets coming from different shards that have the same key
            List<Bucket> currentBuckets = new ArrayList<>();
            do {
                IteratorAndCurrent top = pq.top();

                if (Double.compare(top.current.centroid(), key) != 0) {
                    // The key changes, reduce what we already buffered and reset the buffer for current buckets.
                    final Bucket reduced = reduceBucket(currentBuckets, reduceContext);
                    reduceContext.consumeBucketsAndMaybeBreak(1);
                    reducedBuckets.add(reduced);
                    currentBuckets.clear();
                    key = top.current.centroid();
                }

                currentBuckets.add(top.current);

                if (top.iterator.hasNext()) {
                    Bucket next = top.iterator.next();
                    assert next.compareKey(top.current) >= 0 : "shards must return data sorted by centroid";
                    top.current = next;
                    pq.updateTop();
                } else {
                    pq.pop();
                }
            } while(pq.size() > 0);

            if (currentBuckets.isEmpty() == false) {
                final Bucket reduced = reduceBucket(currentBuckets, reduceContext);
                reduceContext.consumeBucketsAndMaybeBreak(1);
                reducedBuckets.add(reduced);
            }
        }

        mergeBucketsIfNeeded(reducedBuckets, targetNumBuckets, reduceContext);
        return reducedBuckets;
    }

    class BucketRange{
        int startIdx;
        int endIdx;

        /**
         * These are optional utility fields
         * They're useful for determining whether buckets should be merged
         */
        double min;
        double max;
        double centroid;
        long docCount;

        public void mergeWith(BucketRange other){
            startIdx = Math.min(startIdx, other.startIdx);
            endIdx = Math.max(endIdx, other.endIdx);

            if(docCount + other.docCount > 0) {
                // Avoids div by 0 error. This condition could be false if the optional docCount field was not set
                centroid = ((centroid * docCount) + (other.centroid * other.docCount)) / (docCount + other.docCount);
                docCount += other.docCount;
            }
            min = Math.min(min, other.min);
            max = Math.max(max, other.max);
        }
    }

    /**
     * For each range {startIdx, endIdx} in ranges, all the buckets in that index range
     * from buckets are merged, and this merged bucket replaces the entire range.
     */
    private void mergeBucketsWithPlan(List<Bucket> buckets, List<BucketRange> plan, ReduceContext reduceContext){
        for(int i = plan.size() - 1; i >= 0; i--) {
            BucketRange range = plan.get(i);
            int endIdx = range.endIdx;
            int startIdx = range.startIdx;

            if(startIdx == endIdx) continue;

            List<Bucket> toMerge = new ArrayList<>();
            for(int idx = endIdx; idx > startIdx; idx--){
                toMerge.add(buckets.get(idx));
                buckets.remove(idx);
            }
            toMerge.add(buckets.get(startIdx)); // Don't remove the startIdx bucket because it will be replaced by the merged bucket

            int toRemove = toMerge.stream().mapToInt(b -> countInnerBucket(b)+1).sum();
            reduceContext.consumeBucketsAndMaybeBreak(-toRemove + 1);
            Bucket merged_bucket = reduceBucket(toMerge, reduceContext);

            buckets.set(startIdx, merged_bucket);
        }
    }

    /**
     * Makes a merge plan by simulating the merging of the two closest buckets, until the target number of buckets is reached.
     * Distance is determined by centroid comparison.
     * Then, this plan is actually executed and the underlying buckets are merged.
     *
     * Requires: buckets is sorted by centroid.
     */
    private void mergeBucketsIfNeeded(List<Bucket> buckets, int targetNumBuckets, ReduceContext reduceContext) {
        // Make a plan for getting the target number of buckets
        // Each range represents a set of adjacent bucket indices of buckets that will be merged together
        List<BucketRange> ranges = new ArrayList<>();

        // Initialize each range to represent an individual bucket
        for (int i = 0; i < buckets.size(); i++) {
            // Since buckets is sorted by centroid, ranges will be as well
            BucketRange range = new BucketRange();
            range.centroid = buckets.get(i).centroid;
            range.docCount = buckets.get(i).getDocCount();
            range.startIdx = i;
            range.endIdx = i;
            ranges.add(range);
        }

        // Continually merge the two closest ranges until the target is reached
        while (ranges.size() > targetNumBuckets) {

            // Find two closest ranges (i.e. the two closest buckets after the previous merges are completed)
            // We only have to make one pass through the list because it is sorted by centroid
            int closestIdx = 0; // After this loop, (closestIdx, closestIdx + 1) will be the 2 closest buckets
            double smallest_distance = Double.POSITIVE_INFINITY;
            for (int i = 0; i < ranges.size() - 1; i++) {
                double new_distance = ranges.get(i + 1).centroid - ranges.get(i).centroid; // Positive because buckets is sorted
                if (new_distance < smallest_distance) {
                    closestIdx = i;
                    smallest_distance = new_distance;
                }
            }
            // Merge the two closest ranges
            ranges.get(closestIdx).mergeWith(ranges.get(closestIdx + 1));
            ranges.remove(closestIdx + 1);
        }

        // Execute the plan (merge the underlying buckets)
        mergeBucketsWithPlan(buckets, ranges, reduceContext);
    }

    private void mergeBucketsWithSameMin(List<Bucket> buckets, ReduceContext reduceContext){
        // Create a merge plan
        List<BucketRange> ranges = new ArrayList<>();

        // Initialize each range to represent an individual bucket
        for (int i = 0; i < buckets.size(); i++) {
            BucketRange range = new BucketRange();
            range.min = buckets.get(i).min();
            range.startIdx = i;
            range.endIdx = i;
            ranges.add(range);
        }

        // Merge ranges with same min value
        int i = 0;
        while(i < ranges.size() - 1){
            BucketRange range = ranges.get(i);
            BucketRange nextRange = ranges.get(i+1);

            if(range.min == nextRange.min){
                range.mergeWith(nextRange);
                ranges.remove(i+1);
            } else{
                i++;
            }
        }

        // Execute the plan (merge the underlying buckets)
        mergeBucketsWithPlan(buckets, ranges, reduceContext);
    }

    /**
     * When two adjacent buckets A, B overlap (A.max > B.min) then their boundary is set to
     * the midpoint: (A.max + B.min) / 2.
     *
     * After this adjustment, A will contain more values than indicated and B will have less.
     */
    private void adjustBoundsForOverlappingBuckets(List<Bucket> buckets, ReduceContext reduceContext){
        for(int i = 1; i < buckets.size(); i++){
            Bucket curBucket = buckets.get(i);
            Bucket prevBucket = buckets.get(i-1);
            if(curBucket.bounds.min < prevBucket.bounds.max){
                // We don't want overlapping buckets --> Adjust their bounds
                // TODO: Think of a fairer way to do this. Should prev.max = cur.min?
                curBucket.bounds.min = (prevBucket.bounds.max + curBucket.bounds.min) / 2;
                prevBucket.bounds.max = curBucket.bounds.min;
            }
        }
    }

    @Override
    public InternalAggregation reduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) {
        List<Bucket> reducedBuckets = reduceBuckets(aggregations, reduceContext);

        if(reduceContext.isFinalReduce()) {
            buckets.sort(Comparator.comparing(Bucket::min));
            mergeBucketsWithSameMin(reducedBuckets, reduceContext);
            adjustBoundsForOverlappingBuckets(reducedBuckets, reduceContext);
        }
        return new InternalVariableWidthHistogram(getName(), reducedBuckets, emptyBucketInfo, targetNumBuckets,
            format, metadata);
    }

    @Override
    public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
        builder.startArray(CommonFields.BUCKETS.getPreferredName());
        for (Bucket bucket : buckets) {
            bucket.toXContent(builder, params);
        }
        builder.endArray();
        return builder;
    }

    @Override
    public InternalAggregation createAggregation(List<MultiBucketsAggregation.Bucket> buckets) {
        // convert buckets to the right type
        List<Bucket> buckets2 = new ArrayList<>(buckets.size());
        for (Object b : buckets) {
            buckets2.add((Bucket) b);
        }
        buckets2 = Collections.unmodifiableList(buckets2);
        return new InternalVariableWidthHistogram(name, buckets2, emptyBucketInfo, targetNumBuckets,
            format, getMetadata());
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        if (super.equals(obj) == false) return false;

        InternalVariableWidthHistogram that = (InternalVariableWidthHistogram) obj;
        return Objects.equals(buckets, that.buckets)
                && Objects.equals(format, that.format)
                && Objects.equals(emptyBucketInfo, that.emptyBucketInfo);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), buckets, format, emptyBucketInfo);
    }
}


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

import com.facebook.airlift.log.Logger;
import com.facebook.presto.Session;
import com.facebook.presto.execution.DDLDefinitionTask;
import com.facebook.presto.execution.ExecutionFailureInfo;
import com.facebook.presto.execution.QueryStateTimer;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.security.AccessControl;
import com.facebook.presto.spark.classloader_interface.IPrestoSparkQueryExecution;
import com.facebook.presto.spi.WarningCollector;
import com.facebook.presto.sql.tree.Statement;
import com.facebook.presto.transaction.TransactionInfo;
import com.facebook.presto.transaction.TransactionManager;
import com.google.common.util.concurrent.ListenableFuture;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static com.facebook.airlift.concurrent.MoreFutures.getFutureValue;
import static com.facebook.presto.spark.util.PrestoSparkFailureUtils.toPrestoSparkFailure;
import static com.facebook.presto.util.Failures.toFailure;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;

public class PrestoSparkDataDefinitionExecution<T extends Statement>
        implements IPrestoSparkQueryExecution
{
    private static final Logger log = Logger.get(PrestoSparkDataDefinitionExecution.class);

    private final DDLDefinitionTask<T> task;
    private final T statement;
    private final TransactionManager transactionManager;
    private final AccessControl accessControl;
    private final Metadata metadata;
    private final Session session;
    private final QueryStateTimer queryStateTimer;
    private final WarningCollector warningCollector;

    public PrestoSparkDataDefinitionExecution(
            DDLDefinitionTask<T> task,
            T statement,
            TransactionManager transactionManager,
            AccessControl accessControl,
            Metadata metadata,
            Session session,
            QueryStateTimer queryStateTimer,
            WarningCollector warningCollector)
    {
        this.task = requireNonNull(task, "task is null");
        this.statement = requireNonNull(statement, "statement is null");
        this.transactionManager = requireNonNull(transactionManager, "transactionManager is null");
        this.accessControl = requireNonNull(accessControl, "accessControl is null");
        this.metadata = requireNonNull(metadata, "metadata is null");
        this.session = requireNonNull(session, "session is null");
        this.queryStateTimer = requireNonNull(queryStateTimer, "queryStateTimer is null");
        this.warningCollector = requireNonNull(warningCollector, "warningCollector is null");
    }

    @Override
    public List<List<Object>> execute()
    {
        queryStateTimer.beginRunning();
        try {
            ListenableFuture<?> future = task.execute(statement, transactionManager, metadata, accessControl, session, Collections.emptyList(), warningCollector);
            getFutureValue(future);
            queryStateTimer.beginFinishing();
            commit(session, transactionManager);
            queryStateTimer.endQuery();
        }
        catch (Throwable executionException) {
            queryStateTimer.beginFinishing();
            try {
                rollback(session, transactionManager);
            }
            catch (RuntimeException rollbackFailure) {
                log.error(rollbackFailure, "Encountered error when performing rollback");
            }

            Optional<ExecutionFailureInfo> failureInfo = Optional.of(toFailure(executionException));
            queryStateTimer.endQuery();

            throw toPrestoSparkFailure(session, failureInfo.get());
        }
        return Collections.emptyList();
    }

    private static void commit(Session session, TransactionManager transactionManager)
    {
        getFutureValue(transactionManager.asyncCommit(getTransactionInfo(session, transactionManager).getTransactionId()));
    }

    private static void rollback(Session session, TransactionManager transactionManager)
    {
        getFutureValue(transactionManager.asyncAbort(getTransactionInfo(session, transactionManager).getTransactionId()));
    }

    private static TransactionInfo getTransactionInfo(Session session, TransactionManager transactionManager)
    {
        Optional<TransactionInfo> transaction = session.getTransactionId()
                .flatMap(transactionManager::getOptionalTransactionInfo);
        checkState(transaction.isPresent(), "transaction is not present");
        checkState(transaction.get().isAutoCommitContext(), "transaction doesn't have auto commit context enabled");
        return transaction.get();
    }
}


text:
#ifndef CHILD_NODE_STUB_H_INCLUDED
#define CHILD_NODE_STUB_H_INCLUDED

#include "child-node.h"

template <typename charT>
class child_node_stub : public xml::basic_child_node<charT>
{
public:
    typedef          xml::basic_node_interface<charT> node_interface_t;
    typedef typename node_interface_t::type_t         type_t;

    typedef          xml::basic_child_node<charT> child_t;
    typedef typename child_t::child_pointer_t     child_pointer_t;
    typedef typename child_t::child_move_t        child_move_t;

    typedef typename child_t::parent_t            parent_t;
    typedef typename child_t::parent_pointer_t    parent_pointer_t;
    typedef typename child_t::parent_reference_t  parent_reference_t;

    child_node_stub(parent_pointer_t parent = nullptr)
    :
        child_t(parent),
        mId(sIdCreator++),
        mCopyConstructed(false),
        mNumCopy(0),
        mMoveConstructed(false),
        mHasBeenMoved(false)
    {
        ++sObjectNumber;
    }

    child_node_stub(const child_node_stub<charT>& rhs)
    :
        child_t(rhs.mParent),
        mId(rhs.mId),
        mCopyConstructed(true),
        mNumCopy(0),
        mMoveConstructed(false),
        mHasBeenMoved(false)
    {
        rhs.mNumCopy++;
        ++sObjectNumber;
    }

    child_node_stub(child_node_stub<charT>&& rhs)
    :
        child_t(rhs),
        mId(rhs.mId),
        mCopyConstructed(false),
        mNumCopy(0),
        mMoveConstructed(true),
        mHasBeenMoved(false)
    {
        rhs.mHasBeenMoved = true;
    }

    virtual ~child_node_stub()
    {
        if (!mHasBeenMoved)
            --sObjectNumber;
    }

    virtual type_t type () const
    {
        return node_interface_t::stringToType("child-node-stub");
    }

    virtual child_pointer_t clone() const
    {
        return new child_node_stub<charT>(*this);
    }

    virtual child_pointer_t clone(child_move_t rhs) const
    {
        return new child_node_stub<charT>(static_cast<child_node_stub<charT>&&>(rhs));
    }

    parent_pointer_t parent()
    {
        return child_t::mParent;
    }

    child_pointer_t previous()
    {
        return child_t::mPrevious;
    }

    child_pointer_t next()
    {
        return child_t::mNext;
    }

    int id() const
    {
        return mId;
    }

    bool copyConstructed() const
    {
        return mCopyConstructed;
    }

    int numCopy() const
    {
        return mNumCopy;
    }

    bool moveConstructed() const
    {
        return mMoveConstructed;
    }

    bool hasBeenMoved() const
    {
        return mHasBeenMoved;
    }

    static int objectNumber ()
    {
        return sObjectNumber;
    }

private:
    const int mId;

    mutable bool mCopyConstructed; // Whether this element is constructed from a copy
    mutable int  mNumCopy;         // How many times this element has been copied

    mutable bool mMoveConstructed; // Whether this element is constructed from a move
    mutable bool mHasBeenMoved;    // Whether this element has been moved

    static int sIdCreator;
    static int sObjectNumber;
};

template <typename charT>
int child_node_stub<charT>::sIdCreator = 0;

template <typename charT>
int child_node_stub<charT>::sObjectNumber = 0;

#endif /* CHILD_NODE_STUB_H_INCLUDED */


text:
#ifndef TRIANGLE_H
#define TRIANGLE_H

#include "myLogger.h"
#include "myGLFunctions.h"
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <string>

class Triangle {
public:
    Triangle();
    void    PerformGLInits();
    void    Render();
    void    SetViewport(int width, int height);
    bool    IsInitsDone(){return initsDone;}

private:
    void    RenderTriangle();
    void    AnimateTriangle();

    bool    initsDone;

    // vertex buffer for triangle's vertices, colors
    GLuint  vertexBuffer, colorBuffer;
    // will hold attributed for shader variables
    GLuint  vertexAttribute, colorAttribute;
    GLuint  shaderProgramID;

    float   triangleVertexDelta, triangleSwapRate;

};

#endif //TRIANGLE_H


text:
require "tracker/application/version"
require "tracker/application/create_story"
require "tracker/application/create_story_story"
require "tracker/application/load_story"
require "tracker/application/load_story_story"
require "tracker/application/load_unblocked_stories"
require "tracker/application/load_blocked_stories"
require "tracker/application/load_story_parent_story_stories"
require "tracker/application/load_story_child_story_stories"
require "tracker/application/load_epic_stories"
require "tracker/application/load_started_stories"
require "tracker/application/load_finished_stories"
require "tracker/application/load_closed_stories"
require "tracker/application/load_stories_list"
require "tracker/application/start_story"
require "tracker/application/finish_story"
require "tracker/application/close_story"
require "tracker/application/unstart_story"
require "tracker/application/unfinish_story"
require "tracker/application/unclose_story"
require "tracker/application/reset_story"

module Tracker
  module Application
  end
end


text:
**1) Which time management and productivity ideas did you learn about?**

I took a spin through most of the links, and the ones that really stuck out to me were the Pomodoro technique and the link on starting small.

I like the Pomodoro in concept because of its simplicity and use of timeboxing as a way of setting microbursts of productivity.

I like the idea of starting small, since I usually try to start big and find this one particularly applicable to me.

**2) What is "Time Boxing?" How can I use it in Phase 0?**

Timeboxing, as I understand it, is setting a time limit on a specific goal and stopping work on it once that time is reached. The Pomodoro technique could be one example of this (very small timebox). Sprints, as employed by many product teams, would be a longer one.

I think timeboxing could be particularly useful in Phase 0 for helping me get through challenges in a timely and efficient manner. In particular, because of the remote learning, there are concepts that may not stick, so taking the initiative to set limits will help chunk up the work in a way that makes it digestible and allows for breaks and reflection, which will be a good tactic for revisiting work later.

**3) How do I manage my time currently?**

I usually wake up with a few objectives in mind for the next day or two. And make sure that I accomplish those. I try to be fluid and allow for flexibility whenever possible, so as not to impose unnecessary deadlines, but keeping a checklist does help me ensure critical items get completed.

The other technique I employ is setting milestones for bigger goals. For example, if my goal this week is to complete all Week 1 assignments, I will break it up, just as the module has into smaller ones. As I progress through the week, I will make sure that sufficient progress is made mid-week, and later in the week, so that I give myself a realistic chance at completing the entire set of challenges.

**4) Is my current strategy working?**

I think it does. Usually, really critical goals always find a way of getting completed by the due date, since I allow myself to think about what's important each day, and give myself progress checks throughout the course of the week to ensure that I'm not leaving myself with a lot of last minute to-do's.

**5) Can I employ any of the strategies?**

I really think I will give the general notion of timeboxing (loosely with Pomodoro, but maybe not 25 minute increments) a more serious thought. I apply it loosely, but allowing myself to truly focus in without distraction is something I struggle a bit with, so giving myself 1 hour productivity sprints I think will really help me focus.

**6) What is my overall plan for Phase 0 time management?**

My plan is to use my current productivity methods (not trying to change too much), while making improvements using some of the tips here.

In particular, because the work is already structured out with timing expectations, I hope to follow the pathway while keeping myself in check so that I do not leave too much for the end of the week. I will have a part time job during phase 0, so I know that last minute cramming will be very detrimental. I've worked with my part time employer to ensure I have some flexibility and have set expectations on my time outside of work, to make sure I can accomplish my DBC commitments.

I will definitely try timeboxing during my DBC time as well. I sometimes struggle with more nebulous goals, especially ones that are related to self learning (I'm better in person), so I think the short bursts of productivity will be really helpful by placing confines with clear objectives.

# 1.2 The Command Line

**1) What is a shell? What is bash?**

The shell is the way to access the commands (in any OS) -- essentially the command line. Bash appears to be the default / more specific shell type in Unix based OS (like MacOS).

**2) What was most challenging?**

I struggled a bit with the piping and env commands toward the end, at least in understanding what exactly they do. I also don't understand how different modifiers (like -rf for rm) will work, but hopefully that will become more apparent as more use cases come up.

I think this exercise was a great intro, but it's still challenging to see how everything will get be used going forward.

**3) Was I successful in using the commands?**

I think so. Some of them still don't make 100% sense, but I took good notes and I'm sure will explore the use cases more later on.

**4) In my opinion, most useful?**

Besides "cd" (obvs!), I really liked "ls", which I think will help for orienting around what is there in a given directory. I also like "less", which sounds like it will be super useful once we're editing code directly in the terminal.

**5) Commands**

pwd:  Print working directory --> tells me where I am

ls:  Lists all files / paths in current directory (or another specified directory)

mv:  Deceptively appears to rename, rather than move!

cd:  Takes me to a given path specified

../: When used with cd, takes me up one directory

touch:  Creates a new file

mkdir:  Make directory --> creates a new directory

less:  Shows a full screen of a given file, space to paginate, q to exit

rmdir:  Deletes a specified directory, as long as there's nothing else in it

rm:  Deletes files, can delete a directory with things in it if specified correctly

help:  Brings up a help dialogue

# 1.3 Forking and Cloning

**1) If I were going to write instructions for a new person on how to create a new repo, fork a repo, and clone a repo, what would they be? Why would I fork a repository as opposed to create a new one?**

**Creating a new repo:**  To create a blank / empty repo, go to Github.com

1. Click the "+"  on the top right and select new repository
2. Name the repo
3. Choose the access settings (private or public)
4. Select a license as needed
5. Save

**Forking a repo**

1. Using an existing repository
2. Find the "fork" button near the top right
3. Select the destination (usually your own username) for where you'd like to fork the repo

**Cloning a repo**

1. On a given repo, find the HTTPS clone URL (middle / bottom right of the screen)
2. In the shell, navigate to the directory where you'd like to clone the repo using "cd"
3. Type "git clone" followed by the URL, and hit enter

**Why fork vs. create new?**

Forking to me seems like copying an existing repo with information and work already done in it. It would be used for projects with collaboration, where we'd want to work on existing code but not disrupt the master. It's like copy-paste in my mind.

Creating new is more to create an empty repo.

**2) What struggles did I have setting up Git and Github? What did I learn?**

No struggles for me, the installation of git via the shell was simple, and joining Github was fairly straightforward as well.

The key learning for me here was the distinction between Git and Github, which is that one is local and one is remote, and that the remote version is a great online tool used for collaboration with larger teams.


text:
using DKEngine;
using DKEngine.Core;
using DKEngine.Core.Components;
using MarIO.Assets.Models;
using MarIO.Assets.Scenes;
using System;
using static DKEngine.Core.Components.Transform;

namespace MarIO.Assets.Scripts
{
    internal class WorldEnd : Script
    {
        private Mario Player;
        private CharacterController PlayerController;
        private Animator PlayerAnimator;

        private float horiSpeed = 0;
        private float vertSpeed = 0;
        private float Distance = 180;
        private float startX;

        private const float MovementSpeed = 80f;
        private const float FloatSpeed = 300f;

        private const float Acceleration = 3.5f;

        private readonly TimeSpan _delay = new TimeSpan(0, 0, 3);
        private TimeSpan Delay = new TimeSpan();

        private string MOVE
        {
            get
            {
                switch (Player.CurrentState)
                {
                    case Mario.State.Small:
                        return horiSpeed >= 0 ? Shared.Assets.Animations.MARIO_MOVE_RIGHT : Shared.Assets.Animations.MARIO_MOVE_LEFT;

                    case Mario.State.Super:
                        return horiSpeed >= 0 ? Shared.Assets.Animations.MARIO_SUPER_MOVE_RIGHT : Shared.Assets.Animations.MARIO_SUPER_MOVE_LEFT;

                    case Mario.State.Fire:
                        return horiSpeed >= 0 ? Shared.Assets.Animations.MARIO_FIRE_MOVE_RIGHT : Shared.Assets.Animations.MARIO_FIRE_MOVE_LEFT;

                    /*case Mario.State.Invincible:
                        return horiSpeed >= 0 ? Shared.Assets.Animations.MARIO_INVINCIBLE_MOVE_RIGHT : Shared.Assets.Animations.MARIO_INVINCIBLE_MOVE_LEFT;*/

                    default:
                        throw new Exception("JAK");
                }
            }
        }

        private string IDLE
        {
            get
            {
                switch (Player.CurrentState)
                {
                    case Mario.State.Dead:
                    case Mario.State.Small:
                        return horiSpeed < 0 ? Shared.Assets.Animations.MARIO_IDLE_LEFT : Shared.Assets.Animations.MARIO_IDLE_RIGHT;

                    case Mario.State.Super:
                        return horiSpeed < 0 ? Shared.Assets.Animations.MARIO_SUPER_IDLE_LEFT : Shared.Assets.Animations.MARIO_SUPER_IDLE_RIGHT;

                    case Mario.State.Fire:
                        return horiSpeed < 0 ? Shared.Assets.Animations.MARIO_FIRE_IDLE_LEFT : Shared.Assets.Animations.MARIO_FIRE_IDLE_RIGHT;

                    /*case Mario.State.Invincible:
                        return IsFacingLeft ? Shared.Assets.Animations.MARIO_INVINCIBLE_IDLE_LEFT : Shared.Assets.Animations.MARIO_INVINCIBLE_IDLE_RIGHT;*/

                    default:
                        throw new Exception("JAK");
                }
            }
        }

        public WorldEnd(GameObject Parent) : base(Parent)
        {
            startX = Parent.Transform.Position.X;
        }

        protected override void OnColliderEnter(Collider e)
        {
            if (e.Parent is Mario)
                PlayerController.Enabled = false;
        }

        protected override void Start()
        {
            Player = GameObject.Find<Mario>("Player");
            PlayerAnimator = Component.Find<Animator>("Player_Animator");
            PlayerController = Script.Find<CharacterController>(nameof(CharacterController));
        }

        protected override void Update()
        {
            if (Shared.Mechanics.TimeLeft.TotalSeconds <= 0)
            {
                Player.CurrentState = Mario.State.Dead;
                Shared.Mechanics.TimeCounter.Stop();
            }

            if (!PlayerController.Enabled)
            {
                PlayerAnimator.Play(MOVE);

                if (!Player.Collider.Collision(Direction.Down))
                {
                    if (vertSpeed < FloatSpeed)
                    {
                        vertSpeed += Engine.DeltaTime * Acceleration * FloatSpeed;

                        if (vertSpeed > FloatSpeed)
                            vertSpeed = FloatSpeed;
                    }
                    else
                    {
                        vertSpeed = FloatSpeed;
                    }
                }

                if (Player.Transform.Position.X > startX + Distance)
                {
                    PlayerAnimator.Play(IDLE);
                    Delay += new TimeSpan(0, 0, 0, 0, (int)(Engine.DeltaTime * 1000));
                    if (_delay < Delay)
                    {
                        Shared.Mechanics.FXSoundSource.StopSound(Shared.Assets.Sounds.OVERWORLD_THEME_SOUND);
                        Engine.ChangeScene(nameof(GameOver), true);
                    }
                }
                else
                {
                    this.Player.Transform.Position += new Vector3(MovementSpeed * Engine.DeltaTime, vertSpeed, 0);
                }
            }
        }
    }
}


text:
package vm_test

import (
	"os"
	"path/filepath"

	. "github.com/grubby/grubby/interpreter/vm"
	. "github.com/grubby/grubby/interpreter/vm/builtins"
	. "github.com/grubby/grubby/testhelpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Eigenclasses", func() {
	var vm VM

	BeforeEach(func() {
		pathToExecutable, err := filepath.Abs(filepath.Dir(filepath.Dir(filepath.Dir(os.Args[0]))))
		if err != nil {
			panic(err)
		}

		vm = NewVM(pathToExecutable, "fake-irb-under-test")
	})

	Describe("opened by defining a method on a single object", func() {
		BeforeEach(func() {
			_, err := vm.Run(`
object = Object.new

def object.whatever
end
`)

			Expect(err).ToNot(HaveOccurred())
		})

		It("can store instance methods for a given object", func() {
			object := vm.MustGet("object")
			Expect(object).ToNot(BeNil())
			Expect(object).To(HaveMethod("whatever"))
		})

		It("lists its methods when Kernel#singleton_methods is invoked", func() {
			list, err := vm.Run(`
object.singleton_methods
`)

			Expect(err).ToNot(HaveOccurred())

			listAsArray, ok := list.(*Array)
			Expect(ok).To(BeTrue())

			Expect(len(listAsArray.Members())).To(Equal(1))
			Expect(listAsArray.Members()).To(ContainElement(vm.Symbols()["whatever"]))
		})
	})

	Describe("opened by the 'class << self' syntax", func() {
		BeforeEach(func() {
			_, err := vm.Run(`
class MyObject
  class << self
    def my_method
      'bewildering-wildebeest'
    end
  end
end
`)
			Expect(err).ToNot(HaveOccurred())
		})

		It("can store instance methods", func() {
			class := vm.MustGetClass("MyObject")
			Expect(class).To(HaveMethod("my_method"))
		})
	})
})


text:
require 'json'

module Att
  module Codekit
    module Auth

      # A container for tokens returned by the AT&T oauth api
      # @author kh455g
      class OAuthToken
        include Enumerable

        # Set default refresh token expiry to 24 hours (in seconds)
        DEFAULT_REFRESH_EXPIRES_IN = 60*60*24

        attr_reader :access_token, :refresh_token, :expiry, :expires_in, :refresh_expiry
        # @!attribute [r] access_token
        #   @return [String] token used for authentication
        # @!attribute [r] refresh_token
        #   @return [String] token used to refresh access_token if it expires
        # @!attribute [r] expiry
        #   @return [String] the date (seconds from epoch) the token expires
        # @!attribute [r] expires_in
        #   @return [String] the original seconds from request the token
        #     expires
        # @!attribute [r] refresh_expiry
        #   @return [String] the date (seconds from epoch) the refresh token
        #     expires
        alias_method :access, :access_token
        alias_method :refresh, :refresh_token

        # Construct an OAuthToken object
        #
        # @param access_token [String] token used for authentication
        # @param expiry [#to_i] a representation of time in seconds since
        #   epoch of when the token should expire. set nil if never expires
        # @param refresh_token [String] token used for re-obtaining an
        #   access_token after expiry.
        # @param expires_in [#to_i]  the original api response 'unparsed'
        #   expires_in (default: nil)
        def initialize(access_token, expiry, refresh_token, expires_in=nil, refresh_expiry=nil)
          @access_token = access_token
          @refresh_token = refresh_token
          @expiry = expiry.to_i if expiry
          @expires_in = expires_in
          @refresh_expiry = refresh_expiry.to_i
        end

        # Returns if this token can expire
        #
        # @return [Boolean] true if the token is allowed to expire
        def can_expire?
          return !!@expiry
        end

        # Check if access token is expired
        #
        # @return [Boolean] true if access token is expired, false if it's
        #   valid.
        def expired?
          can_expire? && @expiry < Time.now.to_i
        end

        # Returns if this refresh token can expire
        #
        # @return [Boolean] true if the token is allowed to expire
        def can_refresh_expire?
          return !!@refresh_expiry
        end

        # Check if refresh token is expired
        #
        # @return [Boolean] true if refresh token is expired, false if it's
        #   valid.
        def refresh_expired?
          can_refresh_expire? && @refresh_expiry < Time.now.to_i
        end

        # 'Each' definition for OAuthToken object
        #
        # @yieldparam access_token [String] The access token used for
        #   authentication
        # @yieldparam expiry [Time] the time that the access token expires
        # @yieldparam refresh_token [String] the token used to obtain an
        #   access token after expiry
        # @yieldparam expires_in [Integer] the original api response 'unparsed'
        #   expires_in if not nil (for backwards compatibility)
        def each
          yield @access_token
          yield @expiry
          yield @refresh_token
          yield @expires_in unless @expires_in.nil?
          yield @refresh_expiry unless @refresh_expiry.nil?
        end

        def eql?(other)
          self.class.equal?(other.class) &&
            @access_token == other.access_token &&
            @expiry == other.expiry &&
            @refresh_token == other.refresh_token
            @refresh_expiry == other.refresh_expiry
        end
        alias == eql?

        # Serialize token into a json object
        def to_json(*a)
          {
            "json_class" => self.class.name,
            "data" => [@access_token, @expiry, @refresh_token, @expires_in, @refresh_expiry]
          }.to_json(*a)
        end

        class << self # begin static methods

          # Factory method to create an object from a json string
          #
          # @param json [String] a json encoded string
          #
          # @return [OAuthToken] a parsed object
          def createFromJson(json)
            self.createFromParsedJson(JSON.parse(json))
          end

          # Factory method to create an object from a json string
          #
          # @param json [Object] a decoded json string
          #
          # @return [OAuthToken] a parsed object
          def createFromParsedJson(json)
            expires_in = json['expires_in']
            access_token = json['access_token']
            refresh_token = json['refresh_token']

            now = Time.now.to_i

            if expires_in
              #if expires_in is 0 then set expiration to 100 years
              if expires_in.to_i == 0
                expiry = now + (60*60*24*365*100) - 30
              else
                expiry = now + expires_in.to_i - 30
              end
            end

            refresh_expiry = now + DEFAULT_REFRESH_EXPIRES_IN

            new(access_token, expiry, refresh_token, expires_in, refresh_expiry)
          end

          # Deserialize a token object
          #
          # @return [OAuthToken] parsed oauth token object
          def json_create(o)
            new(*o["data"])
          end

          # Open file and save specified token
          #
          # @note Overwrites file if already exists.
          #
          # @param path [String] path of file to save token
          # @param token [OAuthToken] the token to save to file.
          def save_token(path, token)
            File.open(path, 'w') do |f|
              begin
                f.flock(File::LOCK_EX)
                f.puts token.to_json
              ensure
                f.flock(File::LOCK_UN)
              end
            end
          end
          alias_method :save, :save_token

          # Open file and return new OAuthToken
          #
          # @param path [String] path of file to load token from
          #
          # @return [OAuthToken] returns an OAuthToken object
          def open_token(path)
            File.open(path,'r') do |f|
              begin
                f.flock(File::LOCK_EX)
                JSON.load(f.read)
              ensure
                f.flock(File::LOCK_UN)
              end
            end
          end
          alias_method :open, :open_token
          alias_method :load, :open_token
          alias_method :load_token, :open_token

        end # end static methods

      end # END OF CLASS
    end
  end
end
#  vim: set ts=8 sw=2 sts=2 tw=79 et :


text:
package de.benjamindahlhoff.smog.UI;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.benjamindahlhoff.smog.Adapters.StationsAdapter;
import de.benjamindahlhoff.smog.Data.Station;
import de.benjamindahlhoff.smog.R;

/**
 * Created by benjamin on 04.02.17.
 */

public class StationsListActivity extends AppCompatActivity {
    ArrayList<Station> mStations = new ArrayList<>();
    @BindView(R.id.stationsListRecylerView) RecyclerView mStationsListRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stations);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        mStations = intent.getParcelableArrayListExtra(MainActivity.FEINSTAUB_STATIONS);

        StationsAdapter stationsAdapter = new StationsAdapter(this, mStations);
        mStationsListRecyclerView.setAdapter(stationsAdapter);

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        mStationsListRecyclerView.setLayoutManager(layoutManager);

        mStationsListRecyclerView.setHasFixedSize(true);
    }
}