text:
require('css/registrations.css');

var $ = require('jquery');
var ko = require('knockout');
var Raven = require('raven-js');
var bootbox = require('bootbox');
var moment = require('moment');
var History = require('exports?History!history');

require('js/koHelpers');

var $osf = require('js/osfHelpers');
var osfLanguage = require('js/osfLanguage');
var SUPPORT_LINK = osfLanguage.SUPPORT_LINK;
var language = osfLanguage.registrations;

var SaveManager = require('js/saveManager');
var editorExtensions = require('js/registrationEditorExtensions');
var RegistrationModal = require('js/registrationModal');

// This value should match website.settings.DRAFT_REGISTRATION_APPROVAL_PERIOD
var DRAFT_REGISTRATION_MIN_EMBARGO_DAYS = 10;
var DRAFT_REGISTRATION_MIN_EMBARGO_TIMESTAMP = new Date().getTime() + (
        DRAFT_REGISTRATION_MIN_EMBARGO_DAYS * 24 * 60 * 60 * 1000
);

/**
 * @class Comment
 * Model for storing/editing/deleting comments on form fields
 *
 * @param {Object} data: optional data to instatiate model with
 * @param {User} data.user
 * @param {Date string} data.lastModified
 * @param {Date string} data.created
 * @param {Boolean} data.isDeleted
 * @param {String} data.value
 *
 * @type User
 * @property {String} id
 * @property {String} fullname
 **/
function Comment(data) {
    var self = this;

    self.saved = ko.observable(data ? true : false);

    data = data || {};
    self.user = data.user || $osf.currentUser();
    self.value = ko.observable(data.value || '');
    self.value.subscribe(function() {
        self.lastModified = new Date();
    });

    self.created = data.created ? new Date(data.created) : new Date();
    self.lastModified = data.lastModified ? new Date(data.lastModified) : new Date();

    self.isDeleted = ko.observable(data.isDeleted || false);
    self.isDeleted.subscribe(function(isDeleted) {
        if (isDeleted) {
            self.value('');
        }
    });

    self.seenBy = ko.observableArray([self.user.id]);

    /**
     * Returns true if the current user is the comment owner
     **/
    self.isOwner = ko.pureComputed(function() {
        return self.user.id === $osf.currentUser().id;
    });

    /**
     * Returns the author as the actual user, not 'You'
     **/
    self.author = ko.pureComputed(function() {
        return self.user.fullname;
    });

    /**
     * Returns 'You' if the current user is the commenter, else the commenter's name
     */
    self.getAuthor = ko.pureComputed(function() {
        if (self.isOwner()) {
            return 'You';
        } else {
            return self.user.fullname;
        }
    });

    /**
     * Returns true if the current user is the comment creator
     **/
    self.canDelete = ko.pureComputed(function() {
        return self.isOwner();
    });

    /**
     * Returns true if the comment is saved and the current user is the comment creator
     **/
    self.canEdit = ko.pureComputed(function() {
        return !self.isDeleted() && self.saved() && self.isOwner();
    });
}
/** Toggle the comment's save state **/
Comment.prototype.toggleSaved = function(save) {
    var self = this;

    if (!self.saved()) {
        // error handling handled implicitly in save
        save().done(self.saved.bind(self, true));
    }
    else {
        self.saved(false);
    }
};
/** Indicate that a comment is deleted **/
Comment.prototype.delete = function(save) {
    var self = this;
    self.isDeleted(true);
    save();
};
/** Indicate that a user has seen a comment **/
Comment.prototype.viewComment = function(user) {
    if (this.seenBy.indexOf(user.id) === -1) {
        this.seenBy.push(user.id);
    }
};

/**
 * @class Question
 * Model for schema questions
 *
 * @param {Object} questionSchema
 * @param {String} questionSchema.title
 * @param {String} questionSchema.nav: short version of title
 * @param {String} questionSchema.type: 'string' | 'number' | 'choose' | 'object'; data type
 * @param {String} questionSchema.format: 'text' | 'textarea' | 'list'; format corresponding with data.type
 * @param {String} questionSchema.description
 * @param {String} questionSchema.help
 * @param {String} questionSchema.required
 * @param {String[]} questionSchema.options: array of options for 'choose' types
 * @param {Object[]} questionSchema.properties: object of sub-Question properties for 'object' types
 * @param {String} questionSchema.match: optional string that must be matched
 * @param {Object} data
 * @param {Any} data.value
 * @param {Array[Object]} data.comments
 * @param {Object} data.extra
 **/
var Question = function(questionSchema, data) {
    var self = this;

    self.data = data || {};

    self.id = questionSchema.qid;
    self.title = questionSchema.title || 'Untitled';
    self.nav = questionSchema.nav || 'Untitled';
    self.type = questionSchema.type || 'string';
    self.format = questionSchema.format || 'text';
    self.required = questionSchema.required || false;
    self.description = questionSchema.description || '';
    self.help = questionSchema.help;
    self.options = questionSchema.options || [];
    self.properties = questionSchema.properties || [];
    self.match = questionSchema.match || '';

    self.extra = ko.observable(self.data.extra || {});
    self.showExample = ko.observable(false);

    self.comments = ko.observableArray(
        $.map(self.data.comments || [], function(comment) {
            return new Comment(comment);
        })
    );
    self.nextComment = ko.observable('');

    var value;
    if (ko.isObservable(self.data.value)) {
        value = self.data.value();
    } else {
        value = self.data.value || null;
    }

    if (self.type === 'choose' && self.format === 'multiselect') {
        if (value) {
            if(!$.isArray(value)) {
                value = [value];
            }
            self.value = ko.observableArray(value);
        }
        else {
            self.value = ko.observableArray([]);
        }
    }
    else if (self.type === 'object') {
        $.each(self.properties, function(index, field) {
            field.qid = field.id;
            var subData = self.data.value ? self.data.value[field.id] : {};
            self.properties[index] = new Question(field, subData);
        });
        self.value = ko.computed({
            read: function() {
                var compositeValue = {};
                $.each(
                    $.map(self.properties, function(prop) {
                        var ret = {};
                        ret[prop.id] = {
                            value: prop.value(),
                            comments: prop.comments(),
                            extra: prop.extra
                        };
                        return ret;
                    }),
                    $.extend.bind(null, compositeValue)
                );
                return compositeValue;
            },
            deferred: true
        });

        self.required = self.required || $osf.any(
            $.map(self.properties, function(prop) {
                return prop.required;
            })
        );
    }
    else {
        self.value = ko.observable(value);
    }

    if (self.required) {
        self.value.extend({
            required: true
        });
    } else {
        self.value.extend({
            required: false
        });
    }

    /**
     * @returns {Boolean} true if the nextComment <input> is not blank
     **/
    self.allowAddNext = ko.computed(function() {
        return (self.nextComment() || '').trim() !== '';
    });

    /**
     * @returns {Boolean} true if either the question is not required (see logic above) or
     * the question value (or its required children's values) is not empty
     **/
    self.isComplete = ko.computed({
        read: function() {
            if (self.type === 'object') {
                var ret = true;
                $.each(self.properties, function(_, subQuestion) {
                    var value = subQuestion.value();
                    if (subQuestion.required && !(Boolean(value === true || (value && value.length)))) {
                        ret = false;
                        return;
                    }
                });
                return ret;
            } else {
                var value = self.value();
                return !self.required || Boolean(value === true || (value && value.length));
            }
        },
        deferEvaluation: true
    });
};
/**
 * Creates a new comment from the current value of Question.nextComment and clears nextComment
 *
 * @param {function}: save: save function for the current registrationDraft
 **/
Question.prototype.addComment = function(save) {
    var self = this;

    var comment = new Comment({
        value: self.nextComment()
    });
    comment.seenBy.push($osf.currentUser().id);
    self.comments.push(comment);
    self.nextComment('');
    save();
};
/**
 * Shows/hides the Question example
 **/
Question.prototype.toggleExample = function() {
    this.showExample(!this.showExample());
};

/**
 * @class Page
 * A single page within a draft registration
 *
 * @param {Object} schemaPage: page representation from a registration schema (see MetaSchema#pages)
 * @param {Object} schemaData: user data to autoload into page, a key/value map of questionId: questionData
 *
 * @property {ko.observableArray[Question]} questions
 * @property {String} title
 * @property {String} id
 * @property {Question[]} questions
 * @property {Question} current Question
 **/
var Page = function(schemaPage, schemaData) {
    var self = this;
    self.id = schemaPage.id;
    self.title = schemaPage.title;
    self.description = schemaPage.description || '';

    self.active = ko.observable(false);

    schemaData = schemaData || {};
    self.questions = $.map(schemaPage.questions, function(questionSchema) {
        return new Question(questionSchema, schemaData[questionSchema.qid]);
    });

    /**
     * Aggregate lists of comments from each question in questions. Sort by 'created'.
     **/
    self.comments = ko.computed(function() {
        var comments = [];
        $.each(self.questions, function(_, question) {
            comments = comments.concat(question.comments());
        });
        comments.sort(function(a, b) {
            return a.created > b.created;
        });
        return comments;
    });

    // TODO: track currentQuestion based on browser focus
    self.currentQuestion = self.questions[0];
};
Page.prototype.viewComments = function() {
    var self = this;
    var comments = self.comments();
    $.each(comments, function(index, comment) {
        comment.viewComment($osf.currentUser());
    });
};
Page.prototype.getUnseenComments = function() {
    var self = this;
    return self.comments().filter(function(comment) {
        return comment.seenBy.indexOf($osf.currentUser().id) === -1;
    });
};

/**
 * @class MetaSchema
 * Model for MetaSchema instances
 *
 * @param {Object} params: instantiation values
 * @param {String} params.schema_name
 * @param {Integer} params.schema_version
 * @param {String} params.title: display title of schema
 * @param {Schema} params.schema
 *
 * @type Schema
 * @property {String} title
 * @property {Integer} version
 * @property {String} description
 * @property {String[]} fulfills: array of requirements/goals that this schema fulfills
 * @property {Page[]} pages
 *
 * @type Page
 * @property {String} id
 * @property {String} title
 * @property {Question[]} questions
 **/
