text:
#include <sandesh/sandesh_types.h>
#include <sandesh/sandesh.h>

#include "ifmap/ifmap_server.h"

#include <boost/asio/io_service.hpp>
#include <boost/algorithm/string.hpp>

#include "base/logging.h"
#include "bgp/bgp_sandesh.h"
#include "db/db.h"
#include "db/db_graph.h"
#include "db/db_graph_edge.h"
#include "ifmap/ifmap_client.h"
#include "ifmap/ifmap_exporter.h"
#include "ifmap/ifmap_graph_walker.h"
#include "ifmap/ifmap_link_table.h"
#include "ifmap/ifmap_log.h"
#include "ifmap/ifmap_node.h"
#include "ifmap/ifmap_server_table.h"
#include "ifmap/ifmap_server_show_types.h"
#include "ifmap/ifmap_syslog_types.h"
#include "ifmap/ifmap_table.h"
#include "ifmap/ifmap_update_queue.h"
#include "ifmap/ifmap_update_sender.h"
#include "ifmap/ifmap_xmpp.h"
#include "ifmap/ifmap_uuid_mapper.h"
#include "schema/vnc_cfg_types.h"

using std::make_pair;

class IFMapServer::IFMapStaleCleaner : public Task {
public:
    IFMapStaleCleaner(DB *db, DBGraph *graph, IFMapServer *server):
        Task(TaskScheduler::GetInstance()->GetTaskId("db::DBTable"), 0),
        db_(db), graph_(graph), ifmap_server_(server) {
    }

    bool Run() {
        // objects_deleted indicates the count of objects-deleted-but-not-node
        uint32_t nodes_deleted = 0, nodes_changed = 0, links_deleted = 0,
                 objects_deleted = 0;
        uint64_t curr_seq_num =
            ifmap_server_->get_ifmap_channel_sequence_number();

        DBGraph::edge_iterator e_next(graph_);
        for (DBGraph::edge_iterator e_iter = graph_->edge_list_begin();
             e_iter != graph_->edge_list_end(); e_iter = e_next) {

            const DBGraph::DBVertexPair &tuple = *e_iter;
            // increment only after dereferencing
            e_next = ++e_iter;

            IFMapNode *lhs = static_cast<IFMapNode *>(tuple.first);
            IFMapNode *rhs = static_cast<IFMapNode *>(tuple.second);

            IFMapLink *link =
                static_cast<IFMapLink *>(graph_->GetEdge(lhs, rhs));
            assert(link);

            bool exists = false;
            IFMapLink::LinkOriginInfo origin_info =
                link->GetOriginInfo(IFMapOrigin::MAP_SERVER, &exists);
            if (exists && (origin_info.sequence_number < curr_seq_num)) {
                IFMapLinkTable *ltable = static_cast<IFMapLinkTable *>(
                    db_->FindTable("__ifmap_metadata__.0"));
                // Cleanup the node and remove from the graph
                link->RemoveOriginInfo(IFMapOrigin::MAP_SERVER);
                if (link->is_origin_empty()) {
                    ltable->DeleteLink(link, lhs, rhs);
                }
                links_deleted++;
            }
        }

        DBGraph::vertex_iterator v_next(graph_);
        for (DBGraph::vertex_iterator v_iter = graph_->vertex_list_begin();
            v_iter != graph_->vertex_list_end(); v_iter = v_next) {

            IFMapNode *node = static_cast<IFMapNode *>(v_iter.operator->());
            // increment only after dereferencing
            v_next = ++v_iter;

            IFMapObject *object =
                node->Find(IFMapOrigin(IFMapOrigin::MAP_SERVER));
            IFMapServerTable *ntable =
                static_cast<IFMapServerTable *>(node->table());
            if (object != NULL) {
                if (object->sequence_number() < curr_seq_num) {
                    node->Remove(object);
                    bool retb = ntable->DeleteIfEmpty(node);
                    if (retb) {
                        nodes_deleted++;
                    } else {
                        objects_deleted++;
                    }
                } else {
                    // There could be stale properties
                    bool changed = object->ResolveStaleness();
                    if (changed) {
                        nodes_changed++;
                        ntable->Notify(node);
                    }
                }
            } else {
                // The node doesnt have any object. We should delete it if it
                // does not have any neighbors either.
                bool retb = ntable->DeleteIfEmpty(node);
                if (retb) {
                    nodes_deleted++;
                }
            }
        }
        IFMAP_DEBUG(IFMapStaleCleanerInfo, curr_seq_num, nodes_deleted,
                    nodes_changed, links_deleted, objects_deleted);

        return true;
    }

private:
    DB *db_;
    DBGraph *graph_;
    IFMapServer *ifmap_server_;
};

class IFMapServer::IFMapVmSubscribe : public Task {
public:
    IFMapVmSubscribe(DB *db, DBGraph *graph, IFMapServer *server,
                     const std::string &vr_name, const std::string &vm_uuid,
                     bool subscribe, bool has_vms):
            Task(TaskScheduler::GetInstance()->GetTaskId("db::DBTable"), 0),
            db_(db), graph_(graph), ifmap_server_(server), vr_name_(vr_name),
            vm_uuid_(vm_uuid), subscribe_(subscribe), has_vms_(has_vms) {
    }

    bool Run() {

        IFMapServerTable *vm_table = static_cast<IFMapServerTable *>(
            db_->FindTable("__ifmap__.virtual_machine.0"));
        assert(vm_table != NULL);

        // Find the vm's node using its UUID. If the config has not added the
        // vm yet, treat this request as pending since we cant process it right
        // now.
        IFMapNode *vm_node = ifmap_server_->GetVmNodeByUuid(vm_uuid_);
        if (vm_node) {
            IFMapServerTable *vr_table = static_cast<IFMapServerTable *>(
                db_->FindTable("__ifmap__.virtual_router.0"));
            assert(vr_table != NULL);

            std::string vm_name = vm_node->name();
            vr_table->IFMapVmSubscribe(vr_name_, vm_name, subscribe_, has_vms_);

            IFMapClient *client = ifmap_server_->FindClient(vr_name_);
            if (client) {
                if (subscribe_) {
                    ifmap_server_->ClientGraphDownload(client);
                }
            }
        } else {
            ifmap_server_->ProcessVmRegAsPending(vm_uuid_, vr_name_,
                                                 subscribe_);
        }

        return true;
    }

private:
    DB *db_;
    DBGraph *graph_;
    IFMapServer *ifmap_server_;
    std::string vr_name_;
    std::string vm_uuid_;
    bool subscribe_;
    bool has_vms_;
};

IFMapServer::IFMapServer(DB *db, DBGraph *graph,
                         boost::asio::io_service *io_service)
        : db_(db), graph_(graph),
          queue_(new IFMapUpdateQueue(this)),
          exporter_(new IFMapExporter(this)),
          sender_(new IFMapUpdateSender(this, queue())),
          vm_uuid_mapper_(new IFMapVmUuidMapper(db_, this)),
          work_queue_(TaskScheduler::GetInstance()->GetTaskId("db::DBTable"), 0,
                      boost::bind(&IFMapServer::ClientWorker, this, _1)),
          io_service_(io_service),
          stale_cleanup_timer_(TimerManager::CreateTimer(*(io_service_),
                                         "Stale cleanup timer")),
          ifmap_manager_(NULL), ifmap_channel_manager_(NULL) {
}

IFMapServer::~IFMapServer() {
}

void IFMapServer::Initialize() {
    exporter_->Initialize(db_);
    vm_uuid_mapper_->Initialize();
}

void IFMapServer::Shutdown() {
    TimerManager::DeleteTimer(stale_cleanup_timer_);
    vm_uuid_mapper_->Shutdown();
    exporter_->Shutdown();
}

void IFMapServer::ClientRegister(IFMapClient *client) {
    IFMAP_DEBUG(IFMapServerClientRegUnreg, "Register request for client ",
                client->identifier());
    size_t index = client_indexes_.find_first_clear();
    if (index == BitSet::npos) {
        index = client_indexes_.size();
    }
    client_indexes_.set(index);

    client_map_.insert(make_pair(client->identifier(), client));
    index_map_.insert(make_pair(index, client));
    client->Initialize(exporter_.get(), index);
    queue_->Join(index);
}

void IFMapServer::ClientUnregister(IFMapClient *client) {
    IFMAP_DEBUG(IFMapServerClientRegUnreg, "Un-register request for client ",
                client->identifier());
    size_t index = client->index();
    sender_->CleanupClient(index);
    queue_->Leave(index);
    index_map_.erase(index);
    client_map_.erase(client->identifier());
    client_indexes_.reset(index);
}

bool IFMapServer::ProcessClientWork(bool add, IFMapClient *client) {
    if (add) {
        ClientRegister(client);
    } else {
        ClientGraphCleanup(client);
        RemoveSelfAddedLinks(client);
        ClientUnregister(client);
    }
    return true;
}

// To be used only by tests.
void IFMapServer::AddClient(IFMapClient *client) {
    // Let ClientWorker() do all the work in the context of the db-task
    QueueEntry entry;
    entry.op = ADD;
    entry.client = client;
    work_queue_.Enqueue(entry);
}

// To be used only by tests.
void IFMapServer::DeleteClient(IFMapClient *client) {
    // Let ClientWorker() do all the work in the context of the db-task
    QueueEntry entry;
    entry.op = DELETE;
    entry.client = client;
    work_queue_.Enqueue(entry);
}

// To be used only by tests.
void IFMapServer::SimulateDeleteClient(IFMapClient *client) {
    QueueEntry entry;
    entry.op = DELETE;
    entry.client = client;
    ClientWorker(entry);
}

bool IFMapServer::ClientWorker(QueueEntry work_entry) {
    bool add = (work_entry.op == ADD) ? true : false;
    IFMapClient *client = work_entry.client;

    bool done = ProcessClientWork(add, client);

    return done;
}

void IFMapServer::NodeResetClient(DBGraphVertex *vertex, const BitSet &bset) {
    IFMapNode *node = static_cast<IFMapNode *>(vertex);
    IFMapNodeState *state = exporter_->NodeStateLookup(node);
    if (state) {
        state->InterestReset(bset);
        state->AdvertisedReset(bset);
    }
}

void IFMapServer::LinkResetClient(DBGraphEdge *edge, const BitSet &bset) {
    IFMapLink *link = static_cast<IFMapLink *>(edge);
    IFMapLinkState *state = exporter_->LinkStateLookup(link);
    if (state) {
        state->InterestReset(bset);
        state->AdvertisedReset(bset);
    }
}

