text:
$(function(){
    var bs3Wysihtml5Templates = {
        "emphasis": function(locale, options) {
            var size = (options && options.size) ? ' btn-'+options.size : '';
            return "
" +
                "
" +
                "" +
                "" +
                "
" +
                "
";
        },
        "link": function(locale, options) {
            var size = (options && options.size) ? ' btn-'+options.size : '';
            return "
" +
                ""+
                "
" +
                "
"+
                "
"+
                "
" +
                "×" +
                "
" + locale.link.insert + "
" +
                "
" +
                "
" +
                "<input value='http://' class='bootstrap-wysihtml5-insert-link-url form-control'>" +
                " <input type='checkbox' class='bootstrap-wysihtml5-insert-link-target' checked>" + locale.link.target + "" +
                "
" +
                "
" +
                "<button class='btn btn-default' data-dismiss='modal'>" + locale.link.cancel + "</button>" +
                "<button href='#' class='btn btn-primary' data-dismiss='modal'>" + locale.link.insert + "</button>" +
                "
" +
                "
" +
                "
" +
                "
" +
                "" +
                "
";
        },
        "html": function(locale, options) {
            var size = (options && options.size) ? ' btn-'+options.size : '';
            return "
" +
                "
" +
                "" +
                "
" +
                "
";
        }
    };

    var dummyBodies = ["
Why painful the sixteen how minuter looking nor. Subject but why ten earnest husband imagine sixteen brandon. Are unpleasing occasional celebrated motionless unaffected conviction out. Evil make to no five they. Stuff at avoid of sense small fully it whose an. Ten scarcely distance moreover handsome age although. As when have find fine or said no mile. He in dispatched in imprudence dissimilar be possession unreserved insensible. She evil face fine calm have now. Separate screened he outweigh of distance landlord.
",
        "somm text bodt. Reall small. ust few lines", "
Lose john poor same it case do year we. Full how way even the sigh. Extremely nor furniture fat questions now provision incommode preserved. Our side fail find like now. Discovered travelling for insensible partiality unpleasing impossible she. Sudden up my excuse to suffer ladies though or. Bachelor possible marianne directly confined relation as on he.
",
        "empty"];

    function initMailboxApp(){
        "use strict";

        var STARRED_FOLDER_ID = 33;

        var Email = Backbone.Model.extend({

            defaults:function(){
                return {
                    sender: '',
                    senderMail: '',
                    subject: '',
                    body: dummyBodies[Math.round(Math.random()*3)],
                    receiver: '',
                    timestamp: new Date(new Date().getTime() - 2*60*60*1000).getTime(),  //two hours ago
                    read: true,
                    starred: false,
                    attachment: false,
                    folderId: 1,

                    selected:false
                }
            },
            markRead: function() {
                this.save( {read: true } );
            },

            toggleStarred: function() {
                this.save( { starred: !this.get("starred")} );
            },

            toggleSelected: function(){
                this.save( {selected: !this.get("selected")});
            }
        });

        var Folder = Backbone.Model.extend({

            defaults: {
                name: '',
                current: false,
                order: 3,
                unread: 0
            },

            sync: function(){
                //just swallow this call
            }
        });

        var FolderList = Backbone.Collection.extend({

            model: Folder,

            url: 'demo/json/folders.json',

            comparator: 'order',

            parse: function(response){
                //add fake starred folder
                response.push({name: 'Starred', id: STARRED_FOLDER_ID, order: 4});
                return response;
            }
        });

        var Folders = new FolderList();

        var FolderView = Backbone.View.extend({

            tagName:  "li",

            template: _.template($('#folder-template').html()),

            events: {
                "click": 'selectFolder'
            },

            initialize: function() {
                this.listenTo(this.model, 'change', this.render);
            },

            render: function() {
                this.$el.attr('class', this.model.get("current") ? 'active' : '');
                this.$el.html(this.template(this.model.toJSON()));
                return this;
            },

            selectFolder: function(){
                var that = this;
                Folders.each(function(folder){
                    folder.save({current: folder == that.model})
                });
                App.showEmailsView();
            }

        });

        var EmailList = window.EmailList = Backbone.Collection.extend({

            model: Email,

            url: 'demo/json/emails.json',

            comparator: function(mail){
                return -mail.get('timestamp');
            },

            search: function(word, folderId){
                if (word=="") return this.where({folderId: folderId});

                var pat = new RegExp(word, 'gi');
                return this.filter( function(mail) {
                        return mail.get("folderId") == folderId && pat.test(mail.get('subject')) || pat.test(mail.get('sender'));
                    }
                );
            }

        });

        var Emails = new EmailList();

        var EmailView = Backbone.View.extend({

            tagName:  "tr",

            template: _.template($('#mail-item-template').html()),

            events: {
                "change .selected-checkbox": 'toggleSelected',
                "click .starred": 'toggleStarred',
                "click .name,.subject": 'openEmail'
            },

            initialize: function() {
                this.listenTo(this.model, 'change', this.render);
            },

            render: function() {
                this.$el.attr('class', this.model.get("read") ? '' : 'unread');
                this.$el.html(this.template(this.model.toJSON()));
                return this;
            },

            formatDate: function(dateInt){
                var date = new Date(dateInt),
                    now = new Date(),
                    todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
                if (date.getTime() > todayStart){
                    return date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
                }
                return ['Jan', 'Feb', 'Mar', 'Apr',
                    'May', 'Jun', 'Jul', 'Aug',
                    'Sep', 'Oct', 'Nov', 'Dec'][date.getMonth()] + ' ' + date.getDate();
            },

            toggleSelected: function(){
                this.model.toggleSelected();
            },

            toggleStarred: function(){
                this.model.toggleStarred();
            },

            openEmail: function(){
                this.model.save({read: true});
                App.setCurrentView(new EmailOpenedView({model: this.model}));
            }

        });

        var EmailOpenedView = Backbone.View.extend({

            template: _.template($('#email-view-template').html()),

            attributes: {
                id: 'email-view',
                class: 'email-view'
            },

            events: {
                "click #email-opened-reply": 'replyEmail'
            },

            initialize: function() {
                this.listenTo(this.model, 'change', this.render);
            },

            render: function() {
                $('#widget-email-header').html(
                        "
" + this.model.get('subject') + "
" +
                        '

'
                );
                $('#folder-stats').addClass('hide');
                $('#back-btn').removeClass('hide');
                this.$el.html(this.template(this.model.toJSON()));
                return this;
            },

            formatDate: function(dateInt){
                var date = new Date(dateInt),
                    now = new Date(),
                    todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
                if (date.getTime() > todayStart){
                    return date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
                }
                var daysAgo = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24));
                return ['Jan', 'Feb', 'Mar', 'Apr',
                    'May', 'Jun', 'Jul', 'Aug',
                    'Sep', 'Oct', 'Nov', 'Dec'][date.getMonth()] + ' ' + date.getDate() + ' (' + daysAgo + ' days ago)';
            },

            replyEmail: function(){
                var body = "

" +
                        "
" +
                        this.model.get("body") +
                        "

",
                    newEmail = new Email({
                        body: body,
                        receiver: this.model.get("sender") ? this.model.get("sender") : this.model.get("senderMail"),
                        subject: "Re: " + this.model.get("subject")
                    });
                App.showComposeView(newEmail);
            }

        });

        var ComposeView = Backbone.View.extend({

            template: _.template($('#compose-view-template').html()),

            attributes: {
                id: 'compose-view',
                class: 'compose-view'
            },

            events: {
                "click #compose-save-button, #compose-send-button, #compose-discard-button": 'backToFolders'
            },

            render: function() {
                $('#widget-email-header').html(
                    '
Compose New
'
                );
                $('#folder-stats').addClass('hide');
                $('#back-btn').removeClass('hide');
                this.$el.html(this.template(this.model.toJSON()));
                this._initViewComponents();
                return this;
            },

            backToFolders: function(){
                App.showEmailsView();
            },

            _initViewComponents: function(){
                this.$("textarea").wysihtml5({
                    html: true,
                    customTemplates: bs3Wysihtml5Templates,
                    stylesheets: []
                });
            }

        });

        var EmailListView = Backbone.View.extend({

            tagName: 'table',

            attributes: {
                id: 'folder-view',
                class: 'table table-striped table-emails table-hover'
            },

            template: _.template($('#folders-view-template').html()),

            events: {
                "change #toggle-all":  "toggleAll"
            },

            initialize: function() {
                this.currentFolderEmails = new EmailList();
                this.folders = Folders;

                this.listenTo(this.currentFolderEmails, 'reset', this.renderEmails);  //when displayed first time, and after
                this.listenTo(this.currentFolderEmails, 'all', this.renderFolderActions); //when something starred or selected display folder actions
                this.listenTo(this.currentFolderEmails, 'destroy', this.renderEmails); //when model deleted
                this.listenTo(this.folders, 'change', this.resetEmails); //when current folder changed
            },

            render: function() {
                $('#widget-email-header').html($('#email-list-view-header-template').html());
                $('#folder-stats').removeClass('hide');
                $('#back-btn').addClass('hide');
                /* manually attach events as we have few elements outside of main $el */
                $('#select-all').on('click', $.proxy(this.selectAll, this));
                $('#select-none').on('click', $.proxy(this.selectNone, this));
                $('#select-read').on('click', $.proxy(this.selectRead, this));
                $('#select-unread').on('click', $.proxy(this.selectUnread, this));
                $('#mark-as-read').on('click', $.proxy(this.markSelectedAsRead, this));
                $('#mark-as-unread').on('click', $.proxy(this.markSelectedAsUnread, this));
                $('#delete').on('click', $.proxy(this.deleteEmails, this));

                this.resetEmails();
                this.delegateEvents(this.events);
                return this;
            },

            renderFolderActions: function() {
                var selectedCount = this.currentFolderEmails.where({selected: true}).length,
                    allSelected = selectedCount == this.currentFolderEmails.length,
                    anySelected = selectedCount > 0;
                this.$toggleAllCheckbox = this.$('#toggle-all');
                this.$toggleAllCheckbox.prop('checked', allSelected);
            },

            addOne: function(email) {
                var view = new EmailView({model: email});
                this.$el.find("tbody").append(view.render().el);
            },

            renderEmails: function() {
                this.reset();
                if (this.currentFolderEmails.length){
                    this.currentFolderEmails.each(this.addOne, this);
                } else {
                    this.$el.find("tbody").append('
Nothing here yet
')
                }
                var currentFolder = this.folders.where({current: true})[0],
                    unreadCount = this.currentFolderEmails.where({read: false}).length,
                    currentFolderTitle = 'Inbox';
                if (currentFolder){
                    currentFolderTitle = currentFolder.get("name");
                }
            },

            reset: function(){
                this.$el.html(this.template());
            },

            resetEmails: function(){
                var item = this.folders.where({current: true})[0],
                    folderId = 1;
                if (item){
                    folderId = item.get("id");
                }
                if (folderId == STARRED_FOLDER_ID){
                    this.currentFolderEmails.reset(Emails.where({
                        starred: true
                    }));
                } else {
                    this.currentFolderEmails.reset(Emails.where({
                        folderId: folderId
                    }));
                }
            },

            toggleAll: function(){
                var selectAll = this.$toggleAllCheckbox.prop('checked');
                this.currentFolderEmails.each(function (email) { email.save({'selected': selectAll}); });
            },

            selectAll: function(){
                this.$toggleAllCheckbox.prop('checked', true);
                this.toggleAll();
            },

            selectNone: function(){
                this.$toggleAllCheckbox.prop('checked', false);
                this.toggleAll();
            },

            selectRead: function(){
                this.selectNone();
                _(this.currentFolderEmails.where({read: true})).each(function (email) { email.save({'selected': true}); });
            },

            selectUnread: function(){
                this.selectNone();
                _(this.currentFolderEmails.where({read: false})).each(function (email) { email.save({'selected': true}); });
            },

            search: function(){
                var item = this.folders.where({current: true})[0],
                    folderId = 1;
                if (item){
                    folderId = item.get("id");
                }
                this.currentFolderEmails.reset(Emails.search($('#mailbox-search').val(), folderId));
            },

            markSelectedAsRead: function(){
                _(this.currentFolderEmails.where({selected: true})).each(function (email) { email.save({'read': true}); });
            },

            markSelectedAsUnread: function(){
                _(this.currentFolderEmails.where({selected: true})).each(function (email) { email.save({'read': false}); });
            },

            deleteEmails: function(){
                _(this.currentFolderEmails.where({selected: true})).each(function (email) { email.destroy(); });
            }

        });

        var EmailsView = new EmailListView();

        var AppView = Backbone.View.extend({

            el: $("#content"),
            $content: $("#mailbox-content"),

            events: {
                "keyup #mailbox-search": 'search',
                "click #compose-btn": 'handleComposeBtnClick',
                "click #back-btn": 'handleBackBtnClick'
            },

            initialize: function() {
                this.currentView = EmailsView;
                this.folders = Folders;

                this.listenTo(this.folders, 'reset', this.renderFolders);

                var view = this;
                this.folders.fetch({success: function(){
                    Emails.fetch({success: function(){
                        view.render();
                    }, reset: true});
                }, reset: true});
            },

            render: function(){
                this.$content.html(this.currentView.render().el);
            },

            setCurrentView: function(view){
                if (this.currentView !== EmailsView){
                    this.currentView.remove();
                }
                this.currentView = view;
                this.render();
            },

            renderFolders: function(){
                this.resetFoldersList();
                this.folders.each(this.addFolder, this);
            },

            resetFoldersList: function(){
                this.$("#folders-list").html('');
            },

            addFolder: function(folder){
                var view = new FolderView({model: folder});
                this.$("#folders-list").append(view.render().el);
            },

            search: function(){
                if (typeof this.currentView.search === 'function'){
                    this.currentView.search();
                }
            },

            showEmailsView: function(){
                if (this.currentView != EmailsView){
                    this.setCurrentView(EmailsView)
                }
            },

            handleComposeBtnClick: function(){
                this.showComposeView();
                return false;
            },

            handleBackBtnClick: function(){
                this.showEmailsView();
                return false;
            },

            showComposeView: function(model){
                model = model ? model : new Email({body: ''});
                this.setCurrentView(new ComposeView({model: model}));
            }

        });

        var App = new AppView;
    }

    /* this is only for demo. can be removed */
    function initMailboxAppDemo(){
        setTimeout(function(){
            $('#app-alert').removeClass('hide')
                .one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend',function(){
                    $(this).removeClass('animated bounceInLeft');
                });
        }, 3000)
    }

    function pageLoad(){
        $('#wysiwyg').wysihtml5({
            html: true,
            customTemplates: bs3Wysihtml5Templates,
            stylesheets: []
        });

        initMailboxApp();

        initMailboxAppDemo()
    }
    pageLoad();
    SingApp.onPageLoad(pageLoad);
});


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

