text:
package cc.redpen.validator.section;

import cc.redpen.RedPen;
import cc.redpen.RedPenException;
import cc.redpen.config.Configuration;
import cc.redpen.config.ValidatorConfiguration;
import cc.redpen.model.Document;
import cc.redpen.model.Sentence;
import cc.redpen.validator.ValidationError;
import junit.framework.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DuplicatedSectionValidatorTest {

    @Test
    public void testDetectDuplicatedSection() throws RedPenException {
        Configuration config = Configuration.builder()
                .addValidatorConfig(new ValidatorConfiguration("DuplicatedSection"))
                .build();

        List<Document> documents = new ArrayList<>();
        documents.add(
                Document.builder()
                        .addSection(1)
                        .addSectionHeader("this is header")
                        .addParagraph()
                        .addSentence(new Sentence("he is a super man.", 1))
                        .addSection(1)
                        .addSectionHeader("this is header 2")
                        .addParagraph()
                        .addSentence(new Sentence("he is a super man.", 2))
                        .build());

        RedPen redPen = new RedPen(config);
        Map<Document, List<ValidationError>> errors = redPen.validate(documents);
        Assert.assertEquals(2, errors.get(documents.get(0)).size());
    }

    @Test
    public void testDetectNonDuplicatedSection() throws RedPenException {
        Configuration config = Configuration.builder()
                .addValidatorConfig(new ValidatorConfiguration("DuplicatedSection"))
                .build();

        List<Document> documents = new ArrayList<>();
        documents.add(
                Document.builder()
                        .addSection(1)
                        .addSectionHeader("foobar")
                        .addParagraph()
                        .addSentence(new Sentence("baz baz baz", 1))
                        .addSection(1)
                        .addSectionHeader("aho")
                        .addParagraph()
                        .addSentence(new Sentence("zoo zoo zoo", 2))
                        .build());

        RedPen redPen = new RedPen(config);
        Map<Document, List<ValidationError>> errors = redPen.validate(documents);
        Assert.assertEquals(0, errors.get(documents.get(0)).size());
    }

    @Test
    public void testDetectDuplicatedSectionWithSameHeader() throws RedPenException {
        Configuration config = Configuration.builder()
                .addValidatorConfig(new ValidatorConfiguration("DuplicatedSection"))
                .build();

        List<Document> documents = new ArrayList<>();
        documents.add(
                Document.builder()
                        .addSection(1)
                        .addSectionHeader("this is header.")
                        .addParagraph()
                        .addSentence(new Sentence("he is a super man.", 1))
                        .addSection(1)
                        .addSectionHeader("this is header.")
                        .addParagraph()
                        .addSentence(new Sentence("he is a super man.", 2))
                        .build());

        RedPen redPen = new RedPen(config);
        Map<Document, List<ValidationError>> errors = redPen.validate(documents);
        Assert.assertEquals(2, errors.get(documents.get(0)).size());
    }

    @Test
    public void testDetectNonDuplicatedSectionWithLowThreshold() throws RedPenException {
        Configuration config = Configuration.builder()
                .addValidatorConfig(new ValidatorConfiguration("DuplicatedSection").addProperty("threshold", "0.0"))
                .build();

        List<Document> documents = new ArrayList<>();
        // create two section which contains only one same word, "baz"
        documents.add(
        Document.builder()
                .addSection(1)
                .addSectionHeader("foobar")
                .addParagraph()
                .addSentence(new Sentence("baz foo foo", 1))
                .addSection(1)
                .addSectionHeader("aho")
                .addParagraph()
                .addSentence(new Sentence("baz zoo zoo", 2))
                .build());

        RedPen redPen = new RedPen(config);
        Map<Document, List<ValidationError>> errors = redPen.validate(documents);
        Assert.assertEquals(2, errors.get(documents.get(0)).size());
    }
}


text:
package org.elasticsearch.tasks;

import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.xcontent.XContentType;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

import static org.elasticsearch.tasks.TaskInfoTests.randomTaskInfo;

/**
 * Round trip tests for {@link TaskResult} and those classes that it includes like {@link TaskInfo} and {@link RawTaskStatus}.
 */
public class TaskResultTests extends ESTestCase {
    public void testBinaryRoundTrip() throws IOException {
        NamedWriteableRegistry registry = new NamedWriteableRegistry(
            Collections.singletonList(new NamedWriteableRegistry.Entry(Task.Status.class, RawTaskStatus.NAME, RawTaskStatus::new))
        );
        TaskResult result = randomTaskResult();
        TaskResult read;
        try (BytesStreamOutput out = new BytesStreamOutput()) {
            result.writeTo(out);
            try (StreamInput in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), registry)) {
                read = new TaskResult(in);
            }
        } catch (IOException e) {
            throw new IOException("Error processing [" + result + "]", e);
        }
        assertEquals(result, read);
    }

    public void testXContentRoundTrip() throws IOException {
        /*
         * Note that this round trip isn't 100% perfect - status will always be read as RawTaskStatus. Since this test uses RawTaskStatus
         * as the status we randomly generate then we can assert the round trip with .equals.
         */
        TaskResult result = randomTaskResult();
        TaskResult read;
        try (XContentBuilder builder = XContentBuilder.builder(randomFrom(XContentType.values()).xContent())) {
            result.toXContent(builder, ToXContent.EMPTY_PARAMS);
            try (XContentBuilder shuffled = shuffleXContent(builder); XContentParser parser = createParser(shuffled)) {
                read = TaskResult.PARSER.apply(parser, null);
            }
        } catch (IOException e) {
            throw new IOException("Error processing [" + result + "]", e);
        }
        assertEquals(result, read);
    }

    public void testTaskInfoIsForwardCompatible() throws IOException {
        TaskInfo taskInfo = randomTaskInfo();
        TaskInfo read;
        try (XContentBuilder builder = XContentBuilder.builder(randomFrom(XContentType.values()).xContent())) {
            builder.startObject();
            taskInfo.toXContent(builder, ToXContent.EMPTY_PARAMS);
            builder.endObject();
            try (XContentBuilder withExtraFields = addRandomUnknownFields(builder)) {
                try (XContentBuilder shuffled = shuffleXContent(withExtraFields)) {
                    try (XContentParser parser = createParser(shuffled)) {
                        read = TaskInfo.PARSER.apply(parser, null);
                    }
                }
            }
        } catch (IOException e) {
            throw new IOException("Error processing [" + taskInfo + "]", e);
        }
        assertEquals(taskInfo, read);
    }

    private XContentBuilder addRandomUnknownFields(XContentBuilder builder) throws IOException {
        try (XContentParser parser = createParser(builder)) {
            Map<String, Object> map = parser.mapOrdered();
            int numberOfNewFields = randomIntBetween(2, 10);
            for (int i = 0; i < numberOfNewFields; i++) {
                if (randomBoolean()) {
                    map.put("unknown_field" + i, randomAlphaOfLength(20));
                } else {
                    map.put("unknown_field" + i, Collections.singletonMap("inner", randomAlphaOfLength(20)));
                }
            }
            XContentBuilder xContentBuilder = XContentFactory.contentBuilder(parser.contentType());
            return xContentBuilder.map(map);
        }
    }

    private static TaskResult randomTaskResult() throws IOException {
        switch (between(0, 2)) {
            case 0:
                return new TaskResult(randomBoolean(), randomTaskInfo());
            case 1:
                return new TaskResult(randomTaskInfo(), new RuntimeException("error"));
            case 2:
                return new TaskResult(randomTaskInfo(), randomTaskResponse());
            default:
                throw new UnsupportedOperationException("Unsupported random TaskResult constructor");
        }
    }

    private static ToXContent randomTaskResponse() {
        Map<String, String> result = new TreeMap<>();
        int fields = between(0, 10);
        for (int f = 0; f < fields; f++) {
            result.put(randomAlphaOfLength(5), randomAlphaOfLength(5));
        }
        return new ToXContent() {
            @Override
            public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
                // Responses in Elasticsearch never output a leading startObject. There isn't really a good reason, they just don't.
                for (Map.Entry<String, String> entry : result.entrySet()) {
                    builder.field(entry.getKey(), entry.getValue());
                }
                return builder;
            }
        };
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

