text:
//this is a blank WinJS control structure. It's intended to use as a startup for new controls

(function () {
    'use strict';
    var leftArrowGlyph = "",
                rightArrowGlyph = "",
                topArrowGlyph = "",
                bottomArrowGlyph = "";

    WinJS.Namespace.define("WinJSContrib.UI", {
        FlipView: WinJS.Class.mix(WinJS.Class.define(function ctor(element, options) {
            var ctrl = this;
            this.element = element || document.createElement('DIV');
            options = options || {};
            this.element.winControl = this;
            this.element.classList.add('mcn-flipview');
            this.element.classList.add('win-disposable');
            this._pages = [];
            this.pagesBuffer = 2;
            this._currentPage = 0;
            this._itemTemplate = null;
            this._items = null;

            this.wrapper = document.createElement("DIV");
            this.wrapper.className = "mcn-flipview-wrapper";
            this.element.appendChild(this.wrapper);

            this.pagesContainer = document.createElement("DIV");
            this.pagesContainer.className = "mcn-flipview-pages";
            this.wrapper.appendChild(this.pagesContainer);

            this.buttonsContainer = document.createElement("DIV");
            this.buttonsContainer.className = "mcn-flipview-buttons";
            this.wrapper.appendChild(this.buttonsContainer);

            this.navLeft = document.createElement("BUTTON");
            this.navLeft.className = "mcn-nav-button win-navleft hidden";
            this.navLeft.innerHTML = leftArrowGlyph;
            this.buttonsContainer.appendChild(this.navLeft);
            this.navLeft.onclick = function () {
                ctrl.goPrevious();
            }
            this.navRight = document.createElement("BUTTON");
            this.navRight.className = "mcn-nav-button win-navright hidden";
            this.navRight.innerHTML = rightArrowGlyph;
            this.navRight.onclick = function () {
                ctrl.goNext();
            }
            this.buttonsContainer.appendChild(this.navRight);

            WinJS.UI.setOptions(this, options);
        }, {
            itemTemplate: {
                get: function () {
                    return this._itemTemplate;
                },
                set: function (val) {
                    if (val.winControl)
                        val = val.winControl;

                    this._itemTemplate = val;
                    this._destroyAllPages();
                    this.moveToPageIndex(this._currentPage);
                }
            },

            items: {
                get: function () {
                    return this._items;
                },
                set: function (val) {
                    this._items = val;
                    this._destroyAllPages();
                    this.moveToPageIndex(this._currentPage);
                }
            },

            currentPage: {
                get: function () {
                    return this._currentPage;
                },
                set: function (val) {
                    if (val != this._currentPage) {
                        this.moveToPageIndex(val);
                    }
                }
            },

            goPrevious : function(){
                var ctrl = this;
                var currentPage = ctrl._pages[ctrl._currentPage];
                if (currentPage) {
                    ctrl._exitPage(currentPage, WinJSContrib.UI.Animation.slideToRight);
                }
                ctrl.moveToPageIndex(ctrl._currentPage - 1);
            },

            goNext: function () {
                var ctrl = this;
                var currentPage = ctrl._pages[ctrl._currentPage];
                if (currentPage) {
                    ctrl._exitPage(currentPage, WinJSContrib.UI.Animation.slideToLeft);
                }
                ctrl.moveToPageIndex(ctrl._currentPage + 1);
            },

            _exitPage: function (page, animation) {
                if (page && page.element) {
                    page.element.classList.remove("selected");
                    animation(page.element).then(function () {
                        if (page.element) page.element.classList.add("hidden");
                    });
                }
            },

            moveToPageIndex: function (index) {
                var ctrl = this;

                if (index < 0)
                    index = 0;
                if (ctrl.items && index >= ctrl.items.length)
                    index = ctrl.items.length - 1;

                var oldPageIndex = ctrl._currentPage;
                this._currentPage = index;
                var diff = this._currentPage - oldPageIndex;
                if (!ctrl.itemTemplate || !ctrl.items)
                    return;

                var item = ctrl.items[ctrl._currentPage];
                if (item) {
                    var page = ctrl._createPage(item, ctrl._currentPage);
                    page.element.style.opacity = "";
                    page.element.classList.remove("hidden");
                    page.element.classList.add("selected");
                    if (diff > 0) {
                        WinJSContrib.UI.Animation.slideFromRight(page.element).then(function () {
                            page.cleanTransform();
                        });
                    } else if (diff < 0) {
                        WinJSContrib.UI.Animation.slideFromLeft(page.element).then(function () {
                            page.cleanTransform();
                        });
                    }
                    ctrl.dispatchEvent("pageselected", { currentPage: ctrl._currentPage });
                    setImmediate(function () {
                        ctrl._cleanPages();
                        ctrl.preparePreviousPage(ctrl._currentPage - 1);
                        ctrl.prepareNextPage(ctrl._currentPage + 1);
                    });

                    if (ctrl._currentPage == 0) {
                        ctrl.navLeft.classList.add("hidden");
                    } else {
                        ctrl.navLeft.classList.remove("hidden");
                    }
                    if (ctrl._currentPage >= ctrl._items.length - 1) {
                        ctrl.navRight.classList.add("hidden");
                    } else {
                        ctrl.navRight.classList.remove("hidden");
                    }
                }
            },

            preparePreviousPage : function(index){
                var ctrl = this;
                if (index < 0 || !ctrl.items || !ctrl.items.length) {
                    return;
                }

                var item = ctrl.items[index];
                if (item) {
                    var page = ctrl._createPage(item, index);

                    //if (page.element.style.webkitTransform != undefined) {
                    //    page.element.style.webkitTransform = "translate3d(-100%, 0, 0)";
                    //} else {
                    //    page.element.style.transform = "translate3d(-100%, 0, 0)";
                    //}
                    //page.element.classList.remove("hidden");
                }
            },

            prepareNextPage: function (index) {
                var ctrl = this;
                if (!ctrl.items || !ctrl.items.length || index >= ctrl.items.length) {
                    return;
                }

                var item = ctrl.items[index];
                if (item) {
                    var page = ctrl._createPage(item, index);

                    //if (page.element.style.webkitTransform != undefined) {
                    //    page.element.style.webkitTransform = "translate3d(100%, 0, 0)";
                    //} else {
                    //    page.element.style.transform = "translate3d(100%, 0, 0)";
                    //}
                    //page.element.classList.remove("hidden");
                }
            },

            _cleanPages: function () {
                var ctrl = this;
                if (ctrl._pages && ctrl._pages.length) {
                    var min = ctrl._currentPage - ctrl.pagesBuffer;
                    var max = ctrl._currentPage + ctrl.pagesBuffer;

                    ctrl._pages.forEach(function (p, index) {
                        if (p && (index < min || index > max)) {
                            p.dispose();
                            ctrl._pages[index] = null;
                        }
                    });
                }
            },

            _destroyAllPages: function () {
                if (this._pages && this._pages.length) {
                    this._pages.forEach(function (p) {
                        if (p) {
                            p.dispose();
                        }
                    });
                }
                this.pagesContainer.innerHTML = "";
                this._pages = [];
            },

            _createPage: function (item, index) {
                var ctrl = this;
                if (ctrl._pages[index])
                    return ctrl._pages[index];

                var page = {
                    element: document.createElement("DIV"),
                    swipeslide: null,
                    index: index,
                    contentPromise: null,
                    eventTracker: new WinJSContrib.UI.EventTracker(),
                    cleanTransform: function () {
                        if (this.element) {
                            if (this.element.style.webkitTransform) {
                                this.element.style.webkitTransition = "";
                                this.element.style.webkitTransform = "";
                            } else {
                                this.element.style.transition = "";
                                this.element.style.transform = "";
                            }
                        }
                    },
                    dispose: function () {
                        this.eventTracker.dispose();
                        if (this.element)
                            ctrl.pagesContainer.removeChild(this.element);
                        this.element = null;
                    }
                };

                page.element.className = "mcn-flipview-page win-disposable hidden";
                ctrl.pagesContainer.appendChild(page.element);
                var swipeslide = new WinJSContrib.UI.SwipeSlide(page.element);
                page.swipeslide = swipeslide;
                page.element.winControl = page;

                page.eventTracker.addEvent(swipeslide, "swipe", function (swipearg) {
                    if (swipearg.direction == "left" && swipeslide.allowed.left) {
                        console.log("swipe to left");
                        swipeslide.swipeHandled = true;
                        ctrl._exitPage(page, WinJSContrib.UI.Animation.slideToLeft);
                        ctrl.currentPage = ctrl.currentPage + 1;
                    } else if (swipearg.direction == "right" && swipeslide.allowed.right) {
                        console.log("swipe to right");
                        swipeslide.swipeHandled = true;
                        ctrl._exitPage(page, WinJSContrib.UI.Animation.slideToRight);
                        ctrl.currentPage = ctrl.currentPage - 1;
                    }
                });

                if (index == 0) {
                    page.swipeslide.allowed.right = false;
                }
                if (index == ctrl.items.length - 1) {
                    page.swipeslide.allowed.left = false;
                }

                var p = null;
                if (typeof ctrl.itemTemplate === "function")
                    p = ctrl.itemTemplate(WinJS.Promise.wrap({ index : index, data: item }));
                else
                    p = ctrl.itemTemplate.render(item);

                page.contentPromise = p.then(function (rendered) {
                    page.element.appendChild(rendered);
                });

                ctrl._pages[index] = page;

                return page;
            },

            dispose: function () {
                WinJS.Utilities.disposeSubTree(this.element);
                this.element = null;
            }
        }),
		WinJS.Utilities.eventMixin,
		WinJS.Utilities.createEventProperties("pageselected"))
    });
})();


text:
require_relative "../internal"