@import Flutter;
@import XCTest;
@import webview_flutter_wkwebview;

#import <OCMock/OCMock.h>

@interface FWFObjectHostApiTests : XCTestCase
@end

@implementation FWFObjectHostApiTests
/**
 * Creates a partially mocked FWFObject and adds it to instanceManager.
 *
 * @param instanceManager Instance manager to add the delegate to.
 * @param identifier Identifier for the delegate added to the instanceManager.
 *
 * @return A mock FWFObject.
 */
- (id)mockObjectWithManager:(FWFInstanceManager *)instanceManager identifier:(long)identifier {
  FWFObject *object =
      [[FWFObject alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger))
                                 instanceManager:instanceManager];

  [instanceManager addDartCreatedInstance:object withIdentifier:0];
  return OCMPartialMock(object);
}

/**
 * Creates a  mock FWFObjectFlutterApiImpl with instanceManager.
 *
 * @param instanceManager Instance manager passed to the Flutter API.
 *
 * @return A mock FWFObjectFlutterApiImpl.
 */
- (id)mockFlutterApiWithManager:(FWFInstanceManager *)instanceManager {
  FWFObjectFlutterApiImpl *flutterAPI = [[FWFObjectFlutterApiImpl alloc]
      initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger))
              instanceManager:instanceManager];
  return OCMPartialMock(flutterAPI);
}

- (void)testAddObserver {
  NSObject *mockObject = OCMClassMock([NSObject class]);

  FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
  [instanceManager addDartCreatedInstance:mockObject withIdentifier:0];

  FWFObjectHostApiImpl *hostAPI =
      [[FWFObjectHostApiImpl alloc] initWithInstanceManager:instanceManager];

  NSObject *observerObject = [[NSObject alloc] init];
  [instanceManager addDartCreatedInstance:observerObject withIdentifier:1];

  FlutterError *error;
  [hostAPI
      addObserverForObjectWithIdentifier:@0
                      observerIdentifier:@1
                                 keyPath:@"myKey"
                                 options:@[
                                   [FWFNSKeyValueObservingOptionsEnumData
                                       makeWithValue:FWFNSKeyValueObservingOptionsEnumOldValue],
                                   [FWFNSKeyValueObservingOptionsEnumData
                                       makeWithValue:FWFNSKeyValueObservingOptionsEnumNewValue]
                                 ]
                                   error:&error];

  OCMVerify([mockObject addObserver:observerObject
                         forKeyPath:@"myKey"
                            options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew)
                            context:nil]);
  XCTAssertNil(error);
}

- (void)testRemoveObserver {
  NSObject *mockObject = OCMClassMock([NSObject class]);

  FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
  [instanceManager addDartCreatedInstance:mockObject withIdentifier:0];

  FWFObjectHostApiImpl *hostAPI =
      [[FWFObjectHostApiImpl alloc] initWithInstanceManager:instanceManager];

  NSObject *observerObject = [[NSObject alloc] init];
  [instanceManager addDartCreatedInstance:observerObject withIdentifier:1];

  FlutterError *error;
  [hostAPI removeObserverForObjectWithIdentifier:@0
                              observerIdentifier:@1
                                         keyPath:@"myKey"
                                           error:&error];
  OCMVerify([mockObject removeObserver:observerObject forKeyPath:@"myKey"]);
  XCTAssertNil(error);
}

- (void)testDispose {
  NSObject *object = [[NSObject alloc] init];

  FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
  [instanceManager addDartCreatedInstance:object withIdentifier:0];

  FWFObjectHostApiImpl *hostAPI =
      [[FWFObjectHostApiImpl alloc] initWithInstanceManager:instanceManager];

  FlutterError *error;
  [hostAPI disposeObjectWithIdentifier:@0 error:&error];
  // Only the strong reference is removed, so the weak reference will remain until object is set to
  // nil.
  object = nil;
  XCTAssertFalse([instanceManager containsInstance:object]);
  XCTAssertNil(error);
}

- (void)testObserveValueForKeyPath {
  FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];

  FWFObject *mockObject = [self mockObjectWithManager:instanceManager identifier:0];
  FWFObjectFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager];

  OCMStub([mockObject objectApi]).andReturn(mockFlutterAPI);

  NSObject *object = [[NSObject alloc] init];
  [instanceManager addDartCreatedInstance:object withIdentifier:1];

  [mockObject observeValueForKeyPath:@"keyPath"
                            ofObject:object
                              change:@{NSKeyValueChangeOldKey : @"key"}
                             context:nil];
  OCMVerify([mockFlutterAPI
      observeValueForObjectWithIdentifier:@0
                                  keyPath:@"keyPath"
                         objectIdentifier:@1
                               changeKeys:[OCMArg checkWithBlock:^BOOL(
                                                      NSArray<FWFNSKeyValueChangeKeyEnumData *>
                                                          *value) {
                                 return value[0].value == FWFNSKeyValueChangeKeyEnumOldValue;
                               }]
                             changeValues:[OCMArg checkWithBlock:^BOOL(id value) {
                               return [@"key" isEqual:value[0]];
                             }]
                               completion:OCMOCK_ANY]);
}
@end

redpajama_set_name: RedPajamaGithub


text:
@interface SFStringAdditionsTests : SenTestCase {
    NSString *_testString;
    NSString *_stringToTestAgainst;
}
@end

@implementation SFStringAdditionsTests

- (void)setUp
{
    _stringToTestAgainst = @"hello World!";
}

- (void)testContainsShouldReturnNoWhenStringIsNotMatched
{
    NSString *testString = @"Hello";
	STAssertFalse([_stringToTestAgainst containsString:testString], nil);
}

- (void)testContainsShouldReturnYesWhenStringIsMatched
{
    NSString *testString = @"Hello";
    STAssertTrue([_stringToTestAgainst containsString:testString options:NSCaseInsensitiveSearch], nil);
}

- (void)testContainsShouldReturnYesWhenStringIsMatchedWithoutOptions
{
    NSString *testString = @"hello";
    STAssertTrue([_stringToTestAgainst containsString:testString], nil);
}

@end