class CallBackTest extends DatabaseTest
{
	public function set_up($connection_name=null)
	{
		parent::set_up($connection_name);

		// ensure VenueCB model has been loaded
		VenueCB::find(1);

		$this->callback = new ActiveRecord\CallBack('VenueCB');
	}

	public function assert_has_callback($callback_name, $method_name=null)
	{
		if (!$method_name)
			$method_name = $callback_name;

		$this->assert_true(in_array($method_name,$this->callback->get_callbacks($callback_name)));
	}

	public function assert_implicit_save($first_method, $second_method)
	{
		$i_ran = array();
		$this->callback->register($first_method,function($model) use (&$i_ran, $first_method) { $i_ran[] = $first_method; });
		$this->callback->register($second_method,function($model) use (&$i_ran, $second_method) { $i_ran[] = $second_method; });
		$this->callback->invoke(null,$second_method);
		$this->assert_equals(array($first_method,$second_method),$i_ran);
	}

	public function test_gh_266_calling_save_in_after_save_callback_uses_update_instead_of_insert()
	{
		$venue = new VenueAfterCreate();
		$venue->name = 'change me';
		$venue->city = 'Awesome City';
		$venue->save();

		$this->assert_true(VenueAfterCreate::exists(array('conditions'=>
		     array('name'=>'changed!'))));
		$this->assert_false(VenueAfterCreate::exists(array('conditions'=>
		     array('name'=>'change me'))));
	}

	public function test_generic_callback_was_auto_registered()
	{
		$this->assert_has_callback('after_construct');
	}

	public function test_register()
	{
		$this->callback->register('after_construct');
		$this->assert_has_callback('after_construct');
	}

	public function test_register_non_generic()
	{
		$this->callback->register('after_construct','non_generic_after_construct');
		$this->assert_has_callback('after_construct','non_generic_after_construct');
	}

	/**
	 * @expectedException ActiveRecord\ActiveRecordException
	 */
	public function test_register_invalid_callback()
	{
		$this->callback->register('invalid_callback');
	}

	/**
	 * @expectedException ActiveRecord\ActiveRecordException
	 */
	public function test_register_callback_with_undefined_method()
	{
		$this->callback->register('after_construct','do_not_define_me');
	}

	public function test_register_with_string_definition()
	{
		$this->callback->register('after_construct','after_construct');
		$this->assert_has_callback('after_construct');
	}

	public function test_register_with_closure()
	{
		$this->callback->register('after_construct',function($mode) { });
	}

	public function test_register_with_null_definition()
	{
		$this->callback->register('after_construct',null);
		$this->assert_has_callback('after_construct');
	}

	public function test_register_with_no_definition()
	{
		$this->callback->register('after_construct');
		$this->assert_has_callback('after_construct');
	}

	public function test_register_appends_to_registry()
	{
		$this->callback->register('after_construct');
		$this->callback->register('after_construct','non_generic_after_construct');
		$this->assert_equals(array('after_construct','after_construct','non_generic_after_construct'),$this->callback->get_callbacks('after_construct'));
	}

	public function test_register_prepends_to_registry()
	{
		$this->callback->register('after_construct');
		$this->callback->register('after_construct','non_generic_after_construct',array('prepend' => true));
		$this->assert_equals(array('non_generic_after_construct','after_construct','after_construct'),$this->callback->get_callbacks('after_construct'));
	}

	public function test_registers_via_static_array_definition()
	{
		$this->assert_has_callback('after_destroy','after_destroy_one');
		$this->assert_has_callback('after_destroy','after_destroy_two');
	}

	public function test_registers_via_static_string_definition()
	{
		$this->assert_has_callback('before_destroy','before_destroy_using_string');
	}

	/**
	 * @expectedException ActiveRecord\ActiveRecordException
	 */
	public function test_register_via_static_with_invalid_definition()
	{
		$class_name = "Venues_" . md5(uniqid());
		eval("class $class_name extends ActiveRecord\\Model { static \$table_name = 'venues'; static \$after_save = 'method_that_does_not_exist'; };");
		new $class_name();
		new ActiveRecord\CallBack($class_name);
	}

	public function test_can_register_same_multiple_times()
	{
		$this->callback->register('after_construct');
		$this->callback->register('after_construct');
		$this->assert_equals(array('after_construct','after_construct','after_construct'),$this->callback->get_callbacks('after_construct'));
	}

	public function test_register_closure_callback()
	{
		$closure = function($model) {};
		$this->callback->register('after_save',$closure);
		$this->assert_equals(array($closure),$this->callback->get_callbacks('after_save'));
	}

	public function test_get_callbacks_returns_array()
	{
		$this->callback->register('after_construct');
		$this->assert_true(is_array($this->callback->get_callbacks('after_construct')));
	}

	public function test_get_callbacks_returns_null()
	{
		$this->assert_null($this->callback->get_callbacks('this_callback_name_should_never_exist'));
	}

	public function test_invoke_runs_all_callbacks()
	{
		$mock = $this->get_mock('VenueCB',array('after_destroy_one','after_destroy_two'));
		$mock->expects($this->once())->method('after_destroy_one');
		$mock->expects($this->once())->method('after_destroy_two');
		$this->callback->invoke($mock,'after_destroy');
	}

	public function test_invoke_closure()
	{
		$i_ran = false;
		$this->callback->register('after_validation',function($model) use (&$i_ran) { $i_ran = true; });
		$this->callback->invoke(null,'after_validation');
		$this->assert_true($i_ran);
	}

	public function test_invoke_implicitly_calls_save_first()
	{
		$this->assert_implicit_save('before_save','before_create');
		$this->assert_implicit_save('before_save','before_update');
		$this->assert_implicit_save('after_save','after_create');
		$this->assert_implicit_save('after_save','after_update');
	}

	/**
	 * @expectedException ActiveRecord\ActiveRecordException
	 */
	public function test_invoke_unregistered_callback()
	{
		$mock = $this->get_mock('VenueCB', array('columns'));
		$this->callback->invoke($mock,'before_validation_on_create');
	}

	public function test_before_callbacks_pass_on_false_return_callback_returned_false()
	{
		$this->callback->register('before_validation',function($model) { return false; });
		$this->assert_false($this->callback->invoke(null,'before_validation'));
	}

	public function test_before_callbacks_does_not_pass_on_false_for_after_callbacks()
	{
		$this->callback->register('after_validation',function($model) { return false; });
		$this->assert_true($this->callback->invoke(null,'after_validation'));
	}

	public function test_gh_28_after_create_should_be_invoked_after_auto_incrementing_pk_is_set()
	{
		$that = $this;
		VenueCB::$after_create = function($model) use ($that) { $that->assert_not_null($model->id); };
		ActiveRecord\Table::clear_cache('VenueCB');
		$venue = VenueCB::find(1);
		$venue = new VenueCB($venue->attributes());
		$venue->id = null;
		$venue->name = 'alksdjfs';
		$venue->save();
	}

