<commit_before>/**
 * Copyright 2015-2019 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html} from "lit";
import UtilsNew from "../../core/utilsNew.js";
import "../../webcomponents/commons/forms/data-form.js";
import "../../webcomponents/commons/tool-header.js";

export default class IvaProfile extends LitElement {

    constructor() {
        super();
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    _init() {

    }

    connectedCallback() {
        super.connectedCallback();
        this._config = {...this.getDefaultConfig(), ...this.config};

    }

    updated(changedProperties) {
        if (changedProperties.has("property")) {
            this.propertyObserver();
        }
        if (changedProperties.has("opencgaSession")) {
            this.opencgaSessionObserver();
        }
    }

    opencgaSessionObserver() {
        this.requestUpdate();

    }

    onFilterChange(field, value) {
        console.log("field, value", field, value)

    }

    getDefaultConfig() {
        return {
            title: "Your profile",
            icon: "",
            display: {
                collapsable: true,
                showTitle: false,
                labelWidth: 2,
                defaultValue: "-"
            },
            sections: [
                {
                    title: "General",
                    collapsed: false,
                    elements: [
                        {
                            name: "id",
                            field: "user.id"
                        },
                        {
                            name: "Name",
                            field: "user.name"
                        },
                        {
                            name: "Organization",
                            field: "user.organization"
                        },
                        {
                            name: "Account type",
                            field: "user.account.type"
                        },
                        {
                            name: "Status",
                            field: "user.internal.status",
                            type: "custom",
                            display: {
                                render: field => `${field?.name} (${UtilsNew.dateFormatter(field?.date)})`
                            }
                        },
                        {
                            name: "Data release",
                            type: "custom",
                            field: "project.attributes",
                            display: {
                                visible: data => !!data.project?.attributes?.release,
                                render: attributes => attributes?.release
                            }
                        },
                        {
                            name: "Project and studies",
                            field: "projects",
                            type: "table",
                            display: {
                                columns: [
                                    {
                                        name: "Id",
                                        field: "id"
                                    },
                                    {
                                        name: "Name",
                                        field: "name"
                                    },
                                    {
                                        name: "Studies",
                                        field: "studies",
                                        type: "custom",
                                        display: {
                                            render: studies => {
                                                return studies.map( study => study.name).join(", ")
                                            }
                                        }
                                    }
                                ]
                            }
                        }
                        /*{
                            name: "Quota",
                            field: "quota",
                            type: "custom",
                            display: {
                                render: field => html`${Object.entries(field).map( ([k, v]) => html`${k}:${v}
`)}`
                            }
                        }*/
                    ]
                }
                /*{
                    title: "Administration",
                    collapsed: false,
                    elements: [
                        {
                            name: "User",
                            field: "user.id",
                            type: "custom",
                            display: {
                                render: data => {
                                    const config = {
                                        addButton: false,
                                        fields: item => ({
                                            name: item.id
                                        }),
                                        dataSource: (query, process) => {
                                            this.opencgaSession.opencgaClient.studies().acl(this.opencgaSession.study.fqn).then(restResponse => {
                                                const results = restResponse.getResults();
                                                process(results.map(config.fields));
                                            });
                                        }
                                    };
                                    return html`<select-field-filter-autocomplete .opencgaSession="${this.opencgaSession}" .config=${config} .value="${this.value}" @filterChange="${e => this.onFilterChange("userid", e.detail.value)}"></select-field-filter-autocomplete>`
                                }
                            }
                        },
                        {
                            name: "Permissions",
                            type: "select",
                            multiple: true,
                            defaultValue: ["WRITE_FILES"],
                            allowedValues: ["CONFIDENTIAL_VARIABLE_SET_ACCESS", "EXECUTION",
                                {name: "Files", fields: ["WRITE_FILES", "VIEW_FILE_HEADERS", "VIEW_FILE_CONTENTS", "VIEW_FILES", "DELETE_FILES", "DOWNLOAD_FILES", "UPLOAD_FILES", "WRITE_FILE_ANNOTATIONS", "VIEW_FILE_ANNOTATIONS", "DELETE_FILE_ANNOTATIONS"]},
                                {name: "Jobs", fields: ["VIEW_JOBS", "WRITE_JOBS", "DELETE_JOBS"]},
                                {name: "Sample", fields: ["VIEW_SAMPLES", "WRITE_SAMPLES", "DELETE_SAMPLES", "WRITE_SAMPLE_ANNOTATIONS", "VIEW_SAMPLE_ANNOTATIONS", "DELETE_SAMPLE_ANNOTATIONS"]},
                                {name: "Individual", fields: ["VIEW_INDIVIDUALS", "WRITE_INDIVIDUALS", "DELETE_INDIVIDUALS", "WRITE_INDIVIDUAL_ANNOTATIONS", "VIEW_INDIVIDUAL_ANNOTATIONS", "DELETE_INDIVIDUAL_ANNOTATIONS"]},
                                {name: "Family", fields: ["VIEW_FAMILIES", "WRITE_FAMILIES", "DELETE_FAMILIES", "WRITE_FAMILY_ANNOTATIONS", "VIEW_FAMILY_ANNOTATIONS", "DELETE_FAMILY_ANNOTATIONS"]},
                                {name: "Cohort", fields: ["VIEW_COHORTS", "WRITE_COHORTS", "DELETE_COHORTS", "WRITE_COHORT_ANNOTATIONS", "VIEW_COHORT_ANNOTATIONS", "DELETE_COHORT_ANNOTATIONS"]},
                                {name: "Disease Panels", fields: ["VIEW_PANELS", "WRITE_PANELS", "DELETE_PANELS"]},
                                {name: "Clinical Analysis", fields: ["VIEW_CLINICAL_ANALYSIS", "WRITE_CLINICAL_ANALYSIS", "DELETE_CLINICAL_ANALYSIS"]}]
                        },
                        {
                            name: "Study",
                            field: "study",
                            type: "select",
                            allowedValues: ["study1"],
                            defaultValue: ["study1"],
                            errorMessage: "No found...",
                            display: {
                                width: 9
                            }
                        }
                    ]
                },*/

            ]
        };
    }

    render() {
        return html`

                <tool-header title="${this._config.title}" icon="${"fa fa-user-circle"}"></tool-header>

                            <data-form .data=${this.opencgaSession} .config="${this._config}"></data-form>

        `;
    }

}

customElements.define("iva-profile", IvaProfile);
<commit_msg>minor fix in iva-profile.js<commit_after>/**
 * Copyright 2015-2019 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html} from "lit";
import UtilsNew from "../../core/utilsNew.js";
import "../../webcomponents/commons/forms/data-form.js";
import "../../webcomponents/commons/tool-header.js";

export default class IvaProfile extends LitElement {

    constructor() {
        super();
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    _init() {

    }

    connectedCallback() {
        super.connectedCallback();
        this._config = {...this.getDefaultConfig(), ...this.config};

    }

    updated(changedProperties) {
        if (changedProperties.has("property")) {
            this.propertyObserver();
        }
        if (changedProperties.has("opencgaSession")) {
            this.opencgaSessionObserver();
        }
    }

    opencgaSessionObserver() {
        this.requestUpdate();

    }

    onFilterChange(field, value) {
        console.log("field, value", field, value)

    }

    getDefaultConfig() {
        return {
            title: "Your profile",
            icon: "",
            display: {
                collapsable: true,
                showTitle: false,
                labelWidth: 2,
                defaultValue: "-"
            },
            sections: [
                {
                    title: "General",
                    collapsed: false,
                    elements: [
                        {
                            name: "id",
                            field: "user.id"
                        },
                        {
                            name: "Name",
                            field: "user.name"
                        },
                        {
                            name: "Organization",
                            field: "user.organization"
                        },
                        {
                            name: "Account type",
                            field: "user.account.type"
                        },
                        {
                            name: "Status",
                            field: "user.internal.status",
                            type: "custom",
                            display: {
                                render: field => `${field?.name} (${UtilsNew.dateFormatter(field?.date)})`
                            }
                        },
                        {
                            name: "Data release",
                            type: "custom",
                            field: "project.attributes",
                            display: {
                                visible: data => !!data.project?.attributes?.release,
                                render: attributes => attributes?.release
                            }
                        },
                        {
                            name: "Project and studies",
                            field: "projects",
                            type: "table",
                            display: {
                                columns: [
                                    {
                                        name: "Id",
                                        field: "id"
                                    },
                                    {
                                        name: "Name",
                                        field: "name"
                                    },
                                    {
                                        name: "Studies",
                                        field: "studies",
                                        type: "custom",
                                        display: {
                                            render: studies => {
                                                return UtilsNew.renderHTML(`${studies.map(study => study.name).join("<br>")}`);
                                            }
                                        }
                                    }
                                ]
                            }
                        }
                        /*{
                            name: "Quota",
                            field: "quota",
                            type: "custom",
                            display: {
                                render: field => html`${Object.entries(field).map( ([k, v]) => html`${k}:${v}
`)}`
                            }
                        }*/
                    ]
                }
                /*{
                    title: "Administration",
                    collapsed: false,
                    elements: [
                        {
                            name: "User",
                            field: "user.id",
                            type: "custom",
                            display: {
                                render: data => {
                                    const config = {
                                        addButton: false,
                                        fields: item => ({
                                            name: item.id
                                        }),
                                        dataSource: (query, process) => {
                                            this.opencgaSession.opencgaClient.studies().acl(this.opencgaSession.study.fqn).then(restResponse => {
                                                const results = restResponse.getResults();
                                                process(results.map(config.fields));
                                            });
                                        }
                                    };
                                    return html`<select-field-filter-autocomplete .opencgaSession="${this.opencgaSession}" .config=${config} .value="${this.value}" @filterChange="${e => this.onFilterChange("userid", e.detail.value)}"></select-field-filter-autocomplete>`
                                }
                            }
                        },
                        {
                            name: "Permissions",
                            type: "select",
                            multiple: true,
                            defaultValue: ["WRITE_FILES"],
                            allowedValues: ["CONFIDENTIAL_VARIABLE_SET_ACCESS", "EXECUTION",
                                {name: "Files", fields: ["WRITE_FILES", "VIEW_FILE_HEADERS", "VIEW_FILE_CONTENTS", "VIEW_FILES", "DELETE_FILES", "DOWNLOAD_FILES", "UPLOAD_FILES", "WRITE_FILE_ANNOTATIONS", "VIEW_FILE_ANNOTATIONS", "DELETE_FILE_ANNOTATIONS"]},
                                {name: "Jobs", fields: ["VIEW_JOBS", "WRITE_JOBS", "DELETE_JOBS"]},
                                {name: "Sample", fields: ["VIEW_SAMPLES", "WRITE_SAMPLES", "DELETE_SAMPLES", "WRITE_SAMPLE_ANNOTATIONS", "VIEW_SAMPLE_ANNOTATIONS", "DELETE_SAMPLE_ANNOTATIONS"]},
                                {name: "Individual", fields: ["VIEW_INDIVIDUALS", "WRITE_INDIVIDUALS", "DELETE_INDIVIDUALS", "WRITE_INDIVIDUAL_ANNOTATIONS", "VIEW_INDIVIDUAL_ANNOTATIONS", "DELETE_INDIVIDUAL_ANNOTATIONS"]},
                                {name: "Family", fields: ["VIEW_FAMILIES", "WRITE_FAMILIES", "DELETE_FAMILIES", "WRITE_FAMILY_ANNOTATIONS", "VIEW_FAMILY_ANNOTATIONS", "DELETE_FAMILY_ANNOTATIONS"]},
                                {name: "Cohort", fields: ["VIEW_COHORTS", "WRITE_COHORTS", "DELETE_COHORTS", "WRITE_COHORT_ANNOTATIONS", "VIEW_COHORT_ANNOTATIONS", "DELETE_COHORT_ANNOTATIONS"]},
                                {name: "Disease Panels", fields: ["VIEW_PANELS", "WRITE_PANELS", "DELETE_PANELS"]},
                                {name: "Clinical Analysis", fields: ["VIEW_CLINICAL_ANALYSIS", "WRITE_CLINICAL_ANALYSIS", "DELETE_CLINICAL_ANALYSIS"]}]
                        },
                        {
                            name: "Study",
                            field: "study",
                            type: "select",
                            allowedValues: ["study1"],
                            defaultValue: ["study1"],
                            errorMessage: "No found...",
                            display: {
                                width: 9
                            }
                        }
                    ]
                },*/

            ]
        };
    }

    render() {
        return html`

                <tool-header title="${this._config.title}" icon="${"fa fa-user-circle"}"></tool-header>

                            <data-form .data=${this.opencgaSession} .config="${this._config}"></data-form>

        `;
    }

}