void IFMapServer::RemoveSelfAddedLinks(IFMapClient *client) {
    IFMapServerTable *vr_table = static_cast<IFMapServerTable *>(
        db_->FindTable("__ifmap__.virtual_router.0"));
    assert(vr_table != NULL);

    IFMapNode *node = vr_table->FindNode(client->identifier());
    if ((node != NULL) && node->IsVertexValid()) {
        for (DBGraphVertex::adjacency_iterator iter = node->begin(graph_), next;
            iter != node->end(graph_); iter = next) {
            IFMapNode *adj = static_cast<IFMapNode *>(iter.operator->());
            next = ++iter;
            if (adj->table()->name() == "__ifmap__.virtual_machine.0") {
                vr_table->IFMapRemoveVrVmLink(node, adj);
            }
        }
    }
}

void IFMapServer::ClientGraphDownload(IFMapClient *client) {
    IFMapTable *table = IFMapTable::FindTable(db_, "virtual-router");
    assert(table);

    IFMapNode *node = table->FindNode(client->identifier());
    if ((node != NULL) && node->IsVertexValid()) {
        for (DBGraphVertex::adjacency_iterator iter = node->begin(graph_);
            iter != node->end(graph_); ++iter) {
            IFMapNode *adj = static_cast<IFMapNode *>(iter.operator->());
            if (exporter_->FilterNeighbor(node, adj)) {
                continue;
            }
            DBGraphEdge *edge = graph_->GetEdge(node, adj);
            DBTable *link_table = static_cast<DBTable *>(
                db_->FindTable("__ifmap_metadata__.0"));
            link_table->Change(edge);
        }
    }
}

void IFMapServer::ClientGraphCleanup(IFMapClient *client) {
    IFMapTable *table = IFMapTable::FindTable(db_, "virtual-router");
    assert(table);

    IFMapNode *node = table->FindNode(client->identifier());
    if (node != NULL) {
        IFMapNodeState *state = exporter_->NodeStateLookup(node);
        if (state == NULL) {
            return;
        }

        BitSet rm_bs;
        rm_bs.set(client->index());
        state->InterestReset(rm_bs);
        state->AdvertisedReset(rm_bs);

        if (node->IsVertexValid()) {
            graph_->Visit(node,
                boost::bind(&IFMapServer::NodeResetClient, this, _1, rm_bs),
                boost::bind(&IFMapServer::LinkResetClient, this, _1, rm_bs));
        }
    }
}

IFMapClient *IFMapServer::FindClient(const std::string &id) {
    ClientMap::iterator loc = client_map_.find(id);
    if (loc != client_map_.end()) {
        return loc->second;
    }
    return NULL;
}

IFMapClient *IFMapServer::GetClient(int index) {
    IndexMap::iterator loc = index_map_.find(index);
    if (loc != index_map_.end()) {
        return loc->second;
    }
    return NULL;
}

bool IFMapServer::StaleNodesProcTimeout() {
    IFMapStaleCleaner *cleaner = new IFMapStaleCleaner(db_, graph_, this);

    TaskScheduler *scheduler = TaskScheduler::GetInstance();
    scheduler->Enqueue(cleaner);
    return false;
}

void IFMapServer::StaleNodesCleanup() {
    if (stale_cleanup_timer_->running()) {
        stale_cleanup_timer_->Cancel();
    }
    stale_cleanup_timer_->Start(kStaleCleanupTimeout,
            boost::bind(&IFMapServer::StaleNodesProcTimeout, this),
            NULL);
}

void IFMapServer::ProcessVmSubscribe(std::string vr_name, std::string vm_uuid,
                                     bool subscribe, bool has_vms) {
    IFMapVmSubscribe *vm_sub = new IFMapVmSubscribe(db_, graph_, this,
                                                    vr_name, vm_uuid,
                                                    subscribe, has_vms);
    TaskScheduler *scheduler = TaskScheduler::GetInstance();
    scheduler->Enqueue(vm_sub);
}

void IFMapServer::ProcessVmSubscribe(std::string vr_name, std::string vm_uuid,
                                     bool subscribe) {
    IFMapClient *client = FindClient(vr_name);
    assert(client);
    IFMapVmSubscribe *vm_sub =
        new IFMapVmSubscribe(db_, graph_, this, vr_name, vm_uuid, subscribe,
                             client->HasVms());
    TaskScheduler *scheduler = TaskScheduler::GetInstance();
    scheduler->Enqueue(vm_sub);
}

void IFMapServer::ProcessVmRegAsPending(std::string vm_uuid,
                                        std::string vr_name, bool subscribe) {
    vm_uuid_mapper_->ProcessVmRegAsPending(vm_uuid, vr_name, subscribe);
}

IFMapNode *IFMapServer::GetVmNodeByUuid(const std::string &vm_uuid) {
    return vm_uuid_mapper_->GetVmNodeByUuid(vm_uuid);
}

void IFMapServer::FillClientMap(IFMapServerShowClientMap *out_map) {
    out_map->set_count(client_map_.size());
    out_map->clients.reserve(client_map_.size());
    for (ClientMap::const_iterator iter = client_map_.begin();
         iter != client_map_.end(); ++iter) {
        IFMapClient *client = iter->second;
        IFMapServerClientMapShowEntry entry;
        entry.set_client_name(client->identifier());
        out_map->clients.push_back(entry);
    }
}

void IFMapServer::FillIndexMap(IFMapServerShowIndexMap *out_map) {
    out_map->set_count(index_map_.size());
    out_map->clients.reserve(index_map_.size());
    for (IndexMap::const_iterator iter = index_map_.begin();
         iter != index_map_.end(); ++iter) {
        IFMapClient *client = iter->second;
        IFMapServerIndexMapShowEntry entry;
        entry.set_client_index(iter->first);
        entry.set_client_name(client->identifier());
        out_map->clients.push_back(entry);
    }
}


text:
package com.facebook.buck.cli;

import com.facebook.buck.util.DirtyPrintStreamDecorator;
import com.facebook.buck.util.cache.FileHashCacheVerificationResult;

import java.io.IOException;

/**
 * Verify the contents of our FileHashCache.
 */
public class VerifyHashCacheCommand extends AbstractCommand {
  @Override
  public int runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException {
    FileHashCacheVerificationResult result = params.getFileHashCache().verify();
    DirtyPrintStreamDecorator stdOut = params.getConsole().getStdOut();
    stdOut.println("Examined " + result.getCachesExamined() + " caches.");
    stdOut.println("Examined " + result.getFilesExamined() + " files.");
    if (result.getVerificationErrors().isEmpty()) {
      stdOut.println("No errors");
      return 0;
    } else {
      stdOut.println("Errors detected:");
      for (String err : result.getVerificationErrors()) {
        stdOut.println("  " + err);
      }
      return 1;
    }
  }

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

  @Override
  public String getShortDescription() {
    return "Verify contents of FileHashCache";
  }
}

redpajama_set_name: RedPajamaGithub


text:
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Add Guest

                <form id="add-guest" onsubmit="return false;" method="post" class="form-horizontal form-bordered" novalidate="novalidate">

                        First Name *

                            <input type="text" id="user_first_name" name="guest_first_name" class="form-control" placeholder="Enter first name here...">

                        Last Name

                            <input type="text" id="user_last_name" name="guest_last_name" class="form-control" placeholder="Enter last name here...">

                        Email*

                            <input type="email" id="user_email" name="guest_email" class="form-control" placeholder="Please enter email here...">

                        Mobile No. *

                            <input type="text" id="user_mobile" name="guest_mobile_no" class="form-control" placeholder="Mobile number here...">

                        Gender

                                <input type="radio" id="user_gender_male" checked="" name="guest_gender" value="male"> Male

                                <input type="radio" id="user_gender_female" name="guest_gender" value="female"> Female

                            <button type="submit" class="btn btn-sm btn-primary"> Submit</button>
                            <button type="reset" class="btn btn-sm btn-warning"> Reset</button>

                </form>


text:
import { Alto } from './alto.model';
export declare class HtmlFormatter {
    altoToHtml(alto: Alto): string;
}


text:
/**
 * @module Ink.Autoload
 * @version 1
 * Create Ink UI components easily
 */