module ChefUtils
  module DSL
    module Which
      include Internal

      # Lookup an executable through the systems search PATH.  Allows specifying an array
      # of executables to look for.  The first executable that is found, along any path entry,
      # will be the preferred one and returned first.  The extra_path will override any default
      # extra_paths which are added (allowing the user to pass an empty array to remove them).
      #
      # When passed a block the block will be called with the full pathname of any executables
      # which are found, and the block should return truthy or falsey values to further filter
      # the executable based on arbitrary criteria.
      #
      # This is syntactic sugar for `where(...).first`
      #
      # This helper can be used in target mode in chef or with train using the appropriate
      # wiring externally.
      #
      # @example Find the most appropriate python executable, searching through the system PATH
      #          plus additionally the "/usr/libexec" directory, which has the dnf libraries
      #          installed and available.
      #
      #   cmd = which("platform-python", "python", "python3", "python2", "python2.7", extra_path: "/usr/libexec") do |f|
      #     shell_out("#{f} -c 'import dnf'").exitstatus == 0
      #   end
      #
      # @param [Array<String>] list of commands to search for
      # @param [String,Array<String>] array of extra paths to search through
      # @return [String] the first match
      #
      def which(*cmds, extra_path: nil, &block)
        where(*cmds, extra_path: extra_path, &block).first || false
      end

      # Lookup all the instances of an an executable that can be found through the systems search PATH.
      # Allows specifying an array of executables to look for.  All the instances of the first executable
      # that is found will be returned first.  The extra_path will override any default extra_paths
      # which are added (allowing the user to pass an empty array to remove them).
      #
      # When passed a block the block will be called with the full pathname of any executables
      # which are found, and the block should return truthy or falsey values to further filter
      # the executable based on arbitrary criteria.
      #
      # This helper can be used in target mode in chef or with train using the appropriate
      # wiring externally.
      #
      # @example Find all the python executables, searching through the system PATH plus additionally
      #          the "/usr/libexec" directory, which have the dnf libraries installed and available.
      #
      #   cmds = where("platform-python", "python", "python3", "python2", "python2.7", extra_path: "/usr/libexec") do |f|
      #     shell_out("#{f} -c 'import dnf'").exitstatus == 0
      #   end
      #
      # @param [Array<String>] list of commands to search for
      # @param [String,Array<String>] array of extra paths to search through
      # @return [String] the first match
      #
      def where(*cmds, extra_path: nil, &block)
        extra_path ||= __extra_path
        paths = __env_path.split(File::PATH_SEPARATOR) + Array(extra_path)
        paths.uniq!
        exts = ENV["PATHEXT"] ? ENV["PATHEXT"].split(";") : []
        exts.unshift("")
        cmds.map do |cmd|
          paths.map do |path|
            exts.map do |ext|
              filename = File.join(path, "#{cmd}#{ext}")
              filename if __valid_executable?(filename, &block)
            end.compact
          end
        end.flatten
      end

      private

      # This is for injecting common extra_paths into the search PATH.  The chef-client codebase overrides this into its
      # own custom mixin to ensure that /usr/sbin, /sbin, etc are in the search PATH for chef-client.
      #
      # @api private
      def __extra_path
        nil
      end

      # Windows compatible and train/target-mode-enhanced helper to determine if an executable is valid.
      #
      # @api private
      def __valid_executable?(filename, &block)
        is_executable =
          if __transport_connection
            __transport_connection.file(filename).stat[:mode] & 1 && !__transport_connection.file(filename).directory?
          else
            File.executable?(filename) && !File.directory?(filename)
          end
        return false unless is_executable

        block ? yield(filename) : true
      end

      extend self
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
class ListValueRewriter {
 public:
  explicit ListValueRewriter(clang::tooling::Replacements* replacements);

  void RegisterMatchers(clang::ast_matchers::MatchFinder* match_finder);

 private:
  class AppendCallback
      : public clang::ast_matchers::MatchFinder::MatchCallback {
   public:
    explicit AppendCallback(clang::tooling::Replacements* replacements);

    void run(
        const clang::ast_matchers::MatchFinder::MatchResult& result) override;

   protected:
    clang::tooling::Replacements* const replacements_;
  };

  class AppendBooleanCallback : public AppendCallback {
   public:
    explicit AppendBooleanCallback(clang::tooling::Replacements* replacements);

    void run(
        const clang::ast_matchers::MatchFinder::MatchResult& result) override;
  };

  class AppendIntegerCallback : public AppendCallback {
   public:
    explicit AppendIntegerCallback(clang::tooling::Replacements* replacements);

    void run(
        const clang::ast_matchers::MatchFinder::MatchResult& result) override;
  };

  class AppendDoubleCallback : public AppendCallback {
   public:
    explicit AppendDoubleCallback(clang::tooling::Replacements* replacements);

    void run(
        const clang::ast_matchers::MatchFinder::MatchResult& result) override;
  };

  class AppendStringCallback : public AppendCallback {
   public:
    explicit AppendStringCallback(clang::tooling::Replacements* replacements);

    void run(
        const clang::ast_matchers::MatchFinder::MatchResult& result) override;
  };

  class AppendReleasedUniquePtrCallback
      : public clang::ast_matchers::MatchFinder::MatchCallback {
   public:
    explicit AppendReleasedUniquePtrCallback(
        clang::tooling::Replacements* replacements);

    void run(
        const clang::ast_matchers::MatchFinder::MatchResult& result) override;

   private:
    clang::tooling::Replacements* const replacements_;
  };

  class AppendRawPtrCallback
      : public clang::ast_matchers::MatchFinder::MatchCallback {
   public:
    explicit AppendRawPtrCallback(clang::tooling::Replacements* replacements);

    void run(
        const clang::ast_matchers::MatchFinder::MatchResult& result) override;

   private:
    clang::tooling::Replacements* const replacements_;
    std::unordered_set<const clang::VarDecl*> visited_;
  };

  AppendBooleanCallback append_boolean_callback_;
  AppendIntegerCallback append_integer_callback_;
  AppendDoubleCallback append_double_callback_;
  AppendStringCallback append_string_callback_;
  AppendReleasedUniquePtrCallback append_released_unique_ptr_callback_;
  AppendRawPtrCallback append_raw_ptr_callback_;
};

#endif  // TOOLS_CLANG_VALUE_CLEANUP_LIST_VALUE_REWRITER_H_


text:
package org.spoofax.jsglr.rnsglr;

public class Config {

	public boolean verboseFlag;
	public boolean statsFlag;
	public boolean returnOutput;

}


text:
package topotools

import (
	"reflect"
	"sort"
	"sync"

	"golang.org/x/net/context"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/vt/topo"
)

// FindTabletByIPAddrAndPort searches within a tablet map for tablets
func FindTabletByIPAddrAndPort(tabletMap map[topo.TabletAlias]*topo.TabletInfo, addr, portName string, port int) (topo.TabletAlias, error) {
	for alias, ti := range tabletMap {
		if ti.IPAddr == addr && ti.Portmap[portName] == port {
			return alias, nil
		}
	}
	return topo.TabletAlias{}, topo.ErrNoNode
}

// GetAllTablets returns a sorted list of tablets.
func GetAllTablets(ctx context.Context, ts topo.Server, cell string) ([]*topo.TabletInfo, error) {
	aliases, err := ts.GetTabletsByCell(ctx, cell)
	if err != nil {
		return nil, err
	}
	sort.Sort(topo.TabletAliasList(aliases))

	tabletMap, err := topo.GetTabletMap(ctx, ts, aliases)
	if err != nil {
		// we got another error than topo.ErrNoNode
		return nil, err
	}
	tablets := make([]*topo.TabletInfo, 0, len(aliases))
	for _, tabletAlias := range aliases {
		tabletInfo, ok := tabletMap[tabletAlias]
		if !ok {
			// tablet disappeared on us (GetTabletMap ignores
			// topo.ErrNoNode), just echo a warning
			log.Warningf("failed to load tablet %v", tabletAlias)
		} else {
			tablets = append(tablets, tabletInfo)
		}
	}

	return tablets, nil
}

// GetAllTabletsAcrossCells returns all tablets from known cells.
// If it returns topo.ErrPartialResult, then the list is valid, but partial.
func GetAllTabletsAcrossCells(ctx context.Context, ts topo.Server) ([]*topo.TabletInfo, error) {
	cells, err := ts.GetKnownCells(ctx)
	if err != nil {
		return nil, err
	}

	results := make([][]*topo.TabletInfo, len(cells))
	errors := make([]error, len(cells))
	wg := sync.WaitGroup{}
	wg.Add(len(cells))
	for i, cell := range cells {
		go func(i int, cell string) {
			results[i], errors[i] = GetAllTablets(ctx, ts, cell)
			wg.Done()
		}(i, cell)
	}
	wg.Wait()

	err = nil
	var allTablets []*topo.TabletInfo
	for i := range cells {
		if errors[i] == nil {
			allTablets = append(allTablets, results[i]...)
		} else {
			err = topo.ErrPartialResult
		}
	}
	return allTablets, err
}

// SortedTabletMap returns two maps:
// - The slaveMap contains all the non-master non-scrapped hosts.
//   This can be used as a list of slaves to fix up for reparenting
// - The masterMap contains all the tablets without parents
//   (scrapped or not). This can be used to special case
//   the old master, and any tablet in a weird state, left over, ...
func SortedTabletMap(tabletMap map[topo.TabletAlias]*topo.TabletInfo) (map[topo.TabletAlias]*topo.TabletInfo, map[topo.TabletAlias]*topo.TabletInfo) {
	slaveMap := make(map[topo.TabletAlias]*topo.TabletInfo)
	masterMap := make(map[topo.TabletAlias]*topo.TabletInfo)
	for alias, ti := range tabletMap {
		if ti.Type != topo.TYPE_MASTER && ti.Type != topo.TYPE_SCRAP {
			slaveMap[alias] = ti
		} else {
			masterMap[alias] = ti
		}
	}
	return slaveMap, masterMap
}

// CopyMapKeys copies keys from from map m into a new slice with the
// type specified by typeHint.  Reflection can't make a new slice type
// just based on the key type AFAICT.
func CopyMapKeys(m interface{}, typeHint interface{}) interface{} {
	mapVal := reflect.ValueOf(m)
	keys := reflect.MakeSlice(reflect.TypeOf(typeHint), 0, mapVal.Len())
	for _, k := range mapVal.MapKeys() {
		keys = reflect.Append(keys, k)
	}
	return keys.Interface()
}

// CopyMapValues copies values from from map m into a new slice with the
// type specified by typeHint.  Reflection can't make a new slice type
// just based on the key type AFAICT.
func CopyMapValues(m interface{}, typeHint interface{}) interface{} {
	mapVal := reflect.ValueOf(m)
	vals := reflect.MakeSlice(reflect.TypeOf(typeHint), 0, mapVal.Len())
	for _, k := range mapVal.MapKeys() {
		vals = reflect.Append(vals, mapVal.MapIndex(k))
	}
	return vals.Interface()
}

// MapKeys returns an array with th provided map keys.
func MapKeys(m interface{}) []interface{} {
	keys := make([]interface{}, 0, 16)
	mapVal := reflect.ValueOf(m)
	for _, kv := range mapVal.MapKeys() {
		keys = append(keys, kv.Interface())
	}
	return keys
}


text:
namespace policy {

BooleanDisablingPolicyHandler::BooleanDisablingPolicyHandler(
    const char* policy_name,
    const char* pref_path)
    : TypeCheckingPolicyHandler(policy_name, base::Value::Type::BOOLEAN),
      pref_path_(pref_path) {}

BooleanDisablingPolicyHandler::~BooleanDisablingPolicyHandler() {}

void BooleanDisablingPolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  if (!pref_path_)
    return;