customElements.define("iva-profile", IvaProfile);
<|endoftext|>


<commit_before>// Define Pokemon Object. Requires `Data` to be defined.

function Pokemon(name, set) {
	this.id = toID(name);
	if (!this.id) return false;
	var set = set || {item:"",ability:"",ivs:{},evs:{}};
	for (var prop in Data.Pokedex[this.id]) this[prop] = Data.Pokedex[this.id][prop];
	this.set = {ivs:{},evs:{}};
	for (var prop in set) this.set[prop] = set[prop];
	this.item = toID(this.set.item || (this.set.items && this.set.items[0]) || "");
	this.ability = toID(this.set.ability || (this.set.abilities && this.set.abilities[0]) || this.abilities[0]);
	this.nature = this.set.nature || (this.set.natures && this.set.natures[0]) || "Docile";
	this.level = parseInt(this.set.level) || 100;
	var statTable = {"hp" : "HP","atk" : "Atk","def" : "Def","spa" : "SpA","spd" : "SpD","spe" : "Spe"}
	this.ivs = {}; this.evs = {};
	this.baseStats = this.baseStats || {};
	this.boosts = this.set.boosts || {};
	for (var stat in statTable) {
		this.baseStats[stat] = parseInt(this.baseStats[stat]) || 10;
		this.ivs[stat] = parseInt(this.set.ivs[stat]) || 31;
		this.evs[stat] = parseInt(this.set.evs[stat]) || 0;
		if (stat !== 'hp') this.boosts[stat] = parseInt(this.boosts[stat]) || 0;
	}
	this.calcStats();
	this.moveset = (this.set.moveset || this.randomMoveset() || []).slice(0,4).map(toID);
	while (this.moveset.length < 4) this.moveset.push('');
	if (!this.genderRatio && !this.gender) this.genderRatio = {M:0.5,F:0.5};
	this.gender = this.gender || this.set.gender || this.randomGender();
	var hpTypes = ["Fighting", "Flying", "Poison", "Ground", "Rock", "Bug", "Ghost", "Steel", "Fire", "Water", "Grass", "Electric", "Psychic", "Ice", "Dragon", "Dark"];
	var hpTypeIndex = Math.floor(parseInt(function() { var buf = ""; buf += ''+(this.ivs[stat] % 2) ; return buf; }, 2) * 15 / 63)
	this.hpType = hpTypes[hpTypeIndex];
	this.hpPower = 60; //Math.floor(parseInt(function() { var buf = ""; for (var stat in statTable) { buf += ''+((this.ivs[stat] & 2) / 2) }; return buf; }, 2) * 40 / 63 + 30)
	this.status = this.set.status || "";
	this.currentHP = parseInt(this.set.currentHP || this.stats['hp']);
	this.happiness = parseInt(this.set.happiness || 255);
};

Pokemon.prototype.changeSet = function(set) {
	set = set || {item:"",ability:"",ivs:{},evs:{}};
	this.set = {};
	for (var prop in set) this.set[prop] = set[prop];
	this.item = toID(this.set.item || (this.set.items && this.set.items[0]) || "");
	this.ability = toID(this.set.ability || (this.set.abilities && this.set.abilities[0]) || this.abilities[0]);
	this.nature = this.set.nature || "Docile";
	this.level = this.set.level || 100;
	var statTable = {"hp" : "HP" , "atk" : "Atk" , "def" : "Def" , "spa" : "SpA" , "spd" : "SpD" , "spe" : "Spe"};
	this.ivs = {}; this.evs = {};
	for (var stat in statTable) {
		this.baseStats[stat] = this.baseStats[stat] || 10;
		this.ivs[stat] = this.set.ivs[stat] || 31;
		this.evs[stat] = this.set.evs[stat] || 0;
	}
	this.moveset = (this.set.moveset || ["","","",""]).map(toID);
};
Pokemon.prototype.calcStats = function() {
	this.stats = {};
	for (var stat in {"hp":"HP","atk":"Atk","def":"Def","spa":"SpA","spd":"SpD","spe":"Spe"}) {
		if (stat === 'hp') this.stats[stat] = (this.baseStats[stat] === 1 ? 1 : Math.floor(Math.floor(2*this.baseStats[stat] + this.ivs[stat] + this.evs[stat]/4) * this.level/100) + this.level + 10);
		else {
			var nature = Data.Natures[this.nature];
			var natureBoost = (nature.plus === stat ? 1.1 : (nature.minus === stat ? 0.9 : 1));
			this.stats[stat] = Math.floor(Math.floor(Math.floor(2*this.baseStats[stat] + this.ivs[stat] + this.evs[stat]/4) * this.level/100 + 5) * natureBoost);
		}
	}
}
Pokemon.prototype.randomGender = function () {
	if (!this.genderRatio) return this.gender || "N";
	return (Math.floor(Math.random()*0x100)/0x100 < this.genderRatio['M'] ? 'F' : 'M');
};
Pokemon.prototype.randomMoveset = function() {
	if (!Data.getLearnset) return null;
	var lset = Data.getLearnset(this.id);
	if (!lset) return false;
	var moves = Object.keys(lset['sketch'] ? Data.Movedex : lset);
	var randSet = [];
	for (var i = 0; i < 4; i++) {
		randSet.push(moves[parseInt(Math.random()*moves.length)]);
	}
	return randSet;
};
Pokemon.prototype.resetDetails = function() {
	var newPoke = new Pokemon(this.id);
	for (var prop in newPoke) this[prop] = newPoke[prop];
};
Pokemon.prototype.update = function() {
	this.calcStats();
};
<commit_msg>Add `Pokemon.randomMoveset()`<commit_after>// Define Pokemon Object. Requires `Data` to be defined.

function Pokemon(name, set) {
	this.id = toID(name);
	if (!this.id) return false;
	var set = set || {item:"",ability:"",ivs:{},evs:{}};
	for (var prop in Data.Pokedex[this.id]) this[prop] = Data.Pokedex[this.id][prop];
	this.set = {ivs:{},evs:{}};
	for (var prop in set) this.set[prop] = set[prop];
	this.item = toID(this.set.item || (this.set.items && this.set.items[0]) || "");
	this.ability = toID(this.set.ability || (this.set.abilities && this.set.abilities[0]) || this.abilities[0]);
	this.nature = this.set.nature || (this.set.natures && this.set.natures[0]) || "Docile";
	this.level = parseInt(this.set.level) || 100;
	var statTable = Data.StatTable;
	this.ivs = {}; this.evs = {};
	this.baseStats = this.baseStats || {};
	this.boosts = this.set.boosts || {};
	for (var stat in statTable) {
		this.baseStats[stat] = parseInt(this.baseStats[stat]) || 10;
		this.ivs[stat] = parseInt(this.set.ivs[stat]) || 31;
		this.evs[stat] = parseInt(this.set.evs[stat]) || 0;
		if (stat !== 'hp') this.boosts[stat] = parseInt(this.boosts[stat]) || 0;
	}
	this.calcStats();
	this.moveset = (this.set.moveset || this.randomMoveset() || []).slice(0,4).map(toID);
	while (this.moveset.length < 4) this.moveset.push('');
	if (!this.genderRatio && !this.gender) this.genderRatio = {M:0.5,F:0.5};
	this.gender = this.gender || this.set.gender || this.randomGender();
	var hpTypes = ["Fighting", "Flying", "Poison", "Ground", "Rock", "Bug", "Ghost", "Steel", "Fire", "Water", "Grass", "Electric", "Psychic", "Ice", "Dragon", "Dark"];
	var hpTypeIndex = Math.floor(parseInt(function() { var buf = ""; buf += ''+(this.ivs[stat] % 2) ; return buf; }, 2) * 15 / 63)
	this.hpType = hpTypes[hpTypeIndex];
	this.hpPower = 60; //Math.floor(parseInt(function() { var buf = ""; for (var stat in statTable) { buf += ''+((this.ivs[stat] & 2) / 2) }; return buf; }, 2) * 40 / 63 + 30)
	this.status = this.set.status || "";
	this.currentHP = parseInt(this.set.currentHP || this.stats['hp']);
	this.happiness = parseInt(this.set.happiness || 255);
};