var MetaSchema = function(params, schemaData) {
    var self = this;

    self.name = params.schema_name;
    self.version = params.schema_version;
    self.title = params.title || params.schema.title;
    self.schema = params.schema || {};
    self.id = params.id;

    // Used for initally selecting a schema
    self._selected = ko.observable(false);

    self.requiresApproval = params.requires_approval || false;
    self.fulfills = params.fulfills || [];
    self.messages = params.messages || {};

    self.requiresConsent = params.requires_consent || false;

    self.pages = $.map(self.schema.pages, function(page) {
        return new Page(page, schemaData);
    });
};
/**
 * @returns {Question[]} a flat list of the schema's questions
 **/
MetaSchema.prototype.flatQuestions = function() {
    var self = this;

    var flat = [];
    $.each(self.pages, function(i, page) {
        flat = flat.concat(page.questions);
    });
    return flat;
};
/**
 * @param Boolean pre: consent before beginning or submitting?
 **/
MetaSchema.prototype.askConsent = function(pre) {
    var self = this;

    var ret = $.Deferred();

    if (typeof pre === 'undefined') {
        pre = false;
    }

    var message = (pre ? self.messages.preConsentHeader : self.messages.postConsentHeader) + self.messages.consentBody;

    var viewModel = {
        mustAgree: !pre,
        message: message,
        consent: ko.observable(false),
        submit: function() {
            $osf.unblock();
            bootbox.hideAll();
            ret.resolve();
        },
        cancel: function() {
            $osf.unblock();
            bootbox.hideAll();
            ret.reject();
        }
    };

    bootbox.dialog({
        size: 'large',
        message: function() {
            ko.renderTemplate('preRegistrationConsent', viewModel, {}, this);
        }
    });

    return ret.promise();
};

/**
 * @class Draft
 * Model for DraftRegistrations
 *
 * @param {Object} params
 * @param {String} params.pk: primary key of Draft
 * @param {Object} params.registration_schema: data to be passed to MetaSchema constructor
 * @param {Object} params.registration_metadata: saved Draft data
 * @param {User} params.initiator
 * @param {Date} params.initiated
 * @param {Boolean} params.is_pending_review
 * @param {Boolean} params.is_approved
 * @param {Date} params.updated
 * @param {Object} params.urls
 * @param {String} params.urls.edit
 * @param {String} params.urls.before_register
 * @param {String} params.urls.register
 * @property {Float} completion: percent completion of schema
 **/
var Draft = function(params, metaSchema) {
    var self = this;

    self.pk = params.pk;
    self.schemaData = params.registration_metadata || {};
    self.metaSchema = metaSchema || new MetaSchema(params.registration_schema, self.schemaData);
    self.schema = ko.pureComputed(function() {
        return self.metaSchema.schema;
    });

    self.initiator = params.initiator;
    self.initiated = new Date(params.initiated);
    self.updated = new Date(params.updated);

    self.urls = params.urls || {};

    self.isPendingApproval = params.is_pending_approval;
    self.isApproved = params.is_approved;

    self.requiresApproval = ko.pureComputed(function() {
        return self.metaSchema && self.metaSchema.requiresApproval;
    });
    self.fulfills = ko.pureComputed(function() {
        return self.metaSchema ? self.metaSchema.fulfills : [];
    });

    self.pages = ko.computed(function() {
        return self.metaSchema.pages;
    });

    self.userHasUnseenComment = ko.computed(function() {
        return $osf.any(
            $.map(self.pages(), function(page) {
                return page.getUnseenComments().length > 0;
            })
        );
    });

    self.hasRequiredQuestions = ko.pureComputed(function() {
        return self.metaSchema.flatQuestions().filter(function(q) {
            return q.required;
        }).length > 0;
    });

    self.completion = ko.computed(function() {
        var complete = 0;
        var questions = self.metaSchema.flatQuestions()
                .filter(function(question) {
                    return question.required;
                });
        $.each(questions, function(_, question) {
            if (question.isComplete()) {
                complete++;
            }
        });
        return Math.ceil(100 * (complete / questions.length));
    });
};
Draft.prototype.getUnseenComments = function() {
    var unseen = [];
    $.each(self.pages(), function(_, page) {
        unseen = unseen.concat(page.getUnseenComments());
    });
    return unseen;
};
Draft.prototype.preRegisterPrompts = function(response, confirm) {
    var self = this;
    var validator = null;
    if (self.metaSchema.requiresApproval) {
        validator = {
            validator: function(value) {
                return (new Date(value)).getTime() > DRAFT_REGISTRATION_MIN_EMBARGO_TIMESTAMP;
            },
            message: 'Embargo end date must be at least ' + DRAFT_REGISTRATION_MIN_EMBARGO_DAYS + ' days in the future.'
        };
    }
    var preRegisterPrompts = response.prompts || [];

    var registrationModal = new RegistrationModal.ViewModel(
        confirm, preRegisterPrompts, validator
    );
    registrationModal.show();
};
Draft.prototype.preRegisterErrors = function(response, confirm) {
    bootbox.confirm({
        message: $osf.joinPrompts(
            response.errors,
            'Before you continue...'
        ) + '<br />' + language.registerSkipAddons,
        callback: function(result) {
            if (result) {
                confirm();
            }},
        buttons: {
            confirm: {
                label:'Continue with registration',
                className:'btn-primary'
            }}
    });
};

Draft.prototype.beforeRegister = function(url) {
    var self = this;

    $osf.block();

    url = url || self.urls.register;

    var request = $.getJSON(self.urls.before_register);
    request.done(function(response) {
        $osf.unblock();
        if (response.errors && response.errors.length) {
            self.preRegisterErrors(
                response,
                self.preRegisterPrompts.bind(
                    self,
                    response,
                    self.register.bind(self, url)
                )
            );
        }
        else {
            self.preRegisterPrompts(
                response,
                self.register.bind(self, url)
            );
        }
    }).fail($osf.unblock);
    return request;
};
Draft.prototype.registerWithoutReview = function() {
    var self = this;
    bootbox.dialog({
        title: 'Notice',
        message: self.metaSchema.messages.beforeSkipReview,
        buttons: {
            cancel: {
                label: 'Cancel',
                className: 'btn-default',
                callback: bootbox.hideAll
            },
            submit: {
                label: 'Continue',
                className: 'btn-warning',
                callback: self.beforeRegister.bind(self, null)
            }
        }
    });
};
Draft.prototype.onRegisterFail = bootbox.alert.bind(null, {
    title: 'Registration failed',
    message: language.registerFail
});
Draft.prototype.register = function(url, data) {
    var self = this;

    $osf.block();
    var request = $osf.postJSON(url, data);
    request
        .done(function(response) {
            if (response.status === 'initiated') {
                window.location.assign(response.urls.registrations);
            }
        })
        .fail(function() {
            self.onRegisterFail();
        })
        .always($osf.unblock);
    return request;
};
Draft.prototype.submitForReview = function() {
    var self = this;

    var metaSchema = self.metaSchema;

    if (self.metaSchema.requiresConsent) {
        return self.metaSchema.askConsent()
            .always(bootbox.hideAll)
            .then(function() {
                self.beforeRegister(self.urls.submit.replace('{draft_pk}', self.pk));
            });
    }
    else {
        self.beforeRegister(self.urls.submit.replace('{draft_pk}', self.pk));
    }
};

/**
 * @class RegistrationEditor
 *
 * @param {Object} urls
 * @param {String} urls.update: endpoint to update a draft instance
 * @param {String} editorId: id of editor DOM node
 * @param {Boolean} preview: enable preview mode-- adds a KO binding handler to allow extensions to define custom preview behavior
 * @property {ko.observable[Boolean]} readonly
 * @property {ko.observable[Draft]} draft
 * @property {ko.observable[Question]} currentQuestion
 * @property {Object} extensions: mapping of extenstion names to their view models
 **/
var RegistrationEditor = function(urls, editorId, preview) {
    var self = this;

    self.urls = urls;

    self.readonly = ko.observable(false);

    self.draft = ko.observable();

    self.currentQuestion = ko.observable();
    self.showValidation = ko.observable(false);

    self.pages = ko.computed(function () {
        // empty array if self.draft is not set.
        return self.draft() ? self.draft().pages() : [];
    });
    self.currentPage = ko.observable();
    self.currentPage.subscribe(function(currentPage) {
        $.each(self.draft().pages(), function(i, page) {
            page.active(false);
        });
        currentPage.active(true);
        History.replaceState({page: self.pages().indexOf(currentPage)});
    });

    self.onLastPage = ko.pureComputed(function() {
        return self.currentPage() === self.pages()[self.pages().length - 1];
    });

    // An incrementing dirty flag. The 0 state represents not-dirty.
    // States greater than 0 imply dirty, and incrementing the number
    // allows for reliable mutations of the ko.observable.
    self.dirtyCount = ko.observable(0);
    self.needsSave = ko.computed(function() {
        return self.dirtyCount();
    }).extend({
        rateLimit: 3000,
        method: 'notifyWhenChangesStop'
    });
    self.currentPage.subscribe(function(page) {
        // lazily apply subscriptions to question values
        $.each(page.questions, function(_, question) {
            question.value.subscribe(function() {
                self.dirtyCount(self.dirtyCount() + 1);
            });
        });
        page.viewComments();
    });

    self.validationErrors = ko.computed(function() {
        if (self.onLastPage()) {
            var errors = [];
            var questions = self.flatQuestions() || [];
            if (questions.length && questions.filter(function(question) {
                return question.required && !question.isComplete();
            }).length) {
                return 'Some required questions are unanswered.';
            }
            else {
                return '';
            }
        }
        return '';
    });

    self.canSubmit = ko.computed(function() {
        var canSubmit = true;
        var questions = self.flatQuestions();
        for (var i = 0; i < questions.length; i++) {
            var question = questions[i];
            canSubmit = !question.required || (question.required && question.isComplete());
            if (!canSubmit) {
                break;
            }
        }
        return canSubmit;
    });

    self.iterObject = $osf.iterObject;

    // TODO: better extensions system?
    self.extensions = {
        'osf-upload': editorExtensions.Uploader,
        'osf-author-import': editorExtensions.AuthorImport
    };

    preview = preview || false;
    if (preview) {
        ko.bindingHandlers.previewQuestion = {
            init: function(elem, valueAccessor) {
                var question = valueAccessor();
                var $elem = $(elem);

                if (question.type === 'object') {
                    $elem.append(
                        $.map(question.properties, function(subQuestion) {
                            subQuestion = self.context(subQuestion);
                            var value;
                            if (self.extensions[subQuestion.type] ) {
                                value = subQuestion.preview();
                            } else {
                                value = $osf.htmlEscape(subQuestion.value() || '');
                            }
                            return $('<p>').append(value);
                        })
                    );
                } else {
                    var value;
                    if (self.extensions[question.type] ) {
                        value = question.preview();
                    } else {
                        value = $osf.htmlEscape(question.value() || '');
                    }
                    $elem.append(value);
                }
            }
        };
    }
};
/**
 * Load draft data into the editor
 *
 * @param {Draft} draft
 **/