  const base::Value* value = policies.GetValue(policy_name());

  if (value && value->GetBool() == false) {
    // Only apply the policy to the pref if the policy value is false.
    prefs->SetBoolean(pref_path_, false);
  }
}

}  // namespace policy


text:
'use strict';

var EventEmitter = require('events').EventEmitter;
var util = require('util');
var http = require('http');

var _ = require('lodash');
var assert = require('assert-plus');
var errors = require('restify-errors');
var uuid = require('uuid');

var Chain = require('./chain');
var RouterRegistryRadix = require('./routerRegistryRadix');

///--- Globals

var MethodNotAllowedError = errors.MethodNotAllowedError;
var ResourceNotFoundError = errors.ResourceNotFoundError;

///--- API

/**
 * Router class handles mapping of http verbs and a regexp path,
 * to an array of handler functions.
 *
 * @class
 * @public
 * @param  {Object} options - an options object
 * @param  {Bunyan} options.log - Bunyan logger instance
 * @param {Boolean} [options.onceNext=false] - Prevents calling next multiple
 *  times
 * @param {Boolean} [options.strictNext=false] - Throws error when next() is
 *  called more than once, enabled onceNext option
 * @param {Object} [options.registry] - route registry
 * @param {Boolean} [options.ignoreTrailingSlash=false] - ignore trailing slash
 * on paths
 */
function Router(options) {
    assert.object(options, 'options');
    assert.object(options.log, 'options.log');
    assert.optionalBool(options.onceNext, 'options.onceNext');
    assert.optionalBool(options.strictNext, 'options.strictNext');
    assert.optionalBool(
        options.ignoreTrailingSlash,
        'options.ignoreTrailingSlash'
    );

    EventEmitter.call(this);

    this.log = options.log;
    this.onceNext = !!options.onceNext;
    this.strictNext = !!options.strictNext;
    this.name = 'RestifyRouter';

    // Internals
    this._anonymousHandlerCounter = 0;
    this._registry = options.registry || new RouterRegistryRadix(options);
}
util.inherits(Router, EventEmitter);

/**
 * Lookup for route
 *
 * @public
 * @memberof Router
 * @instance
 * @function lookup
 * @param  {Request} req - request
 * @param  {Response} res - response
 * @returns {Chain|undefined} handler or undefined
 */
Router.prototype.lookup = function lookup(req, res) {
    var pathname = req.getUrl().pathname;

    // Find route
    var registryRoute = this._registry.lookup(req.method, pathname);

    // Not found
    if (!registryRoute) {
        return undefined;
    }

    // Decorate req
    req.params = Object.assign(req.params, registryRoute.params);
    req.route = registryRoute.route;

    // Call handler chain
    return registryRoute.handler;
};

/**
 * Lookup by name
 *
 * @public
 * @memberof Router
 * @instance
 * @function lookupByName
 * @param {String} name - route name
 * @param  {Request} req - request
 * @param  {Response} res - response
 * @returns {Chain|undefined} handler or undefined
 */
Router.prototype.lookupByName = function lookupByName(name, req, res) {
    var self = this;
    var route = self._registry.get()[name];

    if (!route) {
        return undefined;
    }

    // Decorate req
    req.route = route;

    return route.chain.run.bind(route.chain);
};

/**
 * Takes an object of route params and query params, and 'renders' a URL.
 *
 * @public
 * @function render
 * @param    {String} routeName - the route name
 * @param    {Object} params -    an object of route params
 * @param    {Object} query -     an object of query params
 * @returns  {String} URL
 * @example
 * server.get({
 *      name: 'cities',
 *      path: '/countries/:name/states/:state/cities'
 * }, (req, res, next) => ...));
 * let cities = server.router.render('cities', {
 *      name: 'Australia',
 *      state: 'New South Wales'
 * });
 * // cities:  '/countries/Australia/states/New%20South%20Wales/cities'
 */
Router.prototype.render = function render(routeName, params, query) {
    var self = this;

    function pathItem(match, key) {
        if (params.hasOwnProperty(key) === false) {
            throw new Error(
                'Route <' + routeName + '> is missing parameter <' + key + '>'
            );
        }
        return '/' + encodeURIComponent(params[key]);
    }

    function queryItem(key) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(query[key]);
    }

    var route = self._registry.get()[routeName];

    if (!route) {
        return null;
    }

    var _path = route.spec.path;
    var _url = _path.replace(/\/:([A-Za-z0-9_]+)(\([^\\]+?\))?/g, pathItem);
    var items = Object.keys(query || {}).map(queryItem);
    var queryString = items.length > 0 ? '?' + items.join('&') : '';
    return _url + queryString;
};

/**
 * Adds a route.
 *
 * @public
 * @memberof Router
 * @instance
 * @function mount
 * @param    {Object} opts - an options object
 * @param    {String} opts.name - name
 * @param    {String} opts.method - method
 * @param    {String} opts.path - path can be any String
 * @param    {Function[]} handlers - handlers
 * @returns  {String} returns the route name if creation is successful.
 * @fires ...String#mount
 */
Router.prototype.mount = function mount(opts, handlers) {
    var self = this;

    assert.object(opts, 'opts');
    assert.string(opts.method, 'opts.method');
    assert.arrayOfFunc(handlers, 'handlers');
    assert.optionalString(opts.name, 'opts.name');

    var chain = new Chain({
        onceNext: self.onceNext,
        strictNext: self.strictNext
    });

    // Route
    var route = {
        name: self._getRouteName(opts.name, opts.method, opts.path),
        method: opts.method,
        path: opts.path,
        spec: opts,
        chain: chain
    };

    handlers.forEach(function forEach(handler) {
        // Assign name to anonymous functions
        handler._name =
            handler.name || 'handler-' + self._anonymousHandlerCounter++;

        // Attach to middleware chain
        chain.add(handler);
    });

    self._registry.add(route);
    self.emit('mount', route.method, route.path);

    return route;
};

/**
 * Unmounts a route.
 *
 * @public
 * @memberof Router
 * @instance
 * @function unmount
 * @param    {String} name - the route name
 * @returns  {Object|undefined} removed route if found
 */
Router.prototype.unmount = function unmount(name) {
    assert.string(name, 'name');

    var route = this._registry.remove(name);
    return route;
};

/**
 * toString() serialization.
 *
 * @public
 * @memberof Router
 * @instance
 * @function toString
 * @returns  {String} stringified router
 */
Router.prototype.toString = function toString() {
    return this._registry.toString();
};

/**
 * Return information about the routes registered in the router.
 *
 * @public
 * @memberof Router
 * @instance
 * @returns {object} The routes in the router.
 */
Router.prototype.getDebugInfo = function getDebugInfo() {
    var routes = this._registry.get();
    return _.mapValues(routes, function mapValues(route, routeName) {
        return {
            name: route.name,
            method: route.method.toLowerCase(),
            path: route.path,
            handlers: route.chain.getHandlers()
        };
    });
};

/**
 * Return mounted routes
 *
 * @public
 * @memberof Router
 * @instance
 * @returns {object} The routes in the router.
 */
Router.prototype.getRoutes = function getRoutes() {
    return this._registry.get();
};

/**
 * Returns true if the router generated a 404 for an options request.
 *
 * TODO: this is relevant for CORS only. Should move this out eventually to a
 * userland middleware? This also seems a little like overreach, as there is no
 * option to opt out of this behavior today.
 *
 * @private
 * @static
 * @function _optionsError
 * @param    {Object}     req - the request object
 * @param    {Object}     res - the response object
 * @returns  {Boolean} is options error
 */
Router._optionsError = function _optionsError(req, res) {
    var pathname = req.getUrl().pathname;
    return req.method === 'OPTIONS' && pathname === '*';
};

/**
 * Default route, when no route found
 * Responds with a ResourceNotFoundError error.
 *
 * @private
 * @memberof Router
 * @instance
 * @function defaultRoute
 * @param  {Request} req - request
 * @param  {Response} res - response
 * @param  {Function} next - next
 * @returns {undefined} no return value
 */
Router.prototype.defaultRoute = function defaultRoute(req, res, next) {
    var self = this;
    var pathname = req.getUrl().pathname;

    // Allow CORS
    if (Router._optionsError(req, res, pathname)) {
        res.send(200);
        next(null, req, res);
        return;
    }

    // Check for 405 instead of 404
    var allowedMethods = http.METHODS.filter(function some(method) {
        return method !== req.method && self._registry.lookup(method, pathname);
    });

    if (allowedMethods.length) {
        res.methods = allowedMethods;
        res.setHeader('Allow', allowedMethods.join(', '));
        var methodErr = new MethodNotAllowedError(
            '%s is not allowed',
            req.method
        );
        next(methodErr, req, res);
        return;
    }

    // clean up the url in case of potential xss
    // https://github.com/restify/node-restify/issues/1018
    var err = new ResourceNotFoundError('%s does not exist', pathname);
    next(err, req, res);
};

/**
 * Generate route name
 *
 * @private
 * @memberof Router
 * @instance
 * @function _getRouteName
 * @param    {String|undefined} name - Name of the route
 * @param    {String} method - HTTP method
 * @param    {String} path - path
 * @returns  {String} name of the route
 */
Router.prototype._getRouteName = function _getRouteName(name, method, path) {
    // Generate name
    if (!name) {
        name = method + '-' + path;
        name = name.replace(/\W/g, '').toLowerCase();
    }

    // Avoid name conflict: GH-401
    if (this._registry.get()[name]) {
        name += uuid.v4().substr(0, 7);
    }

    return name;
};

module.exports = Router;


text:
#region License

#endregion

#region Imports

using System;
using Spring.Util;

#endregion

namespace Spring.Aop.Support
{
	/// <summary>
	/// Simple <see cref="Spring.Aop.ITypeFilter"/> implementation that matches
	/// all classes classes (and any derived subclasses) of a give root
	/// <see cref="System.Type"/>.
	/// </summary>
	/// <author>Rod Johnson</author>
	/// <author>Aleksandar Seovic (.NET)</author>
    [Serializable]
    public class RootTypeFilter : ITypeFilter
	{
		private Type _rootType;

		/// <summary>
		/// Creates a new instance of the
		/// <see cref="RootTypeFilter"/> for the supplied
		/// <paramref name="rootType"/>.
		/// </summary>
		/// <param name="rootType">The root <see cref="System.Type"/>.</param>
		/// <exception cref="System.ArgumentNullException">
		/// If the supplied <paramref name="rootType"/> is <see langword="null"/>.
		/// </exception>
		public RootTypeFilter(Type rootType)
		{
			AssertUtils.ArgumentNotNull(rootType, "rootType");
			_rootType = rootType;
		}