text:
package net.i2p.router.transport;
/*
 * free (adj.): unencumbered; not under the control of others
 * Written by jrandom in 2003 and released into the public domain
 * with no warranty of any kind, either expressed or implied.
 * It probably won't make your computer catch on fire, or eat
 * your children, but it might.  Use at your own risk.
 *
 */

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.i2p.data.i2np.I2NPMessage;
import net.i2p.router.Job;
import net.i2p.router.MessageSelector;
import net.i2p.router.OutNetMessage;
import net.i2p.router.ReplyJob;
import net.i2p.router.RouterContext;
import net.i2p.util.ConcurrentHashSet;
import net.i2p.util.Log;
import net.i2p.util.SimpleTimer2;

/**
 *  Tracks outbound messages.
 */
public class OutboundMessageRegistry {
    private final Log _log;
    /** list of currently active MessageSelector instances */
    private final List<MessageSelector> _selectors;
    /** map of active MessageSelector to either an OutNetMessage or a List of OutNetMessages causing it (for quick removal) */
    private final Map<MessageSelector, Object> _selectorToMessage;
    /**
     *  set of active OutNetMessage (for quick removal and selector fetching)
     *  !! Really? seems only for dup detection in registerPending().
     *  Changed to concurrent, but it could perhaps be removed completely,
     *  It would seem difficult to add a dup since every OutNetMessage is different,
     *  and it's generally instantiated just before ctx.outNetMessagePool().add().
     *  But in TransportImpl.afterSend() it does requeue a previous ONM if allowRequeue=true.
     */
    private final Set<OutNetMessage> _activeMessages;
    private final CleanupTask _cleanupTask;
    private final RouterContext _context;

    public OutboundMessageRegistry(RouterContext context) {
        _context = context;
        _log = _context.logManager().getLog(OutboundMessageRegistry.class);
        _selectors = new ArrayList<MessageSelector>(64);
        _selectorToMessage = new HashMap<MessageSelector, Object>(64);
        _activeMessages = new ConcurrentHashSet<OutNetMessage>(64);
        _cleanupTask = new CleanupTask();
    }

    /**
     *  Does something @since 0.8.8
     */
    public void shutdown() {
        synchronized (_selectors) {
            _selectors.clear();
        }
        synchronized (_selectorToMessage) {
            _selectorToMessage.clear();
        }
        // Calling the fail job for every active message would
        // be way too much at shutdown/restart, right?
        _activeMessages.clear();
    }

    /**
     *  @since 0.8.8
     */
    public void restart() {
        shutdown();
    }

    /**
     * Retrieve all messages that are waiting for the specified message.  In
     * addition, those matches may include instructions to either continue or not
     * continue waiting for further replies - if it should continue, the matched
     * message remains in the registry, but if it shouldn't continue, the matched
     * message is removed from the registry.
     *
     * This is called only by InNetMessagePool.
     *
     * TODO this calls isMatch() in the selectors from inside the lock, which
     * can lead to deadlocks if the selector does too much in isMatch().
     * Remove the lock if possible.
     *
     * @param message Payload received that may be a reply to something we sent
     * @return non-null List of OutNetMessage describing messages that were waiting for
     *         the payload
     */
    public List<OutNetMessage> getOriginalMessages(I2NPMessage message) {
        List<MessageSelector> matchedSelectors = null;
        List<MessageSelector> removedSelectors = null;

        synchronized (_selectors) {
            // ConcurrentModificationException - why?
            //for (Iterator<MessageSelector> iter = _selectors.iterator(); iter.hasNext(); ) {
            //    MessageSelector sel = iter.next();
            for (int i = 0; i < _selectors.size(); i++) {
                MessageSelector sel = _selectors.get(i);
                boolean isMatch = sel.isMatch(message);
                if (isMatch) {
                    if (matchedSelectors == null) matchedSelectors = new ArrayList<MessageSelector>(1);
                    matchedSelectors.add(sel);
                    if (!sel.continueMatching()) {
                        if (removedSelectors == null) removedSelectors = new ArrayList<MessageSelector>(1);
                        removedSelectors.add(sel);
                        //iter.remove();
                        _selectors.remove(i);
                        i--;
                    }
                }
            }
        }

        List<OutNetMessage> rv;
        if (matchedSelectors != null) {
            rv = new ArrayList<OutNetMessage>(matchedSelectors.size());
            for (MessageSelector sel : matchedSelectors) {
                boolean removed = false;
                OutNetMessage msg = null;
                List<OutNetMessage> msgs = null;
                synchronized (_selectorToMessage) {
                    Object o = null;
                    if ( (removedSelectors != null) && (removedSelectors.contains(sel)) ) {
                        o = _selectorToMessage.remove(sel);
                        removed = true;
                    } else {
                        o = _selectorToMessage.get(sel);
                    }

                    if (o instanceof OutNetMessage) {
                        msg = (OutNetMessage)o;
                        rv.add(msg);
                    } else if (o instanceof List) {
                        msgs = (List<OutNetMessage>)o;
                        rv.addAll(msgs);
                    }
                }
                if (removed) {
                    if (msg != null) {
                        _activeMessages.remove(msg);
                    } else if (msgs != null) {
                        _activeMessages.removeAll(msgs);
                    }
                }
            }
        } else {
            rv = Collections.emptyList();
        }

        return rv;
    }

    /**
     *  Registers a new, empty OutNetMessage, with the reply and timeout jobs specified.
     *  The onTimeout job is called at replySelector.getExpiration() (if no reply is received by then)
     *
     *  @param replySelector non-null; The same selector may be used for more than one message.
     *  @param onReply non-null
     *  @param onTimeout may be null
     *  @return a dummy OutNetMessage where getMessage() is null. Use it to call unregisterPending() later if desired.
     */
    public OutNetMessage registerPending(MessageSelector replySelector, ReplyJob onReply, Job onTimeout) {
        OutNetMessage msg = new OutNetMessage(_context);
        msg.setOnFailedReplyJob(onTimeout);
        msg.setOnReplyJob(onReply);
        msg.setReplySelector(replySelector);
        registerPending(msg, true);
        if (_log.shouldLog(Log.DEBUG))
            _log.debug("Registered: " + replySelector + " with reply job " + onReply +
                       " and timeout job " + onTimeout);
        return msg;
    }

    /**
     *  Register the message. Each message must have a non-null
     *  selector at msg.getReplySelector().
     *  The same selector may be used for more than one message.
     *
     *  @param msg msg.getMessage() and msg.getReplySelector() must be non-null
     */
    public void registerPending(OutNetMessage msg) { registerPending(msg, false); }

    /**
     *  @param allowEmpty is msg.getMessage() allowed to be null?
     */
    private void registerPending(OutNetMessage msg, boolean allowEmpty) {
        if ( (!allowEmpty) && (msg.getMessage() == null) )
                throw new IllegalArgumentException("OutNetMessage doesn't contain an I2NPMessage? wtf");
        MessageSelector sel = msg.getReplySelector();
        if (sel == null) throw new IllegalArgumentException("No reply selector?  wtf");

        if (!_activeMessages.add(msg))
            return; // dont add dups

        synchronized (_selectorToMessage) {
            Object oldMsg = _selectorToMessage.put(sel, msg);
            if (oldMsg != null) {
                List<OutNetMessage> multi = null;
                if (oldMsg instanceof OutNetMessage) {
                    //multi = Collections.synchronizedList(new ArrayList(4));
                    multi = new ArrayList<OutNetMessage>(4);
                    multi.add((OutNetMessage)oldMsg);
                    multi.add(msg);
                    _selectorToMessage.put(sel, multi);
                } else if (oldMsg instanceof List) {
                    multi = (List<OutNetMessage>)oldMsg;
                    multi.add(msg);
                    _selectorToMessage.put(sel, multi);
                }
                if (_log.shouldLog(Log.WARN))
                    _log.warn("a single message selector [" + sel + "] with multiple messages ("+ multi + ")");
            }
        }
        synchronized (_selectors) { _selectors.add(sel); }

        _cleanupTask.scheduleExpiration(sel);
    }

    /**
     *  @param msg may be be null
     */
    public void unregisterPending(OutNetMessage msg) {
        if (msg == null) return;
        MessageSelector sel = msg.getReplySelector();
        boolean stillActive = false;
        synchronized (_selectorToMessage) {
            Object old = _selectorToMessage.remove(sel);
            if (old != null) {
                if (old instanceof List) {
                    List<OutNetMessage> l = (List<OutNetMessage>)old;
                    l.remove(msg);
                    if (!l.isEmpty()) {
                        _selectorToMessage.put(sel, l);
                        stillActive = true;
                    }
                }
            }
        }
        if (!stillActive)
            synchronized (_selectors) { _selectors.remove(sel); }
        _activeMessages.remove(msg);
    }

    /** @deprecated unused */
    public void renderStatusHTML(Writer out) throws IOException {}

    private class CleanupTask extends SimpleTimer2.TimedEvent {
        private long _nextExpire;

        public CleanupTask() {
            super(_context.simpleTimer2());
            _nextExpire = -1;
        }

        public void timeReached() {
            long now = _context.clock().now();
            List<MessageSelector> removing = new ArrayList<MessageSelector>(8);
            synchronized (_selectors) {
                // CME?
                //for (Iterator<MessageSelector> iter = _selectors.iterator(); iter.hasNext(); ) {
                //    MessageSelector sel = iter.next();
                for (int i = 0; i < _selectors.size(); i++) {
                    MessageSelector sel = _selectors.get(i);
                    long expiration = sel.getExpiration();
                    if (expiration <= now) {
                        removing.add(sel);
                        //iter.remove();
                        _selectors.remove(i);
                        i--;
                    } else if (expiration < _nextExpire || _nextExpire < now) {
                        _nextExpire = expiration;
                    }
                }
            }
            boolean log = _log.shouldLog(Log.DEBUG);
            if (!removing.isEmpty()) {
                for (MessageSelector sel : removing) {
                    OutNetMessage msg = null;
                    List<OutNetMessage> msgs = null;
                    synchronized (_selectorToMessage) {
                        Object o = _selectorToMessage.remove(sel);
                        if (o instanceof OutNetMessage) {
                            msg = (OutNetMessage)o;
                        } else if (o instanceof List) {
                            //msgs = new ArrayList((List)o);
                            msgs = (List<OutNetMessage>)o;
                        }
                    }
                    if (msg != null) {
                        _activeMessages.remove(msg);
                        Job fail = msg.getOnFailedReplyJob();
                        if (fail != null)
                            _context.jobQueue().addJob(fail);
                        if (log)
                            _log.debug("Expired: " + sel + " with timeout job " + fail);
                    } else if (msgs != null) {
                        _activeMessages.removeAll(msgs);
                        for (OutNetMessage m : msgs) {
                            Job fail = m.getOnFailedReplyJob();
                            if (fail != null)
                                _context.jobQueue().addJob(fail);
                            if (log)
                                _log.debug("Expired: " + sel + " with timeout job(s) " + fail);
                        }
                    } else {
                        if (log)
                            _log.debug("Expired: " + sel + " with no known messages");
                    }
                }
            }

            if (log) {
                int e = removing.size();
                int r = _selectors.size();
                int a = _activeMessages.size();
                if (r > 0 || e > 0 || a > 0)
                    _log.debug("Expired: " + e + " remaining: " + r + " active: " + a);
            }
            if (_nextExpire <= now)
                _nextExpire = now + 10*1000;
            schedule(_nextExpire - now);
        }