	public function test_before_create_returned_false_halts_execution()
	{
		VenueCB::$before_create = array('before_create_halt_execution');
		ActiveRecord\Table::clear_cache('VenueCB');
		$table = ActiveRecord\Table::load('VenueCB');

		$i_ran = false;
		$i_should_have_ran = false;
		$table->callback->register('before_save', function($model) use (&$i_should_have_ran) { $i_should_have_ran = true; });
		$table->callback->register('before_create',function($model) use (&$i_ran) { $i_ran = true; });
		$table->callback->register('after_create',function($model) use (&$i_ran) { $i_ran = true; });

		$v = VenueCB::find(1);
		$v->id = null;
		VenueCB::create($v->attributes());

		$this->assert_true($i_should_have_ran);
		$this->assert_false($i_ran);
		$this->assert_true(strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'INSERT') === false);
	}

	public function test_before_save_returned_false_halts_execution()
	{
		VenueCB::$before_update = array('before_update_halt_execution');
		ActiveRecord\Table::clear_cache('VenueCB');
		$table = ActiveRecord\Table::load('VenueCB');

		$i_ran = false;
		$i_should_have_ran = false;
		$table->callback->register('before_save', function($model) use (&$i_should_have_ran) { $i_should_have_ran = true; });
		$table->callback->register('before_update',function($model) use (&$i_ran) { $i_ran = true; });
		$table->callback->register('after_save',function($model) use (&$i_ran) { $i_ran = true; });

		$v = VenueCB::find(1);
		$v->name .= 'test';
		$ret = $v->save();

		$this->assert_true($i_should_have_ran);
		$this->assert_false($i_ran);
		$this->assert_false($ret);
		$this->assert_true(strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'UPDATE') === false);
	}

	public function test_before_destroy_returned_false_halts_execution()
	{
		VenueCB::$before_destroy = array('before_destroy_halt_execution');
		ActiveRecord\Table::clear_cache('VenueCB');
		$table = ActiveRecord\Table::load('VenueCB');

		$i_ran = false;
		$table->callback->register('before_destroy',function($model) use (&$i_ran) { $i_ran = true; });
		$table->callback->register('after_destroy',function($model) use (&$i_ran) { $i_ran = true; });

		$v = VenueCB::find(1);
		$ret = $v->delete();

		$this->assert_false($i_ran);
		$this->assert_false($ret);
		$this->assert_true(strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'DELETE') === false);
	}

	public function test_before_validation_returned_false_halts_execution()
	{
		VenueCB::$before_validation = array('before_validation_halt_execution');
		ActiveRecord\Table::clear_cache('VenueCB');
		$table = ActiveRecord\Table::load('VenueCB');

		$v = VenueCB::find(1);
		$v->name .= 'test';
		$ret = $v->save();

		$this->assert_false($ret);
		$this->assert_true(strpos(ActiveRecord\Table::load('VenueCB')->last_sql, 'UPDATE') === false);
	}
}


text:
package grails.plugins.jaxrs.support;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;

/**
 * Base class for simple message body readers.
 *
 * @param T
 *            type of object to be read from the request entity.
 *
 * @author Martin Krasser
 */
public abstract class MessageBodyReaderSupport<T> extends ProviderSupport implements MessageBodyReader<T> {

    public MessageBodyReaderSupport() {
        setTypeArgument(ProviderUtils.getReaderTypeArgument(this));
    }