Ink.createModule('Ink.Autoload', 1, ['Ink.Dom.Selector_1', 'Ink.Util.Array_1', 'Ink.Dom.Loaded_1', 'Ink.UI.SmoothScroller_1', 'Ink.UI.Close_1', 'Ink.UI.Drawer_1'], function( Selector, InkArray, Loaded, Scroller, Close, Drawer ){
    'use strict';

    /**
     * @namespace Ink.Autoload
     * @static
     */

    var el = document.createElement('div');
    // See if a selector is valid.
    function validSelector(sel) {
        try {
            Selector.select(sel, el);
        } catch(e) {
            Ink.error(e);
            return false;
        }
        return true;
    }

    var Autoload = {
        /**
         * Matches module names to default selectors.
         *
         * @property selectors {Object}
         * @public
         **/
        selectors: {
            /* Match module names to element classes (or more complex selectors)
             * which get the UI modules instantiated automatically. */
            // 'Animate_1'     : '.wcv-animate',
            // 'Carousel_1'    : '.wcv-carousel',
            // 'DatePicker_1'  : '.wcv-datepicker',
            // 'DragDrop_1'    : '.wcv-dragdrop',
            // 'Draggable_1'   : '.wcv-draggable',
            // 'Dropdown_1'    : '.wcv-dropdown',
            // 'Droppable_1.add' : '.wcv-droppable',
            'FormValidator_2' : '.wcv-formvalidator',
            // 'Gallery_1'     : 'ul.wcv-gallery-source',
            // 'LazyLoad_1'    : '.wcv-lazyload',
            'Modal_1'       : '.wcv-modal',
            // 'ProgressBar_1' : '.wcv-progress-bar',
            // 'SortableList_1': '.wcv-sortable-list',
            // 'Spy_1'         : '[data-spy="true"]',
            // 'Stacker_1'     : '.wcv-stacker',
            // 'Sticky_1'      : '.wcv-sticky, .sticky',
            'Table_1'       : '.wcv-table',
            'Tabs_1'        : '.wcv-tabs',
            // 'Toggle_1'      : '.wcv-toggle, .toggle',
            'Tooltip_1'     : '.wcv-tooltip, .tooltip',
            // 'TreeView_1'    : '.wcv-tree-view'
        },
        defaultOptions: {},

        /**
         * Run Autoload on a specific element.
         *
         * Useful when you load something from AJAX and want it to have automatically loaded Ink modules.
         * @method run
         * @param {Element} parentEl Root element. The children of this element will be processed by Autoload.
         * @param {Object}  [options] Options object, containing:
         * @param {Boolean} [options.forceAutoload] Autoload things on elements even if they have `data-autoload="false"`
         * @param {Boolean} [options.createClose] Whether to create the Ink.UI.Close component. Defaults to `true`.
         * @param {Boolean} [options.createSmoothScroller] Whether to create the Scroller component. Defaults to `true`.
         * @param {Object} [options.selectors=Ink.Autoload.selectors] A hash mapping module names to selectors that match elements to load these modules. For example, `{ 'Modal_1': '.my-specific-modal' }`.
         * @param {Boolean} [options.waitForDOMLoaded=false] Do nothing until the DOM is loaded. Uses Ink.Dom.Loaded.run();
         * @return {void}
         * @public
         * @sample Autoload_1.html
         **/
        run: function (parentEl, options){
            options = Ink.extendObj({
                // The below lines are not required because undefined is falsy anyway..
                // forceAutoload: false,
                // waitForDOMLoaded: false,
                // createClose: false,
                // createSmoothScroller: false,
                selectors: Autoload.selectors
            }, options || {});

            for(var mod in options.selectors) if (options.selectors.hasOwnProperty(mod)) {
                // `elements` need to be in a closure because requireModules is async.
                findElements(mod);
            }
            if (options.createClose !== false) {
                new Close();
            }
            if (options.createSmoothScroller !== false) {
                Scroller.init();
            }
            if (options.createDrawer !== false) {
                if (Selector.matchesSelector(document.body, '.ink-drawer') &&
                        !(Drawer.getInstance && Drawer.getInstance(document.body))) {
                    new Drawer(document.body);
                }
            }

            function findElements(mod) {
                var fname;
                if (/\./.test(mod)) {  // Droppable.add(elm, options)
                    mod = mod.split('.');
                    fname = mod[1];
                    mod = mod[0];
                }
                var modName = 'Ink.UI.' + mod;
                var elements = Selector.select( options.selectors[mod], parentEl );

                elements = InkArray.filter(elements, autoloadElement);

                if( elements.length ){
                    Ink.requireModules( [modName], function( Component ) {
                        InkArray.forEach(elements, function (el) {
                            if (typeof Component.getInstance === 'function' &&
                                    Component.getInstance(el) != null) {
                                return; // Avoid multiple instantiation.
                            }
                            if (!fname) {
                                new Component(el, Autoload.defaultOptions[mod]);
                            } else {
                                Component[fname](el, Autoload.defaultOptions[mod]);
                            }
                        });
                    });
                }
            }

            function autoloadElement(element) {
                if (options.forceAutoload === true) { return true; }
                if (typeof element.getAttribute === 'function' || typeof element.getAttribute === 'object') {
                    return element.getAttribute('data-autoload') !== 'false';
                }
            }
        },
        /**
         * Add a new entry to be autoloaded.
         * @method add
         * @param {String} moduleName The module name (Example: 'Modal_1', or 'Dropdown_1')
         * @param {String} selector   A selector which finds elements where this module should be autoloaded (Example: '.my-modal' or '.my-dropdown')
         * @return {void}
         * @public
         */
        add: function (moduleName, selector) {
            if (!validSelector(selector)) { return false; }

            if (Autoload.selectors[moduleName]) {
                Autoload.selectors[moduleName] += ', ' + selector;
            } else {
                Autoload.selectors[moduleName] = selector;
            }
        },
        /**
         * Removes a module from autoload, making it not be automatically loaded.
         * @method remove
         * @param {String} moduleName The module's name and version ('Name_ver')
         * @return {void}
         * @public
         **/
        remove: function (moduleName) {
            delete Autoload.selectors[moduleName];
        }
    };

    for (var k in Autoload.selectors) if (Autoload.selectors.hasOwnProperty(k)) {
        Autoload.defaultOptions[k] = {};
    }

    if (!window.INK_NO_AUTO_LOAD) {
        Loaded.run(function () {
            Autoload.run(document, {
                createSmoothScroller: true,
                createClose: true
            });
            Autoload.firstRunDone = true;
        });
    }

    return Autoload;
});


text:
Fabricator(:post) do
  transient :user, :link_url
  user_id { |attrs| attrs[:user] }
  link { |attrs| attrs[:link_url] }
  thumbnail_url nil
  title { "Post test title" }
  body { "Post test body" }
  provider_name { "Post test provider_name" }
end


text:
// Directives
using Microsoft.Devices;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Windows.Storage;
using SimpleCamera.Resources;

namespace SimpleCamera
{

    public partial class MainPage : PhoneApplicationPage
    {
        // Variables
        private int frameCounter = 1;
        PhotoCamera cam;
        MediaLibrary library = new MediaLibrary();
        // Holds current flash mode.
        private string currentFlashMode;
        // Holds the current resolution index.
        int currentResIndex = 0;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        //Code for initialization, capture completed, image availability events; also setting the source for the viewfinder.
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {

            // Check to see if the camera is available on the phone.
            if (PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true)
            {

                // Otherwise, use standard camera on back of phone.
                cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);

                // Event is fired when the PhotoCamera object has been initialized.
                cam.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized);

                // Event is fired when the capture sequence is complete.
                cam.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(cam_CaptureCompleted);

                // Event is fired when the capture sequence is complete and an image is available.
                cam.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(cam_CaptureImageAvailable);

                // Event is fired when the capture sequence is complete and a thumbnail image is available.
                cam.CaptureThumbnailAvailable += new EventHandler<ContentReadyEventArgs>(cam_CaptureThumbnailAvailable);

                //Set the VideoBrush source to the camera.
                viewfinderBrush.SetSource(cam);
            }
            else
            {
                // The camera is not supported on the phone.
                this.Dispatcher.BeginInvoke(delegate()
                {
                    // Write message.
                    txtDebug.Text = "A Camera is not available on this phone.";
                });

                // Disable UI.
                ShutterButton.IsEnabled = false;
                FlashButton.IsEnabled = false;
                FinishButton.IsEnabled = false;
                ResButton.IsEnabled = false;
            }
        }
        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (cam != null)
            {
                // Dispose camera to minimize power consumption and to expedite shutdown.
                cam.Dispose();

                // Release memory, ensure garbage collection.
                cam.Initialized -= cam_Initialized;
                cam.CaptureCompleted -= cam_CaptureCompleted;
                cam.CaptureImageAvailable -= cam_CaptureImageAvailable;
                cam.CaptureThumbnailAvailable -= cam_CaptureThumbnailAvailable;
            }
        }

        // Update the UI if initialization succeeds.
        void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
        {
            if (e.Succeeded)
            {
                this.Dispatcher.BeginInvoke(delegate()
                {
                    // Write message.
                    txtDebug.Text = "Camera initialized.";
                    // Set flash button text.
                    FlashButton.Content = "Fl:" + cam.FlashMode.ToString();
                });
            }
        }

        // Ensure that the viewfinder is upright in LandscapeRight.
        protected override void OnOrientationChanged(OrientationChangedEventArgs e)
        {
            if (cam != null)
            {
                // LandscapeRight rotation when camera is on back of phone.
                int landscapeRightRotation = 180;

                // Change LandscapeRight rotation for front-facing camera.
                if (cam.CameraType == CameraType.FrontFacing) landscapeRightRotation = -180;

                // Rotate video brush from camera.
                if (e.Orientation == PageOrientation.LandscapeRight)
                {
                    // Rotate for LandscapeRight orientation.
                    viewfinderBrush.RelativeTransform =
                        new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = landscapeRightRotation };
                }
                else
                {
                    // Rotate for standard landscape orientation.
                    viewfinderBrush.RelativeTransform =
                        new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 0 };
                }
            }

            base.OnOrientationChanged(e);
        }

        private void changeRes_Clicked(object sender, System.Windows.RoutedEventArgs e)
        {
            // Variables
            IEnumerable<Size> resList = cam.AvailableResolutions;
            int resCount = resList.Count<Size>();
            Size res;

            // Poll for available camera resolutions.
            for (int i = 0; i < resCount; i++)
            {
                res = resList.ElementAt<Size>(i);
            }

            // Set the camera resolution.
            res = resList.ElementAt<Size>((currentResIndex + 1) % resCount);
            cam.Resolution = res;
            currentResIndex = (currentResIndex + 1) % resCount;

            // Update the UI.
            txtDebug.Text = String.Format("Setting capture resolution: {0}x{1}", res.Width, res.Height);
            ResButton.Content = "R" + res.Width;
        }

        private void finishCapture_Clicked(object sender, System.Windows.RoutedEventArgs e)
        {

        }

        private void ShutterButton_Click(object sender, RoutedEventArgs e)
        {
            if (cam != null)
            {
                try
                {
                    // Start image capture.
                    cam.CaptureImage();
                }
                catch (Exception ex)
                {
                    this.Dispatcher.BeginInvoke(delegate()
                    {
                        // Cannot capture an image until the previous capture has completed.
                        txtDebug.Text = ex.Message;
                    });
                }
            }
        }

        void cam_CaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
        {
            // Increments the savedCounter variable used for generating JPEG file names.
            //frameCounter++;
        }

        // Informs when full resolution photo has been taken, saves to local media library and the local folder.
        void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
        {
            //  once the image has been captured
            //  save it
            DateTime t = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local);
            string fileName = frameCounter + "-" + t.Hour + "-" + t.Minute + "-" + t.Second + "-" + t.Millisecond + ".jpg";
            frameCounter++;
            try
            {   // Write message to the UI thread.
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    txtDebug.Text = "Captured image available, saving photo.";
                });

                // Save photo to the media library camera roll.
                library.SavePictureToCameraRoll(fileName, e.ImageStream);

                // Write message to the UI thread.
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    txtDebug.Text = "Photo has been saved to camera roll.";

                });

                // Set the position of the stream back to start
                e.ImageStream.Seek(0, SeekOrigin.Begin);

                // Save photo as JPEG to the local folder.
                using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
                    {
                        // Initialize the buffer for 4KB disk pages.
                        byte[] readBuffer = new byte[4096];
                        int bytesRead = -1;

                        // Copy the image to the local folder.
                        while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                        {
                            targetStream.Write(readBuffer, 0, bytesRead);
                        }
                    }
                }

                // Write message to the UI thread.
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    txtDebug.Text = "Photo has been saved to the local folder.";

                });
            }
            finally
            {
                // Close image stream
                e.ImageStream.Close();
            }

        }

        // Informs when thumbnail photo has been taken, saves to the local folder
        // User will select this image in the Photos Hub to bring up the full-resolution.
        public void cam_CaptureThumbnailAvailable(object sender, ContentReadyEventArgs e)
        {
            string fileName = frameCounter + "_th.jpg";

            try
            {
                // Write message to UI thread.
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    txtDebug.Text = "Captured image available, saving thumbnail.";
                });

                // Save thumbnail as JPEG to the local folder.
                using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
                    {
                        // Initialize the buffer for 4KB disk pages.
                        byte[] readBuffer = new byte[4096];
                        int bytesRead = -1;

                        // Copy the thumbnail to the local folder.
                        while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                        {
                            targetStream.Write(readBuffer, 0, bytesRead);
                        }
                    }
                }

                // Write message to UI thread.
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    txtDebug.Text = "Thumbnail has been saved to the local folder.";

                });
            }
            finally
            {
                // Close image stream
                e.ImageStream.Close();
            }
        }

        // Activate a flash mode.
        // Cycle through flash mode options when the flash button is pressed.
        private void changeFlash_Clicked(object sender, RoutedEventArgs e)
        {

            switch (cam.FlashMode)
            {
                case FlashMode.Off:
                    if (cam.IsFlashModeSupported(FlashMode.On))
                    {
                        // Specify that flash should be used.
                        cam.FlashMode = FlashMode.On;
                        FlashButton.Content = "Fl:On";
                        currentFlashMode = "Flash mode: On";
                    }
                    break;
                case FlashMode.On:
                    if (cam.IsFlashModeSupported(FlashMode.RedEyeReduction))
                    {
                        // Specify that the red-eye reduction flash should be used.
                        cam.FlashMode = FlashMode.RedEyeReduction;
                        FlashButton.Content = "Fl:RER";
                        currentFlashMode = "Flash mode: RedEyeReduction";
                    }
                    else if (cam.IsFlashModeSupported(FlashMode.Auto))
                    {
                        // If red-eye reduction is not supported, specify automatic mode.
                        cam.FlashMode = FlashMode.Auto;
                        FlashButton.Content = "Fl:Auto";
                        currentFlashMode = "Flash mode: Auto";
                    }
                    else
                    {
                        // If automatic is not supported, specify that no flash should be used.
                        cam.FlashMode = FlashMode.Off;
                        FlashButton.Content = "Fl:Off";
                        currentFlashMode = "Flash mode: Off";
                    }
                    break;
                case FlashMode.RedEyeReduction:
                    if (cam.IsFlashModeSupported(FlashMode.Auto))
                    {
                        // Specify that the flash should be used in the automatic mode.
                        cam.FlashMode = FlashMode.Auto;
                        FlashButton.Content = "Fl:Auto";
                        currentFlashMode = "Flash mode: Auto";
                    }
                    else
                    {
                        // If automatic is not supported, specify that no flash should be used.
                        cam.FlashMode = FlashMode.Off;
                        FlashButton.Content = "Fl:Off";
                        currentFlashMode = "Flash mode: Off";
                    }
                    break;
                case FlashMode.Auto:
                    if (cam.IsFlashModeSupported(FlashMode.Off))
                    {
                        // Specify that no flash should be used.
                        cam.FlashMode = FlashMode.Off;
                        FlashButton.Content = "Fl:Off";
                        currentFlashMode = "Flash mode: Off";
                    }
                    break;
            }

            // Display current flash mode.
            this.Dispatcher.BeginInvoke(delegate()
            {
                txtDebug.Text = currentFlashMode;
            });
        }
    }
}