        public void scheduleExpiration(MessageSelector sel) {
            long now = _context.clock().now();
            if ( (_nextExpire <= now) || (sel.getExpiration() < _nextExpire) ) {
                _nextExpire = sel.getExpiration();
                reschedule(_nextExpire - now);
            }
        }
    }
}


text:
% do single-depth comparisons

% clear
%
% pass_number = 33;
% doFalseNeg = 0;
% sumfig = 20;
% enable_boxed = 0;
%
% bm_depth_min = 4.7;
% bm_depth_max = 4.9;
%
% new_dir = 2;

%% load everything

disp('Loading...');

start_frame_pass = zeros(1, 35);
end_frame_pass = zeros(1, 35);

start_frame_pass(1) = 1990;
start_frame_pass(2) = 989;
start_frame_pass(3) = 809;
start_frame_pass(6) = 62;

start_frame_pass(27) = 5313;
start_frame_pass(29) = 6111;
start_frame_pass(33) = 2851;

end_frame_pass(1) = 2046;
end_frame_pass(2) = 1112;
end_frame_pass(3) = 1416;
end_frame_pass(6) = 5630;

end_frame_pass(27) = 11198;
end_frame_pass(29) = 11962;

end_frame_pass(33) = 8794;

addpath('../../scripts/logs');

%dir = '../../logs/logs/2014-04-18-near-goalposts/bm-stereo/new/';
%filename = ['pass' num2str(pass_number) '.mat'];

if new_dir == 0
  dir = '../../logs/logs/2014-04-18-near-goalposts/bm-stereo/';
  filename = ['pass' num2str(pass_number) '_disp3_3.mat'];
elseif new_dir == 1
  dir = '../../logs/logs/2014-07-24-outside-stereo-test1/bm-stereo/';
  filename = ['pass' num2str(pass_number) '_log.mat'];
elseif new_dir == 2
  dir = '../../logs/logs/2014-07-24-outside-stereo-test2/bm-stereo/';
  filename = ['pass' num2str(pass_number) '_log.mat'];

end
%filename = ['pass' num2str(pass_number) '_disp3_random3.mat']/;
%filename = ['pass' num2str(pass_number) '_fix_random2.mat'];

loadDeltawing

% grab what we need from that load

bm_stereo = stereo_bm;

% dir = '../../logs/logs/2014-04-18-near-goalposts/bm-stereo/';
% filename = ['pass' num2str(pass_number) '_pushbroom.mat'];
%
% loadDeltawing

clear STATE_ESTIMATOR_POSE battery_status stereoBmVals u
clear imu stereoReplayVals wind_groundspeed attitude est stereoVals
clear wind_gspeed baro log stereo_bm wingeron_u baro_airspeed gps
clear servo_out stereo_replay battery gpsValues this_number

%% apply boxes

if enable_boxed == 1
  disp('Apply bounding boxes...');
  bbox = LoadBoundingBox(['box_clicking/pass' num2str(pass_number) '.csv']);

  bm_stereo_boxed = ProcessBoundingBoxBmStereo(bm_stereo, bbox);

  bm_stereo = bm_stereo_boxed;
end

%% crop bm_stero's depth

disp('Cropping depth...');

row_size = size(bm_stereo.x, 2);

bm_stereo_cropped.utime = bm_stereo.utime;
bm_stereo_cropped.frame_number = bm_stereo.frame_number;
bm_stereo_cropped.video_number = bm_stereo.video_number;
bm_stereo_cropped.logtime = bm_stereo.logtime;
%

bm_stereo_cropped.x = zeros(size(bm_stereo.x));
bm_stereo_cropped.y = zeros(size(bm_stereo.y));
bm_stereo_cropped.z = zeros(size(bm_stereo.z));

for i = 1 : length(bm_stereo.frame_number)

  valid_ind = find(bm_stereo.z(i,:) > bm_depth_min & bm_stereo.z(i,:) < bm_depth_max);

  this_len = length(valid_ind);

  bm_stereo_cropped.number_of_points(i) = this_len;

  bm_stereo_cropped.x(i,:) = [ bm_stereo.x(i, valid_ind) zeros(1, row_size - this_len) ];
  bm_stereo_cropped.y(i,:) = [ bm_stereo.y(i, valid_ind) zeros(1, row_size - this_len) ];
  bm_stereo_cropped.z(i,:) = [ bm_stereo.z(i, valid_ind) zeros(1, row_size - this_len) ];

  if mod(i, 100) == 0
    disp(['Frame ' num2str(i) ' / ' num2str(length(bm_stereo.frame_number))]);
  end

end

%% align

disp('Aligning...');

% everything is loaded and we have two main variables:
% bm_stereo and stereo_octomap

% we want to compare the distances from pushbroom to bm

% align based on frame number

frame_diff = bm_stereo_cropped.frame_number(1) - stereo.frame_number(1);

stereo_start = 1;
stereo_end = length(stereo.frame_number) - 1;

bm_start = 1;
bm_end = length(bm_stereo_cropped.frame_number) - 1;

if (frame_diff > 0)
  stereo_start = frame_diff+1;
  bm_start = 1;

elseif (frame_diff < 0)

  stereo_start = 1;
  bm_start = -frame_diff+1;

end

end_diff = bm_stereo_cropped.frame_number(end) - stereo.frame_number(end);

if (end_diff > 0)

  bm_end = bm_end - end_diff;

else

  stereo_end = stereo_end + end_diff;

end

% ok everything is aligned now.
% now figure out where we want to look
bm_stereo_aligned.frame_number = bm_stereo_cropped.frame_number(bm_start:bm_end);
stereo_aligned.frame_number = stereo.frame_number(stereo_start:stereo_end);

diff_start2 = start_frame_pass(pass_number) - bm_stereo_aligned.frame_number(1);

if (diff_start2 < 0)
  error(['Requested start frame is earlier than we have data for (first frame is: ' num2str(bm_stereo_aligned.frame_number(1)) ').']);
else
  bm_start = bm_start + diff_start2;
  stereo_start = stereo_start + diff_start2;
end

diff_end2 = bm_stereo_aligned.frame_number(end) - end_frame_pass(pass_number);

if (diff_end2 < 0)
  error(['Requested end frame is later than we have data for (last frame is: ' num2str(bm_stereo_aligned.frame_number(end)) ').']);
else
  bm_end = bm_end - diff_end2;
  stereo_end = stereo_end - diff_end2;
end

bm_stereo_aligned.frame_number = bm_stereo_cropped.frame_number(bm_start:bm_end);
stereo_aligned.frame_number = stereo.frame_number(stereo_start:stereo_end);

bm_stereo_aligned.x = bm_stereo_cropped.x(bm_start:bm_end, :);
bm_stereo_aligned.y = bm_stereo_cropped.y(bm_start:bm_end, :);
bm_stereo_aligned.z = bm_stereo_cropped.z(bm_start:bm_end, :);

bm_stereo_aligned.utime = bm_stereo_cropped.utime(stereo_start:stereo_end);
bm_stereo_aligned.number_of_points = bm_stereo_cropped.number_of_points(stereo_start:stereo_end);
bm_stereo_aligned.video_number = bm_stereo_cropped.video_number(stereo_start:stereo_end);
bm_stereo_aligned.logtime = bm_stereo_cropped.logtime(stereo_start:stereo_end);

stereo_aligned.utime = stereo.utime(stereo_start:stereo_end);
stereo_aligned.number_of_points = stereo.number_of_points(stereo_start:stereo_end);
stereo_aligned.video_number = stereo.video_number(stereo_start:stereo_end);
stereo_aligned.logtime = stereo.logtime(stereo_start:stereo_end);

stereo_aligned.x = stereo.x(stereo_start:stereo_end, :);
stereo_aligned.y = stereo.y(stereo_start:stereo_end, :);
stereo_aligned.z = stereo.z(stereo_start:stereo_end, :);

bm_stereo_aligned.frame_number(1:5)
stereo_aligned.frame_number(1:5)

bm_stereo_aligned.frame_number(end-5:end)
stereo_aligned.frame_number(end-5:end)

%% process

%ComparePlot(bm_stereo_aligned, stereo_aligned);

distances = SmallestDistance(stereo_aligned.x, stereo_aligned.y, stereo_aligned.z, bm_stereo_aligned.x, bm_stereo_aligned.y, bm_stereo_aligned.z, 0, 100);
distances2 = SmallestDistance(bm_stereo_aligned.x, bm_stereo_aligned.y, bm_stereo_aligned.z, stereo_aligned.x, stereo_aligned.y, stereo_aligned.z, 0, 100);

real_dists = distances(find(distances));
real_dists2 = distances2(find(distances2));

%% plot
figure(1)
clf
hist(real_dists,0:.1:ceil(max(real_dists)));
xlabel('Minimum separation (meters)')
ylabel('Number of pixels')
title(strrep(filename, '_','-'));
xlim([-1 11]);
set(gca, 'XTickLabel',{'0','2','4','6','8','No Match'});
%ylim([0 500]);
grid on

if sum_false_pos == 1
  real_dists_array{pass_number} = real_dists;
end

figure(2)
clf
hist(real_dists2,0:.1:ceil(max(real_dists2)));
xlabel('Minimum separation (meters)')
ylabel('Number of pixels')
title(strrep(filename, '_','-'));
xlim([-1 11]);
set(gca, 'XTickLabel',{'0','2','4','6','8','No Match'});
%ylim([0 500]);
grid on

if sum_false_pos ~= 1
  real_dists_array{pass_number} = real_dists;
end

%% sum up