Pokemon.prototype.changeSet = function(set) {
	set = set || {item:"",ability:"",ivs:{},evs:{}};
	this.set = {};
	for (var prop in set) this.set[prop] = set[prop];
	this.item = toID(this.set.item || (this.set.items && this.set.items[0]) || "");
	this.ability = toID(this.set.ability || (this.set.abilities && this.set.abilities[0]) || this.abilities[0]);
	this.nature = this.set.nature || "Docile";
	this.level = this.set.level || 100;
	var statTable = Data.StatTable;
	this.ivs = {}; this.evs = {};
	this.baseStats = this.baseStats || {};
	this.boosts = this.set.boosts || {};
	for (var stat in statTable) {
		this.baseStats[stat] = parseInt(this.baseStats[stat]) || 10;
		this.ivs[stat] = parseInt(this.set.ivs[stat]) || 31;
		this.evs[stat] = parseInt(this.set.evs[stat]) || 0;
		if (stat !== 'hp') this.boosts[stat] = parseInt(this.boosts[stat]) || 0;
	}
	this.calcStats();
	this.moveset = (this.set.moveset || ["","","",""]).map(toID);
	return this;
};
Pokemon.prototype.calcStats = function() {
	this.stats = {};
	for (var stat in {"hp":"HP","atk":"Atk","def":"Def","spa":"SpA","spd":"SpD","spe":"Spe"}) {
		if (stat === 'hp') this.stats[stat] = (this.baseStats[stat] === 1 ? 1 : Math.floor(Math.floor(2*this.baseStats[stat] + this.ivs[stat] + this.evs[stat]/4) * this.level/100) + this.level + 10);
		else {
			var nature = Data.Natures[this.nature];
			var natureBoost = (nature.plus === stat ? 1.1 : (nature.minus === stat ? 0.9 : 1));
			this.stats[stat] = Math.floor(Math.floor(Math.floor(2*this.baseStats[stat] + this.ivs[stat] + this.evs[stat]/4) * this.level/100 + 5) * natureBoost);
		}
	}
}
Pokemon.prototype.randomGender = function () {
	if (!this.genderRatio) return this.gender || "N";
	return (Math.floor(Math.random()*0x100)/0x100 < this.genderRatio['M'] ? 'F' : 'M');
};
Pokemon.prototype.randomMoveset = function() {
	if (!Data.getLearnset) return null;
	var lset = Data.getLearnset(this.id);
	if (!lset) return false;
	var moves = Object.keys(lset['sketch'] ? Data.Movedex : lset);
	var randSet = [];
	for (var i = 0; i < 4; i++) {
		randSet.push(moves[parseInt(Math.random()*moves.length)]);
	}
	return randSet;
};
Pokemon.prototype.resetDetails = function() {
	var newPoke = new Pokemon(this.id);
	for (var prop in newPoke) this[prop] = newPoke[prop];
};
Pokemon.prototype.update = function() {
	this.calcStats();
};
Pokemon.randomMoveset = function (pokemon) { // This one is accessible outside the Pokemon object
	if (!Data.getLearnset) return null;
	var lset = Data.getLearnset(toID(pokemon));
	if (!lset) return false;
	var moves = Object.keys(lset['sketch'] ? Data.Movedex : lset);
	var randSet = [];
	for (var i = 0; i < 4; i++) {
		randSet.push(moves[parseInt(Math.random()*moves.length)]);
	}
	return randSet;
}

<|endoftext|>


<commit_before>'use strict';

var Instance = require('sivart-GCE/Instance');
var fs = require('fs');
var CreateScript = require('./CreateScript');
var path = require('path');
var printf = require('util').format;
var uuid = require('uuid');
var gcloud = require('gcloud');
var Auth = require('sivart-GCE/Auth');

var dataset = gcloud.datastore.dataset(Auth);

function Project(eventName, args) {
  // TODO(trostler): handle other events (like PR)
  this.eventName = eventName;
  this.keepVM = args.keepVM;
  this.github = args;
  this.timeout = args.timeout || 3600;
  this.nochangeTimeout = args.nochangeTimeout || 600;

  this.repoName = args.repository.full_name;
  this.cloneURL = args.repository.clone_url;
  this.yamlURL = printf('https://raw.githubusercontent.com/%s/%s/.travis.yml', this.repoName, this.branch || 'master');
  this.metadata = { eventName: eventName, message: args };

  if (eventName === 'push') {
    this.branch = path.basename(args.ref);
    this.commit = args.after;
  } else if (eventName === 'pull_request') { // PR
    this.pr = args.number;
    this.action = args.action; // 'synchronize' or 'closed' or 'unlabeled'
    /*
     * probably only want opened/closed/synchronized?
    if (action == 'opened' || action == 'closed' || action == 'synchronized') {
      // ...
    } else {
      return null;
    }
    */
  } else {
    throw new Error('Cannot handle ' + eventName);
  }

  this.createScript = new CreateScript(this);
  this.slaveFile = args.slaveJSON || path.join(__dirname, 'gce/slave.json');
  this.zone = args.zone || 'us-central1-a';
  this.projectId = args.projectId || Auth.projectId;
  this.slaves = {};
}

Project.prototype.createScripts = function(cb) {
  var me = this;
  this.createScript.getScripts(function(err, scripts) {
    if (err) {
      cb(err);
    } else {
      me.scripts = scripts;
      cb(null, scripts);
    }
  });
};

Project.prototype.createSlave = function(script, cb) {
  var me = this;
  var instanceName = uuid.v1();
  var data = JSON.parse(fs.readFileSync(this.slaveFile));
  data.name = instanceName;
  data.disks[0].deviceName = 'slave-disk';
  data.disks[0].initializeParams.sourceImage = 'global/images/slave'; // Created with 'createSnapshot.js'
  // data.metadata.items[0].value = script.script.replace('$', '\\$');
  data.metadata.items[0].value = script.script; // .replace('$', '\\$');
  var sivartSlave = new Instance(Auth.projectId, this.zone, instanceName);
  sivartSlave.create({ instance: data }, function(err) { // , resp) {
    if (err) {
      cb('ERROR creating instance:' + err);
    } else {
      script.metadata.created = new Date().getTime();
      me.slaves[instanceName] = script.metadata;
      cb(null, instanceName);
    }
  });
};

Project.prototype.createAllSlaves = function(cb) {
  var me = this;
  this.createScripts(function(cserr, scripts) {
    if (cserr) {
      cb(cserr);
    } else {
      var done = 0;
      var errors = [];
      var responses = {};
      scripts.forEach(function(script) {
        me.createSlave(script, function(cslaveerr, data) {
          if (cslaveerr) {
            errors.push(cslaveerr);
          } else {
            responses[data] = script.metadata;
          }
          // use promises :)
          done++;
          if (done === scripts.length) {
            me.initialSave(errors, responses, function(err, key) {
              if (err) {
                errors.push(err);
              }
              cb(errors, responses, key);
            });
          }
        });
      });
    }
  });
};