text:
import pause from './pause';

export default async (fixture, delay, name, value, customDelay?) => {
  return new Promise(async resolve => {
    (async function controlGetter() {
      let component = fixture.componentInstance;
      let form = component['form'];
      let {controls} = form;
      let control = controls[name];

      if(!control) {
        await pause(delay);
        controlGetter();
      } else {
        control.setValue(value);
        control.markAsDirty();
        control.updateValueAndValidity();
        fixture.detectChanges();
        await pause(delay || customDelay);
        resolve(control);
      }
    })();
  });
};


text:
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/crypto_module_password_dialog.h"

#include <pk11pub.h>

#include "base/bind.h"
#include "base/logging.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/crypto_module.h"
#include "net/base/x509_certificate.h"

#if defined(OS_CHROMEOS)
#include "crypto/nss_util.h"
#endif

using content::BrowserThread;

namespace {

bool ShouldShowDialog(const net::CryptoModule* module) {
  // The wincx arg is unused since we don't call PK11_SetIsLoggedInFunc.
  return (PK11_NeedLogin(module->os_module_handle()) &&
          !PK11_IsLoggedIn(module->os_module_handle(), NULL /* wincx */));
}

// Basically an asynchronous implementation of NSS's PK11_DoPassword.
// Note: This currently handles only the simple case.  See the TODOs in
// GotPassword for what is yet unimplemented.
class SlotUnlocker {
 public:
  SlotUnlocker(const net::CryptoModuleList& modules,
               chrome::CryptoModulePasswordReason reason,
               const std::string& host,
               const base::Closure& callback);

  void Start();

 private:
  void GotPassword(const char* password);
  void Done();

  size_t current_;
  net::CryptoModuleList modules_;
  chrome::CryptoModulePasswordReason reason_;
  std::string host_;
  base::Closure callback_;
  PRBool retry_;
};

SlotUnlocker::SlotUnlocker(const net::CryptoModuleList& modules,
                           chrome::CryptoModulePasswordReason reason,
                           const std::string& host,
                           const base::Closure& callback)
    : current_(0),
      modules_(modules),
      reason_(reason),
      host_(host),
      callback_(callback),
      retry_(PR_FALSE) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

void SlotUnlocker::Start() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  for (; current_ < modules_.size(); ++current_) {
    if (ShouldShowDialog(modules_[current_].get())) {
#if defined(OS_CHROMEOS)
      if (crypto::IsTPMTokenReady()) {
        std::string token_name;
        std::string user_pin;
        crypto::GetTPMTokenInfo(&token_name, &user_pin);
        if (modules_[current_]->GetTokenName() == token_name) {
          // The user PIN is a well known secret on this machine, and
          // the user didn't set it, so we need to fetch the value and
          // supply it for them here.
          GotPassword(user_pin.c_str());
          return;
        }
      }
#endif
      ShowCryptoModulePasswordDialog(
          modules_[current_]->GetTokenName(),
          retry_,
          reason_,
          host_,
          base::Bind(&SlotUnlocker::GotPassword, base::Unretained(this)));
      return;
    }
  }
  Done();
}

void SlotUnlocker::GotPassword(const char* password) {
  // TODO(mattm): PK11_DoPassword has something about PK11_Global.verifyPass.
  // Do we need it?
  // http://mxr.mozilla.org/mozilla/source/security/nss/lib/pk11wrap/pk11auth.c#577

  if (!password) {
    // User cancelled entering password.  Oh well.
    ++current_;
    Start();
    return;
  }

  // TODO(mattm): handle protectedAuthPath
  SECStatus rv = PK11_CheckUserPassword(modules_[current_]->os_module_handle(),
                                        password);
  if (rv == SECWouldBlock) {
    // Incorrect password.  Try again.
    retry_ = PR_TRUE;
    Start();
    return;
  }

  // TODO(mattm): PK11_DoPassword calls nssTrustDomain_UpdateCachedTokenCerts on
  // non-friendly slots.  How important is that?

  // Correct password (SECSuccess) or too many attempts/other failure
  // (SECFailure).  Either way we're done with this slot.
  ++current_;
  Start();
}

void SlotUnlocker::Done() {
  DCHECK_EQ(current_, modules_.size());
  callback_.Run();
  delete this;
}

}  // namespace

namespace chrome {

void UnlockSlotsIfNecessary(const net::CryptoModuleList& modules,
                            chrome::CryptoModulePasswordReason reason,
                            const std::string& host,
                            const base::Closure& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  for (size_t i = 0; i < modules.size(); ++i) {
    if (ShouldShowDialog(modules[i].get())) {
      (new SlotUnlocker(modules, reason, host, callback))->Start();
      return;
    }
  }
  callback.Run();
}

void UnlockCertSlotIfNecessary(net::X509Certificate* cert,
                               chrome::CryptoModulePasswordReason reason,
                               const std::string& host,
                               const base::Closure& callback) {
  net::CryptoModuleList modules;
  modules.push_back(net::CryptoModule::CreateFromHandle(
      cert->os_cert_handle()->slot));
  UnlockSlotsIfNecessary(modules, reason, host, callback);
}

}  // namespace chrome


text:
using System;

namespace StringlyTyped
{
    internal static class ExceptionFactory
    {
        internal static ArgumentOutOfRangeException IncorrectStringFormat<T>(string value, Exception innerException = null)
        {
            return new ArgumentOutOfRangeException(
                $"Unable to create type '{typeof(T).Name}' from value '{value}'.", innerException);
        }
    }
}


text:
<?php

namespace Database\Seeders;

use App\Models\CommentBlock;
use App\Models\Comment;
use Illuminate\Database\Seeder;

class CommentBlocksTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //CommentBlock::create();
        //Comment::create(['comment_block_id' => 1, 'text' => 'test', 'user_id' => 1]);
    }
}


text:
using namespace llvm;
using namespace llvm::pdb;

extern const char *TestMainArgv0;

static std::string getExePath() {
  SmallString<128> InputsDir = unittest::getInputFileDirectory(TestMainArgv0);
  llvm::sys::path::append(InputsDir, "SimpleTest.exe");
  return std::string(InputsDir);
}

TEST(NativeSessionTest, TestCreateFromExe) {
  std::unique_ptr<IPDBSession> S;
  // Tests that the PDB file can be found if it is in the same directory as the
  // executable.
  Error E = pdb::loadDataForEXE(PDB_ReaderType::Native, getExePath(), S);
  ASSERT_THAT_ERROR(std::move(E), Succeeded());
}

TEST(NativeSessionTest, TestSetLoadAddress) {
  std::unique_ptr<IPDBSession> S;
  Error E = pdb::loadDataForEXE(PDB_ReaderType::Native, getExePath(), S);
  ASSERT_THAT_ERROR(std::move(E), Succeeded());

  S->setLoadAddress(123);
  EXPECT_EQ(S->getLoadAddress(), 123U);
}