		/// <summary>
		/// Should the pointcut apply to the supplied
		/// <see cref="System.Type"/>?
		/// </summary>
		/// <remarks>
		/// <p>
		/// Returns <see langword="true"/> if the supplied <paramref name="type"/>
		/// can be assigned to the root <see cref="System.Type"/>.
		/// </p>
		/// </remarks>
		/// <param name="type">
		/// The candidate <see cref="System.Type"/>.
		/// </param>
		/// <returns>
		/// <see langword="true"/> if the advice should apply to the supplied
		/// <paramref name="type"/>
		/// </returns>
		public virtual bool Matches(Type type)
		{
			return _rootType.IsAssignableFrom(type);
		}
	}
}


text:
'use babel';

import { requirePackages } from 'atom-utils'
import WorkingFilesView from './working-files-view'

let addIconToElement;

export default {
  workingFilesView: null,
	config: {
		collapsable: {
			title: 'Collapsable',
			description: 'If selected, the open files panel becomes collapsable, i.e., it can be collapsed with a click on the header',
			type: 'boolean',
			default: true
		},
		maxHeight: {
			title: 'Maximum Height',
			description: 'Maximum height for the working files area.  The value can be a specific pixel value (200px) or a percentage of the window height (30%).',
			type: 'string',
			default: '30%'
		},
		sortOrder: {
			title: 'Sort Order',
			description: 'Indicate the order of the criteria for the sorting of the open files list, separated by commas. Options: base (filename), ext (extension), dir (directory)',
			type: 'string',
			default: 'base, ext, dir'
		}
	},

  consumeElementIcons(func) {
    addIconToElement = func;
  },

  activate(state) {
		return requirePackages('tree-view').then(([treeView]) => {
			this.workingFilesView = new WorkingFilesView(addIconToElement);

			if (treeView.treeView) {
				this.workingFilesView.show()
			}
			atom.commands.add('atom-workspace', 'tree-view:toggle', () => {
				if (treeView.treeView.is(':visible')) {
					return this.workingFilesView.show()
				} else {
					return this.workingFilesView.hide()
				}
			})

			return atom.commands.add('atom-workspace', 'tree-view:show', () => {
				return this.workingFilesView.show()
			})
		})
	},

  deactivate() {
    return this.workingFilesView.destroy();
  },

  serialize() {}
}


text:
module Tomify::Concerns::Default::Helper
  def setting(name)
    Tomify.setting(name)
  end

  def root_page
    Tomify.models.page.root
  end

  def page
    return @page if @page

    default_page = Tomify.models.page.default
    default_page.admin = self.class.name.include? "Admin::"
    default_page
  end
end


text:
@class XUIEditableListViewController, XUIEditableListCell;

@protocol XUIEditableListViewControllerDelegate <NSObject>

- (void)editableListViewControllerContentListChanged:(XUIEditableListViewController *)controller;

@end

@interface XUIEditableListViewController : XUIViewController

@property (nonatomic, strong) NSArray <NSString *> *contentList;
@property (nonatomic, weak) id <XUIEditableListViewControllerDelegate> delegate;
@property (nonatomic, strong, readonly) XUIEditableListCell *cell;
- (instancetype)initWithCell:(XUIEditableListCell *)cell;

@end


text:
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.sync.ui;

import android.accounts.Account;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import org.chromium.chrome.R;
import org.chromium.chrome.browser.init.ChromeBrowserInitializer;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.signin.services.IdentityServicesProvider;
import org.chromium.chrome.browser.sync.SyncErrorNotifier;
import org.chromium.chrome.browser.sync.SyncService;
import org.chromium.components.signin.base.CoreAccountInfo;
import org.chromium.components.signin.identitymanager.ConsentLevel;

/**
 * This activity is used for requesting a sync passphrase from the user. Typically,
 * this will be the target of an Android notification.
 */
public class PassphraseActivity extends AppCompatActivity
        implements PassphraseDialogFragment.Listener, FragmentManager.OnBackStackChangedListener {
    public static final String FRAGMENT_PASSPHRASE = "passphrase_fragment";
    public static final String FRAGMENT_SPINNER = "spinner_fragment";
    private static final String TAG = "PassphraseActivity";

    private SyncService.SyncStateChangedListener mSyncStateChangedListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // The Chrome browser process must be started here because this Activity
        // may be started explicitly from Android notifications.
        // During a normal user flow the ChromeTabbedActivity would start the Chrome browser
        // process and this wouldn't be necessary.
        ChromeBrowserInitializer.getInstance().handleSynchronousStartup();
        assert SyncService.get() != null;
        getSupportFragmentManager().addOnBackStackChangedListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Account account = CoreAccountInfo.getAndroidAccountFrom(
                IdentityServicesProvider.get()
                        .getIdentityManager(Profile.getLastUsedRegularProfile())
                        .getPrimaryAccountInfo(ConsentLevel.SYNC));
        if (account == null) {
            finish();
            return;
        }

        if (!isShowingDialog(FRAGMENT_PASSPHRASE)) {
            if (SyncService.get().isEngineInitialized()) {
                displayPassphraseDialog();
            } else {
                addSyncStateChangedListener();
                displaySpinnerDialog();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Make sure we don't receive callbacks while in the background.
        // See http://crbug.com/469890.
        removeSyncStateChangedListener();
    }

    private void addSyncStateChangedListener() {
        if (mSyncStateChangedListener != null) {
            return;
        }
        mSyncStateChangedListener = new SyncService.SyncStateChangedListener() {
            @Override
            public void syncStateChanged() {
                if (SyncService.get().isEngineInitialized()) {
                    removeSyncStateChangedListener();
                    displayPassphraseDialog();
                }
            }
        };
        SyncService.get().addSyncStateChangedListener(mSyncStateChangedListener);
    }

    private void removeSyncStateChangedListener() {
        if (mSyncStateChangedListener != null) {
            SyncService.get().removeSyncStateChangedListener(mSyncStateChangedListener);
            mSyncStateChangedListener = null;
        }
    }

    private boolean isShowingDialog(String tag) {
        return getFragmentManager().findFragmentByTag(tag) != null;
    }

    private void displayPassphraseDialog() {
        assert SyncService.get().isEngineInitialized();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.addToBackStack(null);
        PassphraseDialogFragment.newInstance(null).show(ft, FRAGMENT_PASSPHRASE);
    }

    private void displaySpinnerDialog() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.addToBackStack(null);
        SpinnerDialogFragment dialog = new SpinnerDialogFragment();
        dialog.show(ft, FRAGMENT_SPINNER);
    }

    /**
     * Callback for PassphraseDialogFragment.Listener
     */
    @Override
    public boolean onPassphraseEntered(String passphrase) {
        if (!passphrase.isEmpty() && SyncService.get().setDecryptionPassphrase(passphrase)) {
            // The passphrase was correct - close this activity.
            finish();
            return true;
        }
        return false;
    }

    @Override
    public void onPassphraseCanceled() {
        // Re add the notification.
        SyncErrorNotifier.get().syncStateChanged();
        finish();
    }

    @Override
    public void onBackStackChanged() {
        if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
            finish();
        }
    }

    /**
     * Dialog shown while sync is loading.
     */
    public static class SpinnerDialogFragment extends DialogFragment {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            ProgressDialog dialog = new ProgressDialog(getActivity());
            dialog.setMessage(getResources().getString(R.string.sync_loading));
            return dialog;
        }
    }
}


text:
      {{ trans('admin.filter') }}
      {{ trans('admin.reset') }}

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                    Close
                </button>

{{ trans('admin.filter') }}

            <form action="{!! $action !!}" method="get" pjax-container>

                        @foreach($filters as $filter)

                                {!! $filter->render() !!}

                        @endforeach

                    <button type="submit" class="btn btn-primary submit">{{ trans('admin.submit') }}</button>
                    <button type="reset" class="btn btn-warning pull-left">{{ trans('admin.reset') }}</button>

            </form>


text:
/* vi: set sw=4 ts=4: */
/*
 * Mostly stolen from: dhcpcd - DHCP client daemon
 * by Yoichi Hariguchi <yoichi@fore.com>
 *
 * Licensed under GPLv2, see file LICENSE in this source tree.
 */
#include <netinet/if_ether.h>
#include <net/if_arp.h>

#include "common.h"

struct arpMsg {
	/* Ethernet header */
	uint8_t  h_dest[6];     /* 00 destination ether addr */
	uint8_t  h_source[6];   /* 06 source ether addr */
	uint16_t h_proto;       /* 0c packet type ID field */

	/* ARP packet */
	uint16_t htype;         /* 0e hardware type (must be ARPHRD_ETHER) */
	uint16_t ptype;         /* 10 protocol type (must be ETH_P_IP) */
	uint8_t  hlen;          /* 12 hardware address length (must be 6) */
	uint8_t  plen;          /* 13 protocol address length (must be 4) */
	uint16_t operation;     /* 14 ARP opcode */
	uint8_t  sHaddr[6];     /* 16 sender's hardware address */
	uint8_t  sInaddr[4];    /* 1c sender's IP address */
	uint8_t  tHaddr[6];     /* 20 target's hardware address */
	uint8_t  tInaddr[4];    /* 26 target's IP address */
	uint8_t  pad[18];       /* 2a pad for min. ethernet payload (60 bytes) */
} PACKED;

enum {
	ARP_MSG_SIZE = 0x2a
};