Project.prototype.initialSave = function(errors, instances, cb) {
  var safeName = this.repoName.replace(/\//g, '.');
  var keyKind = this.eventName;
  var key = dataset.key({ namespace: safeName, path: [ keyKind ] });

  var data = { errors: errors, instances: instances, github: this.github };
  data = JSON.parse(JSON.stringify(data, function(k, v) {
    if (!v) {
      // Datasets don't like nulls in them - replace with empty strings
      return '';
    } else if (v instanceof Object && !Object.keys(v).length) {
      // Datasets also don't like empty objects!
      return ''; // or maybe { ____iamempty: 0 }?
    } else {
      return v;
    }
  }));

  console.log('Saving: data:');
  console.log(require('util').inspect(data, { showHidden: true, depth: null }));

  dataset.save({ key: key, data: data }, function(err) { // , r) {
    if (err) {
      cb(err);
    } else {
      cb(null, key);
    }
  });
};

module.exports = Project;
<commit_msg>better debug<commit_after>'use strict';

var Instance = require('sivart-GCE/Instance');
var fs = require('fs');
var CreateScript = require('./CreateScript');
var path = require('path');
var printf = require('util').format;
var uuid = require('uuid');
var gcloud = require('gcloud');
var Auth = require('sivart-GCE/Auth');

var dataset = gcloud.datastore.dataset(Auth);

function Project(eventName, args) {
  // TODO(trostler): handle other events (like PR)
  this.eventName = eventName;
  this.keepVM = args.keepVM;
  this.github = args;
  this.timeout = args.timeout || 3600;
  this.nochangeTimeout = args.nochangeTimeout || 600;

  this.repoName = args.repository.full_name;
  this.cloneURL = args.repository.clone_url;
  this.yamlURL = printf('https://raw.githubusercontent.com/%s/%s/.travis.yml', this.repoName, this.branch || 'master');
  this.metadata = { eventName: eventName, message: args };

  if (eventName === 'push') {
    this.branch = path.basename(args.ref);
    this.commit = args.after;
  } else if (eventName === 'pull_request') { // PR
    this.pr = args.number;
    this.action = args.action; // 'synchronize' or 'closed' or 'unlabeled'
    /*
     * probably only want opened/closed/synchronized?
    if (action == 'opened' || action == 'closed' || action == 'synchronized') {
      // ...
    } else {
      return null;
    }
    */
  } else {
    throw new Error('I do not handle github event: ' + eventName);
  }

  this.createScript = new CreateScript(this);
  this.slaveFile = args.slaveJSON || path.join(__dirname, 'gce/slave.json');
  this.zone = args.zone || 'us-central1-a';
  this.projectId = args.projectId || Auth.projectId;
  this.slaves = {};
}

Project.prototype.createScripts = function(cb) {
  var me = this;
  this.createScript.getScripts(function(err, scripts) {
    if (err) {
      cb(err);
    } else {
      me.scripts = scripts;
      cb(null, scripts);
    }
  });
};

Project.prototype.createSlave = function(script, cb) {
  var me = this;
  var instanceName = uuid.v1();
  var data = JSON.parse(fs.readFileSync(this.slaveFile));
  data.name = instanceName;
  data.disks[0].deviceName = 'slave-disk';
  data.disks[0].initializeParams.sourceImage = 'global/images/slave'; // Created with 'createSnapshot.js'
  // data.metadata.items[0].value = script.script.replace('$', '\\$');
  data.metadata.items[0].value = script.script; // .replace('$', '\\$');
  var sivartSlave = new Instance(Auth.projectId, this.zone, instanceName);
  sivartSlave.create({ instance: data }, function(err) { // , resp) {
    if (err) {
      cb('ERROR creating instance:' + err);
    } else {
      script.metadata.created = new Date().getTime();
      me.slaves[instanceName] = script.metadata;
      cb(null, instanceName);
    }
  });
};

Project.prototype.createAllSlaves = function(cb) {
  var me = this;
  this.createScripts(function(cserr, scripts) {
    if (cserr) {
      cb(cserr);
    } else {
      var done = 0;
      var errors = [];
      var responses = {};
      scripts.forEach(function(script) {
        me.createSlave(script, function(cslaveerr, data) {
          if (cslaveerr) {
            errors.push(cslaveerr);
          } else {
            responses[data] = script.metadata;
          }
          // use promises :)
          done++;
          if (done === scripts.length) {
            me.initialSave(errors, responses, function(err, key) {
              if (err) {
                errors.push(err);
              }
              cb(errors, responses, key);
            });
          }
        });
      });
    }
  });
};

Project.prototype.initialSave = function(errors, instances, cb) {
  var safeName = this.repoName.replace(/\//g, '.');
  var keyKind = this.eventName;
  var key = dataset.key({ namespace: safeName, path: [ keyKind ] });

  var data = { errors: errors, instances: instances, github: this.github };
  data = JSON.parse(JSON.stringify(data, function(k, v) {
    if (!v) {
      // Datasets don't like nulls in them - replace with empty strings
      return '';
    } else if (v instanceof Object && !Object.keys(v).length) {
      // Datasets also don't like empty objects!
      return ''; // or maybe { ____iamempty: 0 }?
    } else {
      return v;
    }
  }));

  console.log('Saving: data:');
  console.log(require('util').inspect(data, { showHidden: true, depth: null }));

  dataset.save({ key: key, data: data }, function(err) { // , r) {
    if (err) {
      cb(err);
    } else {
      cb(null, key);
    }
  });
};

module.exports = Project;
<|endoftext|>


<commit_before>(function() {
	// Ignore the rest if there is native Promises
	if(window.Promise) {
		if(typeof module !== 'undefined' && module.exports) {
			module.exports = window.Promise;
		}
		return;
	}

	var asap = window.setImmediate || function(fn){ setTimeout(fn, 0) };
	function Promise(fn) {
		if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
		if (typeof fn !== 'function') throw new TypeError('not a function');
		this._state = null;
		this._value = null;
		this._deferreds = [];
		var self = this;

		doResolve(fn, function(data) {
			resolve.call(self, data);
		}, function(reason) {
			reject.call(self, reason);
		});
	}

	function handle(deferred) {
		var self = this;
		if (this._state === null) {
			this._deferreds.push(deferred);
			return;
		}
		asap(function() {
			var cb = self._state ? deferred.onFulfilled : deferred.onRejected;
			if (cb === null) {
				(self._state ? deferred.resolve : deferred.reject)(self._value);
				return;
			}
			var ret;
			try {
				ret = cb(self._value);
			}
			catch (e) {
				deferred.reject(e);
				return;
			}
			deferred.resolve(ret);
		})
	}

	function resolve(newValue) {
		var self = this;
		try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
			if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');
			if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
				var then = newValue.then;
				if (typeof then === 'function') {
					doResolve(function() {
						then.call(newValue)
					}, function(data) {
						resolve.call(self, data);
					}, function(reason) {
						reject.call(self, reason);
					});
					return;
				}
			}
			this._state = true;
			this._value = newValue;
			finale.call(this);
		} catch (e) { reject(e) }
	}

	function reject(newValue) {
		this._state = false;
		this._value = newValue;
		finale.call(this);
	}

	function finale() {
		for (var i = 0, len = this._deferreds.length; i < len; i++) {
			handle.call(this, this._deferreds[i]);
		}
		this._deferreds = null;
	}

	function Handler(onFulfilled, onRejected, resolve, reject){
		this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
		this.onRejected = typeof onRejected === 'function' ? onRejected : null;
		this.resolve = resolve;
		this.reject = reject;
	}

	/**
	 * Take a potentially misbehaving resolver function and make sure
	 * onFulfilled and onRejected are only called once.
	 *
	 * Makes no guarantees about asynchrony.
	 */
	function doResolve(fn, onFulfilled, onRejected) {
		var done = false;
		try {
			fn(function (value) {
				if (done) return;
				done = true;
				onFulfilled(value);
			}, function (reason) {
				if (done) return;
				done = true;
				onRejected(reason);
			})
		} catch (ex) {
			if (done) return;
			onRejected(ex);
		}
	}

	Promise.all = function () {
		var args = Array.prototype.slice.call(arguments.length === 1 && Array.isArray(arguments[0]) ? arguments[0] : arguments);

		return new Promise(function (resolve, reject) {
			if (args.length === 0) return resolve([]);
			var remaining = args.length;
			function res(i, val) {
				try {
					if (val && (typeof val === 'object' || typeof val === 'function')) {
						var then = val.then;
						if (typeof then === 'function') {
							then.call(val, function (val) { res(i, val) }, reject);
							return;
						}
					}
					args[i] = val;
					if (--remaining === 0) {
						resolve(args);
					}
				} catch (ex) {
					reject(ex);
				}
			}
			for (var i = 0; i < args.length; i++) {
				res(i, args[i]);
			}
		});
	};

	/* Prototype Methods */
	Promise.prototype.then = function(onFulfilled, onRejected) {
		var self = this;
		return new Promise(function(resolve, reject) {
			handle.call(self, new Handler(onFulfilled, onRejected, resolve, reject));
		})
	};

	Promise.prototype['catch'] = function (onRejected) {
		return this.then(null, onRejected);
	};

	Promise.resolve = function (value) {
		return new Promise(function (resolve) {
			resolve(value);
		});
	};

	Promise.reject = function (value) {
		return new Promise(function (resolve, reject) {
			reject(value);
		});
	};

	Promise.race = function (values) {
		return new Promise(function (resolve, reject) {
			values.map(function(value){
				value.then(resolve, reject);
			})
		});
	};

	if(typeof module !== 'undefined' && module.exports) {
		module.exports = Promise;
	} else {
		window.Promise = Promise;
	}
})();
<commit_msg>Fixed a bug when resolving a promise with a promise<commit_after>(function() {
	// Ignore the rest if there is native Promises
	if(window.Promise) {
		if(typeof module !== 'undefined' && module.exports) {
			module.exports = window.Promise;
		}
		return;
	}

	var asap = window.setImmediate || function(fn){ setTimeout(fn, 0) };
	function Promise(fn) {
		if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
		if (typeof fn !== 'function') throw new TypeError('not a function');
		this._state = null;
		this._value = null;
		this._deferreds = [];
		var self = this;

		doResolve(fn, function(data) {
			resolve.call(self, data);
		}, function(reason) {
			reject.call(self, reason);
		});
	}

	function handle(deferred) {
		var self = this;
		if (this._state === null) {
			this._deferreds.push(deferred);
			return;
		}
		asap(function() {
			var cb = self._state ? deferred.onFulfilled : deferred.onRejected;
			if (cb === null) {
				(self._state ? deferred.resolve : deferred.reject)(self._value);
				return;
			}
			var ret;
			try {
				ret = cb(self._value);
			}
			catch (e) {
				deferred.reject(e);
				return;
			}
			deferred.resolve(ret);
		})
	}

	function resolve(newValue) {
		var self = this;
		try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
			if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');
			if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
				if (typeof newValue.then === 'function') {
					doResolve(function() {
						newValue.then(function(value) {
							resolve.call(self, value);
						}, function(reason) {
							reject.call(self, reason);
						});
					}, function(data) {
						resolve.call(self, data);
					}, function(reason) {
						reject.call(self, reason);
					});
					return;
				}
			}
			this._state = true;
			this._value = newValue;
			finale.call(this);
		} catch (e) { reject(e) }
	}

	function reject(newValue) {
		this._state = false;
		this._value = newValue;
		finale.call(this);
	}

	function finale() {
		for (var i = 0, len = this._deferreds.length; i < len; i++) {
			handle.call(this, this._deferreds[i]);
		}
		this._deferreds = null;
	}

	function Handler(onFulfilled, onRejected, resolve, reject){
		this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
		this.onRejected = typeof onRejected === 'function' ? onRejected : null;
		this.resolve = resolve;
		this.reject = reject;
	}

	/**
	 * Take a potentially misbehaving resolver function and make sure
	 * onFulfilled and onRejected are only called once.
	 *
	 * Makes no guarantees about asynchrony.
	 */
	function doResolve(fn, onFulfilled, onRejected) {
		var done = false;
		try {
			fn(function (value) {
				if (done) return;
				done = true;
				onFulfilled(value);
			}, function (reason) {
				if (done) return;
				done = true;
				onRejected(reason);
			})
		} catch (ex) {
			if (done) return;
			onRejected(ex);
		}
	}

	Promise.all = function () {
		var args = Array.prototype.slice.call(arguments.length === 1 && Array.isArray(arguments[0]) ? arguments[0] : arguments);

		return new Promise(function (resolve, reject) {
			if (args.length === 0) return resolve([]);
			var remaining = args.length;
			function res(i, val) {
				try {
					if (val && (typeof val === 'object' || typeof val === 'function')) {
						var then = val.then;
						if (typeof then === 'function') {
							then.call(val, function (val) { res(i, val) }, reject);
							return;
						}
					}
					args[i] = val;
					if (--remaining === 0) {
						resolve(args);
					}
				} catch (ex) {
					reject(ex);
				}
			}
			for (var i = 0; i < args.length; i++) {
				res(i, args[i]);
			}
		});
	};

	/* Prototype Methods */
	Promise.prototype.then = function(onFulfilled, onRejected) {
		var self = this;
		return new Promise(function(resolve, reject) {
			handle.call(self, new Handler(onFulfilled, onRejected, resolve, reject));
		})
	};

	Promise.prototype['catch'] = function (onRejected) {
		return this.then(null, onRejected);
	};

	Promise.resolve = function (value) {
		return new Promise(function (resolve) {
			resolve(value);
		});
	};

	Promise.reject = function (value) {
		return new Promise(function (resolve, reject) {
			reject(value);
		});
	};

	Promise.race = function (values) {
		return new Promise(function (resolve, reject) {
			values.map(function(value){
				value.then(resolve, reject);
			})
		});
	};

	if(typeof module !== 'undefined' && module.exports) {
		module.exports = Promise;
	} else {
		window.Promise = Promise;
	}
})();
<|endoftext|>