figure(sumfig)
real_sum = [];
for i = 1 : length(real_dists_array)
  real_sum = [real_sum; real_dists_array{i}];
end
hist(real_sum(:,1), 0:.1:ceil(max(real_sum(:,1))));
xlabel('Minimum separation (meters)')
ylabel('Number of pixels')

if doFalseNeg == 0
  title('')
else
  title('False Negative Check');
end

xlim([-1 11]);
set(gca, 'XTickLabel',{'0','2','4','6','8','No Match'});
%ylim([0 1500]);
grid on

%% compute statistics

% within 1 meter
one_meter = length(find(real_sum(:,1) < 1.0)) / length(real_sum(:,1));

disp([num2str(one_meter * 100) ' % within 1.0 meters'])

two_meters = length(find(real_sum(:,1) < 2.0)) / length(real_sum(:,1));

disp([num2str(two_meters * 100) ' % within 2.0 meters'])

five_meters = length(find(real_sum(:,1) >= 5.0)) / length(real_sum(:,1));

disp([num2str(five_meters * 100) ' % outside of 5.0 meters'])


text:
package org.tawja.maven.plugins.parallelexec;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.IOUtil;
import org.tawja.maven.plugins.parallelexec.executable.ExecutableDescriptor;
import org.tawja.maven.plugins.parallelexec.executable.FileProcessDescriptor;
import org.twdata.maven.mojoexecutor.MojoExecutor;

/**
 * Common properties for all maven goals related to ParallelExec. Additionnaly
 * manage all inputs needed for the execution (scan source files).
 *
 * @author Adam DUBIEL
 * @author Jaafar BENNANI-SMIRES
 */
public abstract class BaseMavenParallelExecMojo extends AbstractMojo {

    /**
     * Exec arguments.
     */
    @Parameter
    protected String[] arguments;

    /**
     * Exec checks, used to validate environnement variables.
     */
    @Parameter
    protected Map<String, String> checks;

    /**
     * Disable the execution
     */
    @Parameter(property = ParallelExecConstants.PROP_PREFIX + ".disabled", defaultValue = "false")
    protected boolean disabled;

    /**
     * Set the thread pool size
     */
    @Parameter(property = ParallelExecConstants.PROP_PREFIX + ".threadPoolSize")
    protected int threadPoolSize = 4;

    /**
     * Map of environment variables passed to npm install.
     */
    @Parameter
    protected Map<String, String> environmentVar;

    /**
     * Extention that will be used for Windows OS (will replace unix one if any)
     */
    @Parameter(property = ParallelExecConstants.PROP_PREFIX + ".windowsExtension")
    protected String windowsExtension;

    /**
     * Tells if output files are overwritten even if they are newer than input
     * files.
     */
    @Parameter(property = ParallelExecConstants.PROP_PREFIX + ".overwriteIfNewer", defaultValue = "false")
    protected Boolean overwriteIfNewer;

    /**
     * Defines which of the included files in the source directories to exclude
     * (non by default).
     */
    @Parameter
    protected String[] excludes;
    /**
     * Name of executable in PATH, defaults to ''.
     */
    @Parameter(property = ParallelExecConstants.PROP_PREFIX + ".executable", required = true)
    protected String executable;
    /**
     * File that will contains files list managed, defaults to
     * ${project.build.directory}/parallelexec-listfiles.txt.
     */
    @Parameter(property = ParallelExecConstants.PROP_PREFIX + ".fileListFile", defaultValue = "${project.build.directory}/parallelexec-listfiles.txt")
    protected File fileListFile;

    /**
     * Defines files in the source directories to include (all .java files by
     * default).
     */
    @Parameter(required = true)
    protected String[] includes;

    protected List<FileProcessDescriptor> fileProcessDescriptors = new ArrayList<>();
    protected List<ExecutableDescriptor> executableDescriptors = new ArrayList<>();

    /**
     * Access to Maven Project object
     */
    @Parameter(property = "project", readonly = true, required = true)
    protected MavenProject mavenProject;

    /**
     * Access to Maven Session object
     */
    @Parameter(property = "session", readonly = true, required = true)
    protected MavenSession mavenSession;
    /**
     * List of additional options passed to npm when calling install.
     */
    @Parameter(property = ParallelExecConstants.PROP_PREFIX + ".options")
    protected String[] options;
    /**
     * Inject building OS name.
     */
    @Parameter(defaultValue = "${os.name}")
    protected String osName;

    /**
     * Maven 2.x uncompatibility.
     */
    @Component
    protected BuildPluginManager pluginManager;

    /**
     * Path for source files directory (from where input files are seached),
     * defaults to ${basedir}/src/main/resources.
     */
    @Parameter(property = ParallelExecConstants.PROP_PREFIX + ".sourceDirectory", defaultValue = "${basedir}/src/main/resources")
    protected String sourceDirectory;

    /**
     * Path for target files directory (where ouput files will be put), defaults
     * to ${project.build.directory}/generrated-resources.
     */
    @Parameter(property = ParallelExecConstants.PROP_PREFIX + ".targetDirectory", defaultValue = "${project.build.directory}/generated-resources")
    protected String targetDirectory;

    /**
     * Extension for target files (ouput files type)
     */
    @Parameter(property = ParallelExecConstants.PROP_PREFIX + ".targetExtension")
    protected String targetExtension;

    /**
     * Path to working directory (from where to call the executable), defaults
     * to ${project.build.directory}.
     */
    @Parameter(property = ParallelExecConstants.PROP_PREFIX + ".workingDirectory", defaultValue = "${project.build.directory}")
    protected String workingDirectory;

    protected String basedir() {
        try {
            return mavenProject.getBasedir().getCanonicalPath();
        } catch (IOException exception) {
            throw new IllegalStateException("Could not extract basedir of project.", exception);
        }
    }

    /**
     * Main execution method. Childs should only override executeInternal()
     *
     * @throws org.apache.maven.plugin.MojoExecutionException
     * @throws org.apache.maven.plugin.MojoFailureException
     */
    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        final Log log = getLog();

        log.info("ParallelExe Information :");
        log.info("     - Executable = '" + executable + "'");
        log.info("     - WorkingDirectory = '" + workingDirectory + "'");
        log.info("     - SourceDirectory = '" + sourceDirectory + "'");
        log.info("     - TargetDirectory = '" + targetDirectory + "'");
        log.info("     - TargetDExtension = '" + targetExtension + "'");

        Boolean hasCheckErrors = checkInputs();

        if (hasCheckErrors) {
            throw new MojoFailureException("Execution stopped due to check errors.");
        }

        String rootDir = basedir();

        if (sourceDirectory != null && !sourceDirectory.isEmpty()) {
            try {
                rootDir = new File(sourceDirectory).getCanonicalPath();
            } catch (IOException exception) {
                throw new IllegalStateException("Could not extract sourceDirectory of project.", exception);
            }
        }

        initializeParameters();

        if (disabled) {
            getLog().info("Execution disabled using configuration option.");
            return;
        }

        BufferedWriter writer = null;
        try {
            fileListFile.getParentFile().mkdirs();
            writer = new BufferedWriter(new FileWriter(fileListFile));
        } catch (IOException e) {
            throw new MojoExecutionException("Could not open files list '" + fileListFile + "'", e);
        }
        scanFiles(new File(rootDir), writer);
        IOUtil.close(writer);

        executeInternal();
    }

    /**
     * Check all Inputs
     *
     * @return
     */
    protected Boolean checkInputs() {
        final Log log = getLog();
        Boolean hasErrors = false;

        // User defined checks
        if (checks != null && checks.size() > 0) {
            for (Entry<String, String> entrySet : checks.entrySet()) {
                String key = entrySet.getKey();
                String value = entrySet.getValue();
                if (value == null || value.isEmpty()) {
                    log.error("Check fails : " + key + " : Value not defined");
                    hasErrors = true;
                }
            }
        }

        return hasErrors;
    }

    /**
     * Simplified execution method. Used by childs.
     *
     * @throws org.apache.maven.plugin.MojoExecutionException
     * @throws org.apache.maven.plugin.MojoFailureException
     */
    protected abstract void executeInternal() throws MojoExecutionException, MojoFailureException;

    /**
     * Initialize parameters
     */
    private void initializeParameters() {
        // TODO : ...
    }

    /* TODO : Add in child mojos
     protected String fullTargetDirectory() {
     return basedir() + File.separator + targetDirectory;
     }
     */
    protected MojoExecutor.ExecutionEnvironment getPluginExecutionEnvironment() {
        MojoExecutor.ExecutionEnvironment environment;
        /*
         try {
         Object o = mavenSession.lookup("org.apache.maven.plugin.BuildPluginManager");
         environment = MojoExecutor.executionEnvironment(mavenProject, mavenSession, (BuildPluginManager) o);
         } catch (ComponentLookupException e) {
         environment = MojoExecutor.executionEnvironment(mavenProject, mavenSession, pluginManager);
         }
         */
        environment = MojoExecutor.executionEnvironment(mavenProject, mavenSession, pluginManager);
        return environment;
    }

    /**
     * Scans a single directory.
     *
     * @param root Directory to scan
     * @param writer Where to write the source list
     * @throws MojoExecutionException in case of IO errors
     */
    protected void scanFiles(File root, BufferedWriter writer) throws MojoExecutionException {
        final Log log = getLog();

        if (!root.exists()) {
            root.mkdirs();
        }

        log.info("Scanning source file directory '" + root + "'");

        final DirectoryScanner directoryScanner = new DirectoryScanner();
        directoryScanner.setIncludes(includes);
        directoryScanner.setExcludes(excludes);
        directoryScanner.setBasedir(root);
        directoryScanner.scan();

        for (String fileName : directoryScanner.getIncludedFiles()) {
            File inputFile = new File(root, fileName);
            FileProcessDescriptor fileProcessDesc = new FileProcessDescriptor(inputFile, sourceDirectory, targetDirectory, targetExtension);
            try {
                if (overwriteIfNewer
                        || (!overwriteIfNewer &&
                                fileProcessDesc.getInputFile().lastModified() > fileProcessDesc.getOutputFile().lastModified()
                        )
                    ) {
                    fileProcessDescriptors.add(fileProcessDesc);
                    writer.write(inputFile.getAbsolutePath());
                    writer.newLine();
                    log.info("Input file : " + inputFile);
                } else {
                    log.debug("Ignored Input file : " + inputFile);
                }
            } catch (Exception e) {
                throw new MojoExecutionException("IO error while writing files list", e);
            }
        }
    }
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'latest_stable'
require 'aruba/rspec'