RegistrationEditor.prototype.init = function(draft) {
    var self = this;

    self.draft(draft);
    var metaSchema = draft ? draft.metaSchema: null;

    self.saveManager = null;
    if (draft) {
        self.saveManager = new SaveManager(
            self.urls.update.replace('{draft_pk}', draft.pk),
            null, {
                dirty: self.dirtyCount
            }
        );
    }

    self.lastSaveTime = ko.computed(function() {
        if (!self.draft()) {
            return null;
        }
        return self.draft().updated;
    });
    self.lastSaved = ko.computed(function() {
        var t = self.lastSaveTime();
        if (t) {
            return t.toGMTString();
        } else {
            return 'never';
        }
    });

    // Set currentPage to the first page
    var pages = self.draft().pages();
    var index = History.getState().data.page || 0;
    if (index > pages.length) {
        index = 0;
    }
    self.currentPage(pages[index]);

    self.needsSave.subscribe(function(dirty) {
        if (dirty) {
            self.save().then(function(last) {
                if (self.dirtyCount() === last){
                    self.dirtyCount(0);
                }
            }.bind(self, self.dirtyCount()));
        }
    });

    self.currentQuestion(self.flatQuestions().shift());
};
/**
 * @returns {Question[]} flat list of the current schema's questions
 **/
RegistrationEditor.prototype.flatQuestions = function() {
    var self = this;
    var draft = self.draft();
    if (draft) {
        return draft.metaSchema.flatQuestions();
    }
    return [];
};
/**
 * Creates a template context for editor type subtemplates. Looks for the data type
 * in the extension map, and if found instantiates that type's ViewModel. Otherwise
 * return the bare data Object
 *
 * @param {Object} data: data in current editor template scope
 * @returns {Object|ViewModel}
 **/
RegistrationEditor.prototype.context = function(data, $root) {
    $.extend(data, {
        save: this.save.bind(this),
        readonly: this.readonly
    });

    if (this.extensions[data.type]) {
        return new this.extensions[data.type](data, $root);
    }
    return data;
};

RegistrationEditor.prototype.toPreview = function () {
    var self = this;
    $osf.block('Saving...');
    self.save().then(function() {
        self.dirtyCount(0);
        window.location.assign(self.draft().urls.register_page);
    }).always($osf.unblock);
};
/**
 * Check that the Draft is valid before registering
 */
RegistrationEditor.prototype.check = function() {
    var self = this;

    var valid = true;
    ko.utils.arrayMap(self.draft().pages(), function(page) {
        ko.utils.arrayMap(page.questions, function(question) {
            if (question.required && !question.value.isValid()) {
                valid = false;
                // Validation for a question failed
                bootbox.dialog({
                    title: 'Registration Not Complete',
                    message: 'There are errors in your registration. Please double check it and submit again.',
                    buttons: {
                        success: {
                            label: 'Return',
                            className: 'btn-primary',
                            callback: function() {
                                self.showValidation(true);
                            }
                        }
                    }
                });
            }
        });
    });
    if (valid) {
        self.toPreview();
    }
};

RegistrationEditor.prototype.viewComments = function() {
    var self = this;

    var comments = self.currentQuestion().comments();
    $.each(comments, function(index, comment) {
        if (comment.seenBy().indexOf($osf.currentUser().id) === -1) {
            comment.seenBy.push($osf.currentUser().id);
        }
    });
};
RegistrationEditor.prototype.getUnseenComments = function(qid) {
    var self = this;

    var question = self.draft().schemaData[qid];
    var comments = question.comments || [];
    for (var key in question) {
        if (key === 'comments') {
            for (var i = 0; i < question[key].length - 1; i++) {
                if (question[key][i].indexOf($osf.currentUser().id) === -1) {
                    comments.push(question[key][i]);
                }
            }
        }
    }
    return comments;
};
/**
 * Select a page, selecting the first question on that page
 **/
RegistrationEditor.prototype.selectPage = function(page) {
    var self = this;

    var questions = page.questions;
    var firstQuestion = questions[Object.keys(questions)[0]];
    self.currentQuestion(firstQuestion);
    self.currentPage(page);

    self.viewComments();
};

RegistrationEditor.prototype.nextPage = function () {
    var self = this;
    if (self.onLastPage() || self.pages().length <= 1) {
        return;
    }

    self.currentPage(self.pages()[ self.pages().indexOf(self.currentPage()) + 1 ]);
    window.scrollTo(0,0);
};
/**
 * Update draft primary key and updated time on server response
 **/
RegistrationEditor.prototype.updateData = function(response) {
    var self = this;

    var draft = self.draft();
    draft.pk = response.pk;
    draft.updated = new Date(response.updated);
    self.draft(draft);
};

RegistrationEditor.prototype.submit = function() {
    var self = this;
    var currentNode = window.contextVars.node;
    var currentUser = $osf.currentUser();
    var messages = self.draft().messages;
    bootbox.confirm(messages.beforeSubmitForApproval, function(result) {
        var url = self.urls.submit.replace('{draft_pk}', self.draft().pk);
        if (result) {
            var request = $osf.postJSON(url, {
                node: currentNode,
                auth: currentUser
            });
            request.done(function() {
                bootbox.dialog({
                    message: messages.afterSubmitForApproval,
                    title: 'Pre-Registration Prize Submission',
                    buttons: {
                        registrations: {
                            label: 'Return to registrations page',
                            className: 'btn-primary pull-right',
                            callback: function() {
                                window.location.assign(self.draft().urls.registrations);
                                $osf.unblock();
                            }
                        }
                    }
                });
            });
            request.fail(function(xhr, status, error) {
                Raven.captureMessage('Could not submit draft registration', {
                    url: url,
                    textStatus: status,
                    error: error
                });
                $osf.growl('Error submitting for review', language.submitForReviewFail);
            });
        }
    });
};
/**
 * Create a new draft
 **/
RegistrationEditor.prototype.create = function(schemaData) {
    var self = this;

    var metaSchema = self.draft().metaSchema;

    var request = $osf.postJSON(self.urls.create, {
        schema_name: metaSchema.name,
        schema_version: metaSchema.version,
        schema_data: schemaData
    });
    request.done(function(response) {
        var draft = self.draft();
        draft.pk = response.pk;
        self.draft(draft);
        self.saveManager = new SaveManager(
            self.urls.update.replace('{draft_pk}', draft.pk),
            null,
            {
                dirty: self.dirtyCount
            }
        );
    });
    return request;
};

RegistrationEditor.prototype.putSaveData = function(payload) {
    var self = this;
    return self.saveManager.save(payload)
        .then(self.updateData.bind(self));
};

RegistrationEditor.prototype.saveForLater = function() {
    var self = this;
    $osf.block('Saving...');
    self.save()
        .always($osf.unblock)
        .then(function() {
            self.dirtyCount(0);
            window.location.assign(self.urls.draftRegistrations);
        });
};

/**
 * Save the current Draft
 **/
RegistrationEditor.prototype.save = function() {
    var self = this;
    var metaSchema = self.draft().metaSchema;
    var data = {};
    $.each(metaSchema.pages, function(i, page) {
        $.each(page.questions, function(_, question) {
            var qid = question.id;
            data[qid] = ko.toJS({
                value: question.value(),
                comments: question.comments(),
                extra: question.extra
            });
        });
    });
    var request;
    if (typeof self.draft().pk === 'undefined') {
        request = self.create(self);
    } else {
        request = self.putSaveData({
            schema_name: metaSchema.name,
            schema_version: metaSchema.version,
            schema_data: data
        });
    }
    request.fail(function(xhr, status, error) {
        Raven.captureMessage('Could not save draft registration', {
            url: self.urls.update.replace('{draft_pk}', self.draft().pk),
            textStatus: status,
            error: error
        });
        $osf.growl('Problem saving draft', 'There was a problem saving this draft. Please try again, and if the problem persists please contact ' + SUPPORT_LINK + '.');
    });
    return request;
};

/**
 * @class RegistrationManager
 * Model for listing DraftRegistrations
 *
 * @param {Object} node: optional data to instatiate model with
 * @param {String} draftsSelector: DOM node to bind VM to
 * @param {Object} urls:
 * @param {String} urls.list:
 * @param {String} urls.get:
 * @param {String} urls.delete:
 * @param {String} urls.edit:
 * @param {String} urls.schemas:
 **/