<commit_before>/**
* @license libAurora.js Copyright (c) 2011-2012 Contributors
* See CONTRIBUTORS.TXT for a full list of copyright holders.
* MIT License
*/
(function(window, document, undefined){
	var
		EventTarget      = window['EventTarget'],
		Aurora           = window['Aurora'] || {},
		Addon            = Aurora['Addon'] || {},
		JSON             = window['JSON'],
		md5              = window['md5'],
		is_array         = window['is_array'],
		array_keys       = window['array_keys'],
		base64_encode    = window['base64_encode'],
		XMLHttpRequest   = window['XMLHttpRequest'],
		http_build_query = window['http_build_query'],
		validateJSONResponse = function(result, expectedResponse){
			if(!(typeof(result) == 'string')){
				throw new TypeError('API result expected to be a string, ' + typeof(result) + ' found.');
			}else{
				var
					result = JSON['parse'](result),
					expectedResponse = expectedResponse || []
				;
				if(typeof(result) != 'object'){
					throw new TypeError('API result expected to be an object, ' + typeof(result) + ' found.');
				}else if(!is_array(expectedResponse)){
					throw new TypeError('Expected Response argument must be specified as an array, not ' + typeof(expectedResponse));
				}
				expectedResponse['forEach'](function(v, k){
					if(!(k in result)){
						throw new Error('Call to API was successful, but required response properties were missing.');
					}else if(array_keys(v)['indexOf'](typeof(result[k])) < 0){
						throw new Error('Call to API was successful, but required response property was of unexpected type.');
					}else if(v[typeof(result[k])] && v[typeof(result[k])]['length'] > 0){
						var
							validValue = false
						;
						v[typeof(result[k])]['forEach'](function(possibleValue, _k){
							if(typeof(_k) == 'number'){
								if(typeof(result[k]) == 'boolean'){
									if(!typeof(possibleValue)){
										throw new TypeError('Only booleans can be given as valid values to a boolean type.');
									}else if(result[k] == possibleValue){
										validValue = true;
										return;
									}
								}else{
									var
										subPropertyKeys = array_keys(possibleValue),
										rkType = typeof(result[k]) == 'object' ? (!is_array(result[k]) ? 'object' : 'array') : typeof(result[k]);
									;
									switch(typeof(rkType)){
										case 'array':
											result[k]['forEach'](function(_v){
												var
													_v_Type = typeof(_v)
												;
												if(subPropertyKeys['indexOf'](_v_Type) < 0){
													throw new TypeError('Call to API was successful, but required response sub-property was of unexpected type.');
												}else if(_v_Type == 'object' && !!possibleValue[_v_Type]){
													var
														pos = possibleValue[_v_Type]
													;
													if(_v_Type == 'object'){
														pos = first(pos);
													}
													if(!!pos){
														pos['forEach'](function(__v, __k){
															if(!_v[__k]){
																throw new Error('Call to API was successful, but required response sub-property property was of missing.');
															}else{
																if(array_keys['indexOf'](typeof(_v[__k])) < 0){
																	throw new TypeError('Call to API was successful, but required response sub-property was of unexpected type.');
																}
															}
														});
													}
												}
											});
											validValue = true;
										break;
										case 'object':
											possibleValue['forEach'](function(_v, _k){
												if(!result[k][_k]){
													throw new Error('Call to API was successful, but required response sub-property property was of missing.');
												}else{
													if(array_keys(possibleValue[_k])['indexOf'](typeof(result[k][_k])) < 0){
														throw new TypeError('Call to API was successful, but required response sub-property was of unexpected type.');
													}
												}
											});
											validValue = true;
										break;
									}
								}
							}else if(result[k] == possibleValue){
								validValue = true;
								return;
							}
						});
						if(!validValue){
							throw new Error('Call to API was successful, but required response property had an unexpected value.');
						}
					}
				});
				return result;
			}
		},
		abstractAPI = function(){
		},
		abstractPasswordAPI = function(serviceUrl, password){
			var
				obj = this
			;
			obj['_serviceURL'] = serviceUrl;
			obj['_password'] = md5(password);
		},
		abstractUsernamePasswordAPI = function(serviceUrl, username, password){
			var
				obj = this
			;
			abstractPasswordAPI.prototype['constructor']['apply'](obj, [serviceUrl, password]);
			obj['_username'] = username;
		},
		abstractAuthBasicAPI = function(serviceUrl, username, password){
			abstractUsernamePasswordAPI.prototype['constructor']['apply'](this, arguments);
		},
		first = function(array){
			var
				array = array || []
			;
			for(var key in array){
				return array[key];
			}
		}
	;
	if(!JSON || !JSON['parse'] || !JSON['stringify']){
		throw new Error('Your browser cannot parse JSON srings.');
	}

	abstractAPI.prototype = new EventTarget();
	abstractAPI.prototype['constructor'] = abstractAPI;

	abstractAPI.prototype['attachedAPIs'] = {};
	abstractAPI['validateJSONResponse'] = validateJSONResponse;

	abstractPasswordAPI.prototype = new abstractAPI();
	abstractPasswordAPI.prototype['constructor'] = abstractPasswordAPI;

	abstractUsernamePasswordAPI.prototype = new abstractPasswordAPI();
	abstractUsernamePasswordAPI.prototype['constructor'] = abstractUsernamePasswordAPI;

	abstractAuthBasicAPI.prototype = new abstractUsernamePasswordAPI();
	abstractAuthBasicAPI.prototype['constructor'] = abstractAuthBasicAPI;

	abstractAuthBasicAPI.prototype['makeCallToAPI'] = function(method, readOnly, args, expectedResponse){
		if(!XMLHttpRequest){
			throw new Error('Your browser does not support XMLHttpRequest');
		}
		var
			obj       = this,
			readOnly  = readOnly || false,
			args      = args || [],
			ch        = new XMLHttpRequest(),
			authTried = false
		;
		if(!!readOnly){
			args['forEach'](function(v, k){
				args[k] = JSON['stringify'](v);
			});
		}
		ch['open'](
			(!!readOnly) ? 'GET' : 'POST',
			obj['_serviceURL'] + '/' + escape(method) + ((!!readOnly) ? '?' + http_build_query(args) : ''),
			true,
			obj['_username'],
			obj['_password']
		);
		ch['setRequestHeader']('Authorization', 'Basic ' + base64_encode(obj['_username'] + ':' + obj['_password']));
		ch['addEventListener']('load', function(){
			if(ch['status'] == 200){
				try{
					obj['fire'](method, {
						'result' : validateJSONResponse(ch['responseText'])
					});
				}catch(e){
					obj['fire']('error', {
						'method' : method,
						'error' : e
					});
				}
			}else{
				switch(ch['status']){
					case 403:
						obj['fire']('error', {
							'method' : method,
							'error' : 'Access to the API method for the configured credentials has been denied.'
						});
					break;
					case 429:
						obj['fire']('error', {
							'method' : method,
							'error' : 'Reached hourly rate limit.'
						});
					break;
					default:
						obj['fire']('error', {
							'method' : method,
							'error' : 'Unknown error occurred.'
						});
					break;
				}
			}
		}, true);
		ch['send']();
	};

	window['Aurora'] = Aurora;
	Aurora['Addon'] = Addon;
	Addon['abstractAPI'] = abstractAPI;
	Addon['abstractPasswordAPI'] = abstractPasswordAPI;
	Addon['abstractUsernamePasswordAPI'] = abstractUsernamePasswordAPI;
	Addon['abstractAuthBasicAPI'] = abstractAuthBasicAPI;
})(window, window['document']);
<commit_msg>cannot iterate directly on objects<commit_after>/**
* @license libAurora.js Copyright (c) 2011-2012 Contributors
* See CONTRIBUTORS.TXT for a full list of copyright holders.
* MIT License
*/
(function(window, document, undefined){
	var
		EventTarget      = window['EventTarget'],
		Aurora           = window['Aurora'] || {},
		Addon            = Aurora['Addon'] || {},
		JSON             = window['JSON'],
		md5              = window['md5'],
		is_array         = window['is_array'],
		array_keys       = window['array_keys'],
		base64_encode    = window['base64_encode'],
		XMLHttpRequest   = window['XMLHttpRequest'],
		http_build_query = window['http_build_query'],
		validateJSONResponse = function(result, expectedResponse){
			if(!(typeof(result) == 'string')){
				throw new TypeError('API result expected to be a string, ' + typeof(result) + ' found.');
			}else{
				var
					result = JSON['parse'](result),
					expectedResponse = expectedResponse || []
				;
				if(typeof(result) != 'object'){
					throw new TypeError('API result expected to be an object, ' + typeof(result) + ' found.');
				}else if(!is_array(expectedResponse)){
					throw new TypeError('Expected Response argument must be specified as an array, not ' + typeof(expectedResponse));
				}
				array_keys(expectedResponse)['forEach'](function(k){
					var
						v = expectedResponse[k]
					;
					if(!(k in result)){
						throw new Error('Call to API was successful, but required response properties were missing.');
					}else if(array_keys(v)['indexOf'](typeof(result[k])) < 0){
						throw new Error('Call to API was successful, but required response property was of unexpected type.');
					}else if(v[typeof(result[k])] && v[typeof(result[k])]['length'] > 0){
						var
							validValue = false
						;
						v[typeof(result[k])]['forEach'](function(possibleValue, _k){
							if(typeof(_k) == 'number'){
								if(typeof(result[k]) == 'boolean'){
									if(!typeof(possibleValue)){
										throw new TypeError('Only booleans can be given as valid values to a boolean type.');
									}else if(result[k] == possibleValue){
										validValue = true;
										return;
									}
								}else{
									var
										subPropertyKeys = array_keys(possibleValue),
										rkType = typeof(result[k]) == 'object' ? (!is_array(result[k]) ? 'object' : 'array') : typeof(result[k]);
									;
									switch(typeof(rkType)){
										case 'array':
											result[k]['forEach'](function(_v){
												var
													_v_Type = typeof(_v)
												;
												if(subPropertyKeys['indexOf'](_v_Type) < 0){
													throw new TypeError('Call to API was successful, but required response sub-property was of unexpected type.');
												}else if(_v_Type == 'object' && !!possibleValue[_v_Type]){
													var
														pos = possibleValue[_v_Type]
													;
													if(_v_Type == 'object'){
														pos = first(pos);
													}
													if(!!pos){
														pos['forEach'](function(__v, __k){
															if(!_v[__k]){
																throw new Error('Call to API was successful, but required response sub-property property was of missing.');
															}else{
																if(array_keys['indexOf'](typeof(_v[__k])) < 0){
																	throw new TypeError('Call to API was successful, but required response sub-property was of unexpected type.');
																}
															}
														});
													}
												}
											});
											validValue = true;
										break;
										case 'object':
											possibleValue['forEach'](function(_v, _k){
												if(!result[k][_k]){
													throw new Error('Call to API was successful, but required response sub-property property was of missing.');
												}else{
													if(array_keys(possibleValue[_k])['indexOf'](typeof(result[k][_k])) < 0){
														throw new TypeError('Call to API was successful, but required response sub-property was of unexpected type.');
													}
												}
											});
											validValue = true;
										break;
									}
								}
							}else if(result[k] == possibleValue){
								validValue = true;
								return;
							}
						});
						if(!validValue){
							throw new Error('Call to API was successful, but required response property had an unexpected value.');
						}
					}
				});
				return result;
			}
		},
		abstractAPI = function(){
		},
		abstractPasswordAPI = function(serviceUrl, password){
			var
				obj = this
			;
			obj['_serviceURL'] = serviceUrl;
			obj['_password'] = md5(password);
		},
		abstractUsernamePasswordAPI = function(serviceUrl, username, password){
			var
				obj = this
			;
			abstractPasswordAPI.prototype['constructor']['apply'](obj, [serviceUrl, password]);
			obj['_username'] = username;
		},
		abstractAuthBasicAPI = function(serviceUrl, username, password){
			abstractUsernamePasswordAPI.prototype['constructor']['apply'](this, arguments);
		},
		first = function(array){
			var
				array = array || []
			;
			for(var key in array){
				return array[key];
			}
		}
	;
	if(!JSON || !JSON['parse'] || !JSON['stringify']){
		throw new Error('Your browser cannot parse JSON srings.');
	}

	abstractAPI.prototype = new EventTarget();
	abstractAPI.prototype['constructor'] = abstractAPI;

	abstractAPI.prototype['attachedAPIs'] = {};
	abstractAPI['validateJSONResponse'] = validateJSONResponse;

	abstractPasswordAPI.prototype = new abstractAPI();
	abstractPasswordAPI.prototype['constructor'] = abstractPasswordAPI;

	abstractUsernamePasswordAPI.prototype = new abstractPasswordAPI();
	abstractUsernamePasswordAPI.prototype['constructor'] = abstractUsernamePasswordAPI;

	abstractAuthBasicAPI.prototype = new abstractUsernamePasswordAPI();
	abstractAuthBasicAPI.prototype['constructor'] = abstractAuthBasicAPI;

	abstractAuthBasicAPI.prototype['makeCallToAPI'] = function(method, readOnly, args, expectedResponse){
		if(!XMLHttpRequest){
			throw new Error('Your browser does not support XMLHttpRequest');
		}
		var
			obj       = this,
			readOnly  = readOnly || false,
			args      = args || [],
			ch        = new XMLHttpRequest(),
			authTried = false
		;
		if(!!readOnly){
			array_keys(args)['forEach'](function(k){
				args[k] = JSON['stringify'](args[k]);
			});
		}
		ch['open'](
			(!!readOnly) ? 'GET' : 'POST',
			obj['_serviceURL'] + '/' + escape(method) + ((!!readOnly) ? '?' + http_build_query(args) : ''),
			true,
			obj['_username'],
			obj['_password']
		);
		ch['setRequestHeader']('Authorization', 'Basic ' + base64_encode(obj['_username'] + ':' + obj['_password']));
		ch['addEventListener']('load', function(){
			if(ch['status'] == 200){
				try{
					obj['fire'](method, {
						'result' : validateJSONResponse(ch['responseText'])
					});
				}catch(e){
					obj['fire']('error', {
						'method' : method,
						'error' : e
					});
				}
			}else{
				switch(ch['status']){
					case 403:
						obj['fire']('error', {
							'method' : method,
							'error' : 'Access to the API method for the configured credentials has been denied.'
						});
					break;
					case 429:
						obj['fire']('error', {
							'method' : method,
							'error' : 'Reached hourly rate limit.'
						});
					break;
					default:
						obj['fire']('error', {
							'method' : method,
							'error' : 'Unknown error occurred.'
						});
					break;
				}
			}
		}, true);
		ch['send']();
	};

	window['Aurora'] = Aurora;
	Aurora['Addon'] = Addon;
	Addon['abstractAPI'] = abstractAPI;
	Addon['abstractPasswordAPI'] = abstractPasswordAPI;
	Addon['abstractUsernamePasswordAPI'] = abstractUsernamePasswordAPI;
	Addon['abstractAuthBasicAPI'] = abstractAuthBasicAPI;
})(window, window['document']);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Two Sigma Open Source
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of git-meta nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";