Dir.glob(::File.expand_path('../support/*.rb', __FILE__)).each { |f| require_relative f }


text:
using System.Collections;
using System.Linq;
using DerConverter.Asn;
using DerConverter.Asn.KnownTypes;
using NUnit.Framework;

namespace DerConverter.Tests.Asn.KnownTypes
{
    [TestFixture]
    public class DerAsnBitStringTests : Base<DerAsnBitString, BitArray>
    {
        public DerAsnBitStringTests() : base(DerAsnIdentifiers.Primitive.BitString) { }

        [TestCase(new bool[0], 0x00)]
        [TestCase(new[] { false, true, false, true, true, true, false, false }, 0x00, 0x5C)]
        [TestCase(new[] { true, false, true, false, false, false, true, true, false, true }, 0x06, 0xA3, 0x40)]
        [TestCase(new[] { true, false, true, false, false, false, true, true, false, false, false }, 0x05, 0xA3, 0x00)]
        public void DecodeConstructor_ShouldDecodeCorrectly(bool[] expectedValue, params int[] rawData)
        {
            base.DecodeConstructor_ShouldDecodeCorrectly(new BitArray(expectedValue.Reverse().ToArray()), rawData);
        }

        [TestCase(new bool[0], 0x00)]
        [TestCase(new[] { false, true, false, true, true, true, false, false }, 0x00, 0x5C)]
        [TestCase(new[] { true, false, true, false, false, false, true, true, false, true }, 0x06, 0xA3, 0x40)]
        [TestCase(new[] { true, false, true, false, false, false, true, true, false, false, false }, 0x05, 0xA3, 0x00)]
        public void Encode_ShouldEncodeCorrectly(bool[] value, params int[] expectedRawData)
        {
            base.Encode_ShouldEncodeCorrectly(new BitArray(value.Reverse().ToArray()), expectedRawData);
        }
    }
}


text:
@interface PNKGetNoteRequestTests : PNKRequestTestCase
@end

@implementation PNKGetNoteRequestTests

- (void)testGetNoteRequest
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"testGetNoteRequest"];
    [self insertCassetteNamed:@"Notes/GetNoteRequest"];

    NSString *identifier = @"c2f024f1eda0f199bfca";
    PNKGetNoteRequest *request = [[PNKGetNoteRequest alloc] initWithIdentifier:identifier];
    request.completionHandler = ^(PNKNote *note, NSError *error) {
        XCTAssertNotNil(note);
        XCTAssertNil(error);

        [expectation fulfill];
    };
    [self.client performRequest:request];

    [self waitForExpectations:@[expectation] timeout:5.0];
}

- (void)testGetNoteRequestInvalidIdentifier
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"testGetNoteRequestInvalidIdentifier"];
    [self insertCassetteNamed:@"Notes/GetNoteRequestInvalidIdentifier"];

    NSString *identifier = @"invalid-identifier";
    PNKGetNoteRequest *request = [[PNKGetNoteRequest alloc] initWithIdentifier:identifier];
    request.completionHandler = ^(PNKNote *note, NSError *error) {
        XCTAssertNil(note);
        XCTAssertNotNil(error);

        [expectation fulfill];
    };
    [self.client performRequest:request];

    [self waitForExpectations:@[expectation] timeout:5.0];
}

@end


text:
First, make sure you know about Python's generators and `yield` keyword.
If you don't, learn it on Google.

#### Write a Source DataFlow