var RegistrationManager = function(node, draftsSelector, urls, createButton) {
    var self = this;

    self.node = node;
    self.draftsSelector = draftsSelector;

    self.urls = urls;

    self.schemas = ko.observableArray();
    self.selectedSchema = ko.computed({
        read: function() {
            return self.schemas().filter(function(s) {
                return s._selected();
            })[0];
        },
        write: function(schema) {
            $.each(self.schemas(), function(_, s) {
                s._selected(false);
            });
            schema._selected(true);
        }
    });
    self.selectedSchemaId = ko.computed({
        read: function() {
            return (self.selectedSchema() || {}).id;
        },
        write: function(id) {
            var schemas = self.schemas();
            var schema = schemas.filter(function(s) {
                return s.id === id;
            })[0];
            self.selectedSchema(schema);
        }
    });

    // TODO: convert existing registration UI to frontend impl.
    // self.registrations = ko.observable([]);
    self.drafts = ko.observableArray();
    self.hasDrafts = ko.pureComputed(function() {
        return self.drafts().length > 0;
    });

    self.loading = ko.observable(true);
    self.loading.subscribe(function(loading) {
        if (!loading) {
            createButton.removeClass('disabled');
        }
    });

    self.preview = ko.observable(false);

    // bound functions
    self.getDraftRegistrations = $.getJSON.bind(null, self.urls.list);
    self.getSchemas = $.getJSON.bind(null, self.urls.schemas);

    if (createButton) {
        createButton.addClass('disabled');
        createButton.on('click', self.createDraftModal.bind(self));
    }
};
RegistrationManager.prototype.init = function() {
    var self = this;

    $osf.applyBindings(self, self.draftsSelector);

    var getSchemas = self.getSchemas();
    getSchemas.done(function(response) {
        self.schemas(
            $.map(response.meta_schemas, function(schema) {
                return new MetaSchema(schema);
            })
        );
    });

    var getDraftRegistrations = self.getDraftRegistrations();
    getDraftRegistrations.done(function(response) {
        var drafts = $.map(response.drafts, function(draft) {
            return new Draft(draft);
        });
        drafts.sort(function(a, b) {
            return a.initiated.getTime() < b.initiated.getTime();
        });
        self.drafts(drafts);
    });

    var ready = $.when(getSchemas, getDraftRegistrations).done(function() {
        self.loading(false);
    });

    var urlParams = $osf.urlParams();
    if (urlParams.campaign && urlParams.campaign === 'prereg') {
        $osf.block();
        ready.done(function() {
            var preregSchema = self.schemas().filter(function(schema) {
                return schema.name === 'Prereg Challenge';
            })[0];
            preregSchema.askConsent(true).then(function() {
                self.selectedSchema(preregSchema);
                $('#newDraftRegistrationForm').submit();
            });
        }).always($osf.unblock);
    }
};
/**
 * Confirm and delete a draft registration
 *
 * @param {Draft} draft:
 **/
RegistrationManager.prototype.deleteDraft = function(draft) {
    var self = this;

    bootbox.dialog({
        title: 'Please confirm',
        message: 'Are you sure you want to delete this draft registration?',
        buttons: {
            cancel: {
                label: 'Cancel',
                className: 'btn-default',
                callback: bootbox.hideAll
            },
            submit: {
                label: 'Delete',
                className: 'btn-danger',
                callback: function() {
                    $.ajax({
                        url: self.urls.delete.replace('{draft_pk}', draft.pk),
                        method: 'DELETE'
                    }).then(function() {
                        self.drafts.remove(function(item) {
                            return item.pk === draft.pk;
                        });
                    });
                }
            }
        }
    });
};
/**
 * Show the draft registration preview pane
 **/
RegistrationManager.prototype.createDraftModal = function(selected) {
    var self = this;
    if (!self.selectedSchema()){
        self.selectedSchema(self.schemas()[0]);
    }

    bootbox.dialog({
        size: 'large',
        title: 'Register <title>',
        message: function() {
            ko.renderTemplate('createDraftRegistrationModal', self, {}, this);
        },
        buttons: {
            cancel: {
                label: 'Cancel',
                className: 'btn btn-default'
            },
            create: {
                label: 'Create draft',
                className: 'btn btn-primary',
                callback: function(event) {
                    var selectedSchema = self.selectedSchema();
                    if (selectedSchema.requiresConsent) {
                        selectedSchema.askConsent(true).then(function() {
                            $('#newDraftRegistrationForm').submit();
                        });
                    }
                    else {
                        $('#newDraftRegistrationForm').submit();
                    }
                }
            }
        }
    });
};
/**
 * Redirect to the draft edit page
 **/
RegistrationManager.prototype.editDraft = function(draft) {
    $osf.block();
    window.location.assign(draft.urls.edit);
    $osf.unblock();
};
RegistrationManager.prototype.previewDraft = function(draft) {
    $osf.block();
    window.location.assign(draft.urls.register_page);
    $osf.unblock();
};

module.exports = {
    Comment: Comment,
    Question: Question,
    Page: Page,
    MetaSchema: MetaSchema,
    Draft: Draft,
    RegistrationEditor: RegistrationEditor,
    RegistrationManager: RegistrationManager
};


text:
module ETL
  class Transform
    class CalculationTransform < ETL::Transform
      attr_reader :function
      attr_reader :fields

      def initialize(control, name, configuration)
        @function = configuration[:function]
        @fields = configuration[:fields]
        super
      end

      def transform(name, value, row)
        return nil if row.nil?
        return nil if row[@fields[0]].nil?

        if (@function.eql? "A + B")
          result = ""
          @fields.each do |field|
            next if field.nil?

            string = ""
            if field.to_s.eql? field
              string = field
              begin
                string = eval('"' + field + '"')
              rescue
              end
            else
              string = row[field]
            end
            next if string.nil?

            result = result + string
          end

          row[name] = result
        end

        if (@function.eql? "date A")
          first = row[@fields[0]]
          row[name] = Time.parse(first)
        end

        if (@function.eql? "trim A")
          first = row[@fields[0]]
          row[name] = first.strip
        end

        if (@function.eql? "lower A")
          first = row[@fields[0]]
          row[name] = first.downcase
        end

        if (@function.eql? "upper A")
          first = row[@fields[0]]
          row[name] = first.upcase
        end

        if (@function.eql? "encoding A")
          # Bug from ruby 1.8 http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/
          first = row[@fields[0]]
          row[name] = Iconv.conv(@fields[1], @fields[2], first + ' ')[0..-2]
        end

        row[name]
      end

    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
/**
 * Test dependencies.
 */
const Coral = require('../../lib/coral')
const db = require('../helper/db')
const express = require('express')
const request = require('supertest')
const bodyParser = require('body-parser')
const app = express()

describe('Coral put tests', () => {
  // require to get req body parameters
  app.use(bodyParser.json())

  before((done) => {
    db.connect()
    db.initialise(done)
  })

  after((done) => {
    db.disconnect(done)
  })

  it('put - must create proper put route and update matching record', (done) => {
    // config for route
    const config = {
      path: '/localhost/user',
      model: db.getModel('User'),
      idAttribute: 'name',
      methods: ['PUT']
    }

    // data to be pass to update data
    const data = {
      name: 'test',
      age: 40
    }

    // call router put with the config
    app.use(new Coral(config))

    // invoke path with supertest
    request(app)
      .put(config.path + '/abc')
      .set('accept', 'application/json')
      .send(data)
      .expect(200)
      .end((err, res) => {
        res.body.name.should.equal('test')
        res.body.age.should.equal(40)
        done(err) // pass err so that fail expect errors will get caught
      })
  })
})


text:
<?php

// @codingStandardsIgnoreFile

namespace Magento\Payment\Test\Unit\Block;

use Magento\Framework\DataObject;

class FormTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $_object;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $_storeManager;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $_eventManager;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $_escaper;

    protected function setUp()
    {
        $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->_storeManager = $this->getMockBuilder(
            '\Magento\Store\Model\StoreManager'
        )->setMethods(
                ['getStore']
            )->disableOriginalConstructor()->getMock();
        $this->_eventManager = $this->getMockBuilder(
            '\Magento\Framework\Event\ManagerInterface'
        )->setMethods(
                ['dispatch']
            )->disableOriginalConstructor()->getMock();
        $this->_escaper = $this->getMock('\Magento\Framework\Escaper', null, [], '', true);
        $context = $helper->getObject(
            'Magento\Framework\View\Element\Template\Context',
            [
                'storeManager' => $this->_storeManager,
                'eventManager' => $this->_eventManager,
                'escaper' => $this->_escaper
            ]
        );
        $this->_object = $helper->getObject('Magento\Payment\Block\Form', ['context' => $context]);
    }

    /**
     * @expectedException \Magento\Framework\Exception\LocalizedException
     */
    public function testGetMethodException()
    {
        $method = new \Magento\Framework\DataObject([]);
        $this->_object->setData('method', $method);
        $this->_object->getMethod();
    }

    public function testGetMethodCode()
    {
        $method = $this->getMock('Magento\Payment\Model\MethodInterface', [], [], '', false);
        $method->expects($this->once())
            ->method('getCode')
            ->will($this->returnValue('method_code'));
        $this->_object->setData('method', $method);
        $this->assertEquals('method_code', $this->_object->getMethodCode());
    }

    /**
     * @dataProvider getInfoDataProvider
     */
    public function testGetInfoData($field, $value, $expected)
    {
        $methodInstance = $this->getMockBuilder('\Magento\Payment\Model\Method\AbstractMethod')
            ->setMethods(['getData'])
            ->disableOriginalConstructor()
            ->getMock();
        $methodInstance->expects($this->any())
            ->method('getData')
            ->with($field)
            ->will($this->returnValue($value));
        $method = $this->getMockBuilder(
            'Magento\Payment\Model\MethodInterface'
        )->getMockForAbstractClass();
        $method->expects($this->any())
            ->method('getInfoInstance')
            ->will($this->returnValue($methodInstance));
        $this->_object->setData('method', $method);
        $this->assertEquals($expected, $this->_object->getInfoData($field));
    }

    /**
     * @return array
     */
    public function getInfoDataProvider()
    {
        return [
            ['info', 'blah-blah', 'blah-blah'],
            ['field1', ['key' => 'val'], ['val']],
            [
                'some_field',
                ['aa', '!@#$%^&*()_#$%@^%&$%^*%&^*', 'cc'],
                ['aa', '!@#$%^&*()_#$%@^%&$%^*%&^*', 'cc']
            ]
        ];
    }

    public function testSetMethod()
    {
        $methodInterfaceMock = $this->getMockBuilder('\Magento\Payment\Model\MethodInterface')
            ->getMockForAbstractClass();

        $this->assertSame($this->_object, $this->_object->setMethod($methodInterfaceMock));
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Samuel
 * Date: 20/07/2015
 * Time: 23:37
 */

namespace Samcrosoft\MultiAuth\Manager\Auth;

use Illuminate\Auth\AuthManager as LaravelAuthManager;
use Samcrosoft\MultiAuth\Manager\Guard\MultiAuthGuard;

/**
 * Class MultiAuthManager
 * @package Samcrosoft\MultiAuth\Manager\Auth
 */
class MultiAuthManager extends LaravelAuthManager
{
    /**
     * Multi-auth configuration.
     *
     * @var array
     */
    protected $config;
    /**
     * Multiauth provider name.
     *
     * @var string
     */
    protected $name;

    public function __construct($app, $name)
    {
        parent::__construct($app);
        $this->name = $name;
    }

    /**
     * Create an instance of the Eloquent driver.
     *
     * @return MultiAuthGuard
     */
    public function createEloquentDriver()
    {
        $provider = $this->createEloquentProvider();
        return new MultiAuthGuard($provider, $this->app['session.store'], $this->name);
    }

}


text:
package net.jahhan.jdbc.annotation;

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

import net.jahhan.jdbc.constant.enumeration.DBConnectLevel;
import net.jahhan.jdbc.constant.enumeration.DBConnectStrategy;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBConnect {
	public static DBConnectStrategy defaultDBConnectStrategy = DBConnectStrategy.UPDATA;

	/**
	 * 数据源
	 */
	public String dataSource() default "";

	/**
	 * 连接策略
	 */
	public DBConnectStrategy value() default DBConnectStrategy.UPDATA;

	/**
	 * 连接等级
	 */
	public DBConnectLevel level() default DBConnectLevel.NONE;

	/**
	 * 是否开启事务
	 */
	public boolean transaction() default true;
}


text:
{% extends 'blog/base.html' %}

{% block content %}

        {% if user.is_authenticated %}

        {% endif %}
        {% autoescape off %}
        {{ page.en_content }}
        {% endautoescape %}

{% endblock %}


text:
{{module.displayName}}
        (Angular UI {{module.package}})

      <tabset>
        <tab heading="Markup">

        </tab>
        <tab heading="Dart">

        </tab>
      </tabset>


text:
namespace asi
{
namespace runtimecommandengine
{

CommandWithGenericParams::CommandWithGenericParams(std::vector<std::string> const &signature,
                                                   std::string const &description, CallFunType call_fun,
                                                   parameter::ParameterAbstract const *const *const in_parameters,
                                                   int const num_params)
    : commandWithoutParams(signature, description, call_fun)
{
	genericParameters.reserve(
	    static_cast<std::vector<parameter::ParameterAbstract const *>::size_type>(num_params));
	for (int i = 0; i < num_params; ++i)
	{
		genericParameters.push_back(in_parameters[i]);
	}
}

std::tuple<bool, int32_t, std::string>
CommandWithGenericParams::EvaluateImpl(std::vector<std::string> const &tokens) const
{
	std::tuple<bool, int32_t, std::string> output(false, 0, "");

	// Check method names
	std::vector<std::string> candidate_method_name;
	if (tokens.size() <= commandWithoutParams.GetSignatureLength() || tokens.size() < genericParameters.size())
	{
		candidate_method_name = tokens;
	}
	else
	{
		candidate_method_name = std::vector<std::string>(
		    tokens.begin(), tokens.begin() + static_cast<signed>(commandWithoutParams.GetSignatureLength()));
	}
	auto const cwp_atis = commandWithoutParams.AreTokensInSignature(candidate_method_name);

	// Check parameter domains
	int32_t last_good_index_p1 = std::get<1>(cwp_atis);
	std::get<1>(output) = last_good_index_p1;
	if (true == std::get<0>(cwp_atis))
	{
		bool match = last_good_index_p1 != static_cast<int32_t>(tokens.size());
		uint32_t potential_good_index = static_cast<uint32_t>(last_good_index_p1) + 1U;
		for (; (potential_good_index < tokens.size()) &&
		       (potential_good_index - commandWithoutParams.GetSignatureLength() < genericParameters.size()) &&
		       genericParameters[potential_good_index - commandWithoutParams.GetSignatureLength()]
		           ->IsInExpectedDomain(tokens[potential_good_index]);
		     ++potential_good_index)
		{
		}
		match = potential_good_index == tokens.size();
		match =
		    match && (tokens.size() == commandWithoutParams.GetSignatureLength() + genericParameters.size());
		last_good_index_p1 = static_cast<int32_t>(potential_good_index) - 1;
		std::get<0>(output) = match;
		std::get<1>(output) = last_good_index_p1;
		if (match)
		{
			commandWithoutParams.CallFun(tokens);
			std::get<2>(output) = GetReceivedMessage(tokens);
		}
	}

	return output;
}

std::vector<std::string> CommandWithGenericParams::GetSignatureExpectationImpl(size_t const index) const
{
	std::vector<std::string> output;
	auto const method_name_length = commandWithoutParams.GetSignatureLength();
	if (index < method_name_length)
	{
		output = commandWithoutParams.GetSignatureExpectation(index);
	}
	else
	{
		output = genericParameters[index - method_name_length]->GetExpectedDomainSet();
	}
	return output;
}

size_t CommandWithGenericParams::GetSignatureLengthImpl() const
{
	return commandWithoutParams.GetSignatureLength() + genericParameters.size();
}

void CommandWithGenericParams::PrependSignatureImpl(std::string const &pre_sig)
{
	commandWithoutParams.PrependSignature(pre_sig);
}

std::string CommandWithGenericParams::GetHelpImpl() const
{
	std::string output = commandWithoutParams.GetHelp();
	output += "\n\tParameters:";
	for (auto parameter : genericParameters)
	{
		std::string param_help = parameter->GetHelp();
		param_help = replaceSubstringWithSubstring(param_help, "\n", "\n\t\t");
		output += "\n\t\t" + param_help;
	}
	return output;
}

} // namespace runtimecommandengine
} // namespace asi


text:
#ifndef __COREFW_RANGE_H__
#define __COREFW_RANGE_H__

typedef struct cfw_range_t {
	size_t start;
	size_t length;
} cfw_range_t;

extern cfw_range_t cfw_range_all;
extern cfw_range_t cfw_range(size_t, size_t);

#endif


text:
ROOT_DIR=${ROOT_DIR:-"$( cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P )"}

set -eu

# URL to binenv distribution list in YAML format.
BINENV_DISTRIBUTION_LIST=${BINENV_DISTRIBUTION_LIST:-https://raw.githubusercontent.com/devops-works/binenv/master/distributions/distributions.yaml}

# Template to use for generating the GH workflow description that will itself
# generate a Docker image for the project. In that template, %DISTRIBUTION% will
# automatically be replaced by the name of the tool (known as a distribution to
# binenv).
BINENV_TEMPLATE=${BINENV_TEMPLATE:-${ROOT_DIR}/binenv.tpl}

# Destination directory for workflow templates.
BINENV_DESTINATION=${BINENV_DESTINATION:-$ROOT_DIR}

# Set this to 1 for more verbosity (or use the -v option).
BINENV_VERBOSE=${BINENV_VERBOSE:-0}

# Force overriding
BINENV_FORCE=${BINENV_FORCE:-0}

usage() {
  # This uses the comments behind the options to show the help. Not extremly
  # correct, but effective and simple.
  echo "$0 is a binenv wrapper with following options:" && \
    grep "[[:space:]].)\ #" "$BINENV_THIS" |
    sed 's/#//' |
    sed -r 's/([a-z])\)/-\1/'
  exit "${1:-0}"
}

while getopts "t:fvh-" opt; do
  case "$opt" in
    t) # Path to YAML template
      BINENV_TEMPLATE=$OPTARG;;
    f) # Force overwriting of existing files, this is dangerous!
      BINENV_FORCE=1;;
    v) # Turn on verbosity
      BINENV_VERBOSE=1;;
    h)
      usage;;
    -)
      break;;
    *)
      usage 1;;
  esac
done
shift $((OPTIND-1))

_verbose() {
  if [ "$BINENV_VERBOSE" = "1" ]; then
    printf %s\\n "$1" >&2
  fi
}

_error() {
  printf %s\\n "$1" >&2
}

_exit() {
  _error "$1"
  exit "${2:-1}"
}

# Download a URL and print its content on stdout, prefers curl, can also use
# wget.
_download() {
  _verbose "Downloading $1"
  if command -v curl >&2 >/dev/null; then
    curl -sSL "$1"
  elif command -v wget >&2 >/dev/null; then
    wget -q -O - "$1"
  else
    _exit "Can neither find curl, nor wget for downloading"
  fi
}

_head() {
  _verbose "Downloading $1"
  if command -v curl >&2 >/dev/null; then
    curl -sSLI "$1" | grep -Eq '^HTTP/[0-9.]+ 2[0-9][0-9]'
  elif command -v wget >&2 >/dev/null; then
    wget --spider -q -O - "$1" >&2 >/dev/null
  else
    _exit "Can neither find curl, nor wget for downloading"
  fi
}

COMMIT=$(git log --no-decorate|grep '^commit'|head -n 1| awk '{print $2}')
DATE=$(date +%Y%m%d-%H%M%S)
# Download the list of distributions known to binenv
DISTRO_LIST=$(mktemp)
_download "$BINENV_DISTRIBUTION_LIST" > "$DISTRO_LIST"

_distributions() {
  grep -E '^  [a-zA-Z0-9_-]+:' "$DISTRO_LIST" |
    sed -E 's/^  ([a-zA-Z0-9_-]+):/\1/g' |
    sed 's/ /\n/g'
}

_generate() {
  tgt=${BINENV_DESTINATION%/}/${1}.yml
  if [ -f "$tgt" ]; then
    _error "Skipping $tgt, exists already"
  else
    # Extract the GitHub API URL for that distribution. We will use this to
    # select projects at GitHub only, and then isolate the name of the target
    # project itself.
    GHAPI=$(  sed -E "/^  ${1}:/,/^$/!d" "$DISTRO_LIST" |
              grep -E '^      url:' |
              grep "api.github.com" |
              sed -E 's/^      url: (.*)/\1/' )
    if [ -n "$GHAPI" ]; then
      # Isolate name of project at GitHub.
      GHPROJ=$( printf %s\\n "$GHAPI" | sed -E -e 's~^https://api.github.com/repos/~~' -e 's~/releases$~~')
      # Try downloading a Dockerfile under the master/main branches. When none
      # exists, create a workflow.
      if _head "https://raw.githubusercontent.com/${GHPROJ}/master/Dockerfile" \
        || _head "https://raw.githubusercontent.com/${GHPROJ}/main/Dockerfile"; then
        _verbose "Project $GHPROJ has already a Dockerfile, skipping"
      else
        _verbose "Generating $tgt"
        sed \
          -e "s/%DISTRIBUTION%/${1}/g" \
          -e "s/%DATE%/${DATE}/g" \
          -e "s/%COMMIT%/${COMMIT}/g" \
          "$BINENV_TEMPLATE" > "$tgt"
      fi
    else
      _verbose "Generating $tgt"
        sed \
          -e "s/%DISTRIBUTION%/${1}/g" \
          -e "s/%DATE%/${DATE}/g" \
          -e "s/%COMMIT%/${COMMIT}/g" \
          "$BINENV_TEMPLATE" > "$tgt"
    fi
  fi
}