/* Returns 1 if no reply received */
int FAST_FUNC arpping(uint32_t test_nip,
		const uint8_t *safe_mac,
		uint32_t from_ip,
		uint8_t *from_mac,
		const char *interface,
		unsigned timeo)
{
	int timeout_ms;
	struct pollfd pfd[1];
#define s (pfd[0].fd)           /* socket */
	int rv = 1;             /* "no reply received" yet */
	struct sockaddr addr;   /* for interface name */
	struct arpMsg arp;

	if (!timeo)
		return 1;

	s = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP));
	if (s == -1) {
		bb_perror_msg(bb_msg_can_not_create_raw_socket);
		return -1;
	}

	if (setsockopt_broadcast(s) == -1) {
		bb_perror_msg("can't enable bcast on raw socket");
		goto ret;
	}

	/* send arp request */
	memset(&arp, 0, sizeof(arp));
	memset(arp.h_dest, 0xff, 6);                    /* MAC DA */
	memcpy(arp.h_source, from_mac, 6);              /* MAC SA */
	arp.h_proto = htons(ETH_P_ARP);                 /* protocol type (Ethernet) */
	arp.htype = htons(ARPHRD_ETHER);                /* hardware type */
	arp.ptype = htons(ETH_P_IP);                    /* protocol type (ARP message) */
	arp.hlen = 6;                                   /* hardware address length */
	arp.plen = 4;                                   /* protocol address length */
	arp.operation = htons(ARPOP_REQUEST);           /* ARP op code */
	memcpy(arp.sHaddr, from_mac, 6);                /* source hardware address */
	memcpy(arp.sInaddr, &from_ip, sizeof(from_ip)); /* source IP address */
	/* tHaddr is zero-filled */                     /* target hardware address */
	memcpy(arp.tInaddr, &test_nip, sizeof(test_nip));/* target IP address */

	memset(&addr, 0, sizeof(addr));
	safe_strncpy(addr.sa_data, interface, sizeof(addr.sa_data));
	if (sendto(s, &arp, sizeof(arp), 0, &addr, sizeof(addr)) < 0) {
		// TODO: error message? caller didn't expect us to fail,
		// just returning 1 "no reply received" misleads it.
		goto ret;
	}

	/* wait for arp reply, and check it */
	timeout_ms = (int)timeo;
	do {
		typedef uint32_t aliased_uint32_t FIX_ALIASING;
		int r;
		unsigned prevTime = monotonic_ms();

		pfd[0].events = POLLIN;
		r = safe_poll(pfd, 1, timeout_ms);
		if (r < 0)
			break;
		if (r) {
			r = safe_read(s, &arp, sizeof(arp));
			if (r < 0)
				break;

			//log3("sHaddr %02x:%02x:%02x:%02x:%02x:%02x",
			//	arp.sHaddr[0], arp.sHaddr[1], arp.sHaddr[2],
			//	arp.sHaddr[3], arp.sHaddr[4], arp.sHaddr[5]);

			if (r >= ARP_MSG_SIZE
			 && arp.operation == htons(ARPOP_REPLY)
			 /* don't check it: Linux doesn't return proper tHaddr (fixed in 2.6.24?) */
			 /* && memcmp(arp.tHaddr, from_mac, 6) == 0 */
			 && *(aliased_uint32_t*)arp.sInaddr == test_nip
			) {
				/* if ARP source MAC matches safe_mac
				 * (which is client's MAC), then it's not a conflict
				 * (client simply already has this IP and replies to ARPs!)
				 */
				if (!safe_mac || memcmp(safe_mac, arp.sHaddr, 6) != 0)
					rv = 0;
				//else log2("sHaddr == safe_mac");
				break;
			}
		}
		timeout_ms -= (unsigned)monotonic_ms() - prevTime + 1;

		/* We used to check "timeout_ms > 0", but
		 * this is more under/overflow-resistant
		 * (people did see overflows here when system time jumps):
		 */
	} while ((unsigned)timeout_ms <= timeo);

 ret:
	close(s);
	log1("%srp reply received for this address", rv ? "no a" : "A");
	return rv;
}


text:
using System;

namespace eCollabro.DataMapper
{
    internal static class EnumUtility
    {
        public static bool IsEnumType(Type type)
        {
            return type.Equals(typeof(SByte)) ||
                   type.Equals(typeof(Int16)) ||
                   type.Equals(typeof(Int32)) ||
                   type.Equals(typeof(Int64)) ||
                   type.Equals(typeof(Byte)) ||
                   type.Equals(typeof(UInt16)) ||
                   type.Equals(typeof(UInt32)) ||
                   type.Equals(typeof(UInt64));
        }
    }
}


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var angular2_1 = require('angular2/angular2');
var priorityqueue_1 = require('./priorityqueue');
var PriorityQueueComponent = (function () {
    function PriorityQueueComponent() {
        //results:Array<number>;
        this.data = [993, 8908, 7, 4, 6, 4, 500, 4, 3, 2, 1, 11];
        this._results = [];
        this.pq = new priorityqueue_1.PriorityQueue(function (a, b) {
            return a < b;
        });
        for (var i = 0; i < this.data.length; i++) {
            this.pq.push(this.data[i]);
        }
        for (var j = 0; j < this.data.length; j++) {
            //document.writeln(pq.peek());
            this._results.push(this.pq.pop());
        }
        //this.results = this._results;
    }
    Object.defineProperty(PriorityQueueComponent.prototype, "results", {
        get: function () {
            return this._results;
        },
        enumerable: true,
        configurable: true
    });
    PriorityQueueComponent = __decorate([
        angular2_1.Component({ selector: 'my-priorityqueue' }),
        angular2_1.View({
            template: "\n\t\t
Priority Queue
\n
\n
\n          {{result}}\n
\n
\n\t",
            directives: [angular2_1.NgFor, angular2_1.NgIf],
        }),
        __metadata('design:paramtypes', [])
    ], PriorityQueueComponent);
    return PriorityQueueComponent;
})();
exports.PriorityQueueComponent = PriorityQueueComponent;

//# sourceMappingURL=priorityqueue.component.js.map


text:
Some helpful tips for making this project more awesome

## Issue

* You'd better search for similar issue before open one.
* provide steps for me to reproducing it.

## Pull Request

### Gitiquette

* Open an issue if there is a change you'd like to make but hasn't been discussed, so we can all participate and no efforts are duplicated or wasted
* Use feature branches, one for each major change to the codebase
* Rebase your feature branch on latest master when opening a Pull Request, to minimise conflicts

### UI Changes

* this project uses autolayout; position UI elements using constraints and avoid ambiguities that lead to many system-defined constraints
* Always rebase on latest master before making changes to the xib; this reduces the amount of conflicts within the file

### Code Style

* General Objective-C or Swift Style
* Avoid adding the comments in the code detailing the changes, use Github issues instead.


text:
package org.kaaproject.kaa.demo.iotworld.smarthome.fragment.device.music;

import org.kaaproject.kaa.demo.iotworld.music.PlaybackInfo;
import org.kaaproject.kaa.demo.iotworld.smarthome.R;
import org.kaaproject.kaa.demo.iotworld.smarthome.data.MusicDevice;
import org.kaaproject.kaa.demo.iotworld.smarthome.fragment.device.AbstractGeoFencingDeviceFragment;
import org.kaaproject.kaa.demo.iotworld.smarthome.widget.MusicTrackWidget;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public abstract class AbstractMusicDeviceFragment extends AbstractGeoFencingDeviceFragment<MusicDevice> {

    protected TextView mNoDataText;

    private View mVolumeControlView;
    private SeekBar mVolumeControls;

    private MusicTrackWidget mMusicTrackWidget;

    public AbstractMusicDeviceFragment() {
        super();
    }

    public AbstractMusicDeviceFragment(String endpointKey) {
        super(endpointKey);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.volume, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_volume) {
            mToolbar.toggleCustomToolbarContent();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void setupView(LayoutInflater inflater, View rootView) {
        super.setupView(inflater, rootView);

        mMusicTrackWidget = (MusicTrackWidget) rootView.findViewById(R.id.music_track_view);

        mNoDataText = (TextView) rootView.findViewById(R.id.noDataText);

        mVolumeControlView = inflater.inflate(R.layout.volume_control, null);
        mVolumeControls = (SeekBar) mVolumeControlView.findViewById(R.id.volumeSeekView);
        mVolumeControls.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                if (fromUser) {
                    mDevice.changeVolume(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}

        });
        mToolbar.setCustomToolbarContent(mVolumeControlView);
    }

    @Override
    protected void bindDevice(boolean firstLoad) {
        super.bindDevice(firstLoad);
        PlaybackInfo playbackInfo = mDevice.getPlaybackInfo();
        if (playbackInfo != null) {
            mVolumeControls.setMax(playbackInfo.getMaxVolume());
            if (!playbackInfo.getIgnoreVolumeUpdate() || firstLoad) {
                mVolumeControls.setProgress(playbackInfo.getVolume());
            }
        }
        if (playbackInfo != null && playbackInfo.getSong() != null) {
            mMusicTrackWidget.bind(mDevice, firstLoad);
            mMusicTrackWidget.setVisible(true, !firstLoad);
        } else {
            mMusicTrackWidget.setVisible(false, !firstLoad);
        }
    }

    @Override
    protected void updateControlsState() {
        mMusicTrackWidget.setControlsEnabled(mControlsEnabled);
        mVolumeControls.setEnabled(mControlsEnabled);
    }

}


text:
ig.module(
    'plusplus.entities.destructable'
)
    .requires(
        'plusplus.entities.explosion',
        'plusplus.entities.particle-debris',
        'plusplus.helpers.utils'
)
    .defines(function() {
        "use strict";

        var _ut = ig.utils;

        /**
         * Entity that is destroyed when triggered by a trigger.
         *
- this entity can be destroyed either through another trigger or by taking damage
         *
- this entity cannot be destroyed through collision
         * @class
         * @extends ig.Spawner
         * @memberof ig
         * @author Collin Hover - collinhover.com
         * @see ig.EntityTrigger
         **/
        ig.EntityDestructable = ig.global.EntityDestructable = ig.EntityExplosion.extend( /**@lends ig.EntityDestructable.prototype */ {

            // editor properties

            _wmBoxColor: 'rgba( 255, 0, 175, 0.7 )',

            /**
             * Destructable should collide and block other entities, but not move.
             * @override
             * @default fixed
             */
            collides: ig.EntityExtended.COLLIDES.FIXED,

            /**
             * Destructable spawns {@link ig.EntityParticleDebris} when killed.
             */
            spawningEntity: ig.EntityParticleDebris,

            /**
             * @override
             * @default
             */
            spawnCountMax: 10,

            /**
             * Destructable spawned entity should not be sticky.
             * @override
             */
            spawnSettings: {
                collisionSticky: false,
                vel: {
                    x: 60,
                    y: 60
                }
            },

            /**
             * Destructable should not activate automatically.
             * @override
             * @default
             */
            activated: false,

            /**
             * Destructable should not activate automatically.
             * @override
             * @default
             */
            triggerable: false,

            /**
             * Destructable checks for characters also.
             * @override
             */
            initTypes: function() {

                this.parent();

                _ut.addType(ig.EntityExtended, this, 'checkAgainst', "CHARACTER");

            },

            /**
             * Destructable is killed on activate.
             * @override
             */
            activate: function(entity) {

                this.parent(entity);

                this.kill();

            },

            /**
             * Destructable is automatically triggered when killed to spawn debris.
             * @override
             */
            kill: function(silent) {

                // make sure we've triggered

                if (!this.activated) {

                    this.trigger(this);

                } else {

                    this.parent(silent);

                }

            }

        });

    });


text:
#include "hostfs_linux.h"

static struct super_operations hostfs_super_ops;