TEST(NativeSessionTest, TestAddressForVA) {
  std::unique_ptr<IPDBSession> S;
  Error E = pdb::loadDataForEXE(PDB_ReaderType::Native, getExePath(), S);
  ASSERT_THAT_ERROR(std::move(E), Succeeded());

  uint64_t LoadAddr = S->getLoadAddress();
  uint32_t Section;
  uint32_t Offset;
  ASSERT_TRUE(S->addressForVA(LoadAddr + 5000, Section, Offset));
  EXPECT_EQ(1U, Section);
  EXPECT_EQ(904U, Offset);

  ASSERT_TRUE(S->addressForVA(-1, Section, Offset));
  EXPECT_EQ(0U, Section);
  EXPECT_EQ(0U, Offset);

  ASSERT_TRUE(S->addressForVA(4, Section, Offset));
  EXPECT_EQ(0U, Section);
  EXPECT_EQ(4U, Offset);

  ASSERT_TRUE(S->addressForVA(LoadAddr + 100000, Section, Offset));
  EXPECT_EQ(3U, Section);
  EXPECT_EQ(83616U, Offset);
}

TEST(NativeSessionTest, TestAddressForRVA) {
  std::unique_ptr<IPDBSession> S;
  Error E = pdb::loadDataForEXE(PDB_ReaderType::Native, getExePath(), S);
  ASSERT_THAT_ERROR(std::move(E), Succeeded());

  uint32_t Section;
  uint32_t Offset;
  ASSERT_TRUE(S->addressForVA(5000, Section, Offset));
  EXPECT_EQ(1U, Section);
  EXPECT_EQ(904U, Offset);

  ASSERT_TRUE(S->addressForVA(-1, Section, Offset));
  EXPECT_EQ(0U, Section);
  EXPECT_EQ(0U, Offset);

  ASSERT_TRUE(S->addressForVA(4, Section, Offset));
  EXPECT_EQ(0U, Section);
  EXPECT_EQ(4U, Offset);

  ASSERT_TRUE(S->addressForVA(100000, Section, Offset));
  EXPECT_EQ(3U, Section);
  EXPECT_EQ(83616U, Offset);
}


text:
// ***********************************************************************
// <copyright file="ICacheHelper.cs" company="Verisk">
//     Copyright © Verisk, All Rights Reserved.
// </copyright>
// <summary>ICacheHelper class</summary>
// ***********************************************************************
namespace TSW.B2B.Common.Interfaces
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// ICacheHelper Interface
    /// </summary>
    public interface ICacheHelper
    {
        /// <summary>
        /// Remove item from cache
        /// </summary>
        /// <param name="key">Name of cached item</param>
        void Clear(string key);

        /// <summary>
        /// clear all cache objects.
        /// </summary>
        void ClearAll();

        /// <summary>
        /// Clear cache items matching where.
        /// </summary>
        /// <param name="predicate">The predicate.</param>
        void ClearWhere(Func<KeyValuePair<string, object>, bool> predicate);

        /// <summary>
        /// Check for item in cache
        /// </summary>
        /// <param name="key">Name of cached item</param>
        /// <returns>return boolean whether or not if the value exists</returns>
        bool Exists(string key);

        /// <summary>
        /// Gets the specified key.
        /// </summary>
        /// <typeparam name="T">Type of key</typeparam>
        /// <param name="key">The key.</param>
        /// <returns>Returns value for given key.</returns>
        T Get<T>(string key);

        /// <summary>
        /// The invalidate.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        void Invalidate(string key);

        /// <summary>
        /// The set.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <param name="data">
        /// The data.
        /// </param>
        void Set(string key, object data);

        /// <summary>
        /// The set.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="cacheTime">
        /// The cache time.
        /// </param>
        void Set(string key, object data, int cacheTime);
    }
}


text:
package network::beeware::snmp::plugin;

use strict;
use warnings;
use base qw(centreon::plugins::script_snmp);

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $self->{version} = '1.0';
    %{$self->{modes}} = (
        'list-reverse-proxy'   => 'network::beeware::snmp::mode::listreverseproxy',
        'reverse-proxy-usage'  => 'network::beeware::snmp::mode::reverseproxyusage',
    );

    return $self;
}

1;

__END__

=head1 PLUGIN DESCRIPTION

Check Beeware equipments in SNMP.
Please use plugin SNMP Linux for system checks ('cpu', 'memory', 'traffic',...).

=cut


text:
'use strict';

var _ = require('lodash');

module.exports = function navigationMapper_DOCS(aliasMap, log) {

  var debug = log.debug;

  function docsMapper (pages, key) {
    var res = {
      name: 'Docs',
      type: 'groups',
      href: key,
      navItems: []
    };

    _(pages)
      .sortBy(docsMapper.sortBy)
      .forEach(function (page) {
        res.navItems.push({
          name: page.name,
          type: '',
          href: page.path,
         title: page.title
        });
    });

    return [res];
  };

  Object.defineProperty(docsMapper, 'area', {
    value: 'docs'
  });

  Object.defineProperty(docsMapper, 'title', {
    value: 'Docs'
  });

  Object.defineProperty(docsMapper, 'sortBy', {
    value: [
      'sortOrder',
      'title'
    ]});

  return docsMapper;
};


text:
rosservice call /add_target '[1, 0, 0]'
# add green toy target
rosservice call /add_target '[2, 1, 0]'

# give time for the plans to be created
sleep 2

# turn the executor on
rosservice call /set_executor_state 1


text:
extern "C" {
#endif

extern int ganglia_quiet_errors;

void debug_msg(const char *format, ...) CHECK_FMT(1,2);
void set_debug_msg_level(int level);
int get_debug_msg_level();

void err_quiet( void );
void err_ret (const char *fmt, ...) CHECK_FMT(1,2);
void err_sys (const char *fmt, ...) CHECK_FMT(1,2);
void err_dump (const char *fmt, ...) CHECK_FMT(1,2);
void err_msg (const char *fmt, ...) CHECK_FMT(1,2);
void err_quit (const char *fmt, ...) CHECK_FMT(1,2);

#ifdef __cplusplus
}
#endif

#endif


text:
class AddUserAssociations < ActiveRecord::Migration
  def change
  	add_column :steps, :user_id, :integer
  end
end


text:
from ceilometer.openstack.common import log
from ceilometer.openstack.common import timeutils

from ceilometer.central import plugin
from ceilometer import counter
from ceilometer import nova_client

class FloatingIPPollster(plugin.CentralPollster):

    LOG = log.getLogger(__name__ + '.floatingip')

    @staticmethod
    def get_counter_names():
        return ['ip.floating']

    def get_counters(self, manager):
        nv = nova_client.Client()
        for ip in nv.floating_ip_get_all():
            self.LOG.info("FLOATING IP USAGE: %s" % ip.address)
            yield counter.Counter(
                name='ip.floating',
                type=counter.TYPE_GAUGE,
                unit='ip',
                volume=1,
                user_id=None,
                project_id=ip.project_id,
                resource_id=ip.id,
                timestamp=timeutils.utcnow().isoformat(),
                resource_metadata={
                    'address': ip.address,
                    'fixed_ip_id': ip.fixed_ip_id,
                    'host': ip.host,
                    'pool': ip.pool,
                    'auto_assigned': ip.auto_assigned
                })


text:
from glob import glob
from keyword import iskeyword
from os.path import dirname, join, split, splitext

# Got this __init__ from: https://github.com/samwyse/sspp

basedir = dirname(__file__)

__all__ = []
for name in glob(join(basedir, '*.py')):
    module = splitext(split(name)[-1])[0]
    if not module.startswith('_') and not iskeyword(module):
        try:
            __import__(__name__+'.'+module)
        except:
            print __name__+'.'+module
            import logging
            logger = logging.getLogger(__name__)
            logger.warning('Ignoring exception while loading the %r plug-in.', module)
        else:
            __all__.append(module)
__all__.sort()


text:
#ifndef __tubeMetaDocument_h
#define __tubeMetaDocument_h

#include "tubeObject.h"

#include <metaUtils.h>

#include <fstream>

namespace tube
{

/**
 * Encodes a meta document file name and its information.
 *
 * \ingroup  ObjectDocuments
 */
class MetaDocument : public Object
{
public:

  typedef MetaDocument                Self;
  typedef Object                      Superclass;
  typedef Self *                      Pointer;
  typedef const Self *                ConstPointer;

  typedef MET_FieldRecordType         FieldType;
  typedef std::vector< FieldType * >  FieldListType;

  /** Constructor. */
  MetaDocument( void );

  /**  Destructor. */
  virtual ~MetaDocument( void );

  /** Return the name of this class. */
  tubeTypeMacro( MetaDocument );

  /** Return the comment. */
  tubeGetStringMacro( Comment );

  /** Return the date modified. */
  tubeGetStringMacro( DateModified );

  /** Return the file name. */
  tubeGetStringMacro( FileName );

  /** Return the name. */
  tubeGetStringMacro( Name );

  /** Set the comment. */
  tubeSetStringMacro( Comment );

  /** Set the date modified. */
  tubeSetStringMacro( DateModified );

  /** Set the file name. */
  tubeSetStringMacro( FileName );

  /** Set the name. */
  tubeSetStringMacro( Name );

  /** Clear all the information. */
  virtual void Clear( void );

  /** Copy information from the specified meta document. */
  virtual void CopyInformation( const Self * self );

  /** Read the information from the specified file. */
  virtual bool Read( const std::string & fileName = "" );

  /** Write the information to the specified file. */
  virtual bool Write( const std::string & fileName = "" );

protected:

  /** Clear all the fields. */
  void ClearFields( void );

  /** Read the fields. */
  virtual bool ReadFields( void );

  /** Initialize the read fields. */
  virtual void SetupReadFields( void );

  /** Initialize the write fields. */
  virtual void SetupWriteFields( void );

  /** Write the fields. */
  virtual bool WriteFields( void );

  /** Print information about this object. */
  virtual void PrintSelf( std::ostream & os, Indent indent ) const override;

  std::ifstream  m_ReadStream;
  std::ofstream  m_WriteStream;
  FieldListType  m_FieldList;

private:

  // Copy constructor not implemented.
  MetaDocument( const Self & self );

  // Copy assignment operator not implemented.
  void operator=( const Self & self );

  std::string  m_Comment;
  std::string  m_DateModified;
  std::string  m_FileName;
  std::string  m_Name;

}; // End class MetaDocument

} // End namespace tube