    /**
     * @see #isSupported(Class, Type, Annotation[], MediaType)
     */
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return isSupported(type, genericType, annotations, mediaType);
    }

    public T readFrom(Class<T> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
            throws IOException, WebApplicationException {
        return readFrom(httpHeaders, entityStream);
    }

    /**
     * Reads the request entity from the input stream and returns an object of
     * type given by this class type parameter.
     *
     * @param httpHeaders
     *            HTTP request headers.
     * @param entityStream
     *            request entity input stream.
     * @return object representation of entity stream.
     * @throws IOException -  TODO add desc
     * @throws WebApplicationException - TODO add desc
     */
    public abstract T readFrom(MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException;
}


text:
var app = angular.module('CrudApp',['ngRoute']);

app.config(['$routeProvider', function($routeProvider){
    $routeProvider
        .when('/', {
            templateUrl : 'app/list.html',
            controller : ListCtrl

        })
        .when('/addtamu',{
            templateUrl : 'app/add.html',
            controller : AddCtrl
        });
        .otherwise({
            redirectTo : '/'

        });

}]);

app.directive('loading', function () {
    return {
      restrict: 'E',
      replace:true,
      template: '

',
      link: function (scope, element, attr) {
              scope.$watch('loading', function (val) {
                if (val)
                    $(element).show();
                else
                    $(element).hide();
            });
        }
      };
});

function ListCtrl($scope, $http)
{
  $scope.loading = true;
  $http.get("http://ifcode.in/test_api.php?m=list")
    .success(function(data){
      //console.log(data);
      $scope.guest=data.data;

    })
    .finally(function(){
      $scope.loading = false;
    });

  $scope.clickMe = function(){
    alert('test');
  };

}

function AddCtrl($scope,$http,$location)
{

}


text:
/*jshint moz:true */
// vi: sts=2 sw=2 et
//
// accelerator setting based on
// https://github.com/ambrice/spatialnavigation-tastycactus.com/blob/master/prefs.js

const Lang = imports.lang;
const Signals = imports.signals;

const Gtk = imports.gi.Gtk;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;

const Gettext = imports.gettext.domain('gnome-shell-screenshot');
const _ = Gettext.gettext;

const Local = imports.misc.extensionUtils.getCurrentExtension();
const Path = Local.imports.path;
const Config = Local.imports.config;
const Filename = Local.imports.filename;
const Convenience = Local.imports.convenience;

let _settings;

const buildHbox = function () {
  return new Gtk.Box({
    orientation: Gtk.Orientation.HORIZONTAL,
    margin_top: 5,
    expand: false
  });
};

const ScreenshotToolSettingsWidget = new GObject.Class({
  Name: 'ScreenshotToolSettingsWidget',
  GTypeName: 'ScreenshotToolSettingsWidget',
  Extends: Gtk.Box,

  _init: function (params) {
    this.parent(params);
    this._initLayout();
  },

  _initLayout: function () {
    this._notebook = new Gtk.Notebook();

    let label;

    this._prefsIndicator = this._makePrefsIndicator();
    label = new Gtk.Label({label: _("Indicator")});
    this._notebook.append_page(this._prefsIndicator, label);

    this._prefsIndicator = this._makePrefsStorage();
    label = new Gtk.Label({label: _("Storage")});
    this._notebook.append_page(this._prefsIndicator, label);

    this._prefsKeybindings = this._makePrefsKeybindings();
    label = new Gtk.Label({label: _("Keybindings")});
    this._notebook.append_page(this._prefsKeybindings, label);

    this.add(this._notebook);
  },

  _makePrefsIndicator: function () {
    let prefs = new Gtk.Box({
      orientation: Gtk.Orientation.VERTICAL,
      margin: 20,
      margin_top: 10,
      expand: false
    });

    let hbox;

    /* Show indicator [on|off] */

    hbox = buildHbox();

    const labelShowIndicator = new Gtk.Label({
      label: _('Show indicator'),
      xalign: 0,
      expand: true
    });

    const switchShowIndicator = new Gtk.Switch();

    switchShowIndicator.connect('notify::active', (button) => {
      _settings.set_boolean(Config.KeyEnableIndicator, button.active);
    });

    switchShowIndicator.active = _settings.get_boolean(
        Config.KeyEnableIndicator
    );

    hbox.add(labelShowIndicator);
    hbox.add(switchShowIndicator);

    prefs.add(hbox, {fill: false});

    /* Default click action [dropdown] */

    hbox = buildHbox();

    const labelDefaultClickAction = new Gtk.Label({
      label: _('Default Click Action'),
      xalign: 0,
      expand: true
    });

    const clickActionOptions = [
      [_("Select Area")     , Config.ClickActions.SELECT_AREA],
      [_("Select Window")   , Config.ClickActions.SELECT_WINDOW],
      [_("Select Desktop")  , Config.ClickActions.SELECT_DESKTOP],
      [_("Show Menu")       , Config.ClickActions.SHOW_MENU]
    ];

    const currentClickAction = _settings.get_enum(Config.KeyClickAction);

    const comboBoxDefaultClickAction = this._getComboBox(
      clickActionOptions, GObject.TYPE_INT, currentClickAction,
      (value) => _settings.set_enum(Config.KeyClickAction, value)
    );

    hbox.add(labelDefaultClickAction);
    hbox.add(comboBoxDefaultClickAction);

    prefs.add(hbox, {fill: false});

    /* Clipboard Action [dropdown] */

    hbox = buildHbox();

    const labelClipboardContent = new Gtk.Label({
      label: _('Default Clipboard Content'),
      xalign: 0,
      expand: true
    });

    const comboBoxOptions = [
      [_("Unchanged")     , Config.ClipboardActions.NONE],
      [_("Image Data")    , Config.ClipboardActions.SET_IMAGE_DATA],
      // [_("Local Path")    , Config.ClipboardActions.SET_LOCAL_PATH]
      // TODO
      // [_("Remote URL")    , Config.ClipboardActions.SET_REMOTE_URL]
    ];

    const currentClipboardAction =
      _settings.get_string(Config.KeyClipboardAction);

    const comboBoxClipboardContent = this._getComboBox(
      comboBoxOptions, GObject.TYPE_STRING, currentClipboardAction,
      (value) => _settings.set_string(Config.KeyClipboardAction, value)
    );

    hbox.add(labelClipboardContent);
    hbox.add(comboBoxClipboardContent);

    prefs.add(hbox, {fill: false});

    return prefs;
  },

  _makePrefsStorage: function () {
    let prefs = new Gtk.Box({
      orientation: Gtk.Orientation.VERTICAL,
      margin: 20,
      margin_top: 10,
      expand: false
    });

    let hbox;

    /* Save Screenshot [on|off] */

    hbox = buildHbox();

    const labelSaveScreenshot = new Gtk.Label({
      label: _('Auto-Save Screenshot'),
      xalign: 0,
      expand: true
    });

    const switchSaveScreenshot = new Gtk.Switch();

    switchSaveScreenshot.connect('notify::active', (button) => {
      _settings.set_boolean(Config.KeySaveScreenshot, button.active);
    });

    switchSaveScreenshot.active = _settings.get_boolean(Config.KeySaveScreenshot);

    hbox.add(labelSaveScreenshot);
    hbox.add(switchSaveScreenshot);

    const saveScreenshotBindSensitivity = (actor) => {
      var setSensitive = () => {
        var sensitive = _settings.get_boolean(Config.KeySaveScreenshot);
        actor.set_sensitive(sensitive)
      };
      switchSaveScreenshot.connect('notify::active', setSensitive);
      setSensitive();
    };

    prefs.add(hbox, {fill: false});

    /* Save Location [filechooser] */

    hbox = buildHbox();

    const labelSaveLocation = new Gtk.Label({
      label: _('Save Location'),
      xalign: 0,
      expand: true
    });

    const chooserSaveLocation = new Gtk.FileChooserButton({
      title: _("Select"),
      local_only: true,
    });
    chooserSaveLocation.set_action(Gtk.FileChooserAction.SELECT_FOLDER);

    try {
      let saveLocation = Path.expand(
        _settings.get_string(Config.KeySaveLocation)
      );
      chooserSaveLocation.set_filename(saveLocation);
    } catch (e) {
      logError(e);
    }
    chooserSaveLocation.connect('file-set', () => {
      log("file-set");
      let dir = Path.expand(_settings.get_string(Config.KeySaveLocation));
      log("dir="+dir);
      let [filename, err] = GLib.filename_from_uri(
        chooserSaveLocation.get_uri()
      );
      if (err) {
        throw new Error("can't resolve uri");
      }
      _settings.set_string(Config.KeySaveLocation, filename);
    });

    saveScreenshotBindSensitivity(labelSaveLocation);
    saveScreenshotBindSensitivity(chooserSaveLocation);

    hbox.add(labelSaveLocation);
    hbox.add(chooserSaveLocation);

    prefs.add(hbox, {fill: false});

    /* Filename */
    hbox = buildHbox();

    const [defaultTemplate,] =
      _settings.get_default_value(Config.KeyFilenameTemplate).get_string();

    const mockDimensions = {width: 800, height: 600};

    const labelFilenameTemplate = new Gtk.Label({
      label: _('Default Filename'),
      xalign: 0,
      expand: true,
    });

    const inputFilenameTemplate = new Gtk.Entry({
      expand: true,
      tooltip_text: Filename.tooltipText(mockDimensions),
      secondary_icon_name: "document-revert",
    });

    hbox.add(labelFilenameTemplate);
    hbox.add(inputFilenameTemplate);

    inputFilenameTemplate.text =
      _settings.get_string(Config.KeyFilenameTemplate);

    prefs.add(hbox, {fill: false});

    /* Filename Preview */

    hbox = buildHbox();

    const labelPreview = new Gtk.Label({
      label: _('Preview'),
      expand: true,
      xalign: 0
    });

    const textPreview = new Gtk.Label({
      xalign: 0,
    });

    const setPreview = (tpl) => {
      try {
        if (tpl == "") {
          return;
        }
        inputFilenameTemplate.get_style_context().remove_class("error");
        let label = Filename.get(tpl, mockDimensions);
        textPreview.label = label;
        _settings.set_string(Config.KeyFilenameTemplate, tpl);
      } catch (e) {
        logError(e);
        textPreview.label = "";
        inputFilenameTemplate.get_style_context().add_class("error");
      }
    }

    ["inserted-text", "deleted-text"].forEach((name) => {
      inputFilenameTemplate.get_buffer().connect(name, ({text}) => {
        setPreview(text);
      })
    })

    inputFilenameTemplate.connect("icon-press", () => {
      inputFilenameTemplate.text = defaultTemplate;
    });

    setPreview(inputFilenameTemplate.text);

    hbox.add(labelPreview);
    hbox.add(textPreview);

    prefs.add(hbox);

    return prefs;
  },

  _makePrefsKeybindings: function () {
    let model = new Gtk.ListStore();

    model.set_column_types([
        GObject.TYPE_STRING,
        GObject.TYPE_STRING,
        GObject.TYPE_INT,
        GObject.TYPE_INT
    ]);

    let bindings = [
      ["shortcut-select-area", _("Select area")],
      ["shortcut-select-window", _("Select window")],
      ["shortcut-select-desktop", _("Select whole desktop")]
    ];

    for (let [name, description] of bindings) {
      log("binding: " + name + " description: " + description);
      let binding = _settings.get_strv(name)[0];

      let key, mods;

      if (binding) {
        [key, mods] = Gtk.accelerator_parse(binding);
      } else {
        [key, mods] = [0, 0];
      }

      let row = model.append();

      model.set(row, [0, 1, 2, 3], [name, description, mods, key]);
    }

    let treeview = new Gtk.TreeView({
        'expand': true,
        'model': model
    });

    let cellrend = new Gtk.CellRendererText();
    let col = new Gtk.TreeViewColumn({
      'title': _('Keyboard Shortcut'),
      'expand': true
    });

    col.pack_start(cellrend, true);
    col.add_attribute(cellrend, 'text', 1);
    treeview.append_column(col);

    cellrend = new Gtk.CellRendererAccel({
      'editable': true,
      'accel-mode': Gtk.CellRendererAccelMode.GTK
    });

    cellrend.connect('accel-edited', (rend, iter, key, mods) => {
      let value = Gtk.accelerator_name(key, mods);
      let [succ, iterator] = model.get_iter_from_string(iter);

      if (!succ) {
        throw new Error("Error updating keybinding");
      }

      let name = model.get_value(iterator, 0);

      model.set(iterator, [2, 3], [mods, key]);
      _settings.set_strv(name, [value]);
    });

    cellrend.connect('accel-cleared', (rend, iter, key, mods) => {
      let [succ, iterator] = model.get_iter_from_string(iter);

      if (!succ) {
        throw new Error("Error clearing keybinding");
      }

      let name = model.get_value(iterator, 0);

      model.set(iterator, [2, 3], [0, 0]);
      _settings.set_strv(name, []);
    });

    col = new Gtk.TreeViewColumn({'title': _('Modify'), min_width: 200});

    col.pack_end(cellrend, false);
    col.add_attribute(cellrend, 'accel-mods', 2);
    col.add_attribute(cellrend, 'accel-key', 3);
    treeview.append_column(col);

    return treeview;
  },

  _getComboBox: function (options, valueType, defaultValue, callback) {
    let model = new Gtk.ListStore();

    let Columns = { LABEL: 0, VALUE: 1 };

    model.set_column_types([GObject.TYPE_STRING, valueType]);

    let comboBox = new Gtk.ComboBox({model: model});
    let renderer = new Gtk.CellRendererText();

    comboBox.pack_start(renderer, true);
    comboBox.add_attribute(renderer, 'text', 0);

    for (let [label, value] of options) {
      let iter;

      model.set(
          iter = model.append(),
          [Columns.LABEL, Columns.VALUE],
          [label, value]
      );

      if (value === defaultValue) {
          comboBox.set_active_iter(iter);
      }
    }

    comboBox.connect('changed', (entry) => {
      let [success, iter] = comboBox.get_active_iter();

      if (!success) {
          return;
      }

      let value = model.get_value(iter, Columns.VALUE);

      callback(value);
    });

    return comboBox;
  }
});

function init() {
  _settings = Convenience.getSettings();
  Convenience.initTranslations();
}

function buildPrefsWidget() {
  let widget = new ScreenshotToolSettingsWidget();
  widget.show_all();

  return widget;
}


text:
#ifndef DEBUG_H
#define DEBUG_H

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif // HAVE_CONFIG_H

#ifndef __STDC_FORMAT_MACROS
// For travis and PRIu64
#  define __STDC_FORMAT_MACROS
#endif // __STDC_FORMAT_MACROS

#include <cinttypes>
#include <string_view>

#include <ngtcp2/ngtcp2.h>
#include <nghttp3/nghttp3.h>

namespace ngtcp2 {

namespace debug {

int handshake_completed(ngtcp2_conn *conn, void *user_data);

int handshake_confirmed(ngtcp2_conn *conn, void *user_data);

bool packet_lost(double prob);

void print_crypto_data(ngtcp2_crypto_level crypto_level, const uint8_t *data,
                       size_t datalen);

void print_stream_data(int64_t stream_id, const uint8_t *data, size_t datalen);

void print_initial_secret(const uint8_t *data, size_t len);

void print_client_in_secret(const uint8_t *data, size_t len);
void print_server_in_secret(const uint8_t *data, size_t len);

void print_handshake_secret(const uint8_t *data, size_t len);

void print_client_hs_secret(const uint8_t *data, size_t len);
void print_server_hs_secret(const uint8_t *data, size_t len);

void print_client_0rtt_secret(const uint8_t *data, size_t len);

void print_client_1rtt_secret(const uint8_t *data, size_t len);
void print_server_1rtt_secret(const uint8_t *data, size_t len);

void print_client_pp_key(const uint8_t *data, size_t len);
void print_server_pp_key(const uint8_t *data, size_t len);

void print_client_pp_iv(const uint8_t *data, size_t len);
void print_server_pp_iv(const uint8_t *data, size_t len);

void print_client_pp_hp(const uint8_t *data, size_t len);
void print_server_pp_hp(const uint8_t *data, size_t len);

void print_secrets(const uint8_t *secret, size_t secretlen, const uint8_t *key,
                   size_t keylen, const uint8_t *iv, size_t ivlen,
                   const uint8_t *hp, size_t hplen);

void print_secrets(const uint8_t *secret, size_t secretlen, const uint8_t *key,
                   size_t keylen, const uint8_t *iv, size_t ivlen);

void print_hp_mask(const uint8_t *mask, size_t masklen, const uint8_t *sample,
                   size_t samplelen);

void log_printf(void *user_data, const char *fmt, ...);

void path_validation(const ngtcp2_path *path,
                     ngtcp2_path_validation_result res);

void print_http_begin_request_headers(int64_t stream_id);

void print_http_begin_response_headers(int64_t stream_id);

void print_http_header(int64_t stream_id, const nghttp3_rcbuf *name,
                       const nghttp3_rcbuf *value, uint8_t flags);

void print_http_end_headers(int64_t stream_id);

void print_http_data(int64_t stream_id, const uint8_t *data, size_t datalen);

void print_http_begin_trailers(int64_t stream_id);

void print_http_end_trailers(int64_t stream_id);

void print_http_request_headers(int64_t stream_id, const nghttp3_nv *nva,
                                size_t nvlen);

void print_http_response_headers(int64_t stream_id, const nghttp3_nv *nva,
                                 size_t nvlen);

std::string_view secret_title(ngtcp2_crypto_level level);

} // namespace debug

} // namespace ngtcp2

#endif // DEBUG_H


text:
[![Build Status](https://travis-ci.org/runtimerevolution/survey.png?branch=master)](https://travis-ci.org/runtimerevolution/survey)
[![Code Climate](https://codeclimate.com/github/runtimerevolution/survey.png)](https://codeclimate.com/github/runtimerevolution/survey)
### Surveys on Rails...

Survey is a Rails Engine that brings quizzes, surveys and contests into your Rails
application. Survey models were designed to be flexible enough in order to be extended and
integrated with your own models. Survey was initially extracted from a real application that handles contests and quizzes.

## Documentation

You can view the Survey documentation in RDoc format here:

http://rubydoc.info/github/runtimerevolution/survey/frames

## Demo App

We have implemented a demo app for you to try out: [Demo App](http://survey-demo.herokuapp.com/surveys)

Here is the repository: https://github.com/runtimerevolution/survey-demo

## Main Features:
 - Surveys can limit the number of attempts for each participant
 - Questions can have multiple answers
 - Answers can have different weights
 - Base Scaffold Support for Active Admin, Rails Admin and default Rails Controllers
 - Base calculation for scores
 - Easy integration with your project

## Installation

Add survey to your Gemfile:
```ruby
gem "survey", "~> 0.1"
```
Then run bundle to install the Gem:
```sh
bundle install
```
Now generate and run migrations:
```sh
rails generate survey:install

bundle exec rake db:migrate
```

## Getting started with Survey

## Survey inside your models
To make a model aware of you just need to add `has_surveys` on it:
```ruby
class User < ActiveRecord::Base
  has_surveys

  #... (your code) ...
end
```
There is the concept of participant, in our example we choose the User Model.
Every participant can respond to surveys and every response is registered as a attempt.
By default, survey logic assumes an infinite number of attempts per participant
but if your surveys need to have a maximum number of attempts
you can pass the attribute `attempts_number` when creating them.
```ruby
# Each Participant can respond 4 times this survey
Survey::Survey.new(:name => "Star Wars Quiz", :description => "A quiz about Star Wars", :attempts_number => 4)
```
## Surveys used in your controllers
In this example we are using the current_user helper
but you can do it in the way you want.

```ruby
class ContestsController < ApplicationController

  helper_method :survey, :participant

  # create a new attempt to this survey
  def new
    @attempt = survey.attempts.new
    # build a number of possible answers equal to the number of options
    survey.questions.size.times { @attempt.answers.build }
  end

  # create a new attempt in this survey
  # an attempt needs to have a participant assigned
  def create
    @attempt = survey.attempts.new(params[:attempt])
    # ensure that current user is assigned with this attempt
    @attempt.participant = participant
    if @attempt.valid? and @attempt.save
      redirect_to contests_path
    else
      render :action => :new
    end
  end

  def participant
    @participant ||= current_user
  end

  def survey
    @survey ||= Survey::Survey.active.first
  end
end
```

## Survey inside your Views

### Controlling Survey avaliability per participant
To control which page participants see you can use method `avaliable_for_participant?`
that checks if the participant already spent his attempts.
```erb
<% if @survey.avaliable_for_participant?(@participant) %>
  <%= render 'form' %>
<% else %>
  Uupss, <%= @participant.name %> you have reach the maximum number of
  attempts for <%= @survey.name %>
<% end %>

<% # in _form.html.erb %>
<%= form_for [:contests, @attempt] do |f| %>
  <%= f.fields_for :answers do |builder| %>
    <ul>
      <% @survey.questions.each do |question| %>
        <li>
          <p><%= question.text %></p>
          <%= builder.hidden_field :question_id, :value => question.id %>
          <% question.options.each do |option| %>
            <%= builder.check_box :option_id, {}, option.id, nil %>
            <%= option.text %> <br/ >
          <% end -%>
        </li>
      <% end -%>
    </ul>
  <% end -%>
  <%= f.submit "Submit" %>
<% end -%>
```

### Scaffolds and CRUD frameworks
If you are using Rails Admin or Active Admin, you can generate base CRUD screens for Survey with:
```sh
rails generate survey active_admin

rails generate survey rails_admin
```
If you want a simple way to get started you can use the `plain` option which is a simple Rails scaffold to generate the controller and views related with survey logic.
By default when you type `rails g survey plain` it generates a controller in the `admin` namespace but you can choose your own namespace as well:
```sh
rails generate survey plain namespace:contests
```

By default when you generates your controllers using the `plain` command the task
generates the associated routes as well.
Afterwards if you want to generate more routes, you can using the command:

```sh
rails generate survey routes namespace:admin
```

## How to use it
Every user has a collection of attempts for each survey that he respond to. Is up to you to
make averages and collect reports based on that information.
What makes Survey useful is that all the logic behind surveys is now abstracted and well integrated,
making your job easier.

## Hacking with Survey through your Models:

```ruby
# select the first active Survey
survey = Survey::Survey.active.first

# select all the attempts from this survey
survey_answers = survey.attempts

# check the highest score for current user
user_highest_score  = survey_answers.for_participant(@user).high_score

#check the highest score made for this survey
global_highest_score = survey_answers.high_score
```
# Compability
### Rails
Survey supports Rails 3 and 4. For use in Rails 4. Rails 4 support is recent, so some minor issues may still be present,
please report them.

### Active Admin
Only support versions of Active Admin higher than 0.3.1.

# Roadmap

- Add a form builder or a helper to improve the creation of Survey forms.
- Add polymorphic relations to help the survey be extended with subclasses.
- Allow adding new fields without breaking the existent logic.

# License
Copyright © 2013 [Runtime Revolution](http://www.runtime-revolution.com), released under the MIT license.


text:
<?php
/**
 * Date: 07.10.12
 * Time: 1:14
 * Author: Ivan Voskoboynyk
 */
class AxisExtendsBehaviorSubclassStubBuilder extends PHP5ExtensionObjectBuilder
{
  const HOST_BEHAVIOR_NAME = 'axis_extends';

  public $overwrite = false;

  public function getPackage()
  {
    return $this->getTable()->getBehavior(static::HOST_BEHAVIOR_NAME)->getParameter('package') ?: parent::getPackage();
  }
  /**
   * Returns the qualified (prefixed) classname that is being built by the current class.
   * This method must be implemented by child classes.
   * @return string
   */
  public function getUnprefixedClassname()
  {
    return $this->getTable()->getBehavior(static::HOST_BEHAVIOR_NAME)->getParameter('class_name');
  }

  protected function addIncludes(&$script)
  {
    // nothing?
    // TODO: Add includes
  }

  protected function addClassOpen(&$script)
  {
    $table = $this->getTable();
    $this->declareClassFromBuilder($this->getObjectBuilder());
    $tableName = $table->getName();
    $tableDesc = $table->getDescription();

    $baseTableName = $this->getTable()->getBehavior(static::HOST_BEHAVIOR_NAME)->getParameter('extends');
    $baseClassname = 'Base'.$this->getClassname();

    $script .= "

/**
 * Skeleton subclass for representing a row from the '$tableName' table.
 *
 * $tableDesc
 *";
    if ($this->getBuildProperty('addTimeStamp')) {
      $now = strftime('%c');
      $script .= "
 * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on:
 *
 * $now
 *";
    }
    $script .= "
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.".$this->getPackage()."
 */
".($table->isAbstract() ? "abstract " : "")."class ".$this->getClassname()." extends $baseClassname {
";
  }
}


text:
namespace ExcelBenchmark.Tests
{
    using System.IO;
    using System.Linq;
    using System.Threading;

    using ExcelBenchmark.Tests.Extensions;

    using ExcelBenmark.Data;
    using ExcelBenmark.EPPPlusLib;

    using NUnit.Framework;

    public class ExcelBenchmarkTest
    {
        private readonly DataProvider dataProvider;

        public ExcelBenchmarkTest()
        {
            dataProvider = new DataProvider();

            if (Directory.Exists("out"))
            {
                Directory.Delete("out", true);
            }
            Thread.Sleep(100);

            Directory.CreateDirectory("out");
        }

        [Test]
        public void TestProduct()
        {
            var products = dataProvider.GetProducts().ToList().Duplicate(10000);
            var epplusTestCase = new EPPlusTestCase();
            epplusTestCase.ExportExcel(products, "out/epplustest.xlsx");
        }
    }
}


text:
require 'bundler'
Bundler.require :default, ENV['RACK_ENV'] || ENV['RAILS_ENV'] || :development

require './lib/ws_syncinator'
WSSyncinator.initialize!


text:
import sys
import json
import pronouncing

from flask import request
from flask_cors import CORS, cross_origin

from flask import Flask
app = Flask(__name__)

CORS(app)

@app.route("/homophone", methods=["POST"])
def processRequest():
    return json.dumps(homophones(request.get_json()["word"]))

"""
@param: word, a lowercase string
@returns: a list of homophones for word
"""
def homophones(word):
    phoneList = pronouncing.phones_for_word(word)
    results = []
    for phone in phoneList:
        # pronouncing.search uses pronouncing to search for a RegEx of sounds
        results.extend(pronouncing.search("^" + phone + "$"))
    return results
"""
Test cases:
bear, two, pear
"""
def main():
    print("BEAR:")
    for i in homophones("bear"):
        print(i)
    print("TWO:")
    for i in homophones("two"):
        print(i)
    print("PEAR")
    for i in homophones("pear"):
        print(i)

"""
if this script is called with arguments, return JSON for each arg's homophones
{ arg1 : ["homophone1","homophone2","homophone3",
arg2 : ["homophone1","homophone2"]

After processing, start up a web server
"""
if __name__ == '__main__':
    if len(sys.argv) > 1:
        result = {}
        for arg in sys.argv[1:]:
            result[arg] = homophones(arg)
        print(json.dumps(result))
    else:
        main()
    app.run()


text:
using namespace IECoreMaya;
using namespace IECore;

IECore::ConstObjectPtr ParameterisedHolderModificationCmd::g_originalValue = 0;
IECore::ConstCompoundDataPtr ParameterisedHolderModificationCmd::g_originalClasses = 0;
IECore::ConstObjectPtr ParameterisedHolderModificationCmd::g_newValue = 0;
IECore::ConstCompoundDataPtr ParameterisedHolderModificationCmd::g_newClasses = 0;

ParameterisedHolderModificationCmd::ParameterisedHolderModificationCmd()
	:	m_parameterisedHolder( 0 ), m_originalValues( 0 ), m_newValues( 0 ), m_changingClass( false )
{
}

ParameterisedHolderModificationCmd::~ParameterisedHolderModificationCmd()
{
}

void *ParameterisedHolderModificationCmd::creator()
{
	return new ParameterisedHolderModificationCmd;
}

bool ParameterisedHolderModificationCmd::isUndoable() const
{
	return true;
}

bool ParameterisedHolderModificationCmd::hasSyntax() const
{
	return false;
}

MStatus ParameterisedHolderModificationCmd::doIt( const MArgList &argList )
{
	// get the node we're operating on

	MSelectionList selection;
	selection.add( argList.asString( 0 ) );

	selection.getDependNode( 0, m_node );
	if( m_node.isNull() )
	{
		return MS::kFailure;
	}

	MFnDependencyNode fnNode( m_node );
	MPxNode *userNode = fnNode.userNode();
	m_parameterisedHolder = dynamic_cast<ParameterisedHolderInterface *>( userNode );
	if( !m_parameterisedHolder )
	{
		return MStatus::kFailure;
	}

	// if we're being asked to change class then store the details of the class we want to set
	// and the one we're replacing

	if( argList.length() == 4 )
	{
		std::string originalClassName;
		std::string originalSearchPathEnvVar;
		m_parameterisedHolder->getParameterised( &originalClassName, &m_originalClassVersion, &originalSearchPathEnvVar );
		m_originalClassName = originalClassName.c_str();
		m_originalSearchPathEnvVar = originalSearchPathEnvVar.c_str();

		m_newClassName = argList.asString( 1 );
		m_newClassVersion = argList.asInt( 2 );
		m_newSearchPathEnvVar = argList.asString( 3 );

		m_changingClass = true;
	}
	else if( argList.length() != 1 )
	{
		displayError( "ieParameterisedHolderSetParameterised : wrong number of arguments." );
		return MS::kFailure;
	}

	// store the original and new values of everything. these are just passed in from
	// the FnParameterisedHolder. in the case of changing the held class we won't have
	// any new values.

	m_originalValues = g_originalValue;
	m_originalClasses = g_originalClasses;
	m_newValues = g_newValue;
	m_newClasses = g_newClasses;

	g_originalValue = 0;
	g_originalClasses = 0;
	g_newValue = 0;
	g_newClasses = 0;

	// change the maya side class or monkey with the maya side class parameters as requested. then remember the new values
	// of everything and which parameters are changing so we can push them in and out during undo and redo.

	if( m_changingClass )
	{
		MStatus s = m_parameterisedHolder->setParameterised( m_newClassName.asChar(), m_newClassVersion, m_newSearchPathEnvVar.asChar() );
		if ( !s )
		{
			return s;
		}
		m_newValues = m_parameterisedHolder->getParameterisedInterface()->parameters()->getValue()->copy();
		storeParametersWithNewValues( m_originalValues, m_newValues, "" );
		despatchSetParameterisedCallbacks();
	}
	else
	{
		storeParametersWithNewValues( m_originalValues, m_newValues, "" );
		m_parameterisedHolder->updateParameterised();
		setNodeValuesForParametersWithNewValues();
		despatchClassSetCallbacks();
	}

	return MS::kSuccess;
}

MStatus ParameterisedHolderModificationCmd::undoIt()
{
	if( !m_parameterisedHolder )
	{
		return MStatus::kFailure;
	}

	MStatus s;
	if( m_changingClass )
	{
		s = m_parameterisedHolder->setParameterised( m_originalClassName.asChar(), m_originalClassVersion, m_originalSearchPathEnvVar.asChar() );
		if( !s )
		{
			return s;
		}
	}

	if( m_originalClasses->readable().size() )
	{
		restoreClassParameterStates( m_originalClasses, m_parameterisedHolder->getParameterisedInterface()->parameters(), "" );
		m_parameterisedHolder->updateParameterised();
	}

	if( m_originalValues )
	{
		m_parameterisedHolder->getParameterisedInterface()->parameters()->setValue( m_originalValues->copy() );
		setNodeValuesForParametersWithNewValues();
	}

	// despatch callbacks only when the dust has settled
	if( m_changingClass )
	{
		despatchSetParameterisedCallbacks();
	}
	else
	{
		despatchClassSetCallbacks();
	}

	return s;
}

MStatus ParameterisedHolderModificationCmd::redoIt()
{
	if( !m_parameterisedHolder )
	{
		return MStatus::kFailure;
	}

	if( m_changingClass )
	{
		MStatus s = m_parameterisedHolder->setParameterised( m_newClassName.asChar(), m_newClassVersion, m_newSearchPathEnvVar.asChar() );
		if ( !s )
		{
			return s;
		}
		despatchSetParameterisedCallbacks();
	}
	else
	{
		restoreClassParameterStates( m_newClasses, m_parameterisedHolder->getParameterisedInterface()->parameters(), "" );
		m_parameterisedHolder->getParameterisedInterface()->parameters()->setValue( m_newValues->copy() );
		m_parameterisedHolder->updateParameterised();
		setNodeValuesForParametersWithNewValues();
		despatchClassSetCallbacks();
	}

	return MS::kSuccess;
}

void ParameterisedHolderModificationCmd::restoreClassParameterStates( const IECore::CompoundData *classes, IECore::Parameter *parameter, const std::string &parentParameterPath )
{
	std::string parameterPath = parentParameterPath;
	if( parentParameterPath.size() )
	{
		parameterPath += ".";
	}
	parameterPath += parameter->name();

	if( parameter->isInstanceOf( "ClassParameter" ) )
	{
		const CompoundData *c = classes->member<const CompoundData>( parameterPath );
		if( c )
		{
			ClassParameterHandler::setClass(
				parameter,
				c->member<const IECore::StringData>( "className" )->readable().c_str(),
				c->member<const IECore::IntData>( "classVersion" )->readable(),
				c->member<const IECore::StringData>( "searchPathEnvVar" )->readable().c_str()
			);
		}
	}
	else if( parameter->isInstanceOf( "ClassVectorParameter" ) )
	{
		const CompoundData *c = classes->member<const CompoundData>( parameterPath );
		if( c )
		{
			IECore::ConstStringVectorDataPtr parameterNames = c->member<const IECore::StringVectorData>( "parameterNames" );
			IECore::ConstStringVectorDataPtr classNames = c->member<const IECore::StringVectorData>( "classNames" );
			IECore::ConstIntVectorDataPtr classVersions = c->member<const IECore::IntVectorData>( "classVersions" );
			MStringArray mParameterNames;
			MStringArray mClassNames;
			MIntArray mClassVersions;
			int numClasses = parameterNames->readable().size();
			for( int i=0; i<numClasses; i++ )
			{
				mParameterNames.append( parameterNames->readable()[i].c_str() );
				mClassNames.append( classNames->readable()[i].c_str() );
				mClassVersions.append( classVersions->readable()[i] );
			}
			ClassVectorParameterHandler::setClasses( parameter, mParameterNames, mClassNames, mClassVersions );
		}
	}

	if( parameter->isInstanceOf( IECore::CompoundParameter::staticTypeId() ) )
	{
		CompoundParameter *compoundParameter = static_cast<CompoundParameter *>( parameter );
		const CompoundParameter::ParameterVector &childParameters = compoundParameter->orderedParameters();
		for( CompoundParameter::ParameterVector::const_iterator it = childParameters.begin(); it!=childParameters.end(); it++ )
		{
			restoreClassParameterStates( classes, constPointerCast<Parameter>( *it ), parameterPath );
		}
	}
}

void ParameterisedHolderModificationCmd::storeParametersWithNewValues( const IECore::Object *originalValue, const IECore::Object *newValue, const std::string &parameterPath )
{
	if( !(originalValue && newValue) )
	{
		// if either of the values isn't present then a parameter is appearing and disappearing due to
		// Class*Parameter edits. we treat it as a parameter with a new value so that it'll get it's value
		// transferred into maya appropriately.
		m_parametersWithNewValues.insert( parameterPath );
	}
	else if( originalValue->typeId() != newValue->typeId() )
	{
		// types are different so there's clearly a new value involved
		m_parametersWithNewValues.insert( parameterPath );
	}
	else if( originalValue->isInstanceOf( CompoundObject::staticTypeId() ) )
	{
		// compound value, representing several child parameters - attempt to recurse.
		// we need to consider children of both the original and new parameters in case a parameter
		// exists only on one side.
		const CompoundObject *originalCompound = static_cast<const CompoundObject *>( originalValue );
		const CompoundObject *newCompound = static_cast<const CompoundObject *>( newValue );
		const CompoundObject::ObjectMap &originalChildren = originalCompound->members();
		for( CompoundObject::ObjectMap::const_iterator it = originalChildren.begin(); it!=originalChildren.end(); it++ )
		{
			std::string childParameterPath;
			if( parameterPath.size() )
			{
				childParameterPath = parameterPath + "." + it->first.value();
			}
			else
			{
				childParameterPath = it->first;
			}
			storeParametersWithNewValues( it->second, newCompound->member<Object>( it->first ), childParameterPath );
		}

		const CompoundObject::ObjectMap &newChildren = static_cast<const CompoundObject *>( newValue )->members();
		for( CompoundObject::ObjectMap::const_iterator it = newChildren.begin(); it!=newChildren.end(); it++ )
		{
			if( originalChildren.find( it->first )==originalChildren.end() )
			{
				// this is a child we didn't encounter in the first iteration.
				std::string childParameterPath;
				if( parameterPath.size() )
				{
					childParameterPath = parameterPath + "." + it->first.value();
				}
				else
				{
					childParameterPath = it->first;
				}
				storeParametersWithNewValues( 0, it->second, childParameterPath );
			}
		}
	}
	else
	{
		if( !originalValue->isEqualTo( newValue ) )
		{
			m_parametersWithNewValues.insert( parameterPath );
		}
	}
}

void ParameterisedHolderModificationCmd::setNodeValuesForParametersWithNewValues() const
{
	ParameterisedInterface *parameterised = m_parameterisedHolder->getParameterisedInterface();
	for( std::set<std::string>::const_iterator it=m_parametersWithNewValues.begin(); it!=m_parametersWithNewValues.end(); it++ )
	{
		Parameter *p = parameterFromPath( parameterised, *it );
		if( p )
		{
			setNodeValue( p );
		}
	}
}

void ParameterisedHolderModificationCmd::setNodeValue( IECore::Parameter *parameter ) const
{
	m_parameterisedHolder->setNodeValue( parameter );

	if( parameter->isInstanceOf( CompoundParameter::staticTypeId() ) )
	{
		// recurse to the children - this is the only reason this function
		// is necessary as ParameterisedHolder::setNodeValue() doesn't recurse.
		CompoundParameter *compoundParameter = static_cast<CompoundParameter *>( parameter );
		const CompoundParameter::ParameterVector &childParameters = compoundParameter->orderedParameters();
		for( CompoundParameter::ParameterVector::const_iterator it = childParameters.begin(); it!=childParameters.end(); it++ )
		{
			ParameterPtr childParameter = *it;
			setNodeValue( childParameter );
		}
	}
}

void ParameterisedHolderModificationCmd::despatchSetParameterisedCallbacks() const
{
	MFnDependencyNode fnNode( m_node );
	MString nodeName = fnNode.name();
	MFnDagNode fnDN( m_node );
	if( fnDN.hasObj( m_node ) )
	{
		nodeName = fnDN.fullPathName();
	}

	MGlobal::executePythonCommand( "import IECoreMaya; IECoreMaya.FnParameterisedHolder._despatchSetParameterisedCallbacks( \"" + nodeName + "\" )" );
}

void ParameterisedHolderModificationCmd::despatchClassSetCallbacks() const
{
	MFnDependencyNode fnNode( m_node );
	MString nodeName = fnNode.name();
	MFnDagNode fnDN( m_node );
	if( fnDN.hasObj( m_node ) )
	{
		nodeName = fnDN.fullPathName();
	}

	ParameterisedInterface *parameterised = m_parameterisedHolder->getParameterisedInterface();

	std::set<IECore::InternedString> names;
	for( IECore::CompoundDataMap::const_iterator it=m_originalClasses->readable().begin(); it!=m_originalClasses->readable().end(); it++ )
	{
		names.insert( it->first );
	}
	for( IECore::CompoundDataMap::const_iterator it=m_newClasses->readable().begin(); it!=m_newClasses->readable().end(); it++ )
	{
		names.insert( it->first );
	}

	for( std::set<IECore::InternedString>::const_iterator it=names.begin(); it!=names.end(); it++ )
	{
		Parameter *parameter = parameterFromPath( parameterised, *it );
		if( parameter )
		{
			IECore::CompoundDataMap::const_iterator it1 = m_originalClasses->readable().find( *it );
			IECore::CompoundDataMap::const_iterator it2 = m_newClasses->readable().find( *it );

			if( it1==m_originalClasses->readable().end() || it2==m_newClasses->readable().end() || !(it1->second->isEqualTo( it2->second ) ) )
			{
				MPlug parameterPlug = m_parameterisedHolder->parameterPlug( parameter );
				MString plugName = nodeName + "." + parameterPlug.partialName();
				if( parameter->isInstanceOf( "ClassParameter" ) )
				{
					MGlobal::executePythonCommand( "import IECoreMaya; IECoreMaya.FnParameterisedHolder._despatchSetClassParameterClassCallbacks( \"" + plugName + "\" )" );
				}
				else
				{
					MGlobal::executePythonCommand( "import IECoreMaya; IECoreMaya.FnParameterisedHolder._despatchSetClassVectorParameterClassesCallbacks( \"" + plugName + "\" )" );
				}
			}
		}
	}
}

IECore::Parameter *ParameterisedHolderModificationCmd::parameterFromPath( ParameterisedInterface *parameterised, const std::string &path ) const
{
	std::vector<std::string> names;
	boost::split( names, path, boost::is_any_of( "." ) );

	CompoundParameter *parent = parameterised->parameters();
	for( int i=0; i<(int)names.size(); i++ )
	{
		if( i==((int)names.size()-1) )
		{
			return parent->parameter<Parameter>( names[i] );
		}
		else
		{
			parent = parent->parameter<CompoundParameter>( names[i] );
			if( !parent )
			{
				return 0;
			}
		}
	}

	return 0;
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShrinkScale : Scale {

	// Use this for initialization
	void Start () {
        startingScale = transform.localScale;
        targetScale = new Vector3(scaleSize, scaleSize, scaleSize);
    }

    public void Shrink()
    {
        StartCoroutine(ScaleObject(transform.localScale, targetScale));
    }

    public void ResetShrink()
    {
        StartCoroutine(ScaleObject(transform.localScale, startingScale));
    }
}


text:
A Dockerfile for accelerated research process, consists of major machine learning libraries.

- [DockerHub](https://registry.hub.docker.com/u/uetchy/ml/)

## Features

- Ubuntu 18.04
- Python 3.6 (Miniconda 3)
- GPU accelerated (CUDA 10.0, cuDNN 7)
- NCCL, CNMeM, Apex (PyTorch only) activated
- Jupyter and OpenCV 3.0 included
- Additional packages (Tensorboard, Hyperdash, etc)

## Available Deep Learning Frameworks

- TensorFlow `uetchy/ml:tensorflow`
- PyTorch `uetchy/ml:pytorch`
- Chainer `uetchy/ml:chainer`
- MXnet `uetchy/ml:mxnet`
- XGBoost `uetchy/ml:xgboost`

## Install

### System Requirements

- Docker
- CUDA-enabled GPUs
- CUDA Driver
- CUDA Toolkit
- nvidia-docker2 (https://github.com/NVIDIA/nvidia-docker)

### Pull the docker image from [DockerHub](https://registry.hub.docker.com/u/uetchy/ml/)

```bash
docker pull uetchy/ml:tensorflow
docker pull uetchy/ml:pytorch
docker pull uetchy/ml:chainer
...
```

### Launch Jupyter Lab on current directory

```bash
docker run --runtime=nvidia -v $PWD:/workspace -p 8888:8888 -it uetchy/ml:pytorch jupyter
open http://localhost:8888
```

### Open Python REPL

```bash
docker run --runtime=nvidia --rm -it uetchy/ml:base python
```

### Run Bash Shell

```bash
docker run --runtime=nvidia --rm -it uetchy/ml:tensorflow
```

## List of Docker images for Data Science

- [TensorFlow](https://hub.docker.com/r/tensorflow/tensorflow)
- [Caffe2](https://hub.docker.com/r/caffe2ai/caffe2)
- [MXNet](https://hub.docker.com/u/mxnet)
- [Caffe](https://github.com/BVLC/caffe/tree/master/docker)

# Contribution

PRs are accepted.

## Contributors

- Yasuaki Uechi
- UpmostScarab
- cyrusmvahid


text:
<?php namespace App\Data\Presenters;

use Laracasts\Presenter\Presenter as BasePresenter;

abstract class Presenter extends BasePresenter
{
	public function created($format = null): string
	{
		return $this->formatDate($format, $this->entity->created_at);
	}

	public function deleted($format = null): string
	{
		return $this->formatDate($format, $this->entity->deleted_at);
	}

	public function updated($format = null): string
	{
		return $this->formatDate($format, $this->entity->updated_at);
	}

	protected function formatDate($format, $entity)
	{
		switch ($format) {
			case 'date':
				return $entity->format('d M Y');
				break;

			case 'raw':
				return $entity;
				break;

			case 'relative':
				return $entity->diffForHumans();
				break;

			case 'time':
				return $entity->format('g:ia');
				break;

			case 'time24':
				return $entity->format('H:i');
				break;

			default:
				return $entity->format('d M Y @ g:ia');
				break;
		}
	}
}