if [ "$#" -gt "0" ]; then
  for DISTRIBUTION in "$@"; do
    _generate "$DISTRIBUTION"
  done
else
  # For all distributions, i.e. tools, generate a GH workflow for Docker image
  # creation if it does not already exist and the remote project doesn't already
  # have a Dockerfile under its root (a heuristic that works much better than one
  # would think).
  for DISTRIBUTION in $(_distributions); do
    _generate "$DISTRIBUTION"
  done
fi

# Remove distribution list cache.
rm -f "$DISTRO_LIST"


text:
<?xml version="1.0" encoding="UTF-8"?>
<database name="propel_scio1" defaultIdMethod="native">
    <vendor type="mysql">
        <parameter name="Engine" value="InnoDB" />
        <parameter name="Charset" value="utf8" />
    </vendor>

        <column name="user_id" type="integer" required="true" primaryKey="true" autoIncrement="true" />
        <column name="user_name" type="varchar" size="20" required="true" />
        <unique name="user_name">
            <unique-column name="user_name" />
        </unique>
        <column name="created_date" type="timestamp" required="true" />

        <column name="comment_id" type="integer" required="true" primaryKey="true" autoIncrement="true" />
        <column name="user_id" type="integer" required="true" />
        <foreign-key foreignTable="users" onDelete="CASCADE">
            <reference local="user_id" foreign="user_id" />
        </foreign-key>
        <column name="comment" type="varchar" size="255" required="true" />
        <column name="created_date" type="timestamp" required="true" />

</database>


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * The team entity.
 *
 * @ORM\Entity(repositoryClass="AppBundle\Repository\TeamRepository")
 * @ORM\Table(uniqueConstraints={
 *     @ORM\UniqueConstraint(columns={"season_id", "constructor_id", "driver_id"}),
 * })
 * @UniqueEntity({"season", "constructor", "driver"})
 *
 * @author Brieuc Thomas <tbrieuc@gmail.com>
 */
class Team
{
    /**
     * The entity identifier.
     *
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     *
     * @var int
     */
    protected $id;

    /**
     * The race season.
     *
     * @ORM\ManyToOne(targetEntity="Season", inversedBy="teams")
     * @ORM\JoinColumn(referencedColumnName="year", nullable=false)
     * @Assert\NotNull
     *
     * @var Season
     */
    protected $season;

    /**
     * The constructor entity.
     *
     * @ORM\ManyToOne(targetEntity="Constructor")
     * @ORM\JoinColumn(nullable=false)
     * @Assert\NotNull
     *
     * @var Constructor
     */
    protected $constructor;

    /**
     * The driver entity.
     *
     * @ORM\ManyToOne(targetEntity="Driver")
     * @ORM\JoinColumn(nullable=false)
     * @Assert\NotNull
     *
     * @var Driver
     */
    protected $driver;

    /**
     * Returns the entity identifier.
     *
     * @return int The entity identifier
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Returns the Season.
     *
     * @return Season
     */
    public function getSeason()
    {
        return $this->season;
    }

    /**
     * Sets the Season.
     *
     * @param Season $season
     *
     * @return $this
     */
    public function setSeason(Season $season)
    {
        $this->season = $season;

        return $this;
    }

    /**
     * Returns the Constructor.
     *
     * @return Constructor
     */
    public function getConstructor()
    {
        return $this->constructor;
    }

    /**
     * Sets the Constructor.
     *
     * @param Constructor $constructor
     *
     * @return $this
     */
    public function setConstructor(Constructor $constructor)
    {
        $this->constructor = $constructor;

        return $this;
    }

    /**
     * Returns the Driver.
     *
     * @return Driver
     */
    public function getDriver()
    {
        return $this->driver;
    }

    /**
     * Sets the Driver.
     *
     * @param Driver $driver
     *
     * @return $this
     */
    public function setDriver(Driver $driver)
    {
        $this->driver = $driver;

        return $this;
    }

    public function __toString(): string
    {
        return implode(' - ', [
            $this->getSeason()->getYear(),
            $this->getDriver()->getName(),
            $this->constructor->getName(),
        ]);
    }
}


text:
import logging
import os
import shutil
import subprocess
from urllib import parse, request

from djcelery.models import PeriodicTask
from django.conf import settings
from django.contrib.gis.geos import Point
from django.db import transaction
from django.db.utils import IntegrityError

from .models import Proposal, Event, Document, Image
from cornerwise import celery_app
from scripts import scrape, arcgis, gmaps

logger = logging.getLogger(__name__)

def last_run():
    "Determine the date and time of the last run of the task."
    try:
        scrape_task = PeriodicTask.objects.get(name="scrape-permits")
        return scrape_task.last_run_at
    except PeriodicTask.DoesNotExist:
        return None

def create_proposal_from_json(p_dict):
    "Constructs a Proposal from a dictionary."
    try:
        proposal = Proposal.objects.get(case_number=p_dict["caseNumber"])

        # TODO: We should track changes to a proposal's status over
        # time. This may mean full version-control, with something
        # like django-reversion, or with a hand-rolled alternative.
    except Proposal.DoesNotExist:
        proposal = Proposal(case_number=p_dict["caseNumber"])

    proposal.address = "{} {}".format(p_dict["number"],
                                      p_dict["street"])
    try:
        proposal.location = Point(p_dict["long"], p_dict["lat"])
    except KeyError:
        # If the dictionary does not have an associated location, do not
        # create a Proposal.
        return

    proposal.summary = p_dict.get("summary")
    proposal.description = p_dict.get("description")
    # This should not be hardcoded
    proposal.source = "http://www.somervillema.gov/departments/planning-board/reports-and-decisions"

    # For now, we assume that if there are one or more documents
    # linked in the 'decision' page, the proposal is 'complete'.
    # Note that we don't have insight into whether the proposal was
    # approved!
    is_complete = bool(p_dict["decisions"]["links"])

    proposal.save()

    # Create associated documents:
    for field, val in p_dict.items():
        if not isinstance(val, dict) or not val.get("links"):
            continue

        for link in val["links"]:
            try:
                doc = proposal.document_set.get(url=link["url"])
            except Document.DoesNotExist:
                doc = Document(proposal=proposal)

                doc.url = link["url"]
                doc.title = link["title"]
                doc.field = field

                doc.save()

    return proposal

@celery_app.task
def fetch_document(doc):
    """Copy the given document (proposal.models.Document) to a local
    directory.
    """
    url = doc.url
    url_components = parse.urlsplit(url)
    filename = os.path.basename(url_components.path)
    path = os.path.join(settings.STATIC_ROOT, "doc",
                        str(doc.pk),
                        filename)

    # Ensure that the intermediate directories exist:
    pathdir = os.path.dirname(path)
    os.makedirs(pathdir, exist_ok=True)

    with request.urlopen(url) as resp, open(path, "wb") as out:
        shutil.copyfileobj(resp, out)
        doc.document = path
        doc.save()

@celery_app.task
def extract_content(doc):
    """If the given document (proposal.models.Document) has been copied to
    the local filesystem, extract its images to a subdirectory of the
    document's directory (docs/<doc id>/images). Extracts the text
    content to docs/<doc id>/content.txt.

    """

    docfile = doc.document

    if not docfile:
        logger.warn("Document has not been copied to the local filesystem:")

    try:
        path = docfile.path
    except:
        path = docfile.name

    if not os.path.exists(path):
        logger.warn("Document %s is not where it says it is: %s",
                    doc.pk, path)
        return

    images_dir = os.path.join(os.path.dirname(path), "images")
    os.makedirs(images_dir, exist_ok=True)

    images_pattern = os.path.join(images_dir, "image")

    logger.info("Extracting images to '%s'", images_dir)
    status = subprocess.call(["pdfimages", "-all", path, images_pattern])

    if status:
        logger.warn("pdfimages failed with exit code %i", status)
    else:
        # Do stuff with the images in the directory
        for image_path in os.listdir(images_dir):
            image = Image(image=image_path)
            image.document = doc
            image.save()

    # Could consider storing the full extracted text of the document in
    # the database and indexing it, rather than extracting it to a file.
    status = subprocess.call(["pdftotext", path])

    if status:
        logger.error("Failed to extract text from {doc}".\
                     format(doc=path))
    else:
        # Do stuff with the contents of the file.
        # Possibly perform some rudimentary scraping?
        pass

@celery_app.task
@transaction.atomic
def scrape_reports_and_decisions(since=None, coder_type="google"):
    if not since:
        # If there was no last run, the scraper will fetch all
        # proposals.
        since = last_run()

    if coder_type == "google":
        geocoder = gmaps.GoogleGeocoder(settings.GOOGLE_API_KEY)
        geocoder.bounds = settings.GEO_BOUNDS
        geocoder.region = settings.GEO_REGION
    else:
        geocoder = arcgis.ArcGISCoder(settings.ARCGIS_CLIENT_ID,
                                      settings.ARCGIS_CLIENT_SECRET)

    # Array of dicts:
    proposals_json = scrape.get_proposals_since(dt=since, geocoder=geocoder)
    proposals = []

    for p_dict in proposals_json:
        p = create_proposal_from_json(p_dict)

        if p:
            p.save()
            proposals.append(p)
        else:
            logger.error("Could not create proposal from dictionary:",
                         p_dict)


text:
<?php

namespace Imie\UserBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UserType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName')
            ->add('lastName')
            ->add('birthDate')
            ->add('address')
            ->add('zipCode')
            ->add('city')
            ->add('phoneNumber')
            ->add('description')
            ->add('availability')
            ->add('trainingCourses')
            ->add('Add','submit')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Imie\UserBundle\Entity\User'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'imie_userbundle_user';
    }
}


text:
#if !SILVERLIGHT && !CF
using System;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Collections.Specialized;
namespace ProtoBuf.ServiceModel.Server
{
    /// <summary>
    /// Provides common functionality required by RPC servers.
    /// </summary>
    public class ServerBase
    {