/**
 * This module contains methods for pushing.
 */

const assert       = require("chai").assert;
const ChildProcess = require("child-process-promise");
const co           = require("co");
const colors       = require("colors");
const NodeGit      = require("nodegit");

const DoWorkQueue         = require("./do_work_queue");
const ForcePushSpec       = require("./force_push_spec");
const GitUtil             = require("./git_util");
const SubmoduleUtil       = require("./submodule_util");
const SubmoduleConfigUtil = require("./submodule_config_util");
const SyntheticBranchUtil = require("./synthetic_branch_util");
const UserError           = require("./user_error");

// This magic SHA represents an empty tree in Git.

const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";

/**
 * For a given commit, determine a reasonably close oid that has
 * already been pushed. This does *not* do a fetch, but rather just
 * compares against all available remote refs.
 *
 * This works by building a revwalk and removing all ancestors of remote refs
 * for the given remote. It then reverses the result, and returns the first
 * parent of the oldest, unpushed commit. This is not an absolute last pushed
 * oid, but is a very good proxy to determine what to push.
 *
 * Returns a commit that exists in a remote ref, or null if no such commit
 * exists. If the given commit exists in a remote ref, will return itself.
 *
 * @async
 * @param {NodeGit.Repository} repo
 * @param {NodeGit.Commit}     commit
 */
exports.getClosePushedCommit = co.wrap(function*(repo, commit) {
    assert.instanceOf(repo, NodeGit.Repository);
    assert.instanceOf(commit, NodeGit.Commit);

    // Search for the first commit that is not an ancestor of a remote ref, ie.
    // the first commit that is unpushed. NodeGit Revwalk is too slow, so
    // we shell out.

    // First, get the list of remote refs to exclude
    const excludeRefs = [];
    for (const ref of (yield NodeGit.Reference.list(repo))) {
        if (ref.startsWith("refs/remotes/")) {
            excludeRefs.push("^" + ref);
        }
    }
    if (excludeRefs.length === 0) {
        return null;
    }

    const args = ["-C", repo.workdir(), "rev-list", "--reverse",
                  "--topo-order", commit, ...excludeRefs];
    let result = yield ChildProcess.execFile("git", args, {
        maxBuffer: 1024*1024*100
    });
    if (result.error) {
        throw new Error(
            `Unexpected error figuring out what to push:
stderr:
{result.stderr}
stdout:
{result.stdout}`);
    }
    const out = result.stdout;
    if (!out) {
        // Nothing new to push
        return commit;
    }

    const firstNewOid = out.substring(0, out.indexOf("\n"));

    const firstNewCommit = yield repo.getCommit(firstNewOid);

    // If the first unpushed commit has no parents, then the entire set of
    // commits to push is new.

    if (0 === firstNewCommit.parentcount()) {
        return null;
    }
    return yield repo.getCommit(firstNewCommit.parentId(0));
});

/**
 * For a given proposed push, return a map from submodule to sha,
 * excluding any submodules that the server likely already has.
 *
 * Return in the map only those submodules that (1) exist locally, in
 * `.git/modules` and (2) are changed between `commit` and the merge base of
 * `commit` and each relevant branch.
 *
 * @async
 * @param {NodeGit.Repository} repo
 * @param {String}             source
 * @param {NodeGit.Commit}     commit
 */
exports.getPushMap = co.wrap(function*(repo,  source, commit) {
    assert.instanceOf(repo, NodeGit.Repository);
    assert.isString(source);
    assert.instanceOf(commit, NodeGit.Commit);

    const baseCommit = yield exports.getClosePushedCommit(repo, commit);
    let baseTree;
    if (null !== baseCommit) {
        baseTree = yield baseCommit.getTree();
    } else {
        baseTree = EMPTY_TREE;
    }

    const tree = yield commit.getTree();
    const diff = yield NodeGit.Diff.treeToTree(repo, baseTree, tree, null);
    const changes = SubmoduleUtil.getSubmoduleChangesFromDiff(diff, true);

    const pushMap = {};
    for (const path of Object.keys(changes)) {
        const change = changes[path];
        if (!change.deleted) {
            pushMap[path] = change.newSha;
        }
    }

    const openSubmodules = yield SubmoduleUtil.listOpenSubmodules(repo);
    const absorbedSubmodules =
        yield SubmoduleUtil.listAbsorbedSubmodules(repo);

    const availableSubmodules = new Set([...openSubmodules,
                                        ...absorbedSubmodules]);

    // Make sure we have the repositories and commits we want to push.
    for (const sub of Object.keys(pushMap)) {
        if (!availableSubmodules.has(sub)) {
            delete pushMap[sub];
            continue;
        }

        const subRepo = yield SubmoduleUtil.getBareRepo(repo, sub);
        try {
            yield subRepo.getCommit(pushMap[sub]);
        } catch (e) {
            delete pushMap[sub];
        }
    }

    return pushMap;
});

/**
 * For each open submodule that exists in the commit indicated by the specified
 * `source`, push a synthetic-meta-ref for the `source` commit.
 * If all sub-repo pushes succeed, push `source` to
 * to the specified `target` branch in `remoteName`.  If any pushes fail, throw
 * a `UserError` object.
 *
 * Note that this strategy is naive: it does not handle the following
 * situations:
 *
 * - closed submodules with commits that need to be pushed
 * - submodules that do not exist in the `source` commit, but did previously
 *   and need synthetic-meta-refs
 * - submodules with divergent histories, i.e., the commit we create the
 *   synthetic-meta-ref for doesn't contain one or more commits that need to be
 *   pushed in its history
 *
 * Addressing these situations would have a performance impact, requiring
 * calculation and traversal of all meta-repo commits being pushed.  We should
 * probably add a way to do an "exhaustive" push.
 *
 * @async
 * @param {NodeGit.Repository} repo
 * @param {String}             remoteName
 * @param {String}             source
 * @param {String}             target
 * @param {Boolean}            force
 */
exports.push = co.wrap(function *(repo, remoteName, source, target, force) {
    assert.instanceOf(repo, NodeGit.Repository);
    assert.isString(remoteName);
    assert.isString(source);
    assert.isString(target);
    assert.instanceOf(force, ForcePushSpec);

    let remoteUrl = yield GitUtil.getUrlFromRemoteName(repo, remoteName);

    const annotatedCommit = yield GitUtil.resolveCommitish(repo, source);
    if (annotatedCommit === null) {
        throw new UserError(`No such ref: ${source}`);
    }
    const sha = annotatedCommit.id();
    const commit = yield repo.getCommit(sha);

    // First, push the submodules.
    const pushMap = yield exports.getPushMap(repo, source, commit);

    let errorMessage = "";

    const urls = yield SubmoduleConfigUtil.getSubmodulesFromCommit(repo,
                                                                   commit);

    const pushSub = co.wrap(function *(subName) {
        // Push to a synthetic branch; first, calculate name.

        const sha = pushMap[subName];
        const syntheticName =
                          SyntheticBranchUtil.getSyntheticBranchForCommit(sha);
        const subRepo = yield SubmoduleUtil.getBareRepo(repo, subName);

        // Resolve the submodule's URL against the URL of the meta-repo,
        // ignoring the remote that is configured in the open submodule.

        if (!(subName in urls)) {
            throw new UserError(
                `The submodule {subName} doesn't have an entry in .gitmodules`);
        }
        const subUrl = SubmoduleConfigUtil.resolveSubmoduleUrl(remoteUrl,
                                                               urls[subName]);

        // Always force push synthetic refs.  It should not be necessary, but
        // if something does go wrong forcing will allow us to auto-correct.
        // If they succeed, no need to print the output inside the submodules.

        const pushResult = yield GitUtil.push(subRepo,
                                              subUrl,
                                              sha,
                                              syntheticName,
                                              ForcePushSpec.Force,
                                              true);
        if (null !== pushResult) {
            errorMessage +=
           `Failed to push submodule ${colors.yellow(subName)}: ${pushResult}`;
        }
    });
    yield DoWorkQueue.doInParallel(Object.keys(pushMap), pushSub);

    // Throw an error if there were any problems pushing submodules; don't push
    // the meta-repo.

    if ("" !== errorMessage) {
        throw new UserError(errorMessage);
    }

    // Finally, push the meta-repo and throw on failure.

    const result = yield GitUtil.push(repo, remoteName, source, target, force);
    if (null !== result) {
        throw new UserError(`Failed to push meta-repo: ${result}`);
    }
});
<commit_msg>fix missing $<commit_after>/*
 * Copyright (c) 2016, Two Sigma Open Source
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of git-meta nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";

/**
 * This module contains methods for pushing.
 */