static int
#ifndef KERNEL_2_6
hostfs_statfs(struct super_block *sb, struct statfs *buf)
#else /* KERNEL_2_6 */
hostfs_statfs(struct super_block *sb, struct kstatfs *buf)
#endif /* KERNEL_2_6 */
{
        struct hf_vfsstat_data data;

        get_host_data(hf_VfsStat, 0, NULL, &data);

        memset(buf, 0, sizeof *buf);
        buf->f_type = HOSTFS_MAGIC;
        buf->f_bsize = data.bsize;
        buf->f_blocks = data.blocks;
        buf->f_bfree = data.bfree;
        buf->f_bavail = data.bavail;
        buf->f_files = data.files;
        buf->f_ffree = data.ffree;
        buf->f_namelen = HOSTFS_FILENAME_LEN;

	return 0;
}

#ifndef KERNEL_2_6
static struct super_block *
#else /* KERNEL_2_6 */
static int
#endif /* KERNEL_2_6 */
hostfs_read_super(struct super_block *sb, void *data, int silent)
{
        struct inode *root_inode;
        struct hf_handshake_data odata;
        struct hf_handshake_reply_data idata;

        odata.version = HOSTFS_VERSION;
        get_host_data(hf_Handshake, 0, &odata, &idata);

        if (idata.sys_error || idata.magic != HOSTFS_MAGIC) {
                printk(DEVICE_NAME " Handshake with Simics module failed "
                       "(err=%d, magic=%x/expected %x!\n", idata.sys_error,
                       idata.magic, HOSTFS_MAGIC);
                goto out_fail;
        }

        printk(DEVICE_NAME " mounted\n");

        sb->s_op = &hostfs_super_ops;
        sb->s_magic = HOSTFS_MAGIC;
        sb->s_blocksize = HOSTFS_BLOCK_SIZE;
        sb->s_blocksize_bits = HOSTFS_BLOCK_BITS;
        root_inode = new_inode(sb);
        if (!root_inode)
                goto out_fail;
        root_inode->i_ino = HOSTFS_ROOT_INO;
        hostfs_read_inode(root_inode);
        sb->s_root = d_alloc_root(root_inode);
        if (!sb->s_root)
                goto out_no_root;

#ifndef KERNEL_2_6
        return sb;
#else /* KERNEL_2_6 */
        return 0;
#endif /* KERNEL_2_6 */

 out_no_root:
        printk(DEVICE_NAME " get root inode failed\n");
        iput(root_inode);

 out_fail:
#ifndef KERNEL_2_6
        return NULL;
#else /* KERNEL_2_6 */
        return -EINVAL;
#endif /* KERNEL_2_6 */
}

static void
hostfs_put_super(struct super_block *sb)
{
        struct hf_common_data idata;
        get_host_data(hf_Unmount, 0, NULL, &idata);
}

static struct super_operations hostfs_super_ops = {
        read_inode: hostfs_read_inode,
        write_inode: hostfs_write_inode,
        put_super: hostfs_put_super,
        statfs:   hostfs_statfs,
};

#ifndef KERNEL_2_6
static DECLARE_FSTYPE(host_fs_type, "simicsfs", hostfs_read_super, 0);
#else /* KERNEL_2_6 */
static struct super_block *
hostfs_get_sb(struct file_system_type *fs_type,
	int flags, const char *dev_name, void *data)
{
	return get_sb_nodev(fs_type, flags, data, hostfs_read_super);
}

static struct file_system_type host_fs_type = {
	.owner =	THIS_MODULE,
	.name =		"simicsfs",
	.get_sb =	hostfs_get_sb,
	.kill_sb =	kill_anon_super,
};

#endif /* KERNEL_2_6 */

static int
__init init_hostfs(void)
{
        printk(DEVICE_NAME " " SYMBOL_TO_STRING(HOSTFS_VERSION) "."     \
               SYMBOL_TO_STRING(HOSTFS_SUBVERSION) " loaded\n");
        init_host_fs();
        return register_filesystem(&host_fs_type);
}

static void
__exit cleanup_hostfs(void)
{
        unregister_filesystem(&host_fs_type);
        printk(DEVICE_NAME " unloaded\n");
}

#ifndef KERNEL_2_6
EXPORT_NO_SYMBOLS;
#endif /* KERNEL_2_6 */

module_init(init_hostfs)
module_exit(cleanup_hostfs)


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class GoClippy extends React.Component<IconBaseProps> { }


text:
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl

import pytest

from openpyxl.xml.functions import tostring, fromstring
from openpyxl.tests.helper import compare_xml

@pytest.fixture
def Scaling():
    from ..axis import Scaling
    return Scaling

def test_scaling(Scaling):

    scale = Scaling()
    xml = tostring(scale.to_tree())
    expected = """
    <scaling>
       <orientation val="minMax"></orientation>
    </scaling>
    """
    diff = compare_xml(xml, expected)
    assert diff is None, diff

@pytest.fixture
def _BaseAxis():
    from ..axis import _BaseAxis
    return _BaseAxis

class TestAxis:

    def test_ctor(self, _BaseAxis, Scaling):
        axis = _BaseAxis(axId=10, crossAx=100)
        xml = tostring(axis.to_tree(tagname="baseAxis"))
        expected = """
        <baseAxis>
            <axId val="10"></axId>
            <scaling>
              <orientation val="minMax"></orientation>
            </scaling>
            <axPos val="l" />
            <crossAx val="100" />
        </baseAxis>
        """
        diff = compare_xml(xml, expected)
        assert diff is None, diff

@pytest.fixture
def TextAxis():
    from ..axis import TextAxis
    return TextAxis

class TestTextAxis:

    def test_ctor(self, TextAxis):
        axis = TextAxis(axId=10, crossAx=100)
        xml = tostring(axis.to_tree())
        expected = """
        <catAx>
            <axId val="10"></axId>
            <scaling>
              <orientation val="minMax"></orientation>
            </scaling>
            <axPos val="l" />
            <crossAx val="100" />
            <lblOffset val="100" />
        </catAx>
        """
        diff = compare_xml(xml, expected)
        assert diff is None, diff

    def from_xml(self, TextAxis):
        src = """
        <catAx>
            <axId val="2065276984"/>
            <scaling>
              <orientation val="minMax"/>
            </scaling>
            <delete val="0"/>
            <axPos val="b"/>
            <majorTickMark val="out"/>
            <minorTickMark val="none"/>
            <tickLblPos val="nextTo"/>
            <crossAx val="2056619928"/>
            <crosses val="autoZero"/>
            <auto val="1"/>
            <lblAlgn val="ctr"/>
            <lblOffset val="100"/>
            <noMultiLvlLbl val="0"/>
        </catAx>
        """
        node = fromstring(src)
        axis = CatAx.from_tree(node)
        assert axis.scaling.orientation == "minMax"
        assert axis.auto is True
        assert axis.majorTickMark == "out"
        assert axis.minorTickMark is None

@pytest.fixture
def NumericAxis():
    from ..axis import NumericAxis
    return NumericAxis

class TestValAx:

    def test_ctor(self, NumericAxis):
        axis = NumericAxis(axId=100, crossAx=10)
        xml = tostring(axis.to_tree())
        expected = """
        <valAx>
          <axId val="100"></axId>
          <scaling>
            <orientation val="minMax"></orientation>
          </scaling>
          <axPos val="l" />
          <majorGridlines />
          <crossAx val="10" />
        </valAx>
        """
        diff = compare_xml(xml, expected)
        assert diff is None, diff

    def test_from_xml(self, NumericAxis):
        src = """
        <valAx>
            <axId val="2056619928"/>
            <scaling>
                <orientation val="minMax"/>
            </scaling>
            <delete val="0"/>
            <axPos val="l"/>
            <majorGridlines/>
            <numFmt formatCode="General" sourceLinked="1"/>
            <majorTickMark val="out"/>
            <minorTickMark val="none"/>
            <tickLblPos val="nextTo"/>
            <crossAx val="2065276984"/>
            <crosses val="autoZero"/>
            <crossBetween val="between"/>
        </valAx>
        """
        node = fromstring(src)
        axis = NumericAxis.from_tree(node)
        assert axis.delete is False
        assert axis.crossAx == 2065276984
        assert axis.crossBetween == "between"

@pytest.fixture
def DateAxis():
    from ..axis import DateAxis
    return DateAxis

class TestDateAx:

    def test_ctor(self, DateAxis):
        axis = DateAxis(axId=500, crossAx=10)
        xml = tostring(axis.to_tree())
        expected = """
        <dateAx>
           <axId val="500"></axId>
           <scaling>
             <orientation val="minMax"></orientation>
           </scaling>
           <axPos val="l" />
           <crossAx val="10" />
           <majorUnit val="1" />
        </dateAx>
        """
        diff = compare_xml(xml, expected)
        assert diff is None, diff

    def test_from_xml(self, DateAxis):
        from openpyxl.chart.data_source import NumFmt

        src = """
        <dateAx>
          <axId val="20"/>
          <scaling>
            <orientation val="minMax"/>
          </scaling>
          <delete val="0"/>
          <axPos val="b"/>
          <numFmt formatCode="d-mmm" sourceLinked="1"/>
          <majorTickMark val="out"/>
          <minorTickMark val="none"/>
          <tickLblPos val="nextTo"/>
          <crossAx val="10"/>
          <crosses val="autoZero"/>
          <auto val="1"/>
          <lblOffset val="100"/>
          <baseTimeUnit val="months"/>
        </dateAx>
        """
        node = fromstring(src)
        axis = DateAxis.from_tree(node)
        assert axis == DateAxis(axId=20, crossAx=10, axPos="b",
                              scaling="minMax", delete=False, numFmt=NumFmt("d-mmm", True),
                              majorTickMark="out", crosses="autoZero", tickLblPos="nextTo",
                              auto=True, lblOffset=100, baseTimeUnit="months")

@pytest.fixture
def SeriesAxis():
    from ..axis import SeriesAxis
    return SeriesAxis

class TestSeriesAxis:

    def test_ctor(self, SeriesAxis):
        axis = SeriesAxis(axId=1000, crossAx=10)
        xml = tostring(axis.to_tree())
        expected = """
        <serAx>
          <axId val="1000"></axId>
          <scaling>
            <orientation val="minMax"></orientation>
          </scaling>
          <axPos val="l" />
          <crossAx val="10" />
        </serAx>
        """
        diff = compare_xml(xml, expected)
        assert diff is None, diff

    def test_from_xml(self, SeriesAxis):
        src = """
        <serAx>
          <axId val="1000"></axId>
          <scaling>
            <orientation val="minMax"></orientation>
          </scaling>
          <axPos val="l" />
          <crossAx val="10" />
        </serAx>
        """
        node = fromstring(src)
        axis = SeriesAxis.from_tree(node)
        assert axis == SeriesAxis()

@pytest.fixture
def DisplayUnitsLabel():
    from ..axis import DisplayUnitsLabel
    return DisplayUnitsLabel