#endif // End !defined( __tubeMetaDocument_h )


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Box2DJS in 3D</title>

Box2DJS in 3D

Based on box2d-js.

Left Click to create a new object.

Right Click (shift-click on OSX) to switch to the next demo.

<textarea id="shader">
uniform float4x4 worldViewProj : WorldViewProjection;
uniform float3 lightWorldPos;
uniform float4 lightColor;
uniform float4x4 world : World;
uniform float4x4 view : View;
uniform float4x4 worldIT : WorldInverseTranspose;
uniform float4 emissive;
uniform float4 ambient;
uniform float4 colorMult;
sampler2D diffuseSampler;
uniform float4 specular;
uniform float shininess;

struct InVertex {
  float4 position : POSITION;
  float4 normal : NORMAL;
  float2 diffuseUV : TEXCOORD0;
};

struct OutVertex {
  float4 position : POSITION;
  float2 diffuseUV : TEXCOORD0;
  float3 n : TEXCOORD1;
  float3 l : TEXCOORD2;
  float3 v : TEXCOORD3;
};

OutVertex vs(InVertex IN) {
  OutVertex OUT;
  OUT.position = mul(IN.position, worldViewProj);
  OUT.diffuseUV = IN.diffuseUV;
  OUT.n = mul(IN.normal, worldIT).xyz;
  OUT.l = lightWorldPos - mul(IN.position, world).xyz;
  OUT.v = (view[3] - mul(IN.position, world)).xyz;
  return OUT;
}

float4 ps(OutVertex IN) : COLOR {
  float4 diffuse = tex2D(diffuseSampler, IN.diffuseUV) * colorMult;
  float3 l = normalize(IN.l); float3 n = normalize(IN.n);
  float3 r = normalize(reflect(n, l));
  float3 v = normalize(IN.v);
  float4 litR = lit(dot(n, l), dot(r, v), shininess);
  return float4((emissive + lightColor *
                 (ambient + diffuse * litR.y + specular * litR.z)).rgb,
                diffuse.a);
}

// #o3d VertexShaderEntryPoint vs
// #o3d PixelShaderEntryPoint ps
// #o3d MatrixLoadOrder RowMajor
</textarea>


text:
package co.gi9.ilsaul.games.pa.multiCompare;
import org.apache.commons.lang.mutable.MutableInt;

public class Row {
	private String line;

	private String key;
	private String value;
	private int startValue;
	private int endValue;

	public Row(String line) {
		this.line = line;

		if (!isComment()) {
			MutableInt pos = new MutableInt(0);
			key = getWord(line, pos);
			value = getAllFromPos(line, pos);
		} else {
			key = null;
			value = null;
		}
	}

	public String getLine() {
		return line;
	}

	public boolean isComment() {
		String s = line.trim();
		return (s.startsWith("#") || s.isEmpty() || s.length() < 3);
	}

	public String getKey() {
		return key;
	}

	public String getValue() {
		return value;
	}

	private static String getWord(String line, MutableInt pos) {
		String word = "";
		boolean marker = false;
		boolean start = false;
		char ch;

		word = "";
		if (line.length() > 0) {
			do {
				ch = line.charAt(pos.intValue());
				start |=  ((ch != ' ') || (ch != '\t'));
				if (ch == '"') marker = !marker;

				if ((marker && start) || (start && (ch != ' ' && ch != '\t'))) {
					word += ch;
				}

				pos.increment();
			} while ((pos.intValue() < line.length()) && (marker || !start || (ch != ' ' && ch != '\t')));
		}

		if (word.length() == 0) word = null;
		return word;
	}

	private String getAllFromPos(String line, MutableInt pos) {
		String word = "";
		boolean start = false;
		char ch;

		word = "";
		if (line.length() > 0) {
			do {
				ch = line.charAt(pos.intValue());
				start |=  ((ch != ' ') && (ch != '\t'));

				if (start || (ch != ' ' && ch != '\t')) {
					if (startValue == 0) startValue = pos.intValue();
					word += ch;
				}

				pos.increment();
			} while (pos.intValue() < line.length());

			endValue = pos.intValue();
		}

		if (word.length() == 0) word = null;
		return word;
	}

	public String getLineWithNewValue(String value) {
		if (value == null || value.isEmpty()) return line;

		String s = line.substring(0, startValue) + value + line.substring(endValue, line.length());

		return s;
	}

	@Override
	public String toString() {
		return "Row [line=" + line + ", key=" + key + ", value=" + value + ", startValue=" + startValue + ", endValue="
				+ endValue + "]";
	}
}


text:
package com.shamilov.dualseekbarlibrary.instrumentation;

import android.graphics.Point;
import android.util.SparseArray;
import android.view.MotionEvent;

import com.shamilov.dualseekbarlibrary.model.DraggingObjectHolder;

public class IntersectionResolver {

    public boolean intersect(DraggingObjectHolder draggingObject, SparseArray<DraggingObjectHolder> actingObjects, MotionEvent event, @MotionDirection.Direction int direction) {
        boolean intersect;
        for (int i = 0; i < actingObjects.size(); i++) {
            intersect = draggingObject != actingObjects.valueAt(i) && samePointCoordinates(event, actingObjects.valueAt(i).getObjectCenter(), direction);
            if (intersect) {
                return true;
            }
        }
        return false;
    }

    public static boolean samePointCoordinates(Point first, Point second) {
        return first.x == second.x && first.y == second.y;
    }

    public static boolean samePointCoordinates(MotionEvent event, Point second, @MotionDirection.Direction int direction) {
        if (direction == MotionDirection.LEFT_TO_RIGHT) {
            return event.getX() > second.x;
        } else if (direction == MotionDirection.RIGHT_TO_LEFT) {
            return event.getX() < second.x;
        } else {
            throw new IllegalArgumentException("Unsupported direction");
        }
    }
}


text:
'use strict';

const stylelint = require('stylelint');
const _ = require('lodash');
const postcssSorting = require('postcss-sorting');
const utils = require('../../utils');
const checkNode = require('./checkNode');
const createExpectedOrder = require('./createExpectedOrder');
const createFlatOrder = require('./createFlatOrder');
const validatePrimaryOption = require('./validatePrimaryOption');

const ruleName = utils.namespace('properties-order');

const messages = stylelint.utils.ruleMessages(ruleName, {
	expected: (first, second) => `Expected "${first}" to come before "${second}"`,
	expectedEmptyLineBefore: (property) => `Expected an empty line before property "${property}"`,
	rejectedEmptyLineBefore: (property) => `Unexpected an empty line before property "${property}"`,
});

const rule = function (expectation, options, context) {
	context = context || {};

	return function (root, result) {
		const validOptions = stylelint.utils.validateOptions(
			result,
			ruleName,
			{
				actual: expectation,
				possible: validatePrimaryOption,
			},
			{
				actual: options,
				possible: {
					unspecified: [
						'top',
						'bottom',
						'ignore',
						'bottomAlphabetical',
					],
					disableFix: _.isBoolean,
				},
				optional: true,
			}
		);

		if (!validOptions) {
			return;
		}

		// By default, ignore unspecified properties
		let unspecified = _.get(options, ['unspecified'], 'ignore');

		const disableFix = _.get(options, ['disableFix'], false);

		if (context.fix && !disableFix) {
			if (unspecified === 'ignore') {
				unspecified = 'bottom';
			}

			const sortingOptions = {
				'properties-order': createFlatOrder(expectation),
				'unspecified-properties-position': unspecified,
			};

			postcssSorting(sortingOptions)(root);
		}

		const expectedOrder = createExpectedOrder(expectation);

		const sharedInfo = {
			expectedOrder,
			expectation,
			unspecified,
			messages,
			ruleName,
			result,
			context,
			disableFix,
		};

		// Check all rules and at-rules recursively
		root.walk(function processRulesAndAtrules(node) {
			if (node.type === 'rule' || node.type === 'atrule') {
				checkNode(node, sharedInfo);
			}
		});
	};
};

rule.primaryOptionArray = true;

rule.ruleName = ruleName;
rule.messages = messages;
module.exports = rule;


text:
<?php
namespace FzyAuth\Exception;

class Acl extends Base
{
}


text:
/*
 * .reel - Image Turntable Plugin
 *
 * Transforms an image tag to act as an projector
 *
 */
/*! Copyright (c) 2009-2010 Petr Vostrel (http://www.pisi.cz/)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://www.vostrel.cz/jquery/reel/
 * Version: 1.0.3
 * Updated: 2010-03-29
 *
 * Requires jQuery 1.3.x or higher
 */
/*
 * Optional nice-to-haves:
 * - jQuery.disableTextSelect (James Dempster, http://www.jdempster.com/category/jquery/disabletextselect/)
 * - jQuery.mouseWheel (Brandon Aaron, http://brandonaaron.net/)
 */