const assert       = require("chai").assert;
const ChildProcess = require("child-process-promise");
const co           = require("co");
const colors       = require("colors");
const NodeGit      = require("nodegit");

const DoWorkQueue         = require("./do_work_queue");
const ForcePushSpec       = require("./force_push_spec");
const GitUtil             = require("./git_util");
const SubmoduleUtil       = require("./submodule_util");
const SubmoduleConfigUtil = require("./submodule_config_util");
const SyntheticBranchUtil = require("./synthetic_branch_util");
const UserError           = require("./user_error");

// This magic SHA represents an empty tree in Git.

const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";

/**
 * For a given commit, determine a reasonably close oid that has
 * already been pushed. This does *not* do a fetch, but rather just
 * compares against all available remote refs.
 *
 * This works by building a revwalk and removing all ancestors of remote refs
 * for the given remote. It then reverses the result, and returns the first
 * parent of the oldest, unpushed commit. This is not an absolute last pushed
 * oid, but is a very good proxy to determine what to push.
 *
 * Returns a commit that exists in a remote ref, or null if no such commit
 * exists. If the given commit exists in a remote ref, will return itself.
 *
 * @async
 * @param {NodeGit.Repository} repo
 * @param {NodeGit.Commit}     commit
 */
exports.getClosePushedCommit = co.wrap(function*(repo, commit) {
    assert.instanceOf(repo, NodeGit.Repository);
    assert.instanceOf(commit, NodeGit.Commit);

    // Search for the first commit that is not an ancestor of a remote ref, ie.
    // the first commit that is unpushed. NodeGit Revwalk is too slow, so
    // we shell out.

    // First, get the list of remote refs to exclude
    const excludeRefs = [];
    for (const ref of (yield NodeGit.Reference.list(repo))) {
        if (ref.startsWith("refs/remotes/")) {
            excludeRefs.push("^" + ref);
        }
    }
    if (excludeRefs.length === 0) {
        return null;
    }

    const args = ["-C", repo.workdir(), "rev-list", "--reverse",
                  "--topo-order", commit, ...excludeRefs];
    let result = yield ChildProcess.execFile("git", args, {
        maxBuffer: 1024*1024*100
    });
    if (result.error) {
        throw new Error(
            `Unexpected error figuring out what to push:
stderr:
{result.stderr}
stdout:
{result.stdout}`);
    }
    const out = result.stdout;
    if (!out) {
        // Nothing new to push
        return commit;
    }

    const firstNewOid = out.substring(0, out.indexOf("\n"));

    const firstNewCommit = yield repo.getCommit(firstNewOid);

    // If the first unpushed commit has no parents, then the entire set of
    // commits to push is new.

    if (0 === firstNewCommit.parentcount()) {
        return null;
    }
    return yield repo.getCommit(firstNewCommit.parentId(0));
});

/**
 * For a given proposed push, return a map from submodule to sha,
 * excluding any submodules that the server likely already has.
 *
 * Return in the map only those submodules that (1) exist locally, in
 * `.git/modules` and (2) are changed between `commit` and the merge base of
 * `commit` and each relevant branch.
 *
 * @async
 * @param {NodeGit.Repository} repo
 * @param {String}             source
 * @param {NodeGit.Commit}     commit
 */
exports.getPushMap = co.wrap(function*(repo,  source, commit) {
    assert.instanceOf(repo, NodeGit.Repository);
    assert.isString(source);
    assert.instanceOf(commit, NodeGit.Commit);

    const baseCommit = yield exports.getClosePushedCommit(repo, commit);
    let baseTree;
    if (null !== baseCommit) {
        baseTree = yield baseCommit.getTree();
    } else {
        baseTree = EMPTY_TREE;
    }

    const tree = yield commit.getTree();
    const diff = yield NodeGit.Diff.treeToTree(repo, baseTree, tree, null);
    const changes = SubmoduleUtil.getSubmoduleChangesFromDiff(diff, true);

    const pushMap = {};
    for (const path of Object.keys(changes)) {
        const change = changes[path];
        if (!change.deleted) {
            pushMap[path] = change.newSha;
        }
    }

    const openSubmodules = yield SubmoduleUtil.listOpenSubmodules(repo);
    const absorbedSubmodules =
        yield SubmoduleUtil.listAbsorbedSubmodules(repo);

    const availableSubmodules = new Set([...openSubmodules,
                                        ...absorbedSubmodules]);

    // Make sure we have the repositories and commits we want to push.
    for (const sub of Object.keys(pushMap)) {
        if (!availableSubmodules.has(sub)) {
            delete pushMap[sub];
            continue;
        }

        const subRepo = yield SubmoduleUtil.getBareRepo(repo, sub);
        try {
            yield subRepo.getCommit(pushMap[sub]);
        } catch (e) {
            delete pushMap[sub];
        }
    }

    return pushMap;
});

/**
 * For each open submodule that exists in the commit indicated by the specified
 * `source`, push a synthetic-meta-ref for the `source` commit.
 * If all sub-repo pushes succeed, push `source` to
 * to the specified `target` branch in `remoteName`.  If any pushes fail, throw
 * a `UserError` object.
 *
 * Note that this strategy is naive: it does not handle the following
 * situations:
 *
 * - closed submodules with commits that need to be pushed
 * - submodules that do not exist in the `source` commit, but did previously
 *   and need synthetic-meta-refs
 * - submodules with divergent histories, i.e., the commit we create the
 *   synthetic-meta-ref for doesn't contain one or more commits that need to be
 *   pushed in its history
 *
 * Addressing these situations would have a performance impact, requiring
 * calculation and traversal of all meta-repo commits being pushed.  We should
 * probably add a way to do an "exhaustive" push.
 *
 * @async
 * @param {NodeGit.Repository} repo
 * @param {String}             remoteName
 * @param {String}             source
 * @param {String}             target
 * @param {Boolean}            force
 */
exports.push = co.wrap(function *(repo, remoteName, source, target, force) {
    assert.instanceOf(repo, NodeGit.Repository);
    assert.isString(remoteName);
    assert.isString(source);
    assert.isString(target);
    assert.instanceOf(force, ForcePushSpec);

    let remoteUrl = yield GitUtil.getUrlFromRemoteName(repo, remoteName);

    const annotatedCommit = yield GitUtil.resolveCommitish(repo, source);
    if (annotatedCommit === null) {
        throw new UserError(`No such ref: ${source}`);
    }
    const sha = annotatedCommit.id();
    const commit = yield repo.getCommit(sha);

    // First, push the submodules.
    const pushMap = yield exports.getPushMap(repo, source, commit);

    let errorMessage = "";

    const urls = yield SubmoduleConfigUtil.getSubmodulesFromCommit(repo,
                                                                   commit);

    const pushSub = co.wrap(function *(subName) {
        // Push to a synthetic branch; first, calculate name.

        const sha = pushMap[subName];
        const syntheticName =
                          SyntheticBranchUtil.getSyntheticBranchForCommit(sha);
        const subRepo = yield SubmoduleUtil.getBareRepo(repo, subName);

        // Resolve the submodule's URL against the URL of the meta-repo,
        // ignoring the remote that is configured in the open submodule.

        if (!(subName in urls)) {
            throw new UserError(
                `The submodule ${subName} doesn't have an entry in .gitmodules`
            );
        }
        const subUrl = SubmoduleConfigUtil.resolveSubmoduleUrl(remoteUrl,
                                                               urls[subName]);

        // Always force push synthetic refs.  It should not be necessary, but
        // if something does go wrong forcing will allow us to auto-correct.
        // If they succeed, no need to print the output inside the submodules.

        const pushResult = yield GitUtil.push(subRepo,
                                              subUrl,
                                              sha,
                                              syntheticName,
                                              ForcePushSpec.Force,
                                              true);
        if (null !== pushResult) {
            errorMessage +=
           `Failed to push submodule ${colors.yellow(subName)}: ${pushResult}`;
        }
    });
    yield DoWorkQueue.doInParallel(Object.keys(pushMap), pushSub);

    // Throw an error if there were any problems pushing submodules; don't push
    // the meta-repo.

    if ("" !== errorMessage) {
        throw new UserError(errorMessage);
    }

    // Finally, push the meta-repo and throw on failure.

    const result = yield GitUtil.push(repo, remoteName, source, target, force);
    if (null !== result) {
        throw new UserError(`Failed to push meta-repo: ${result}`);
    }
});
<|endoftext|>


<commit_before>import React, { useCallback, useState, useRef } from 'react';
import AppWrapper from 'carbon-react/lib/components/app-wrapper';
import ButtonToggleGroup from 'carbon-react/lib/components/button-toggle-group';
import ButtonToggle from 'carbon-react/lib/components/button-toggle';
import { Menu, MenuItem } from 'carbon-react/lib/components/menu';
import I18n from 'i18n-js';
import styled from 'styled-components';
import guid from 'carbon-react/lib/utils/helpers/guid';
import Log, { LogProvider } from './log';

I18n.translations.ch = {
  number: {
    format: {
      delimiter: '\'',
      separator: '.'
    }
  }
};

I18n.translations.fr = {
  number: {
    format: {
      delimiter: '.',
      separator: ','
    }
  }
};

I18n.translations.en = {
  number: {
    format: {
      delimiter: ',',
      separator: '.'
    }
  }
};