class TestDispUnitsLabel:

    def test_ctor(self, DisplayUnitsLabel):
        axis = DisplayUnitsLabel()
        xml = tostring(axis.to_tree())
        expected = """
        <dispUnitsLbl />
        """
        diff = compare_xml(xml, expected)
        assert diff is None, diff

    def test_from_xml(self, DisplayUnitsLabel):
        src = """
        <dispUnitsLbl />
        """
        node = fromstring(src)
        axis = DisplayUnitsLabel.from_tree(node)
        assert axis == DisplayUnitsLabel()

@pytest.fixture
def DisplayUnitsLabelList():
    from ..axis import DisplayUnitsLabelList
    return DisplayUnitsLabelList

class TestDisplayUnitList:

    def test_ctor(self, DisplayUnitsLabelList):
        axis = DisplayUnitsLabelList()
        xml = tostring(axis.to_tree())
        expected = """
        <dispUnits />
        """
        diff = compare_xml(xml, expected)
        assert diff is None, diff

    def test_from_xml(self, DisplayUnitsLabelList):
        src = """
        <dispUnits />
        """
        node = fromstring(src)
        axis = DisplayUnitsLabelList.from_tree(node)
        assert axis == DisplayUnitsLabelList()

@pytest.fixture
def ChartLines():
    from ..axis import ChartLines
    return ChartLines

class TestChartLines:

    def test_ctor(self, ChartLines):
        axis = ChartLines()
        xml = tostring(axis.to_tree())
        expected = """
        <chartLines />
        """
        diff = compare_xml(xml, expected)
        assert diff is None, diff

    def test_from_xml(self, ChartLines):
        src = """
        <chartLines />
        """
        node = fromstring(src)
        axis = ChartLines.from_tree(node)
        assert axis == ChartLines()


text:
title: Un*spoken
subtitle: exploration
layout: default
modal-id: 2
date: 2016-01-02
list: 1
img: ['unspoke01.JPG','unspoke3.png', 'unspoke4.JPG']
thumbnail: unspoke-thumb.jpg
alt: image-alt
project-date: April 2016
client: n/a
category: exploration
description: Un*Spoken is an interactive installation that explores the contrasts between laughter and crying and how these non-language based utterances relate to the emotional responses that arise when one hears music. Emotions compel us and create a universal phenomenon in which we understand and relate to others. Using project-driven research and by translating a database of such sounds into music that can be played back, the piece allows the audience to come to their own conclusions and comparisons. Un*Spoken was created by transcribing audio into dot compositions that can be played through a music box. Because these emotions are so similar, they can easily be misinterpreted but when these non-verbal methods of communication are stripped and transcribed, the potential for an emotional vocabulary is reestablished.

Collaborative work with Megan Pryce

---


text:
using System;
using NUnit.Framework;
using BookStore.Data.Model;

namespace BookStore.Data.Models.Tests.BookTests
{
    [TestFixture]
    public class BookIsDeleted_Should
    {
        [TestCase(true)]
        [TestCase(false)]
        public void IsDeleted_ShouldGetAndSetDataCorrectly(bool testIsDeleted)
        {
            // Arrange & Act
            var product = new Book { IsDeleted = testIsDeleted };

            // Assert
            Assert.AreEqual(testIsDeleted, product.IsDeleted);
        }
    }
}


text:
package server.persistence;

import server.logic.Game;
import server.logic.data.Map;
import server.logic.data.Player;
import server.persistence.dataendpoints.PersistenceEndpoint;
import server.persistence.dataendpoints.SerializableFileEndpoint;
import server.persistence.objects.*;

import java.util.HashMap;

/**
 * Der PeristenceManger dient zur Verwaltung aller Endpunkte, an denen Spielklassen, nachfolgend sourceClass bezeichnet, gespeichert werden können.
 * Dabei kann der PersistenceManager mehrere dieser Endpunkte bereitstellen.
 *
 * Die Endpunkte bestimmen dann genau wie und wo die Daten gespeichert werden. Dies kann Dateibassiert geschehen oder aber in einer Datenbank, genauso wäre eine Aufspaltung zwischen teilweise Datenbank und teilweise Dateibassiert möglich.
 *
 * Die Klassen im Paket objects dienen zur Serialisierung der Spielklassen, sodass z.B. nicht alle Armeen als einzlene Klasse gespeichert werden sondern nur ein Spieler mit seinen Ländern und die Anzahl der Armeen auf diesem Land.
 *
 */

public class PersistenceManager {

    /**
     * Bereits erzeugte endpoints werden hier abgelegt
     */
    private final HashMap<Class,PersistenceEndpoint> endpoints = new HashMap<Class,PersistenceEndpoint>();

    /**
     * Erstellt für eine Logik-Klasse ein PersistensEndpoint
     * @see server.persistence.dataendpoints.PersistenceEndpoint
     * @param type Logik-Klasse
     * @return PerisistensEndpoint<type>
     */
    private PersistenceEndpoint<?> createHandler (Class type){

        if (type == Game.class){
                return new SerializableFileEndpoint<Game>(Game.class,PersistenceGame.class, this);
        }
        else if (type == Player.class ){
                return new SerializableFileEndpoint<Player>(Player.class,PersistencePlayer.class, this);
        }
        else if (type == Map.class){
            return new SerializableFileEndpoint<Map>(Map.class,PersistenceMap.class, this);
        }
        throw new RuntimeException(new ClassNotFoundException("Für die Klasse " + type + " konnte keine Speicherklasse gefudnen werden "));
    }
    /**
     * Erstellt bzw. nimmt den gechachten Handler für die angebene Klasse
     * @param type Logik-Klasse
     * @return Handler s
     */
    private PersistenceEndpoint<?>  getHandler(Class type) {
        if(!endpoints.containsKey(type)){
            endpoints.put(type,this.createHandler(type));
        }
        return endpoints.get(type);
    }

    /**
     * Gibt einen PersistenceEndpoint für die Logik-Klasse Game zurück
     * @return PersistenceEndpoint für Game
     */
    @SuppressWarnings("unchecked")
    public PersistenceEndpoint<Game> getGameHandler(){
        return (PersistenceEndpoint<Game>)this.getHandler(Game.class);
    }
    /**
     * Gibt einen PersistenceEndpoint für die Logik-Klasse Player zurück
     * @return PersistenceEndpoint für Player
     */
    @SuppressWarnings("unchecked")
    public PersistenceEndpoint<Player> getPlayerHandler(){
        return (PersistenceEndpoint<Player>)this.getHandler(Player.class);
    }
    /**
     * Gibt einen PersistenceEndpoint für die Logik-Klasse Map zurück
     * @return PersistenceEndpoint für Map
     */
    @SuppressWarnings("unchecked")
    public PersistenceEndpoint<Map> getMapHandler(){
        return (PersistenceEndpoint<Map>)this.getHandler(Map.class);
    }

}


text:
package rx.internal.operators;

import static rx.Observable.concat;
import static rx.Observable.just;
import static rx.Observable.zip;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.internal.util.UtilityFunctions;

/**
 * Returns an {@link Observable} that emits a single {@code Boolean} value that indicates whether two source
 * {@code Observable}s emit sequences of items that are equivalent to each other.
 */
public final class OperatorSequenceEqual {
    private OperatorSequenceEqual() {
        throw new IllegalStateException("No instances!");
    }

    /** NotificationLite doesn't work as zip uses it. */
    private static final Object LOCAL_ONCOMPLETED = new Object();
    static <T> Observable<Object> materializeLite(Observable<T> source) {
        return concat(
                source.map(new Func1<T, Object>() {

                    @Override
                    public Object call(T t1) {
                        return t1;
                    }

                }), just(LOCAL_ONCOMPLETED));
    }

    /**
     * Tests whether two {@code Observable} sequences are identical, emitting {@code true} if both sequences
     * complete without differing, and {@code false} if the two sequences diverge at any point.
     *
     * @param <T> t
     * @param first
     *      the first of the two {@code Observable}s to compare
     * @param second
     *      the second of the two {@code Observable}s to compare
     * @param equality
     *      a function that tests emissions from each {@code Observable} for equality
     * @return an {@code Observable} that emits {@code true} if {@code first} and {@code second} complete
     *         after emitting equal sequences of items, {@code false} if at any point in their sequences the
     *         two {@code Observable}s emit a non-equal item.
     */
    public static <T> Observable<Boolean> sequenceEqual(
            Observable<? extends T> first, Observable<? extends T> second,
            final Func2<? super T, ? super T, Boolean> equality) {
        Observable<Object> firstObservable = materializeLite(first);
        Observable<Object> secondObservable = materializeLite(second);

        return zip(firstObservable, secondObservable,
                new Func2<Object, Object, Boolean>() {

                    @Override
                    @SuppressWarnings("unchecked")
                    public Boolean call(Object t1, Object t2) {
                        boolean c1 = t1 == LOCAL_ONCOMPLETED;
                        boolean c2 = t2 == LOCAL_ONCOMPLETED;
                        if (c1 && c2) {
                            return true;
                        }
                        if (c1 || c2) {
                            return false;
                        }
                        // Now t1 and t2 must be 'onNext'.
                        return equality.call((T)t1, (T)t2);
                    }

                }).all(UtilityFunctions.<Boolean> identity());
    }
}


text:
using UnityEngine;
using System.Collections;

public class StartingPositions : MonoBehaviour
{
    public Vector2[] possibleNinjaPositions;
}


text:
class AddAutomaticToGroups < ActiveRecord::Migration
  def up
    add_column :groups, :automatic, :boolean, default: false, null: false

    # all numbers below 100 are reserved for automatic
    execute <<SQL
    ALTER SEQUENCE groups_id_seq START WITH 100
SQL
  end

  def down
    remove_column :groups, :automatic
  end
end


text:
import { noteNamings } from './noteNamings'
import { chordQualities } from './chordQualities'
import { chordExtendeds } from './chordExtendeds'
import { chordAddeds } from './chordAddeds.js'
import { chordSuspendeds } from './chordSuspendeds'

export function prettyPrint (chord, opts) {
  opts = opts || {}
  let naming = opts.naming || 'English'

  let toPrintableNote
  // can specify an object here or one of 'English', 'NorthernEuropean', 'SouthernEuropean'
  if (typeof naming === 'string') {
    toPrintableNote = note => noteNamings[naming][note][0]
  } else {
    let noteNamesAsList = Object.keys(noteNamings.English)
    toPrintableNote = note => naming[noteNamesAsList.indexOf(note)]
  }

  // just use the first name for now, but later we may want to add options
  // to allow people to choose how to express chord. e.g. to prefer flats
  // instead of sharps, or prefer certain flats to certain sharps, etc.
  // (e.g. 'Bb' seems to be more common than 'A#', but 'F#' is more common than 'Ab')

  let str = toPrintableNote(chord.root)
  if (chord.extended) {
    str += chordExtendeds[chord.extended][1][0]
  } else {
    str += chordQualities[chord.quality][0]
  }

  if (chord.added) {
    str += chordAddeds[chord.added][0]
  }

  if (chord.suspended) {
    str += chordSuspendeds[chord.suspended][0]
  }

  if (chord.overridingRoot) {
    str += '/' + toPrintableNote(chord.overridingRoot)
  }
  return str
}