        private Dictionary<string, ServiceBase> services = new Dictionary<string, ServiceBase>(StringComparer.InvariantCulture);
        private static Type GetType(object serviceSingleton)
        {
            if (serviceSingleton == null) throw new ArgumentNullException("serviceSingleton");
            return serviceSingleton.GetType();
        }
        /// <summary>
        /// Represents a service endpoint provided by the server.
        /// </summary>
        protected abstract class ServiceBase : IDisposable
        {
            private Dictionary<string, MethodInfo> actions = new Dictionary<string, MethodInfo>(StringComparer.InvariantCulture);
            /// <summary>
            /// Obtains the instance representing the service endpoint for a call.
            /// </summary>
            public abstract object GetInstance();
            /// <summary>
            /// Releases the instance representing the service endpoint for a call.
            /// </summary>
            public abstract void ReleaseInstance(object instance);
            private readonly Type serviceType;
            /// <summary>
            /// Releases any resources associated with the endpoint.
            /// </summary>
            public virtual void Dispose() { }
            Type ServerType { get { return serviceType; } }
            /// <summary>
            /// Initialises a new service endpoint for the given service type.
            /// </summary>
            protected ServiceBase(Type serviceType)
            {
                if (serviceType == null) throw new ArgumentNullException("serviceType");
                if (!serviceType.IsInterface) throw new ArgumentException(serviceType.FullName + " is not an interface", "serviceType");
                this.serviceType = serviceType;

                foreach (MethodInfo method in serviceType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
                {
                    if (method.IsGenericMethod || method.IsGenericMethodDefinition
                        || method.DeclaringType != serviceType) continue;
                    string key = RpcUtils.GetActionName(method);
                    if (actions.ContainsKey(key))
                    {
                        throw new ArgumentException("Duplicate action \"" + key + "\" found on service-contract " + serviceType.FullName, "serviceContractType");
                    }
                    actions.Add(key, method);
                }
            }
            /// <summary>
            /// Obtains the method that represents a given action.
            /// </summary>
            /// <param name="name">The name of the action.</param>
            /// <returns>The method that should be invoked.</returns>
            public MethodInfo GetAction(string name)
            {
                if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name");
                MethodInfo method;
                if (!actions.TryGetValue(name, out method))
                {
                    throw new InvalidOperationException("Action not found on the service: " + ServiceName + "." + name);
                }
                return method;
            }

            /// <summary>
            /// The name of the service endpoint.
            /// </summary>
            public string ServiceName { get { return RpcUtils.GetServiceName(serviceType); } }
        }
        class ServiceSingleton<T> : ServiceBase where T : class
        {
            private T instance;
            public ServiceSingleton(T instance)
                : base(typeof(T))
            {
                if (instance == null) throw new ArgumentNullException("instance");
                this.instance = instance;
            }
            public override void ReleaseInstance(object instance) { }
            public override object GetInstance() { return instance; }
            public override void Dispose()
            {
                ServerBase.Dispose(ref instance);
            }
        }
        class ServicePerCall<TContract, TService> : ServiceBase
            where TContract : class
            where TService : class, TContract, new()
        {
            public ServicePerCall() : base(typeof(TContract))
            {
            }
            public override void ReleaseInstance(object instance)
            {
                TService service = instance as TService;
                ServerBase.Dispose(ref service);
            }
            public override object GetInstance()
            {
                return new TService();
            }
        }

        /// <summary>
        /// Adds a per-call service to the server. An instance of the type will
        /// be created (and disposed if appropriate) per request.
        /// </summary>
        /// <typeparam name="TContract">The type of service-contract to provide.</typeparam>
        /// <typeparam name="TService">The concrete type that will implement the service.</typeparam>
        public void Add<TContract, TService>()
            where TContract : class
            where TService : class, TContract, new()
        {
            AddCore(new ServicePerCall<TContract, TService>());
        }

        /// <summary>
        /// Adds a singleton service to the server. All requests will be
        /// serviced by the supplied instance. This instance will be
        /// disposed (if appropriate) with the server.
        /// </summary>
        /// <typeparam name="T">The type of service to provide.</typeparam>
        public void Add<T>(T singleton) where T : class
        {
            AddCore(new ServiceSingleton<T>(singleton));
        }

        private void AddCore(ServiceBase server)
        {
            if (server == null) throw new ArgumentNullException("server");
            string key = server.ServiceName;
            if (services.ContainsKey(key))
            {
                throw new InvalidOperationException("Cannot add duplicate service: " + key);
            }
            services.Add(key, server);
        }

        /// <summary>
        /// Releases and nulls a given field/variable.
        /// </summary>
        protected static void Dispose<T>(ref T obj) where T : class

        { // note no IDisposable constraint; we're not always sure if
            // the item is disposable...
            if (obj != null && obj is IDisposable)
            {
                try { ((IDisposable)obj).Dispose(); }
#if SILVERLIGHT || CF
                catch {}
#else
                catch (Exception ex)
                { // log only
                    Trace.Write(ex, "HttpServer.Dispose");
                }
#endif
            }
            obj = null;
        }

        /// <summary>
        /// Performs any pre-response operations required.
        /// </summary>
        protected virtual void OnBeforeWriteResponse(object state) { }

        /// <summary>
        /// Performs server-side processing of an action, including deserialization
        /// of arguments, method-invokation, and serialization of the return value and
        /// any `out`/`ref` arguments.
        /// </summary>
        protected void Execute(string service, string action, NameValueCollection headers, Stream request, Stream response, object state)
        {
            if (string.IsNullOrEmpty(service))
            {
                if (services.Count == 1) { // assume that one, then
                    foreach (string key in services.Keys)
                    {
                        service = key;
                    }
                }
                throw new ArgumentNullException("service", "The service must be specified when multiple services are supported");
            }
            if (string.IsNullOrEmpty(action)) throw new ArgumentNullException("action");
            if (headers == null) throw new ArgumentNullException("headers");
            if (request == null) throw new ArgumentNullException("request");
            if (response == null) throw new ArgumentNullException("response");

            string rpcVer = headers[RpcUtils.HTTP_RPC_VERSION_HEADER];
            if (!string.IsNullOrEmpty(rpcVer) && rpcVer != "0.1")
            {
                throw new InvalidOperationException("Incorrect RPC version");
            }

            ServerBase.ServiceBase serviceImpl;
            if (!services.TryGetValue(service, out serviceImpl))
            {
                throw new InvalidOperationException("Service not available: " + service);
            }
            MethodInfo method = serviceImpl.GetAction(action);
            if (method == null) throw new InvalidOperationException("Action not found on service: " + service + "/" + action);
            ParameterInfo[] parameters = method.GetParameters();
            object[] args = new object[parameters.Length];

            RpcUtils.UnpackArgs(request, method, args, RpcUtils.IsRequestArgument);

            object serviceInstance = serviceImpl.GetInstance();
            try
            {
                object responseObj = method.Invoke(serviceInstance, args);
                OnBeforeWriteResponse(state);
                RpcUtils.PackArgs(response, method, responseObj, args, RpcUtils.IsResponseArgument);
            }
#if !(SILVERLIGHT || CF)
            catch (Exception ex)
            {
                Trace.WriteLine(ex, GetType() + ":" + serviceImpl.ServiceName);
                throw;
            }
#endif
            finally // release the singleton if we own it...
            {
                serviceImpl.ReleaseInstance(serviceInstance);
            }
        }
    }
}
#endif


text:
<?php

use Phinx\Migration\AbstractMigration;
use Phinx\Migration\IrreversibleMigrationException;

class RemoveColorsLinkedToColumn extends AbstractMigration {
  public function up() {
    $this->query("UPDATE colors c1 SET hex = c2.hex FROM (SELECT id, hex from colors) c2 WHERE c2.id = c1.linked_to");
    $this->table('colors')->removeColumn('linked_to')->update();
  }

  public function down() {
    throw new IrreversibleMigrationException();
  }
}


text:
require_relative '../type/igw'

module Awspec
  module Helper
    module Type
      def igw(*args)
        name = args.first
        Awspec::Type::Igw.new(name)
      end
    end
  end
end


text:
@interface YYFlowlayoutViewController () <UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView *feedsView;
@end

@implementation YYFlowlayoutViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;

    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:collectionView];
    self.feedsView = collectionView;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 100;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor grayColor];
    UILabel *titleLabel = [cell.contentView viewWithTag:100];
    if (!titleLabel) {
        titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 100, 20)];
        titleLabel.tag = 100;
        titleLabel.textColor = [UIColor blackColor];
        [cell.contentView addSubview:titleLabel];
    }
    titleLabel.text = [NSString stringWithFormat:@"flowc %ld", indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"water cell willDisplay: %ld", indexPath.row);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"water cell didSelectItem: %ld", indexPath.row);
}

#pragma mark - flowLayout Delegate

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(100, 100);
}

//设置水平间距 (同一行的cell的左右间距)
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

//垂直间距 (同一列cell上下间距)
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

@end


text:
layout: documentation
title: IDE integration
---

# Integrating Bazel with IDEs

IDEs integrate with Bazel in a variety of ways, from features that allow Bazel
executions from within the IDE, to awareness of Bazel structures such as syntax
highlighting of the BUILD files.