(function($){
  $.fn.reel= function(options){
    var
      defaults= {
        footage:            6, // number of frames per line/column
        frame:              1, // initial frame
        frames:            36, // total number of frames; every 10° for full rotation
        horizontal:      true, // roll flow; defaults to horizontal
        hotspot:    undefined, // custom jQuery as a hotspot
        hint:              '', // hotspot hint tooltip
        indicator:          0, // size of a visual indicator of reeling (in pixels)
        klass:             '', // plugin instance class name
        loops:           true, // is it a loop?
        reversed:       false, // true for "counter-clockwise sprite"
        saves:          false, // wheather allow user to save the image thumbnail
        sensitivity:       20, // interaction sensitivity
        spacing:            0, // space between frames on reel
        stitched:   undefined, // pixel width (length) of a stitched panoramic reel
        suffix:       '-reel',
        tooltip:           ''  // alias of `hint`
      },
      applicable= (function(tags){
        // Only IMG tags with non-empty SRC and non-zero WIDTH and HEIGHT will pass
        var
          pass= []
        tags.filter('img').each(function(ix){
          var
            $this= $(this),
            src= $this.attr('src'),
            width= number($this.css('width')),
            height= number($this.css('height'))
          if (!src || src=='' || !width || !height ) return;
          pass.push($this);
        });
        return $(pass);
      })(this);
    return applicable.each(function(){
      var
        t= $(this),
        set= $.extend(defaults, options),
        pool= $(document),
        store= function(name, value){
          t.data(name, value);
          t.trigger('store');
          return value;
        },
        recall= function(name){
          var
            value= t.data(name)
          t.trigger('recall')
          return value;
        },
        on= {
          init: function(){
            var
              classes= t.attr('class'),
              src= t.attr('src'),
              image= src.replace(/^(.*)\.(jpg|jpeg|png|gif)$/, '$1' + set.suffix + '.$2'),
              size= { x: number(t.css('width')), y: number(t.css('height')) },
              turntable= $('<div>').attr('class',classes).addClass('jquery-reel').addClass(set.klass),
              external_methods= ['mousewheel', 'disableTextSelect'],
              image_css= set.saves ? { opacity: 0 } : { display: 'none' }
            t= t.wrap(turntable).css(image_css)
            .parent().css({
              width: size.x + 'px',
              height: size.y + 'px',
              backgroundImage: 'url(' + image + ')'
            });
            for (var ev in on) t.bind(ev, on[ev]);
            $.each(external_methods, function(ix,method){
              // Stub wanted methods from missing plugins
              if (!$.fn[method]) $.fn[method]= function(){ return this; };
            });
            t.trigger('setup');
          },
          setup: function(e){
            var
              size= { x: number(t.css('width')), y: number(t.css('height')) }
            store('frames', set.frames);
            store('spacing', set.spacing);
            store('offset', t.offset());
            store('dimensions', size);
            t.trigger('start');
          },
          start: function(e){
            var
              hotspot= set.hotspot ? set.hotspot : t,
              space= recall('dimensions')
            hotspot
              .css({ cursor: 'ew-resize' })
              .mouseenter(function(e){ t.trigger('enter'); })
              .mouseleave(function(e){ t.trigger('leave'); })
              .mousemove(function(e){ t.trigger('over', [e.clientX, e.clientY]); })
              .mousewheel(function(e, delta){ t.trigger('wheel', [delta]); return false; })
              .dblclick(function(e){ t.trigger('animate'); })
              .mousedown(function(e){ t.trigger('down', [e.clientX, e.clientY]); })
              .disableTextSelect();
            if (set.hint || set.tooltip) hotspot.attr('title', set.hint || set.tooltip);
            if (set.indicator) t.append($('<div>')
              .addClass('indicator')
              .css({
                width: set.indicator + 'px',
                height: set.indicator + 'px',
                top: (space.y - set.indicator) + 'px',
                position: 'relative',
                backgroundColor: '#000'
              }));
            t.trigger('frameChange', set.frame);
          },
          animate: function(e){
            // Stub for future compatibility
            // log(e.type);
          },
          down: function(e, x, y){
            var
              clicked= store('clicked',true),
              location= store('clicked_location', x),
              frame= store('last_frame', store('clicked_on_frame', recall('frame')))
            pool
            .mousemove(function(e){ t.trigger('drag', [e.clientX, e.clientY]); })
            .mouseup(function(e){ t.trigger('up'); });
          },
          up: function(e){
            var
              clicked= store('clicked',false)
            pool.unbind('mousemove mouseup');
          },
          drag: function(e, x, y){
            var
              origin= recall('clicked_location'),
              frame= recall('clicked_on_frame'),
              frames= recall('frames'),
              distance= Math.round((origin - x) / set.sensitivity),
              reverse= set.reversed ? -1 : 1,
              frame= store('frame', frame - reverse * distance)
            t.trigger('frameChange');
          },
          frameChange: function(e, frame){
            var
              frame= !frame ? recall('frame') : store('frame', frame),
              last_frame= recall('last_frame'),
              frames= recall('frames'),
              space= recall('dimensions'),
              spacing= recall('spacing'),
              // Take care of the looping
              frame= !set.loops && frame > frames ? frames : frame,
              frame= !set.loops && frame < 1 ? 1 : frame,
              frame= frame - Math.floor(frame / frames) * frames,
              frame= store('last_frame', store('frame', frame < 1 ? frames : frame)),
              // Find out if the movement is reversed
              delta= frame - last_frame,
              delta= Math.abs(delta) > 10 ? 0 - delta : delta,
              reversed= store('reversed', delta != 0 ? (delta > 0) : recall('reversed'))
            if (!set.stitched){
              var
                major= Math.floor(frame / set.footage),
                minor= frame - major * set.footage - 1,
                major= minor == -1 ? major + minor : major,
                minor= minor == -1 ? set.footage + minor : minor,
                // Count new positions
                major_size= set.horizontal ? space.y : space.x,
                minor_size= set.horizontal ? space.x : space.y,
                x= - major * (spacing + major_size),
                y= - minor * (spacing + minor_size),
                rows= Math.ceil(frames / set.footage),
                // Count additional shift when rolling reverse direction
                reverse_shift= rows * major_size + (rows - 1) * spacing,
                x= reversed && set.horizontal ? x - reverse_shift : x,
                y= reversed && !set.horizontal ? y - reverse_shift : y,
                shift= set.horizontal ? y + 'px ' + x + 'px' : x + 'px ' + y + 'px'
            }else{
              var
                step= set.stitched / frames,
                x= frame * step,
                y= 0,
                shift= x + 'px 0' + y + 'px'
            }
            var
              indicator= ((space.x - set.indicator) / (frames - 1) * (frame - 1)) + 'px'
            t.css({ backgroundPosition: shift })
              .find('.indicator').css({ left: indicator });
          },
          wheel: function(e, distance){
            var
              frame= recall('frame'),
              frames= recall('frames'),
              delta= Math.ceil(Math.sqrt(Math.abs(distance))),
              delta= distance < 0 ? - delta : delta,
              reverse= set.reversed ? -1 : 1,
              frame= store('frame', frame - reverse * delta)
            t.trigger('frameChange');
            return false;
          }
        };
      t.ready(on.init);
    });
  }
  // PRIVATE
  function number(input){
    return +input.toString().replace(/[^0-9]+/, '');
  }
})(jQuery);


text:
package io.rx_cache2;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * If sets, it will use the key passed as argument in {@link EncryptKey} in order to encrypt/decrypt
 * the disk cache automatically by RxCache.
 */
@Target(METHOD)
@Retention(RUNTIME)
public @interface Encrypt {
}


text:
<?php

namespace Codeburner\Router;

use Codeburner\Router\Strategies\DispatcherStrategyInterface as StrategyInterface;
use Codeburner\Router\Strategies\UriDispatcherStrategy as DefaultStrategy;
use Codeburner\Router\Mapper as Collection;
use Codeburner\Router\Exceptions\MethodNotAllowedException;
use Codeburner\Router\Exceptions\NotFoundException;
use Exception;

/**
 * The dispatcher class is responsable to find and execute the callback
 * of the approprieted route for a given HTTP method and URI.
 *
 * @author Alex Rohleder <contato@alexrohleder.com.br>
 * @since 1.0.0
 */

class Dispatcher
{

    /**
     * The action dispatch strategy object.
     *
     * @var StrategyInterface
     */

    protected $strategy;

    /**
     * The route collection.
     *
     * @var Collection
     */

    protected $collection;

    /**
     * Define a basepath to all routes.
     *
     * @var string
     */

    protected $basepath;

    /**
     * Construct the route dispatcher.
     *
     * @param Collection        $collection The collection to save routes.
     * @param string            $basepath   Define a URI prefix that must be excluded on matches.
     * @param StrategyInterface $strategy   The strategy to dispatch matched route action.
     */

    public function __construct(Collection $collection, $basepath = '', StrategyInterface $strategy = null)
    {
        $this->collection = $collection;
        $this->basepath   = (string) $basepath;
        $this->strategy   = $strategy ?: new DefaultStrategy;
    }

    /**
     * Find and dispatch a route based on the request http method and uri.
     *
     * @param string $method The HTTP method of the request, that should be GET, POST, PUT, PATCH or DELETE.
     * @param string $uri    The URi of request.
     *
     * @return mixed The request response
     */

    public function dispatch($method, $uri)
    {
        if ($route = $this->match($method, $uri)) {
            return $this->strategy->dispatch(
                $route['action'],
                $route['params']
            );
        }

        $this->dispatchNotFoundRoute($method, $uri);
    }

    /**
     * Find a route that matches the given arguments.
     *
     * @param string $method The HTTP method of the request, that should be GET, POST, PUT, PATCH or DELETE.
     * @param string $uri    The URi of request.
     *
     * @return array|false
     */

    public function match($method, $uri)
    {
        $method = $this->getHttpMethod($method);
        $uri = $this->getUriPath($uri);

        if ($route = $this->collection->getStaticRoute($method, $uri)) {
            return $route;
        }

        if ($route = $this->matchDinamicRoute($this->collection->getDinamicRoutes($method, $uri), $uri)) {
            return [
                'action' => $this->resolveDinamicRouteAction($route['action'], $route['params']),
                'params' => $route['params']
            ];
        }

        return false;
    }

    /**
     * Verify if the given http method is valid.
     *
     * @param  int|string $method
     * @throws Exception
     * @return int
     */

    protected function getHttpMethod($method)
    {
        if (in_array($method, Mapper::$methods)) {
            return $method;
        }

        if (array_key_exists($method = strtolower($method), array_map('strtolower', Mapper::$methods))) {
            return Mapper::$methods[$method];
        }

        throw new Exception('The HTTP method given to the route dispatcher is not supported or is incorrect.');
    }

    /**
     * Get only the path of a given url or uri.
     *
     * @param string $uri The given URL
     *
     * @throws Exception
     * @return string
     */

    protected function getUriPath($uri)
    {
        $path = parse_url(substr(strstr(';' . $uri, ';' . $this->basepath), strlen(';' . $this->basepath)), PHP_URL_PATH);

        if ($path === false) {
            throw new Exception('Seriously malformed URL passed to route dispatcher.');
        }

        return $path;
    }

    /**
     * Find and return the request dinamic route based on the compiled data and uri.
     *
     * @param array  $routes All the compiled data from dinamic routes.
     * @param string $uri    The URi of request.
     *
     * @return array|false If the request match an array with the action and parameters will be returned
     *                     otherwide a false will.
     */

    protected function matchDinamicRoute($routes, $uri)
    {
        foreach ($routes as $route) {
            if (!preg_match($route['regex'], $uri, $matches)) {
                continue;
            }

            list($routeAction, $routeParams) = $route['map'][count($matches)];

            $params = [];
            $i = 0;

            foreach ($routeParams as $name) {
                $params[$name] = $matches[++$i];
            }

            return ['action' => $routeAction, 'params' => $params];
        }

        return false;
    }