There are several existing DataFlow, e.g. [ImageFromFile](../../modules/dataflow.html#tensorpack.dataflow.ImageFromFile),
[DataFromList](../../modules/dataflow.html#tensorpack.dataflow.DataFromList),
which you can use if your data format is simple.
In general, you probably need to write a source DataFlow to produce data for your task,
and then compose it with other DataFlow (e.g. mapping, batching, prefetching, ...).

The easiest way to create a DataFlow to load custom data, is to wrap a custom generator, e.g.:
```python
def my_data_loader():
  # load data from somewhere with Python, and yield them
  for k in range(100):
    yield [my_array, my_label]

df = DataFromGenerator(my_data_loader)
```

To write more complicated DataFlow, you need to inherit the base `DataFlow` class.
Usually, you just need to implement the `__iter__()` method which yields a datapoint every time.
```python
class MyDataFlow(DataFlow):
  def __iter__(self):
    # load data from somewhere with Python, and yield them
    for k in range(100):
      digit = np.random.rand(28, 28)
      label = np.random.randint(10)
      yield [digit, label]

df = MyDataFlow()
df.reset_state()
for datapoint in df:
    print(datapoint[0], datapoint[1])
```

Optionally, you can implement the `__len__` and `reset_state` method.
The detailed semantics of these three methods are explained
in the [API documentation](../../modules/dataflow.html#tensorpack.dataflow.DataFlow).
If you're writing a complicated DataFlow, make sure to read the API documentation
for the semantics.

DataFlow implementations for several well-known datasets are provided in the
[dataflow.dataset](../../modules/dataflow.dataset.html)
module. You can take them as examples.

#### More Data Processing

You can put any data processing you need in the source DataFlow you write, or you can write a new DataFlow for data
processing on top of the source DataFlow, e.g.:

```python
class ProcessingDataFlow(DataFlow):
  def __init__(self, ds):
    self.ds = ds

  def reset_state(self):
    self.ds.reset_state()

  def __iter__(self):
    for datapoint in self.ds:
      # do something
      yield new_datapoint
```

Some built-in dataflows, e.g.
[MapData](../../modules/dataflow.html#tensorpack.dataflow.MapData) and
[MapDataComponent](../../modules/dataflow.html#tensorpack.dataflow.MapDataComponent)
can do common types of data processing for you.


text:
package org.mitre.web;

import java.security.Principal;
import java.util.Locale;
import java.util.Set;

import javax.annotation.Resource;

import org.mitre.openid.connect.client.OIDCAuthenticationFilter;
import org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	// filter reference so we can get class names and things like that.
	@Autowired
	private OIDCAuthenticationFilter filter;

	@Resource(name = "namedAdmins")
	private Set<SubjectIssuerGrantedAuthority> admins;

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model, Principal p) {

		model.addAttribute("issuerServiceClass", filter.getIssuerService().getClass().getSimpleName());
		model.addAttribute("serverConfigurationServiceClass", filter.getServerConfigurationService().getClass().getSimpleName());
		model.addAttribute("clientConfigurationServiceClass", filter.getClientConfigurationService().getClass().getSimpleName());
		model.addAttribute("authRequestOptionsServiceClass", filter.getAuthRequestOptionsService().getClass().getSimpleName());
		model.addAttribute("authRequestUriBuilderClass", filter.getAuthRequestUrlBuilder().getClass().getSimpleName());

		model.addAttribute("admins", admins);

		return "home";
	}

	@RequestMapping("/user")
	@PreAuthorize("hasRole('ROLE_USER')")
	public String user(Principal p) {
		return "user";
	}

	@RequestMapping("/open")
	public String open(Principal p) {
		return "open";
	}

	@RequestMapping("/admin")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public String admin(Model model, Principal p) {

		model.addAttribute("admins", admins);

		return "admin";
	}

	@RequestMapping("/login")
	public String login(Principal p) {
		return "login";
	}

}


text:
title: "Group 6"
client: "The Fridge - Custom"
members: "Izzy Wickerham & Hayley Kishton"
layout: group
link: TBD
livelink: TBD
description: "It's all about the hops man!  At Hops House, we craft the tastiest of brews every week that will keep you coming back for more.  Our brews can only be found at Hops House, and our modern, chill environment is perfect for after-work drinks or a night out on the town."
class: hallahan
semester: fall-2018
date: 2016-7-19 12:00:00
number: 6
##pm: "../pm/group9.pdf"
---


text:
app.controller('loginController', function($rootScope, $scope, $http, $location, session, validation){
  console.log('[loginController.js] - loginController - Scope is up');
  $scope.user = {username:'', password:''};
  // Login method

  $scope.login = function() {
    var res = validation.checkLogin($scope.user);
    if (res.valid == false) {
      $scope.errorMessage = res.message;
      return;
    }
  	$http.post('/auth/signin', $scope.user).success(function(data){
  		if (data.state == 'success') {
        // Public accessible data from the back-end
        $rootScope.authenticatedUser.username = data.user.public.email;
        $rootScope.authenticatedUser.company = data.user.public.company;
        $rootScope.authenticatedUser.type = data.user.public.type;
        $rootScope.authenticatedUser.picture = data.user.public.picture;
        // Additional field
        $rootScope.authenticatedUser.authStatus = true;
        $rootScope.authenticatedUser.id = data.user._id;
        session.saveToSession($rootScope);
        $location.path('/');
      } else {
        $scope.errorMessage = data.message;
      }
  	});
  }
});


text:
<?php

$this->tag['name'] = $this->name;
$this->tag['repeater_name'] = $this->repeater_name;

if( !is_null($this->user_value) )
{
	$this->tag['user_value'] = $this->user_value;
}

$tag = '';

switch( $this->tag['type'] )
{
	case 'repeater':
		#can't nest repeaters right now
		break;
	case 'select':
		echo $this->partial('form/repeater_vertical/select', [ 'tag' => $this->tag ] );
		break;
	case 'textarea':
		echo $this->partial('form/repeater_vertical/textarea', [ 'tag' => $this->tag ] );
		break;
	default:
		echo $this->partial('form/repeater_vertical/input', [ 'tag' => $this->tag ] );
		break;
}


text:
#region License

#endregion
using System.Collections.Generic;
using System.IO;
namespace System.Abstract.Parts
{
    /// <summary>
    /// ITypeSerializer
    /// </summary>
    public interface ITypeSerializer
    {
        /// <summary>
        /// Reads the object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type">The type.</param>
        /// <param name="s">The s.</param>
        /// <returns></returns>
        T ReadObject<T>(Type type, Stream s)
            where T : class;
        /// <summary>
        /// Reads the objects.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type">The type.</param>
        /// <param name="s">The s.</param>
        /// <returns></returns>
        IEnumerable<T> ReadObjects<T>(Type type, Stream s)
            where T : class;
        /// <summary>
        /// Writes the object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type">The type.</param>
        /// <param name="s">The s.</param>
        /// <param name="graph">The graph.</param>
        void WriteObject<T>(Type type, Stream s, T graph)
            where T : class;
        /// <summary>
        /// Writes the objects.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type">The type.</param>
        /// <param name="s">The s.</param>
        /// <param name="graph">The graph.</param>
        void WriteObjects<T>(Type type, Stream s, IEnumerable<T> graph)
            where T : class;
    }
}


text:
import argparse
import base64
import datetime
import hashlib
import hmac
import json
import os
import re
import socket
import time
import urllib
import urllib2

try:
    from elasticsearch import Elasticsearch
    from elasticsearch.exceptions import NotFoundError
    from elasticsearch.helpers import bulk
except ImportError:
    print(
        "It look like elasticsearch-py isn't installed. Please install it"
        "using pip install elasticsearch>=1.0.0,<2.0.0 or pip install "
        "elasticsearch<1.0.0. "
        "See http://elasticsearch-py.readthedocs.org/en/latest/ for more info"
    )
try:
    from raven import Client
except ImportError:
    Client = None
    pass

def main():
    parser = argparse.ArgumentParser(
        description=(
            "This script connect to cloudstack API, list all vms"
            "with details and add  document for each VM in a given ES"
            " cluster index"
        )
    )
    parser.add_argument(
        "-version",
        action="version",
        version="%(prog)s 1.0, Loic Lambiel exoscale",
    )
    parser.add_argument(
        "-acsurl",
        help="Cloudstack API URL",
        required=True,
        type=str,
        dest="acsurl",
    )
    parser.add_argument(
        "-acskey",
        help="Cloudstack API user key",
        required=True,
        type=str,
        dest="acskey",
    )
    parser.add_argument(
        "-acssecret",
        help="Cloudstack API user secret",
        required=True,
        type=str,
        dest="acssecret",
    )
    parser.add_argument(
        "-esindex",
        help="ES index name",
        required=True,
        type=str,
        dest="esindex",
    )
    parser.add_argument(
        "-esnodes",
        help="ES nodes list space separated",
        required=True,
        type=str,
        dest="esnodes",
    )
    if Client is not None:
        parser.add_argument(
            "-sentryapikey",
            help="Sentry API key",
            required=False,
            type=str,
            dest="sentryapikey",
        )
    args = vars(parser.parse_args())
    return args

class BaseClient(object):
    def __init__(self, api, apikey, secret):
        self.api = api
        self.apikey = apikey
        self.secret = secret

    def request(self, command, args):
        args["apikey"] = self.apikey
        args["command"] = command
        args["response"] = "json"

        params = []

        keys = sorted(args.keys())

        for k in keys:
            params.append(
                k + "=" + urllib.quote_plus(args[k]).replace("+", "%20")
            )

        query = "&".join(params)

        signature = base64.b64encode(
            hmac.new(
                self.secret, msg=query.lower(), digestmod=hashlib.sha1
            ).digest()
        )

        query += "&signature=" + urllib.quote_plus(signature)

        response = urllib2.urlopen(self.api + "?" + query)
        decoded = json.loads(response.read())

        propertyResponse = command.lower() + "response"
        if propertyResponse not in decoded:
            if "errorresponse" in decoded:
                raise RuntimeError(
                    "ERROR: " + decoded["errorresponse"]["errortext"]
                )
            else:
                raise RuntimeError("ERROR: Unable to parse the response")

        response = decoded[propertyResponse]
        result = re.compile(r"^list(\w+)s").match(command.lower())

        if result is not None:
            type = result.group(1)

            if type in response:
                return response[type]
            else:
                # sometimes, the 's' is kept, as in :
                # { "listasyncjobsresponse" : { "asyncjobs" : [ ... ] } }
                type += "s"
                if type in response:
                    return response[type]

        return response

    def listVirtualMachines(self, args=None):
        if args is None:
            args = {}
        return self.request("listVirtualMachines", args)

def get_stats(args):

    ACSURL = args["acsurl"]
    ACSKEY = args["acskey"]
    ACSSECRET = args["acssecret"]
    esindex = args["esindex"]
    esnodes = args["esnodes"]

    DOCTYPE = "acs-instancereport"

    now = time.strftime("%Y.%m.%d")
    esindex = esindex + "-" + now

    # collect number of virtual machines
    cloudstack = BaseClient(ACSURL, ACSKEY, ACSSECRET)

    query_tmp = None
    querypage = 1
    querypagesize = 500
    virtualmachines = cloudstack.listVirtualMachines(
        {
            "listall": "true",
            "details": "all",
            "page": str(querypage),
            "pagesize": str(querypagesize),
        }
    )
    all_virtualmachines = []
    if len(virtualmachines) == querypagesize:
        query_tmp = virtualmachines
        while len(query_tmp) > 1:
            all_virtualmachines.extend(query_tmp)
            querypage = querypage + 1
            query_tmp = cloudstack.listVirtualMachines(
                {
                    "listall": "true",
                    "details": "all",
                    "page": str(querypage),
                    "pagesize": str(querypagesize),
                }
            )
    else:
        all_virtualmachines.extend(virtualmachines)
    virtualmachines = all_virtualmachines

    ESCLUSTERNODES = esnodes.split()
    es = Elasticsearch(ESCLUSTERNODES)
    scriptpath = os.path.realpath(__file__)

    timestamp = datetime.datetime.now()
    try:
        es.indices.get(index=esindex)
    except NotFoundError:
        # create indexe
        es.indices.create(index=esindex)
        # create ES mappings
        es.indices.put_mapping(
            index=esindex,
            doc_type=DOCTYPE,
            body={
                DOCTYPE: {
                    "properties": {
                        "account": {"type": "text"},
                        "id": {"type": "text"},
                        "state": {"type": "keyword"},
                        "cpunumber": {"type": "text"},
                        "displayname": {"type": "keyword"},
                        "hostname": {"type": "keyword"},
                        "instancename": {"type": "keyword"},
                        "memory": {"type": "text"},
                        "name": {"type": "keyword"},
                        "serviceofferingid": {"type": "text"},
                        "serviceofferingname": {"type": "text"},
                        "templateid": {"type": "text"},
                        "templatedisplaytext": {"type": "text"},
                        "zoneid": {"type": "text"},
                        "zonename": {"type": "keyword"},
                        "ipaddress": {"type": "text"},
                        "macaddress": {"type": "text"},
                        "securitygroupid": {"type": "text"},
                        "securitygroupname": {"type": "text"},
                        "@source_host": {"type": "text"},
                        "@source": {"type": "text"},
                        "@source_path": {"type": "text"},
                        "@type": {"type": "text"},
                        "@message": {"type": "text"},
                        "@timestamp": {"type": "date"},
                    }
                }
            },
            include_type_name=True,
        )
    except Exception as e:
        raise ValueError("Error while creating index: " + e)
    # create ES document
    if virtualmachines:
        records = []
        for virtualmachine in virtualmachines:
            vmaccount = virtualmachine["account"]
            vmid = virtualmachine["id"]
            vmstate = virtualmachine["state"]
            vmcpunumber = virtualmachine["cpunumber"]
            if "displayname" in virtualmachine:
                vmdisplayname = virtualmachine["displayname"]
            else:
                vmdisplayname = ""
            if virtualmachine["state"] == "Running":
                vmhostname = virtualmachine["hostname"]
            else:
                vmhostname = ""
            vminstancename = virtualmachine["instancename"]
            vmmemory = virtualmachine["memory"]
            vmname = virtualmachine["name"]
            vmserviceofferingid = virtualmachine["serviceofferingid"]
            vmserviceofferingname = virtualmachine["serviceofferingname"]
            vmtemplateid = virtualmachine["templateid"]
            try:
                vmtemplatedisplaytext = virtualmachine["templatedisplaytext"]
            except KeyError:
                vmtemplatedisplaytext = "Not found"
            vmzoneid = virtualmachine["zoneid"]
            vmzonename = virtualmachine["zonename"]
            vmipaddress = []
            vmmacaddress = ""
            for nic in virtualmachine["nic"]:
                if "ipaddress" in nic:
                    vmipaddress.append(nic["ipaddress"])
                if "macaddress" in nic:
                    vmmacaddress = nic["macaddress"]
                if "secondaryip" in nic:
                    for secondaryips in nic["secondaryip"]:
                        vmipaddress.append(secondaryips["ipaddress"])
            vmipaddress = [str(r) for r in vmipaddress]
            vmipaddress = str(vmipaddress).replace("'", "").strip("[]")
            for securitygroup in virtualmachine["securitygroup"]:
                vmsecuritygroupid = securitygroup["id"]
                vmsecuritygroupname = securitygroup["name"]
            sourcehost = socket.gethostname()
            # body
            doc = {
                "account": vmaccount,
                "id": vmid,
                "state": vmstate,
                "cpunumber": vmcpunumber,
                "displayname": vmdisplayname,
                "hostname": vmhostname,
                "instancename": vminstancename,
                "memory": vmmemory,
                "name": vmname,
                "serviceofferingid": vmserviceofferingid,
                "serviceofferingname": vmserviceofferingname,
                "templateid": vmtemplateid,
                "templatedisplaytext": vmtemplatedisplaytext,
                "zoneid": vmzoneid,
                "zonename": vmzonename,
                "ipaddress": vmipaddress,
                "macaddress": vmmacaddress,
                "securitygroupid": vmsecuritygroupid,
                "securitygroupname": vmsecuritygroupname,
                "@source_host": sourcehost,
                "@source_path": scriptpath,
                "@source": scriptpath,
                "@type": "ACS-instancereport",
                "@message": "ACS instance report for vm %s" % vmid,
                "@timestamp": timestamp,
            }
            records.append(doc)

        # index documents
        bulk(es, records, index=esindex, doc_type=DOCTYPE)

# main
if __name__ == "__main__":
    args = main()
    try:
        get_stats(args)
    except Exception:
        if args["sentryapikey"] is None:
            raise
        else:
            client = Client(dsn=args["sentryapikey"])
            client.captureException()


text:
<? defined('C5_EXECUTE') or die("Access Denied.");?>

<? if ($controller->getTask() == 'add'
    || $controller->getTask() == 'add_link'
    || $controller->getTask() == 'edit'
    || $controller->getTask() == 'edit_link'
    || $controller->getTask() == 'delete_link') {

    $url = '';
    $ssHandle = '';
    $action = $view->action('add_link');
    $token = 'add_link';
    $buttonText = t('Add');
    if (is_object($link)) {
        $url = $link->getURL();
        $ssHandle = $link->getServiceHandle();
        $action = $view->action('edit_link', $link->getID());
        $token = 'edit_link';
        $buttonText = t('Save');
    }
    ?>

    <? if (is_object($link)) { ?>

            <button data-dialog="delete-link" class="btn btn-danger"><?php echo t("Delete Link")?></button>

            <form method="post" class="form-stacked" action="<?=$view->action('delete_link')?>">
                <?=Loader::helper("validation/token")->output('delete_link')?>
                <input type="hidden" name="slID" value="<?=$link->getID()?>" />

<?=t('Are you sure? This action cannot be undone.')?>

            </form>

                <button class="btn btn-default pull-left" onclick="jQuery.fn.dialog.closeTop()"><?=t('Cancel')?></button>
                <button class="btn btn-danger pull-right" onclick="$('#ccm-dialog-delete-social-link form').submit()"><?=t('Delete Link')?></button>

    <? } ?>

    <form method="post" class="form-horizontal" action="<?=$action?>">
        <?=$this->controller->token->output($token)?>

            <?=$form->label('ssHandle', t('Service'), array('class' => 'col-md-2'))?>

            <?=$form->select('ssHandle', $services, $ssHandle)?>

            <?=$form->label('url', t('URL'), array('class' => 'col-md-2'))?>

                <?=$form->text('url', $url)?>

                <a href="<?=URL::to('/dashboard/system/basics/social')?>" class="btn btn-default pull-left"><?=t("Cancel")?>
                <button class="pull-right btn btn-success" type="submit" ><?=$buttonText?></button>

    </form>
<? } else { ?>

        <a href="<?php echo View::url('/dashboard/system/basics/social', 'add')?>" class="btn btn-primary"><?php echo t("Add Link")?>

    <? if (count($links) > 0) { ?>

        <? foreach($links as $link) {
            $service = $link->getServiceObject(); ?>

            <?=$service->getServiceIconHTML()?>
            <a href="<?=$view->action('edit', $link->getID())?>"><?=$service->getName()?>
            <?=$link->getURL()?>

        <? } ?>

    <? } else { ?>

<?=t("You have not added any social links.")?>

    <? } ?>

<? } ?>


text:
import React from 'react';
import {  Icon, Tag, Button, Switch, Tooltip   } from 'antd';

class CarService extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
    	return (

				<ServiceItem />

    	);

    }
}

class ServiceItem extends React.Component{
	constructor(props) {
        super(props);
    }

    onChange = (checked) => console.log(`switch to ${checked}`);

    render(){
    	return (

    					旅行租车险
    					<Tooltip title="保全车意外医疗、物品损失,提供紧急救援服务">
    						<Icon type="question-circle" />
  						</Tooltip>
    					¥400

    				<Switch className='switch'  defaultChecked={false} onChange={this.onChange} />

    	);
    }
}

export default CarService;


text:
import cx from 'classnames'
import * as React from 'react'
import * as redux from 'react-redux'
import * as M from '@material-ui/core'

// import Message from 'components/Message'
import SelectDropdown from 'components/SelectDropdown'
import { tokens as tokensSelector } from 'containers/Auth/selectors'
import * as AWS from 'utils/AWS'
import * as Config from 'utils/Config'

export * from './Meta'

// TODO: move here everything that's reused btw Bucket/File, Bucket/PackageTree and Embed/File

const useAdaptiveButtonStyles = M.makeStyles((t) => ({
  root: {
    flexShrink: 0,
    marginBottom: -3,
    marginTop: -3,
  },
  label: {
    marginRight: t.spacing(1),
  },
}))

export function AdaptiveButtonLayout({ className, label, icon, ...props }) {
  const classes = useAdaptiveButtonStyles()
  const t = M.useTheme()
  const sm = M.useMediaQuery(t.breakpoints.down('sm'))

  return sm ? (
    <M.IconButton
      className={cx(classes.root, className)}
      edge="end"
      size="small"
      {...props}
    >
      <M.Icon>{icon}</M.Icon>
    </M.IconButton>
  ) : (
    <M.Button
      className={cx(classes.root, className)}
      variant="outlined"
      size="small"
      startIcon={<M.Icon>{icon}</M.Icon>}
      {...props}
    >
      {label}
    </M.Button>
  )
}

export function DownloadButton({ className, handle }) {
  return AWS.Signer.withDownloadUrl(handle, (url) => (
    <AdaptiveButtonLayout
      className={className}
      href={url}
      download
      label="Download file"
      icon="arrow_downward"
    />
  ))
}

export function ViewModeSelector({ className, ...props }) {
  const classes = useAdaptiveButtonStyles()
  const t = M.useTheme()
  const sm = M.useMediaQuery(t.breakpoints.down('sm'))
  return (
    <SelectDropdown className={cx(classes.root, className)} {...props}>
      {sm ? <M.Icon>visibility</M.Icon> : View as:}
    </SelectDropdown>
  )
}

export function ZipDownloadForm({ className, suffix, label, newTab = false }) {
  const { s3Proxy, noDownload } = Config.use()
  const { token } = redux.useSelector(tokensSelector) || {}
  if (!token || noDownload) return null
  const action = `${s3Proxy}/zip/${suffix}`
  return (
    <form
      action={action}
      target={newTab ? '_blank' : undefined}
      method="POST"
      style={{ flexShrink: 0 }}
    >
      <input type="hidden" name="token" value={token} />
      <AdaptiveButtonLayout
        className={className}
        label={label}
        icon="archive"
        type="submit"
      />
    </form>
  )
}

export function Root(props) {
  return <M.Box pt={2} pb={4} {...props} />
}

/*
export function Header() {
}

export function TopBar() {
}

export function GlobalProgress() {
}

export function GlobalError(props) {
  return <Message {...props} />
}

const renderDownload = (handle) => !!handle && <DownloadButton {...{ handle }} />

function FileView({
  header,
  subheader,
}) {
  return (
    <Root>
      {header}
      <TopBar>
        {subheader}
        'spacer'
        {withDownloadData(renderDownload)}
      </TopBar>
      {withFileData(AsyncResult.case({
        //_: () => <GlobalProgress />,
        _: renderFileProgress,
        // TODO: use proper err msgs
        //Err: (e) => <GlobalError />,
        Err: renderFileErr,
        Ok: () => (
          <>
            {withCodeData(renderCode)}
            {withAnalyticsData(renderAnalytics)}
            {withPreviewData(renderPreview)}
            {withMetaData(renderMeta)}
          </>
        ),
      }))}
    </Root>
  )
}
*/


text:
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import * as Path from 'path'

import { ipcRenderer, remote } from 'electron'

import { App } from './app'
import { Dispatcher, AppStore, GitHubUserStore, GitHubUserDatabase, CloningRepositoriesStore, EmojiStore } from '../lib/dispatcher'
import { URLActionType } from '../lib/parse-url'
import { SelectionType } from '../lib/app-state'
import { ErrorWithMetadata } from '../lib/error-with-metadata'
import { reportError } from './lib/exception-reporting'
import { StatsDatabase, StatsStore } from '../lib/stats'
import { IssuesDatabase, IssuesStore, SignInStore } from '../lib/dispatcher'
import {
  defaultErrorHandler,
  createMissingRepositoryHandler,
  backgroundTaskHandler,
  unhandledExceptionHandler,
} from '../lib/dispatcher'
import { logError } from '../lib/logging/renderer'
import { installDevGlobals } from './install-globals'

if (__DEV__) {
  installDevGlobals()
}

// Tell dugite where to find the git environment,
// see https://github.com/desktop/dugite/pull/85
process.env['LOCAL_GIT_DIRECTORY'] = Path.resolve(__dirname, 'git')

// We're using a polyfill for the upcoming CSS4 `:focus-ring` pseudo-selector.
// This allows us to not have to override default accessibility driven focus
// styles for buttons in the case when a user clicks on a button. This also
// gives better visiblity to individuals who navigate with the keyboard.
//
// See:
//   https://github.com/WICG/focus-ring
//   Focus Ring! -- A11ycasts #16: https://youtu.be/ilj2P5-5CjI
require('wicg-focus-ring')

const startTime = Date.now()

if (!process.env.TEST_ENV) {
  /* This is the magic trigger for webpack to go compile
  * our sass into css and inject it into the DOM. */
  require('../../styles/desktop.scss')
}

process.once('uncaughtException', (error: Error) => {
  reportError(error)
  logError('Uncaught exception on renderer process', error)
  postUnhandledError(error)
})

const gitHubUserStore = new GitHubUserStore(new GitHubUserDatabase('GitHubUserDatabase'))
const cloningRepositoriesStore = new CloningRepositoriesStore()
const emojiStore = new EmojiStore()
const issuesStore = new IssuesStore(new IssuesDatabase('IssuesDatabase'))
const statsStore = new StatsStore(new StatsDatabase('StatsDatabase'))
const signInStore = new SignInStore()

const appStore = new AppStore(
  gitHubUserStore,
  cloningRepositoriesStore,
  emojiStore,
  issuesStore,
  statsStore,
  signInStore,
)

const dispatcher = new Dispatcher(appStore)

function postUnhandledError(error: Error) {
  dispatcher.postError(new ErrorWithMetadata(error, { uncaught: true }))
}

// NOTE: we consider all main-process-exceptions coming through here to be unhandled
ipcRenderer.on('main-process-exception', (event: Electron.IpcRendererEvent, error: Error) => {
  reportError(error)
  postUnhandledError(error)
})

dispatcher.registerErrorHandler(defaultErrorHandler)
dispatcher.registerErrorHandler(backgroundTaskHandler)
dispatcher.registerErrorHandler(createMissingRepositoryHandler(appStore))
dispatcher.registerErrorHandler(unhandledExceptionHandler)

document.body.classList.add(`platform-${process.platform}`)

dispatcher.setAppFocusState(remote.getCurrentWindow().isFocused())

ipcRenderer.on('focus', () => {
  const state = appStore.getState().selectedState
  if (!state || state.type !== SelectionType.Repository) { return }

  dispatcher.setAppFocusState(true)
  dispatcher.refreshRepository(state.repository)
})

ipcRenderer.on('blur', () => {
  // Make sure we stop highlighting the menu button (on non-macOS)
  // when someone uses Alt+Tab to switch application since we won't
  // get the onKeyUp event for the Alt key in that case.
  dispatcher.setAccessKeyHighlightState(false)
  dispatcher.setAppFocusState(false)
})

ipcRenderer.on('url-action', (event: Electron.IpcRendererEvent, { action }: { action: URLActionType }) => {
  dispatcher.dispatchURLAction(action)
})

ReactDOM.render(
  <App dispatcher={dispatcher} appStore={appStore} startTime={startTime}/>,
  document.getElementById('desktop-app-container')!,
)