text:
package com.amazonaws.services.config.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListTagsForResourceRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the supported
     * resources are ConfigRule, ConfigurationAggregator and
     * AggregatorAuthorization.
     *

     */
    private String resourceArn;
    /**
     *

     * The maximum number of tags returned on each page. The limit maximum is 50. You cannot specify a number greater
     * than 50. If you specify 0, Config uses the default.
     *

     */
    private Integer limit;
    /**
     *

     * The nextToken string returned on a previous page that you use to get the next page of results in a
     * paginated response.
     *

     */
    private String nextToken;

    /**
     *

     * The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the supported
     * resources are ConfigRule, ConfigurationAggregator and
     * AggregatorAuthorization.
     *

     *
     * @param resourceArn
     *        The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the
     *        supported resources are ConfigRule, ConfigurationAggregator and
     *        AggregatorAuthorization.
     */

    public void setResourceArn(String resourceArn) {
        this.resourceArn = resourceArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the supported
     * resources are ConfigRule, ConfigurationAggregator and
     * AggregatorAuthorization.
     *

     *
     * @return The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the
     *         supported resources are ConfigRule, ConfigurationAggregator and
     *         AggregatorAuthorization.
     */

    public String getResourceArn() {
        return this.resourceArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the supported
     * resources are ConfigRule, ConfigurationAggregator and
     * AggregatorAuthorization.
     *

     *
     * @param resourceArn
     *        The Amazon Resource Name (ARN) that identifies the resource for which to list the tags. Currently, the
     *        supported resources are ConfigRule, ConfigurationAggregator and
     *        AggregatorAuthorization.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListTagsForResourceRequest withResourceArn(String resourceArn) {
        setResourceArn(resourceArn);
        return this;
    }

    /**
     *

     * The maximum number of tags returned on each page. The limit maximum is 50. You cannot specify a number greater
     * than 50. If you specify 0, Config uses the default.
     *

     *
     * @param limit
     *        The maximum number of tags returned on each page. The limit maximum is 50. You cannot specify a number
     *        greater than 50. If you specify 0, Config uses the default.
     */

    public void setLimit(Integer limit) {
        this.limit = limit;
    }

    /**
     *

     * The maximum number of tags returned on each page. The limit maximum is 50. You cannot specify a number greater
     * than 50. If you specify 0, Config uses the default.
     *

     *
     * @return The maximum number of tags returned on each page. The limit maximum is 50. You cannot specify a number
     *         greater than 50. If you specify 0, Config uses the default.
     */

    public Integer getLimit() {
        return this.limit;
    }

    /**
     *

     * The maximum number of tags returned on each page. The limit maximum is 50. You cannot specify a number greater
     * than 50. If you specify 0, Config uses the default.
     *

     *
     * @param limit
     *        The maximum number of tags returned on each page. The limit maximum is 50. You cannot specify a number
     *        greater than 50. If you specify 0, Config uses the default.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListTagsForResourceRequest withLimit(Integer limit) {
        setLimit(limit);
        return this;
    }

    /**
     *

     * The nextToken string returned on a previous page that you use to get the next page of results in a
     * paginated response.
     *

     *
     * @param nextToken
     *        The nextToken string returned on a previous page that you use to get the next page of results
     *        in a paginated response.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The nextToken string returned on a previous page that you use to get the next page of results in a
     * paginated response.
     *

     *
     * @return The nextToken string returned on a previous page that you use to get the next page of
     *         results in a paginated response.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The nextToken string returned on a previous page that you use to get the next page of results in a
     * paginated response.
     *

     *
     * @param nextToken
     *        The nextToken string returned on a previous page that you use to get the next page of results
     *        in a paginated response.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListTagsForResourceRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getResourceArn() != null)
            sb.append("ResourceArn: ").append(getResourceArn()).append(",");
        if (getLimit() != null)
            sb.append("Limit: ").append(getLimit()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListTagsForResourceRequest == false)
            return false;
        ListTagsForResourceRequest other = (ListTagsForResourceRequest) obj;
        if (other.getResourceArn() == null ^ this.getResourceArn() == null)
            return false;
        if (other.getResourceArn() != null && other.getResourceArn().equals(this.getResourceArn()) == false)
            return false;
        if (other.getLimit() == null ^ this.getLimit() == null)
            return false;
        if (other.getLimit() != null && other.getLimit().equals(this.getLimit()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getResourceArn() == null) ? 0 : getResourceArn().hashCode());
        hashCode = prime * hashCode + ((getLimit() == null) ? 0 : getLimit().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public ListTagsForResourceRequest clone() {
        return (ListTagsForResourceRequest) super.clone();
    }

}


text:
using System;
using System.IO;

using Belikov.GenuineChannels.Connection;
using Belikov.GenuineChannels.Messaging;

namespace Belikov.GenuineChannels.GenuineHttp
{
	/// <summary>
	/// Provides a set of operations for writing and reading HTTP headers.
	/// </summary>
	internal class HttpMessageCoder
	{
		/// <summary>
		/// To prevent creating instances of the HttpMessageCoder class.
		/// </summary>
		private HttpMessageCoder()
		{
		}

		/// <summary>
		/// Writes HTTP header to the specified binary writer.
		/// </summary>
		/// <param name="binaryWriter">The binary writer.</param>
		/// <param name="protocolVersion">The version of the protocol.</param>
		/// <param name="genuineConnectionType">The type of connection.</param>
		/// <param name="hostId">The id of the remote host.</param>
		/// <param name="httpPacketType">The type of the packet.</param>
		/// <param name="sequenceNo">The packet number.</param>
		/// <param name="connectionName">The name of the connection.</param>
		/// <param name="localHostUniqueIdentifier">The unique identifier of the local HostInformation.</param>
		public static void WriteRequestHeader(BinaryWriter binaryWriter, byte protocolVersion, GenuineConnectionType genuineConnectionType, byte[] hostId, HttpPacketType httpPacketType, int sequenceNo, string connectionName, int localHostUniqueIdentifier)
		{
			binaryWriter.Write((byte) MessageCoder.COMMAND_MAGIC_CODE);
			binaryWriter.Write((byte) protocolVersion);
			binaryWriter.Write((byte) genuineConnectionType);
			binaryWriter.Write(hostId);
			binaryWriter.Write((byte) httpPacketType);
			binaryWriter.Write((int) sequenceNo);
			binaryWriter.Write(connectionName);
			binaryWriter.Write((int) localHostUniqueIdentifier);
		}

		/// <summary>
		/// Parses the HTTP header.
		/// </summary>
		/// <param name="binaryReader">The source binary reader.</param>
		/// <param name="protocolVersion">The version of the protocol.</param>
		/// <param name="genuineConnectionType">The type of connection.</param>
		/// <param name="hostId">The identifier of the remote host.</param>
		/// <param name="httpPacketType">The type of the packet.</param>
		/// <param name="sequenceNo">The packet number.</param>
		/// <param name="connectionName">The name of the connection.</param>
		/// <param name="remoteHostUniqueIdentifier">The unique identifier of the HostInformation used by the remote host.</param>
		public static void ReadRequestHeader(BinaryReader binaryReader, out byte protocolVersion, out GenuineConnectionType genuineConnectionType, out Guid hostId, out HttpPacketType httpPacketType, out int sequenceNo, out string connectionName, out int remoteHostUniqueIdentifier)
		{
			if (binaryReader.ReadByte() != MessageCoder.COMMAND_MAGIC_CODE)
				throw GenuineExceptions.Get_Receive_IncorrectData();

			protocolVersion = binaryReader.ReadByte();
			genuineConnectionType = (GenuineConnectionType) binaryReader.ReadByte();
			hostId = new Guid(binaryReader.ReadBytes(16));
			httpPacketType = (HttpPacketType) binaryReader.ReadByte();
			sequenceNo = binaryReader.ReadInt32();

			connectionName = "$/__GC/" + hostId;
			remoteHostUniqueIdentifier = 0;

			if (protocolVersion >= 0x1)
			{
				connectionName = binaryReader.ReadString();
				remoteHostUniqueIdentifier = binaryReader.ReadInt32();
			}
		}

		/// <summary>
		/// Writes the HTTP response header.
		/// </summary>
		/// <param name="binaryWriter">The destination.</param>
		/// <param name="protocolVersion">The version of the protocol.</param>
		/// <param name="serverUri">The server uri.</param>
		/// <param name="sequenceNo">The packet number.</param>
		/// <param name="httpPacketType">The type of the packet.</param>
		/// <param name="localHostUniqueIdentifier">The unique identifier of the local HostInformation.</param>
		public static void WriteResponseHeader(BinaryWriter binaryWriter, byte protocolVersion, string serverUri, int sequenceNo, HttpPacketType httpPacketType, int localHostUniqueIdentifier)
		{
			binaryWriter.Write((byte) MessageCoder.COMMAND_MAGIC_CODE);
			binaryWriter.Write(serverUri);
			binaryWriter.Write((int) sequenceNo);
			binaryWriter.Write((byte) httpPacketType);

			if (protocolVersion > 0)
				binaryWriter.Write((int) localHostUniqueIdentifier);
		}

		/// <summary>
		/// Reads the response from the stream.
		/// </summary>
		/// <param name="binaryReader">The source.</param>
		/// <param name="serverUri">The fetched server uri.</param>
		/// <param name="sequenceNo">The packet number.</param>
		/// <param name="httpPacketType">The type of the packet.</param>
		/// <param name="remoteHostUniqueIdentifier">The unique identifier of the HostInformation used by the remote host.</param>
		public static void ReadResponseHeader(BinaryReader binaryReader, out string serverUri, out int sequenceNo, out HttpPacketType httpPacketType, out int remoteHostUniqueIdentifier)
		{
			if (binaryReader.ReadByte() != MessageCoder.COMMAND_MAGIC_CODE)
				throw GenuineExceptions.Get_Receive_IncorrectData();
			serverUri = binaryReader.ReadString();
			sequenceNo = binaryReader.ReadInt32();
			httpPacketType = (HttpPacketType) binaryReader.ReadByte();
			remoteHostUniqueIdentifier = binaryReader.ReadInt32();
		}
	}
}