const Chrome = ({ children }) => {
  const ref = useRef([]);
  const [history, setHistory] = useState(ref.current);
  const [key, setKey] = useState(1);
  const [lang, setLang] = useState('');
  const onChange = (e) => {
    I18n.locale = e.target.value;
    setKey(key + 1);
    setLang(e.target.value);
  };

  const log = useCallback(({
    target: {
      name, id, value, checked
    }
  }, obj) => {
    ref.current = [...ref.current, {
      ...obj,
      guid: guid(),
      timestamp: new Date().toISOString(),
      name,
      id,
      value,
      checked
    }];
    setHistory(ref.current);
  }, [history, setHistory]);

  const Nav = styled.div`
  display:flex
  justify-content:space-between
  `;

  return (
    <AppWrapper key={ key }>
      <Nav>
        <Menu>
          <MenuItem to='/'>
            Index
          </MenuItem>
        </Menu>
        <ButtonToggleGroup
          id='lang'
          value={ lang } onChange={ onChange }
          name='lang'
        >
          <ButtonToggle value='en'>EN</ButtonToggle>
          <ButtonToggle value='fr'>FR</ButtonToggle>
          <ButtonToggle value='ch'>CH</ButtonToggle>
          <ButtonToggle value=''>None</ButtonToggle>
        </ButtonToggleGroup>
      </Nav>
      <LogProvider value={ log }>{children}</LogProvider>
      <Log history={ history } />
    </AppWrapper>
  );
};

export default Chrome;
<commit_msg>fix: update callback dependency array<commit_after>import React, { useCallback, useState, useRef } from 'react';
import AppWrapper from 'carbon-react/lib/components/app-wrapper';
import ButtonToggleGroup from 'carbon-react/lib/components/button-toggle-group';
import ButtonToggle from 'carbon-react/lib/components/button-toggle';
import { Menu, MenuItem } from 'carbon-react/lib/components/menu';
import I18n from 'i18n-js';
import styled from 'styled-components';
import guid from 'carbon-react/lib/utils/helpers/guid';
import Log, { LogProvider } from './log';

I18n.translations.ch = {
  number: {
    format: {
      delimiter: '\'',
      separator: '.'
    }
  }
};

I18n.translations.fr = {
  number: {
    format: {
      delimiter: '.',
      separator: ','
    }
  }
};

I18n.translations.en = {
  number: {
    format: {
      delimiter: ',',
      separator: '.'
    }
  }
};

const Chrome = ({ children }) => {
  const ref = useRef([]);
  const [history, setHistory] = useState(ref.current);
  const [key, setKey] = useState(1);
  const [lang, setLang] = useState('');
  const onChange = (e) => {
    I18n.locale = e.target.value;
    setKey(key + 1);
    setLang(e.target.value);
  };

  const log = useCallback(({
    target: {
      name, id, value, checked
    }
  }, obj) => {
    ref.current = [...ref.current, {
      ...obj,
      guid: guid(),
      timestamp: new Date().toISOString(),
      name,
      id,
      value,
      checked
    }];
    setHistory(ref.current);
  }, [ref, setHistory]);

  const Nav = styled.div`
  display:flex
  justify-content:space-between
  `;

  return (
    <AppWrapper key={ key }>
      <Nav>
        <Menu>
          <MenuItem to='/'>
            Index
          </MenuItem>
        </Menu>
        <ButtonToggleGroup
          id='lang'
          value={ lang } onChange={ onChange }
          name='lang'
        >
          <ButtonToggle value='en'>EN</ButtonToggle>
          <ButtonToggle value='fr'>FR</ButtonToggle>
          <ButtonToggle value='ch'>CH</ButtonToggle>
          <ButtonToggle value=''>None</ButtonToggle>
        </ButtonToggleGroup>
      </Nav>
      <LogProvider value={ log }>{children}</LogProvider>
      <Log history={ history } />
    </AppWrapper>
  );
};

export default Chrome;
<|endoftext|>


<commit_before>/*!
 * Vue Clazy Load
 * Component-based lazy (CLazy) load images in Vue.js 2
 * @author Matheus Grieger
 * @version 0.2.0
 */
const ClazyLoad = {
  install(Vue) {
    Vue.component('clazy-load', {
      name: 'ClazyLoad',
      props: {
        /**
         * HTML/Component tag name to be used in place of the component
         * @type {Object}
         * @default div
         */
        tag: {
          type: String,
          default: 'div'
        },
        /**
         * Image source URL
         * @type {Object}
         * @required
         */
        src: {
          type: String,
          required: true
        },
        /**
         * IntersectionObserver root element
         * @type {Object}
         */
        element: String,
        /**
         * IntersectionObserver threshold
         * @type {Object}
         */
        threshold: {
          type: [Array, Number],
          default: () => {
            return [0, 0.5, 1]
          }
        },
        /**
         * InserectionObserver visibility ratio
         * @type {Object}
         */
        ratio: {
          type: Number,
          default: 0.4,
          validator(value) {
            // can't be less or equal to 0 and greater than 1
            return value > 0 && value <= 1
          }
        },
        /**
         * IntersectionObserver root margin
         * @type {Object}
         */
        margin: {
          type: String,
          default: '0px'
        }
      },
      data() {
        return {
          loaded: false,
          observer: null,
          errored: false
        }
      },
      methods: {
        /**
         * Start loading image
         */
        load() {
          // disconnect observer
          // so it doesn't load more than once
          this.observer.disconnect()

          if (!this.loaded) {
            // fake image
            let img = new Image

            img.addEventListener('load', () => {
              this.loaded = true
              // emits 'load' event upwards
              this.$emit('load')

              clear()
            })

            img.addEventListener('error', (event) => {
              this.errored = true
              // emits 'error' event upwards
              // adds the original event as argument
              this.$emit('error', event)

              clear()
            })

            // function used to clear variables from memory
            const clear = () => {
              // discard fake image
              img = null
              // remove observer from memory
              this.observer = null
            }

            img.src = this.src
          }
        },

        /**
         * Creates IntersectionObserver instance and observe current element
         */
        observe() {
          let options = {
            threshold: this.threshold,
            root: this.element ? document.querySelector(this.element) : null,
            rootMargin: this.margin
          }

          // creates IO instance
          this.observer = new IntersectionObserver((entries) => {
            // as we instantiated one for each component
            // we can directly access the first index
            if (entries[0].intersectionRatio >= this.ratio) {
              this.load()
            }
          }, options)

          // start observing main component
          this.observer.observe(this.$refs.component)
        }
      },
      render(h) {
        return h(this.tag, {
          // adds 'loaded' class if finished loading
          // or 'loading' class if still loading
          // TODO: allow custom class naming
          class: this.loaded ? 'loaded' : 'loading',
          ref: 'component'
        }, [
          this.loaded
            ? this.$slots.image
            : this.$slots.placeholder
        ])
      },
      mounted() {
        // start observing the element visibility
        // need to request animation frame to ensure the element is in the DOM
        requestAnimationFrame(this.observe)
      }
    })
  }
}

export default ClazyLoad
export const install = ClazyLoad.install
<commit_msg>Fix "Failed to execute 'observe'"<commit_after>/*!
 * Vue Clazy Load
 * Component-based lazy (CLazy) load images in Vue.js 2
 * @author Matheus Grieger
 * @version 0.2.0
 */
const ClazyLoad = {
  install(Vue) {
    Vue.component('clazy-load', {
      name: 'ClazyLoad',
      props: {
        /**
         * HTML/Component tag name to be used in place of the component
         * @type {Object}
         * @default div
         */
        tag: {
          type: String,
          default: 'div'
        },
        /**
         * Image source URL
         * @type {Object}
         * @required
         */
        src: {
          type: String,
          required: true
        },
        /**
         * IntersectionObserver root element
         * @type {Object}
         */
        element: String,
        /**
         * IntersectionObserver threshold
         * @type {Object}
         */
        threshold: {
          type: [Array, Number],
          default: () => {
            return [0, 0.5, 1]
          }
        },
        /**
         * InserectionObserver visibility ratio
         * @type {Object}
         */
        ratio: {
          type: Number,
          default: 0.4,
          validator(value) {
            // can't be less or equal to 0 and greater than 1
            return value > 0 && value <= 1
          }
        },
        /**
         * IntersectionObserver root margin
         * @type {Object}
         */
        margin: {
          type: String,
          default: '0px'
        }
      },
      data() {
        return {
          loaded: false,
          observer: null,
          errored: false
        }
      },
      methods: {
        /**
         * Start loading image
         */
        load() {
          // disconnect observer
          // so it doesn't load more than once
          this.observer.disconnect()

          if (!this.loaded) {
            // fake image
            let img = new Image

            img.addEventListener('load', () => {
              this.loaded = true
              // emits 'load' event upwards
              this.$emit('load')

              clear()
            })

            img.addEventListener('error', (event) => {
              this.errored = true
              // emits 'error' event upwards
              // adds the original event as argument
              this.$emit('error', event)

              clear()
            })

            // function used to clear variables from memory
            const clear = () => {
              // discard fake image
              img = null
              // remove observer from memory
              this.observer = null
            }

            img.src = this.src
          }
        },

        /**
         * Creates IntersectionObserver instance and observe current element
         */
        observe() {
          if (!this.$refs.component)
            return;

          let options = {
            threshold: this.threshold,
            root: this.element ? document.querySelector(this.element) : null,
            rootMargin: this.margin
          }

          // creates IO instance
          this.observer = new IntersectionObserver((entries) => {
            // as we instantiated one for each component
            // we can directly access the first index
            if (entries[0].intersectionRatio >= this.ratio) {
              this.load()
            }
          }, options)

          // start observing main component
          this.observer.observe(this.$refs.component)
        }
      },
      render(h) {
        return h(this.tag, {
          // adds 'loaded' class if finished loading
          // or 'loading' class if still loading
          // TODO: allow custom class naming
          class: this.loaded ? 'loaded' : 'loading',
          ref: 'component'
        }, [
          this.loaded
            ? this.$slots.image
            : this.$slots.placeholder
        ])
      },
      mounted() {
        // start observing the element visibility
        // need to request animation frame to ensure the element is in the DOM
        requestAnimationFrame(this.observe)
      }
    })
  }
}

export default ClazyLoad
export const install = ClazyLoad.install
<|endoftext|>


<commit_before>'use strict';

// External lib
var ADODB = require('./');
var fs = require('fs');
var jpeg = require('jpeg-js');

// Variable declaration
const connection = ADODB.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=node-adodb.mdb;');

process.env.DEBUG = 'ADODB';

// Query
connection
  .query('SELECT * FROM Users')
  .then(data => {
    // console.log(JSON.stringify(data, null, 2));
    // var jpg = jpeg.decode(Buffer.from(data[0].UserAvatar, 'binary'));

    console.log(data[0].UserAvatar);

    fs.writeFileSync('./avatar.jpg', Buffer.from(data[0].UserAvatar));
  })
  .catch(error => {
    console.log(error);
  });
<commit_msg>:sparkles: support binary<commit_after>'use strict';

// External lib
var ADODB = require('./');
var fs = require('fs');

// Variable declaration
const connection = ADODB.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=node-adodb.mdb;');

process.env.DEBUG = 'ADODB';

// Query
connection
  .query('SELECT * FROM Users')
  .then(data => {
    console.log(data[0].UserAvatar);
  })
  .catch(error => {
    console.log(error);
  });
<|endoftext|>