If you are interested in developing an editor or IDE plugin for Bazel, please
join the `#ide` channel on the [Bazel Slack](https://slack.bazel.build) or email
[bazel-dev@googlegroups.com](bazel-dev@googlegroups.com).

## IDEs and editors

### IntelliJ, Android Studio and CLion

[Official plugin](http://ij.bazel.build) for IntelliJ, Android Studio, and
CLion. The plugin is [open source](https://github.com/bazelbuild/intellij).

This is the open source version of the plugin used internally at Google.

Features:

* Interop with language-specific plugins. Supported languages include Java,
  Scala, and Python.
* Import BUILD files into the IDE with semantic awareness of Bazel targets.
* Make your IDE aware of Starlark, the language used for Bazel's BUILD and bzl
  files
* Build, test, and execute binaries directly from the IDE
* Create configurations for debugging and running binaries.

To install, go to the IDE's plugin browser and search for `Bazel`.

To manually install older versions, download the zip files from JetBrains'
Plugin Repository and install the zip file from the IDE's plugin browser:

*  [Android Studio
   plugin](https://plugins.jetbrains.com/plugin/9185-android-studio-with-bazel)
*  [IntelliJ
   plugin](https://plugins.jetbrains.com/plugin/8609-intellij-with-bazel)
*  [CLion plugin](https://plugins.jetbrains.com/plugin/9554-clion-with-bazel)

### Xcode

[Tulsi](https://tulsi.bazel.build) and
[XCHammer](https://github.com/pinterest/xchammer) generate Xcode projects from
Bazel `BUILD` files.

### Visual Studio Code

Official plugin for VS Code.

Features:

* Bazel Build Targets tree
* Starlark debugger for .bzl files during a build (set breakpoints, step through
  code, inspect variables, and so on)

Find [the plugin on the Visual Studio
marketplace](https://marketplace.visualstudio.com/items?itemName=BazelBuild.vscode-bazel).
The plugin is [open source](https://github.com/bazelbuild/vscode-bazel).

### Atom

Find the [`language-bazel` package](https://atom.io/packages/language-bazel) on
the Atom package manager.

### Vim

See [`bazelbuild/vim-bazel` on GitHub](https://github.com/bazelbuild/vim-bazel)

### Emacs

See [`bazelbuild/bazel-emacs-mode` on
GitHub](https://github.com/bazelbuild/emacs-bazel-mode)

### Visual Studio

[Lavender](https://github.com/tmandry/lavender) is an experimental project for
generating Visual Studio projects that use Bazel for building.

## Automatically run build and test on file change

[Bazel watcher](https://github.com/bazelbuild/bazel-watcher) is a tool for
building Bazel targets when source files change.

## Building your own IDE plugin

Read the [**IDE support** blog
post](https://bazel.build/blog/2016/06/10/ide-support.html) to learn more about
the Bazel APIs to use when building an IDE plugin.

## Archived projects

These projects are no longer supported by the Bazel team.

* [Eclipse](https://github.com/bazelbuild/eclipse)


text:
<?php

namespace Tests;

use DesignPatterns\Creational\AbstractFactory\HtmlFactory;
use DesignPatterns\Creational\AbstractFactory\HtmlText;
use DesignPatterns\Creational\AbstractFactory\JsonFactory;
use DesignPatterns\Creational\AbstractFactory\JsonText;

use PHPUnit\Framework\TestCase;

class AbstractFactoryTest extends TestCase
{
    public function testCanCreateHtmlText()
    {
        $factory = new HtmlFactory();
        $text = $factory->createText('foobar');
        $this->assertInstanceOf(HtmlText::class, $text);
    }

    public function testCanCreateJsonText()
    {
        $factory = new JsonFactory();
        $text = $factory->createText('foobar');
        $this->assertInstanceOf(JsonText::class, $text);
    }

}


text:
package org.projectfloodlight.openflow.protocol.ver15;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import com.google.common.collect.ImmutableList;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;

class OFBundlePropTimeVer15 implements OFBundlePropTime {
    private static final Logger logger = LoggerFactory.getLogger(OFBundlePropTimeVer15.class);
    // version: 1.5
    final static byte WIRE_VERSION = 6;
    final static int MINIMUM_LENGTH = 8;

        private final static List<OFTime> DEFAULT_SCHEDULED_TIME = ImmutableList.<OFTime>of();

    // OF message fields
    private final List<OFTime> scheduledTime;
//
    // Immutable default instance
    final static OFBundlePropTimeVer15 DEFAULT = new OFBundlePropTimeVer15(
        DEFAULT_SCHEDULED_TIME
    );

    // package private constructor - used by readers, builders, and factory
    OFBundlePropTimeVer15(List<OFTime> scheduledTime) {
        if(scheduledTime == null) {
            throw new NullPointerException("OFBundlePropTimeVer15: property scheduledTime cannot be null");
        }
        this.scheduledTime = scheduledTime;
    }

    // Accessors for OF message fields
    @Override
    public int getType() {
        return 0x1;
    }

    @Override
    public List<OFTime> getScheduledTime() {
        return scheduledTime;
    }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_15;
    }

    public OFBundlePropTime.Builder createBuilder() {
        return new BuilderWithParent(this);
    }

    static class BuilderWithParent implements OFBundlePropTime.Builder {
        final OFBundlePropTimeVer15 parentMessage;

        // OF message fields
        private boolean scheduledTimeSet;
        private List<OFTime> scheduledTime;

        BuilderWithParent(OFBundlePropTimeVer15 parentMessage) {
            this.parentMessage = parentMessage;
        }

    @Override
    public int getType() {
        return 0x1;
    }

    @Override
    public List<OFTime> getScheduledTime() {
        return scheduledTime;
    }

    @Override
    public OFBundlePropTime.Builder setScheduledTime(List<OFTime> scheduledTime) {
        this.scheduledTime = scheduledTime;
        this.scheduledTimeSet = true;
        return this;
    }
    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_15;
    }

        @Override
        public OFBundlePropTime build() {
                List<OFTime> scheduledTime = this.scheduledTimeSet ? this.scheduledTime : parentMessage.scheduledTime;
                if(scheduledTime == null)
                    throw new NullPointerException("Property scheduledTime must not be null");

                //
                return new OFBundlePropTimeVer15(
                    scheduledTime
                );
        }

    }

    static class Builder implements OFBundlePropTime.Builder {
        // OF message fields
        private boolean scheduledTimeSet;
        private List<OFTime> scheduledTime;

    @Override
    public int getType() {
        return 0x1;
    }

    @Override
    public List<OFTime> getScheduledTime() {
        return scheduledTime;
    }

    @Override
    public OFBundlePropTime.Builder setScheduledTime(List<OFTime> scheduledTime) {
        this.scheduledTime = scheduledTime;
        this.scheduledTimeSet = true;
        return this;
    }
    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_15;
    }

//
        @Override
        public OFBundlePropTime build() {
            List<OFTime> scheduledTime = this.scheduledTimeSet ? this.scheduledTime : DEFAULT_SCHEDULED_TIME;
            if(scheduledTime == null)
                throw new NullPointerException("Property scheduledTime must not be null");

            return new OFBundlePropTimeVer15(
                    scheduledTime
                );
        }

    }

    final static Reader READER = new Reader();
    static class Reader implements OFMessageReader<OFBundlePropTime> {
        @Override
        public OFBundlePropTime readFrom(ByteBuf bb) throws OFParseError {
            int start = bb.readerIndex();
            // fixed value property type == 0x1
            short type = bb.readShort();
            if(type != (short) 0x1)
                throw new OFParseError("Wrong type: Expected=0x1(0x1), got="+type);
            int length = U16.f(bb.readShort());
            if(length < MINIMUM_LENGTH)
                throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length);
            if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
                // Buffer does not have all data yet
                bb.readerIndex(start);
                return null;
            }
            if(logger.isTraceEnabled())
                logger.trace("readFrom - length={}", length);
            // pad: 4 bytes
            bb.skipBytes(4);
            List<OFTime> scheduledTime = ChannelUtils.readList(bb, length - (bb.readerIndex() - start), OFTimeVer15.READER);

            OFBundlePropTimeVer15 bundlePropTimeVer15 = new OFBundlePropTimeVer15(
                    scheduledTime
                    );
            if(logger.isTraceEnabled())
                logger.trace("readFrom - read={}", bundlePropTimeVer15);
            return bundlePropTimeVer15;
        }
    }

    public void putTo(PrimitiveSink sink) {
        FUNNEL.funnel(this, sink);
    }

    final static OFBundlePropTimeVer15Funnel FUNNEL = new OFBundlePropTimeVer15Funnel();
    static class OFBundlePropTimeVer15Funnel implements Funnel<OFBundlePropTimeVer15> {
        private static final long serialVersionUID = 1L;
        @Override
        public void funnel(OFBundlePropTimeVer15 message, PrimitiveSink sink) {
            // fixed value property type = 0x1
            sink.putShort((short) 0x1);
            // FIXME: skip funnel of length
            // skip pad (4 bytes)
            FunnelUtils.putList(message.scheduledTime, sink);
        }
    }

    public void writeTo(ByteBuf bb) {
        WRITER.write(bb, this);
    }

    final static Writer WRITER = new Writer();
    static class Writer implements OFMessageWriter<OFBundlePropTimeVer15> {
        @Override
        public void write(ByteBuf bb, OFBundlePropTimeVer15 message) {
            int startIndex = bb.writerIndex();
            // fixed value property type = 0x1
            bb.writeShort((short) 0x1);
            // length is length of variable message, will be updated at the end
            int lengthIndex = bb.writerIndex();
            bb.writeShort(U16.t(0));

            // pad: 4 bytes
            bb.writeZero(4);
            ChannelUtils.writeList(bb, message.scheduledTime);

            // update length field
            int length = bb.writerIndex() - startIndex;
            bb.setShort(lengthIndex, length);

        }
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder("OFBundlePropTimeVer15(");
        b.append("scheduledTime=").append(scheduledTime);
        b.append(")");
        return b.toString();
    }

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

        if (scheduledTime == null) {
            if (other.scheduledTime != null)
                return false;
        } else if (!scheduledTime.equals(other.scheduledTime))
            return false;
        return true;
    }

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

        result = prime * result + ((scheduledTime == null) ? 0 : scheduledTime.hashCode());
        return result;
    }

}


text:
This is an implementation of Mangopay API aiming to simplify it's integration in a Node.js project. It maps most of MangopayAPI to a simple interface as well as provides some convenience methods.

It uses `request-promise` and `bluebird` so each call returns a promise.

## Usage

Create new instance and configure you API keys:

```js
var clientId = 'myMangopayClientId';
var basicAuthKey = 'myBasicAuthGeneratedKeyWithManyRandomCharacters';

var mp = new Mangopay(clientId, basicAuthKey);
var userData = {
    Email: 'someone@example.com',
    FirstName: 'John',
    LastName: 'Doe',
    Birthday: new Date(1997, 1, 1).getTime() / 1000,
    Nationality: 'fr',
    CountryOfResidence: 'fr'
};
mp.createUser(userData)
    .then(function(mpResponse) {
        console.log('MP UserId is ' + mpResponse.Id);
    });
```

For full data specification of each method, refer to MP documentation.

## TODO

 - this library supports only basic authentification,
 - not all Mangopay interfaces are implemented