    /**
     * Generate an HTTP error request with method not allowed or not found.
     *
     * @param string $method The HTTP method that must not be checked.
     * @param string $uri    The URi of request.
     *
     * @throws NotFoundException
     * @throws MethodNotAllowedException
     */

    protected function dispatchNotFoundRoute($method, $uri)
    {
        $dm = $dm = [];

        if ($sm = ($this->checkStaticRouteInOtherMethods($method, $uri))
                || $dm = ($this->checkDinamicRouteInOtherMethods($method, $uri))) {
            throw new MethodNotAllowedException($method, $uri, array_merge((array) $sm, (array) $dm));
        }

        throw new NotFoundException($method, $uri);
    }

    /**
     * Verify if a static route match in another method than the requested.
     *
     * @param string $jump_method The HTTP method that must not be checked
     * @param string $uri         The URi that must be matched.
     *
     * @return array
     */

    protected function checkStaticRouteInOtherMethods($jump_method, $uri)
    {
        return array_filter(array_diff_key(Mapper::$methods, [$jump_method => true]), function ($method) use ($uri) {
            return (bool) $this->collection->getStaticRoute($method, $uri);
        });
    }

    /**
     * Verify if a dinamic route match in another method than the requested.
     *
     * @param string $jump_method The HTTP method that must not be checked
     * @param string $uri         The URi that must be matched.
     *
     * @return array
     */

    protected function checkDinamicRouteInOtherMethods($jump_method, $uri)
    {
        return array_filter(array_diff_key(Mapper::$methods, [$jump_method => true]), function ($method) use ($uri) {
            return (bool) $this->matchDinamicRoute($this->collection->getDinamicRoutes($method, $uri), $uri);
        });
    }

    /**
     * Resolve dinamic action, inserting route parameters at requested points.
     *
     * @param string|array|closure $action The route action.
     * @param array                $params The dinamic routes parameters.
     *
     * @return string
     */

    protected function resolveDinamicRouteAction($action, $params)
    {
        if (is_array($action)) {
            foreach ($action as $key => $value) {
                if (is_string($value)) {
                    $action[$key] = str_replace(['{', '}'], '', str_replace(array_keys($params), array_values($params), $value));
                }
            }
        }

        return $action;
    }

    /**
     * Get the getCollection() of routes.
     *
     * @return Collection
     */

    public function getCollection()
    {
        return $this->collection;
    }

    /**
     * Get the current dispatch strategy.
     *
     * @return StrategyInterface
     */

    public function getStrategy()
    {
        return $this->strategy;
    }

    /**
     * Get the actual base path of this dispatch.
     *
     * @return string
     */

    public function getBasePath()
    {
        return $this->basepath;
    }

    /**
     * Set a new basepath, this will be a prefix that must be excluded in every
     * requested URi.
     *
     * @param string $basepath The new basepath
     */

    public function setBasePath($basepath)
    {
        $this->basepath = $basepath;
    }

}


text:
package org.cloudmeter.testelement;

import org.apache.jmeter.modifiers.model.*;
import org.apache.jmeter.protocol.http.modifier.AnchorModifier;
import org.apache.jmeter.protocol.http.modifier.*;
import org.apache.jmeter.modifiers.*;
import org.apache.jmeter.protocol.model.*;
import org.apache.jmeter.protocol.http.model.*;
import org.apache.jmeter.protocol.jdbc.processor.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class ProcessorBeans {

	@Bean
	public BeanShellPreProcessorInitializer BeanShellPreProcessorInitializer() {
		return new BeanShellPreProcessorInitializer();
	}

	@Bean
	@Autowired
	public BeanShellPreProcessor BeanShellPreProcessor(BeanShellPreProcessorInitializer initer) {
		return (BeanShellPreProcessor) initer.initilizeElement();
	}

	@Bean
	public HTMLLinkPreProcessorInitializer HTMLLinkPreProcessorInitializer() {
		return new HTMLLinkPreProcessorInitializer();
	}

	@Bean
	@Autowired
	public AnchorModifier HTMLLinkPreProcessor(HTMLLinkPreProcessorInitializer initer) {
		return (AnchorModifier) initer.initilizeElement();
	}

	@Bean
	public JDBCPreProcessorInitializer JDBCPreProcessorInitializer() {
		return new JDBCPreProcessorInitializer();
	}

	@Bean
	@Autowired
	public JDBCPreProcessor JDBCPreProcessor(JDBCPreProcessorInitializer initer) {
		return (JDBCPreProcessor) initer.initilizeElement();
	}

	@Bean
	public JSR223PreProcessorInitializer JSR223PreProcessorInitializer() {
		return new JSR223PreProcessorInitializer();
	}

	@Bean
	@Autowired
	public JSR223PreProcessor JSR223PreProcessor(JSR223PreProcessorInitializer initer) {
		return (JSR223PreProcessor) initer.initilizeElement();
	}

	@Bean
	public RegExUserParametersInitializer RegExUserParametersInitializer() {
		return new RegExUserParametersInitializer();
	}

	@Bean
	@Autowired
	public RegExUserParameters RegExUserParameters(RegExUserParametersInitializer initer) {
		return (RegExUserParameters) initer.initilizeElement();
	}

	@Bean
	public SampleTimeoutInitializer SampleTimeoutInitializer() {
		return new SampleTimeoutInitializer();
	}

	@Bean
	@Autowired
	public SampleTimeout SampleTimeout(SampleTimeoutInitializer initer) {
		return (SampleTimeout) initer.initilizeElement();
	}

	@Bean
	public URLRewritingInitializer URLRewritingInitializer() {
		return new URLRewritingInitializer();
	}

	@Bean
	@Autowired
	public URLRewritingModifier URLRewritingModifier(URLRewritingInitializer initer) {
		return (URLRewritingModifier) initer.initilizeElement();
	}

	@Bean
	public UserParametersInitializer UserParametersInitializer() {
		return new UserParametersInitializer();
	}

	@Bean
	@Autowired
	public UserParameters UserParameters(UserParametersInitializer initer) {
		return (UserParameters) initer.initilizeElement();
	}
}


text:
immutable BasicMCRange{T<:Integer} <: MCRange{T}
  burnin::T
  thinning::T
  nsteps::T
  postrange::StepRange{T, T}
  npoststeps::T

  function BasicMCRange(postrange::StepRange{T, T})
    burnin = first(postrange)-1
    thinning = postrange.step
    nsteps = last(postrange)

    @assert burnin >= 0 "Number of burn-in iterations should be non-negative"
    @assert thinning >= 1 "Thinning should be >= 1"
    @assert nsteps > burnin "Total number of MCMC iterations should be greater than number of burn-in iterations"

    npoststeps = length(postrange)

    new(burnin, thinning, nsteps, postrange, npoststeps)
  end
end

BasicMCRange{T<:Integer}(postrange::StepRange{T, T}) = BasicMCRange{T}(postrange)

BasicMCRange{T<:Integer}(postrange::UnitRange{T}) = BasicMCRange{T}(first(postrange):1:last(postrange))

BasicMCRange{T<:Integer}(; burnin::T=0, thinning::T=1, nsteps::T=100) = BasicMCRange{T}((burnin+1):thinning:nsteps)

Base.show(io::IO, r::BasicMCRange) =
  print(io, "BasicMCRange: number of steps = $(r.nsteps), burnin = $(r.burnin), thinning = $(r.thinning)")

Base.writemime(io::IO, ::MIME"text/plain", r::BasicMCRange) = show(io, r)


text:
namespace FinanceTracker.UniversalApp.UI.ViewModels
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Windows.Input;
    using Control;
    using Data.Contracts;
    using Data.Exceptions;
    using Data.Models.Transactions;
    using Helpers;
    using Pages;
    using Windows.UI.Popups;
    using Windows.UI.Xaml;

    public class CreateTransactionViewModel : BaseViewModel
    {
        private readonly IData dataProvider;

        private bool isAddButtonAvailable;

        public CreateTransactionViewModel(IData dataProvider)
        {
            this.AddTransactionCommand = new DelegateCommand<TransactionModel>(
                this.AddTransaction, this.IsButtonAvailable);
            this.CancelCommand = new DelegateCommand<object>(this.GoToPreviousPage);

            this.Categories = new ObservableCollection<string>();
            this.isAddButtonAvailable = true;

            this.dataProvider = dataProvider;
            this.RefreshCategories();
        }

        public static IEnumerable<TransactionType> TransactionTypes
        {
            get { return Enum.GetValues(typeof(TransactionType)).Cast<TransactionType>(); }
        }

        public ICommand AddTransactionCommand { get; }

        public ICommand CancelCommand { get; }

        public ObservableCollection<string> Categories { get; }

        public bool InProgress
        {
            get { return !this.isAddButtonAvailable; }
        }

        private async void AddTransaction(TransactionModel transactionData)
        {
            if (!this.IsValidModel(transactionData))
            {
                return;
            }

            this.isAddButtonAvailable = false;
            this.RaisePropertyChanged(nameof(this.AddTransactionCommand));
            this.RaisePropertyChanged(nameof(this.InProgress));

            try
            {
                // Todo: Waiting wheel animation
                await this.dataProvider.AddTransactionAsync(transactionData);

                var content = (Window.Current.Content as AppShell).AppFrame;
                content.Navigate(typeof(HomePage));
                var notification = new MessageDialog("Transaction added successfully!");
                await notification.ShowAsync();
            }
            catch (ApplicationException e)
            {
                // Notify User. Show Login Screen
                var messageDialog = new ErrorNotificationDialog();
                string[] messages = { e.Message };
                messageDialog.DataContext = messages;

                await messageDialog.ShowAsync();
            }
            finally
            {
                this.isAddButtonAvailable = true;
                this.RaisePropertyChanged(nameof(this.AddTransactionCommand));
                this.RaisePropertyChanged(nameof(this.InProgress));
            }
        }

        private async void RefreshCategories()
        {
            try
            {
                var categories = await this.dataProvider.GetCategoriesAsync();

                this.Categories.Clear();
                foreach (var category in categories)
                {
                    this.Categories.Add(category);
                }
            }
            catch (ApplicationException e)
            {
                var messageDialog = new ErrorNotificationDialog();
                string[] messages = { e.Message };
                messageDialog.DataContext = messages;

                await messageDialog.ShowAsync();
            }
        }

        private void GoToPreviousPage(object obj)
        {
            var page = obj as CreateTransactionPage;

            page?.Frame.GoBack();
        }

        private bool IsButtonAvailable(object obj)
        {
            return this.isAddButtonAvailable;
        }
    }
}