<commit_before>import {predefinedColors} from "@ignavia/util";

import registry   from "../../registry.js";
import * as utils from "../../utils.js";

/**
 * The default configuration of this style.
 *
 * @type {Object}
 */
export const defaultConf = {

/**
     * How the box should look like.
     *
     * @type {Object}
     */
    box: {

        /**
         * The color to fill the box with.
         *
         * @type {Color}
         */
        backgroundColor: predefinedColors.white,

        /**
         * How the border of the box should look.
         *
         * @type {Object}
         */
        border: {

            /**
             * The color of the border.
             *
             * @type {Color}
             */
            color: predefinedColors.black,

            /**
             * The radius of the border. This option only works when the shape is
             * set to "roundedRect".
             *
             * @type {Number}
             */
            radius: 5,

            /**
             * The width of the border.
             *
             * @type {Number}
             */
            width: 2
        },

        /**
         * The margin to add around the box. This might be necessary to prevent PIXI
         * from cutting some pixels of the border off.
         *
         * @type {Number}
         */
        margin: 2,

        /**
         * The padding to add around the label.
         *
         * @type {Number}
         */
        padding: 10,

        /**
         * The shape of this node. The values "circle", "ellipse", "rect",
         * "roundedRect" are supported.
         *
         * @type {String}
         */
        shape: "rect"
    },

    /**
     * Affects the style of the caption.
     *
     * @type {Object}
     */
    caption: {

        /**
         * How large the gap between the given display object and the caption should be.
         *
         * @type {Number}
         */
        gap: 5,

        /**
         * Where the caption should be positioned in relation to the given display
         * object. Possible options are "center", "above", "right", "below" and "left".
         *
         * @type {String}
         */
        side: "below", // below, above, left, right, center, none

        /**
         * How the text itself should look.
         *
         * @type {Object}
         */
        text: {

            /**
             * The caption to display.
             *
             * @type {String}
             */
            label: "",

            /**
             * How the text should be aligned. The possible values are "left", "center" and
             * "right". For a single line of text this option has no effect.
             *
             * @type {String}
             */
            align:  "left",

            /**
             * How the drop shadow of the text should look.
             *
             * @type {Object}
             */
            dropShadow: {

                /**
                 * The angle of the drop shadow given in radian. An angle of 0 means that the
                 * shadow goes to the right, increasing the angle moves the shadow clockwise.
                 *
                 * @type {Number}
                 */
                angle: Math.PI / 4,

                /**
                 * The color of the shadow.
                 *
                 * @type {Color}
                 */
                color: predefinedColors.gray,

                /**
                 * How long the drop shadow should be. Set this to 0 to remove it.
                 *
                 * @type {Number}
                 */
                distance: 0
            },

            /**
             * The color to fill the text with.
             *
             * @type {Color}
             */
            fillColor: predefinedColors.black,

            /**
             * Configures the font of the text.
             *
             * @type {Object}
             */
            font: {

                /**
                 * The font-family to use.
                 *
                 * @type {String}
                 */
                family: "Arial",

                /**
                 * The font-size to use.
                 *
                 * @type {Number}
                 */
                size: 8,

                /**
                 * The style of the font. This can either be "normal", "italic" or "oblique".
                 *
                 * @type {String}
                 */
                style: "normal",

                /**
                 * The weight of the font. This can either be "light", "normal" or "bold".
                 */
                weight: "normal"
            },

            /**
             * How the stroke around the text should look.
             *
             * @type {Object}
             */
            stroke: {

                /**
                 * The color of the stroke around the text.
                 *
                 * @type {Color}
                 */
                color: predefinedColors.white,

                /**
                 * How thick the stroke should be. Set this to 0 to deactivate it.
                 *
                 * @type {Number}
                 */
                thickness: 0
            },

            /**
             * The width at which the text is going to wrap. Set this to 0 to
             * disable it.
             *
             * @type {Number}
             */
            wordWrapWidth: 0
        }
    },

    /**
     * How the image should look.
     *
     * @type {Object}
     */
    image: {

        /**
         * The path to the image to display.
         *
         * @type {String}
         */
        imagePath: "",

        /**
         * The width of the image. Set this to "orig" to use the width of the
         * original image and to "auto" to keep the aspect ratio when setting
         * the height.
         *
         * @type {Number|String}
         */
        width: "orig",

        /**
         * The height of the image. Set this to "orig" to use the height of the
         * original image and to "auto" to keep the aspect ratio when setting
         * the width.
         *
         * @type {Number|String}
         */
        height: "orig"
    },

    /**
     * Whether the decal should be oriented along the line.
     *
     * @type {Boolean}
     */
    rotateToLine: false,
};

/**
 * Creates a sprite using the given configuration. This function is curried.
 *
 * @param {Object} [conf]
 * Check the documentation of the default configuration for the structure of
 * this object.
 *
 * @return {DisplayObject}
 * The created sprite.
 */
export default function makeSprite(conf = {}) {
    conf = utils.adjustConf(defaultConf, conf);

    const result = utils.makeCaptionedImage(
        conf,
        conf.image.imagePath,
        conf.image.caption.text.label
    );
    const box = utils.makeBox(conf.box, result);
    result.addChildAt(box, 0);
    result.rotateToLine = conf.rotateToLine;

    return result;
};
registry.addEdgeDecalStyle("illustrated", makeSprite);
<commit_msg>Added a margin to the illustrated edge decal style<commit_after>import {predefinedColors} from "@ignavia/util";

import registry   from "../../registry.js";
import * as utils from "../../utils.js";

/**
 * The default configuration of this style.
 *
 * @type {Object}
 */
export const defaultConf = {

/**
     * How the box should look like.
     *
     * @type {Object}
     */
    box: {

        /**
         * The color to fill the box with.
         *
         * @type {Color}
         */
        backgroundColor: predefinedColors.white,

        /**
         * How the border of the box should look.
         *
         * @type {Object}
         */
        border: {

            /**
             * The color of the border.
             *
             * @type {Color}
             */
            color: predefinedColors.black,

            /**
             * The radius of the border. This option only works when the shape is
             * set to "roundedRect".
             *
             * @type {Number}
             */
            radius: 5,

            /**
             * The width of the border.
             *
             * @type {Number}
             */
            width: 2
        },

        /**
         * The margin to add around the box. This might be necessary to prevent PIXI
         * from cutting some pixels of the border off.
         *
         * @type {Number}
         */
        margin: 2,

        /**
         * The padding to add around the label.
         *
         * @type {Number}
         */
        padding: 10,

        /**
         * The shape of this node. The values "circle", "ellipse", "rect",
         * "roundedRect" are supported.
         *
         * @type {String}
         */
        shape: "rect"
    },

    /**
     * Affects the style of the caption.
     *
     * @type {Object}
     */
    caption: {

        /**
         * How large the gap between the given display object and the caption should be.
         *
         * @type {Number}
         */
        gap: 5,

        /**
         * Where the caption should be positioned in relation to the given display
         * object. Possible options are "center", "above", "right", "below" and "left".
         *
         * @type {String}
         */
        side: "below", // below, above, left, right, center, none

        /**
         * How the text itself should look.
         *
         * @type {Object}
         */
        text: {

            /**
             * The caption to display.
             *
             * @type {String}
             */
            label: "",

            /**
             * How the text should be aligned. The possible values are "left", "center" and
             * "right". For a single line of text this option has no effect.
             *
             * @type {String}
             */
            align:  "left",

            /**
             * How the drop shadow of the text should look.
             *
             * @type {Object}
             */
            dropShadow: {

                /**
                 * The angle of the drop shadow given in radian. An angle of 0 means that the
                 * shadow goes to the right, increasing the angle moves the shadow clockwise.
                 *
                 * @type {Number}
                 */
                angle: Math.PI / 4,

                /**
                 * The color of the shadow.
                 *
                 * @type {Color}
                 */
                color: predefinedColors.gray,

                /**
                 * How long the drop shadow should be. Set this to 0 to remove it.
                 *
                 * @type {Number}
                 */
                distance: 0
            },

            /**
             * The color to fill the text with.
             *
             * @type {Color}
             */
            fillColor: predefinedColors.black,

            /**
             * Configures the font of the text.
             *
             * @type {Object}
             */
            font: {

                /**
                 * The font-family to use.
                 *
                 * @type {String}
                 */
                family: "Arial",

                /**
                 * The font-size to use.
                 *
                 * @type {Number}
                 */
                size: 8,

                /**
                 * The style of the font. This can either be "normal", "italic" or "oblique".
                 *
                 * @type {String}
                 */
                style: "normal",

                /**
                 * The weight of the font. This can either be "light", "normal" or "bold".
                 */
                weight: "normal"
            },

            /**
             * How the stroke around the text should look.
             *
             * @type {Object}
             */
            stroke: {

                /**
                 * The color of the stroke around the text.
                 *
                 * @type {Color}
                 */
                color: predefinedColors.white,

                /**
                 * How thick the stroke should be. Set this to 0 to deactivate it.
                 *
                 * @type {Number}
                 */
                thickness: 0
            },

            /**
             * The width at which the text is going to wrap. Set this to 0 to
             * disable it.
             *
             * @type {Number}
             */
            wordWrapWidth: 0
        }
    },

    /**
     * How the image should look.
     *
     * @type {Object}
     */
    image: {

        /**
         * The path to the image to display.
         *
         * @type {String}
         */
        imagePath: "",

        /**
         * The width of the image. Set this to "orig" to use the width of the
         * original image and to "auto" to keep the aspect ratio when setting
         * the height.
         *
         * @type {Number|String}
         */
        width: "orig",

        /**
         * The height of the image. Set this to "orig" to use the height of the
         * original image and to "auto" to keep the aspect ratio when setting
         * the width.
         *
         * @type {Number|String}
         */
        height: "orig"
    },

    /**
     * Whether the decal should be oriented along the line.
     *
     * @type {Boolean}
     */
    rotateToLine: false,
};

/**
 * Creates a sprite using the given configuration. This function is curried.
 *
 * @param {Object} [conf]
 * Check the documentation of the default configuration for the structure of
 * this object.
 *
 * @return {DisplayObject}
 * The created sprite.
 */
export default function makeSprite(conf = {}) {
    conf = utils.adjustConf(defaultConf, conf);

    const result = utils.makeCaptionedImage(
        conf,
        conf.image.imagePath,
        conf.image.caption.text.label
    );
    const box    = utils.makeBox(conf.box, result);
    const margin = utils.makeMargin(conf.box.margin, box);
    container.addChildAt(box, 0);
    container.addChildAt(margin, 0);
    result.rotateToLine = conf.rotateToLine;

    return result;
};
registry.addEdgeDecalStyle("illustrated", makeSprite);
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

//This file is mostly a copy of layout.js from Sunstone.
//Instead of opening a south panel, it opens an east panel.
//Apart from document.ready() modifications, the rest of different lines are
//makerd with MODIFIED

var activeTab;
var outerLayout, innerLayout;

function hideDialog(){
    innerLayout.close("east");//MODIFIED
}

function popDialog(content){
    $("#dialog").html(content);
    innerLayout.open("east");//MODIFIED
}

function popDialogLoading(){
    var loading = '

';
    popDialog(loading);
}

function showTab(tabname,highlight_tab){
    //Since menu items no longer have an  element
    //we no longer expect #tab_id here, but simply tab_id
    //So safety check - remove # from #tab_id if present to ensure compatibility
    if (tabname.indexOf('#') == 0)
        tabname = tabname.substring(1);
    if (highlight_tab && highlight_tab.indexOf('#') == 0)
        highlight_tab == highlight.substring(1);

    var activeTab = tabname;

    if (!highlight_tab) highlight_tab = activeTab;

    //clean selected menu
    $("#navigation li").removeClass("navigation-active-li");
    $("div#header ul#menutop_ul li").removeClass("navigation-active-li");

    //select tab in left menu
    var li = $("#navigation li#li_"+highlight_tab)
    li.addClass("navigation-active-li");

    //select tab in top menu
    var top_li = $("div#header ul#menutop_ul li#top_"+highlight_tab);
    top_li.addClass("navigation-active-li");

    //show tab
    $(".tab").hide();
    $('#'+activeTab).show();
//    innerLayout.close("south");//MODIFIED commented
};

function setupTabs(){

    var topTabs = $(".outer-west ul li.topTab");
    var subTabs = $(".outer-west ul li.subTab");

    subTabs.live("click",function(){
        //leave floor to topTab listener in case of tabs with both classes
        if ($(this).hasClass('topTab')) return false;

        var tab = $(this).attr('id').substring(3);
        showTab(tab);
        return false;
    });

    topTabs.live("click",function(e){
        var tab = $(this).attr('id').substring(3);
        //Subtabs have a class with the name of  this tab
        var subtabs = $('div#menu li.'+tab);

        //toggle subtabs only when clicking on the icon or when clicking on an
        //already selected menu
        if ($(e.target).is('span') ||
            $(this).hasClass("navigation-active-li")){
            //for each subtab, we hide the subsubtabs
            subtabs.each(function(){
                //for each subtab, hide its subtabs
                var subsubtabs = $(this).attr('id').substr(3);
                //subsubtabs class
                subsubtabs = $('div#menu li.'+subsubtabs);
                subsubtabs.hide();
            });
            //hide subtabs and reset icon to + position, since all subsubtabs
            //are hidden
            subtabs.fadeToggle('fast');
            $('span',subtabs).removeClass('ui-icon-circle-minus');
            $('span',subtabs).addClass('ui-icon-circle-plus');
            //toggle icon on this tab
            $('span',this).toggleClass('ui-icon-circle-plus ui-icon-circle-minus');
        };
        //if we are clicking on the icon only, do not show the tab
        if ($(e.target).is('span')) return false;

        showTab(tab);
        return false;
    });

};

function setupTopMenu(){
    $('div#header ul#menutop_ul li').live('click',function(){
        var tab = "#" + $(this).attr('id').substring(4);
        showTab(tab);
    });
};

$(document).ready(function () {
    $(".tab").hide();

    setupTabs();
    //setupTopMenu();

    outerLayout = $('body').layout({
        applyDefaultStyles:       false
    ,   center__paneSelector:	".outer-center"
    ,	west__paneSelector:		".outer-west"
    ,	west__size:				160
    ,	north__size:			26
    ,   south__size:            26
    ,	spacing_open:			0 // ALL panes
    ,	spacing_closed:			0 // ALL panes
    //,	north__spacing_open:	0
    //,	south__spacing_open:	0
    ,	north__maxSize:			200
    ,	south__maxSize:			200
    ,   south__closable:        false
    ,   north__closable:        false
    ,   west__closable:         false
    ,   south__resizable:       false
    ,   north__resizable:       false
    ,   west__resizable:        false
    });

    var factor = 0.45;
    var dialog_height = Math.floor($(".outer-center").width()*factor);

    innerLayout = $('div.outer-center').layout({
        fxName:                 "slide"
    ,   initClosed:             true
    ,   center__paneSelector:	".inner-center"
    ,	east__paneSelector:	".inner-east"
    ,   east__size:            dialog_height
    ,   east__minSize:         400
    ,	spacing_open:			5  // ALL panes
    ,	spacing_closed:			5 // ALL panes
    });

});

<commit_msg>Bug #1314: Increase menu size in self-service so all menu items stay in one line (problem with French) (cherry picked from commit 500155937babf99db4f30c822c0cc6214546ef1b)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

//This file is mostly a copy of layout.js from Sunstone.
//Instead of opening a south panel, it opens an east panel.
//Apart from document.ready() modifications, the rest of different lines are
//makerd with MODIFIED

var activeTab;
var outerLayout, innerLayout;

function hideDialog(){
    innerLayout.close("east");//MODIFIED
}

function popDialog(content){
    $("#dialog").html(content);
    innerLayout.open("east");//MODIFIED
}

function popDialogLoading(){
    var loading = '

';
    popDialog(loading);
}

function showTab(tabname,highlight_tab){
    //Since menu items no longer have an  element
    //we no longer expect #tab_id here, but simply tab_id
    //So safety check - remove # from #tab_id if present to ensure compatibility
    if (tabname.indexOf('#') == 0)
        tabname = tabname.substring(1);
    if (highlight_tab && highlight_tab.indexOf('#') == 0)
        highlight_tab == highlight.substring(1);

    var activeTab = tabname;

    if (!highlight_tab) highlight_tab = activeTab;

    //clean selected menu
    $("#navigation li").removeClass("navigation-active-li");
    $("div#header ul#menutop_ul li").removeClass("navigation-active-li");

    //select tab in left menu
    var li = $("#navigation li#li_"+highlight_tab)
    li.addClass("navigation-active-li");

    //select tab in top menu
    var top_li = $("div#header ul#menutop_ul li#top_"+highlight_tab);
    top_li.addClass("navigation-active-li");

    //show tab
    $(".tab").hide();
    $('#'+activeTab).show();
//    innerLayout.close("south");//MODIFIED commented
};

function setupTabs(){

    var topTabs = $(".outer-west ul li.topTab");
    var subTabs = $(".outer-west ul li.subTab");

    subTabs.live("click",function(){
        //leave floor to topTab listener in case of tabs with both classes
        if ($(this).hasClass('topTab')) return false;

        var tab = $(this).attr('id').substring(3);
        showTab(tab);
        return false;
    });

    topTabs.live("click",function(e){
        var tab = $(this).attr('id').substring(3);
        //Subtabs have a class with the name of  this tab
        var subtabs = $('div#menu li.'+tab);

        //toggle subtabs only when clicking on the icon or when clicking on an
        //already selected menu
        if ($(e.target).is('span') ||
            $(this).hasClass("navigation-active-li")){
            //for each subtab, we hide the subsubtabs
            subtabs.each(function(){
                //for each subtab, hide its subtabs
                var subsubtabs = $(this).attr('id').substr(3);
                //subsubtabs class
                subsubtabs = $('div#menu li.'+subsubtabs);
                subsubtabs.hide();
            });
            //hide subtabs and reset icon to + position, since all subsubtabs
            //are hidden
            subtabs.fadeToggle('fast');
            $('span',subtabs).removeClass('ui-icon-circle-minus');
            $('span',subtabs).addClass('ui-icon-circle-plus');
            //toggle icon on this tab
            $('span',this).toggleClass('ui-icon-circle-plus ui-icon-circle-minus');
        };
        //if we are clicking on the icon only, do not show the tab
        if ($(e.target).is('span')) return false;

        showTab(tab);
        return false;
    });

};

function setupTopMenu(){
    $('div#header ul#menutop_ul li').live('click',function(){
        var tab = "#" + $(this).attr('id').substring(4);
        showTab(tab);
    });
};

$(document).ready(function () {
    $(".tab").hide();

    setupTabs();
    //setupTopMenu();

    outerLayout = $('body').layout({
        applyDefaultStyles:       false
    ,   center__paneSelector:	".outer-center"
    ,	west__paneSelector:		".outer-west"
    ,	west__size:				181
    ,	north__size:			26
    ,   south__size:            26
    ,	spacing_open:			0 // ALL panes
    ,	spacing_closed:			0 // ALL panes
    //,	north__spacing_open:	0
    //,	south__spacing_open:	0
    ,	north__maxSize:			200
    ,	south__maxSize:			200
    ,   south__closable:        false
    ,   north__closable:        false
    ,   west__closable:         false
    ,   south__resizable:       false
    ,   north__resizable:       false
    ,   west__resizable:        false
    });

    var factor = 0.45;
    var dialog_height = Math.floor($(".outer-center").width()*factor);

    innerLayout = $('div.outer-center').layout({
        fxName:                 "slide"
    ,   initClosed:             true
    ,   center__paneSelector:	".inner-center"
    ,	east__paneSelector:	".inner-east"
    ,   east__size:            dialog_height
    ,   east__minSize:         400
    ,	spacing_open:			5  // ALL panes
    ,	spacing_closed:			5 // ALL panes
    });

});

<|endoftext|>


<commit_before>global.swintVar = {};

module.exports = {
	defaultize: require('./defaultize'),
	validate: require('./validate'),
	print: require('./print'),
	walk: require('./walk'),
	concat: require('./concat'),
	createHash: require('./createHash')
};

global.print = module.exports.print;
<commit_msg>Build: Added 'use strict' on index<commit_after>'use strict';

global.swintVar = {};

module.exports = {
	defaultize: require('./defaultize'),
	validate: require('./validate'),
	print: require('./print'),
	walk: require('./walk'),
	concat: require('./concat'),
	createHash: require('./createHash')
};

global.print = module.exports.print;
<|endoftext|>


<commit_before>/**
* EditableForm utilites
*/
(function ($) {
    //utils
    $.fn.editableutils = {
        /**
        * classic JS inheritance function
        */
        inherit: function (Child, Parent) {
            var F = function() { };
            F.prototype = Parent.prototype;
            Child.prototype = new F();
            Child.prototype.constructor = Child;
            Child.superclass = Parent.prototype;
        },

        /**
        * set caret position in input
        * see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
        */
        setCursorPosition: function(elem, pos) {
            if (elem.setSelectionRange) {
                elem.setSelectionRange(pos, pos);
            } else if (elem.createTextRange) {
                var range = elem.createTextRange();
                range.collapse(true);
                range.moveEnd('character', pos);
                range.moveStart('character', pos);
                range.select();
            }
        },

        /**
        * function to parse JSON in *single* quotes. (jquery automatically parse only double quotes)
        * That allows such code as:
        * safe = true --> means no exception will be thrown
        * for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery
        */
        tryParseJson: function(s, safe) {
            if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) {
                if (safe) {
                    try {
                        /*jslint evil: true*/
                        s = (new Function('return ' + s))();
                        /*jslint evil: false*/
                    } catch (e) {} finally {
                        return s;
                    }
                } else {
                    /*jslint evil: true*/
                    s = (new Function('return ' + s))();
                    /*jslint evil: false*/
                }
            }
            return s;
        },

        /**
        * slice object by specified keys
        */
        sliceObj: function(obj, keys, caseSensitive /* default: false */) {
            var key, keyLower, newObj = {};

            if (!$.isArray(keys) || !keys.length) {
                return newObj;
            }

            for (var i = 0; i < keys.length; i++) {
                key = keys[i];
                if (obj.hasOwnProperty(key)) {
                    newObj[key] = obj[key];
                }

                if(caseSensitive === true) {
                    continue;
                }

                //when getting data-* attributes via $.data() it's converted to lowercase.
                //details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery
                //workaround is code below.
                keyLower = key.toLowerCase();
                if (obj.hasOwnProperty(keyLower)) {
                    newObj[key] = obj[keyLower];
                }
            }

            return newObj;
        },

        /**
        * exclude complex objects from $.data() before pass to config
        */
        getConfigData: function($element) {
            var data = {};
            $.each($element.data(), function(k, v) {
                if(typeof v !== 'object' || (v && typeof v === 'object' && v.constructor === Object)) {
                    data[k] = v;
                }
            });
            return data;
        },

        objectKeys: function(o) {
            if (Object.keys) {
                return Object.keys(o);
            } else {
                if (o !== Object(o)) {
                    throw new TypeError('Object.keys called on a non-object');
                }
                var k=[], p;
                for (p in o) {
                    if (Object.prototype.hasOwnProperty.call(o,p)) {
                        k.push(p);
                    }
                }
                return k;
            }

        },

       /**
        method to escape html.
       **/
       escape: function(str) {
           return $('
').text(str).html();
       },

       /*
        returns array items from sourceData having value property equal or inArray of 'value'
       */
       itemsByValue: function(value, sourceData) {
           if(!sourceData || value === null) {
               return [];
           }

           if(!$.isArray(value)) {
               value = [].push(value);
           }

           /*jslint eqeq: true*/
           var result = $.grep(sourceData, function(o){
               return $.grep(value, function(v){ return v == o.value; }).length;
           });
           /*jslint eqeq: false*/

           return result;
       }

    };
}(window.jQuery));<commit_msg>fix error in itemsByValue<commit_after>/**
* EditableForm utilites
*/
(function ($) {
    //utils
    $.fn.editableutils = {
        /**
        * classic JS inheritance function
        */
        inherit: function (Child, Parent) {
            var F = function() { };
            F.prototype = Parent.prototype;
            Child.prototype = new F();
            Child.prototype.constructor = Child;
            Child.superclass = Parent.prototype;
        },

        /**
        * set caret position in input
        * see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
        */
        setCursorPosition: function(elem, pos) {
            if (elem.setSelectionRange) {
                elem.setSelectionRange(pos, pos);
            } else if (elem.createTextRange) {
                var range = elem.createTextRange();
                range.collapse(true);
                range.moveEnd('character', pos);
                range.moveStart('character', pos);
                range.select();
            }
        },

        /**
        * function to parse JSON in *single* quotes. (jquery automatically parse only double quotes)
        * That allows such code as:
        * safe = true --> means no exception will be thrown
        * for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery
        */
        tryParseJson: function(s, safe) {
            if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) {
                if (safe) {
                    try {
                        /*jslint evil: true*/
                        s = (new Function('return ' + s))();
                        /*jslint evil: false*/
                    } catch (e) {} finally {
                        return s;
                    }
                } else {
                    /*jslint evil: true*/
                    s = (new Function('return ' + s))();
                    /*jslint evil: false*/
                }
            }
            return s;
        },

        /**
        * slice object by specified keys
        */
        sliceObj: function(obj, keys, caseSensitive /* default: false */) {
            var key, keyLower, newObj = {};

            if (!$.isArray(keys) || !keys.length) {
                return newObj;
            }

            for (var i = 0; i < keys.length; i++) {
                key = keys[i];
                if (obj.hasOwnProperty(key)) {
                    newObj[key] = obj[key];
                }

                if(caseSensitive === true) {
                    continue;
                }

                //when getting data-* attributes via $.data() it's converted to lowercase.
                //details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery
                //workaround is code below.
                keyLower = key.toLowerCase();
                if (obj.hasOwnProperty(keyLower)) {
                    newObj[key] = obj[keyLower];
                }
            }

            return newObj;
        },

        /**
        * exclude complex objects from $.data() before pass to config
        */
        getConfigData: function($element) {
            var data = {};
            $.each($element.data(), function(k, v) {
                if(typeof v !== 'object' || (v && typeof v === 'object' && v.constructor === Object)) {
                    data[k] = v;
                }
            });
            return data;
        },

        objectKeys: function(o) {
            if (Object.keys) {
                return Object.keys(o);
            } else {
                if (o !== Object(o)) {
                    throw new TypeError('Object.keys called on a non-object');
                }
                var k=[], p;
                for (p in o) {
                    if (Object.prototype.hasOwnProperty.call(o,p)) {
                        k.push(p);
                    }
                }
                return k;
            }

        },

       /**
        method to escape html.
       **/
       escape: function(str) {
           return $('
').text(str).html();
       },

       /*
        returns array items from sourceData having value property equal or inArray of 'value'
       */
       itemsByValue: function(value, sourceData) {
           if(!sourceData || value === null) {
               return [];
           }

           //convert to array
           if(!$.isArray(value)) {
               value = [value];
           }

           /*jslint eqeq: true*/
           var result = $.grep(sourceData, function(o){
               return $.grep(value, function(v){ return v == o.value; }).length;
           });
           /*jslint eqeq: false*/

           return result;
       }

    };
}(window.jQuery));<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------
// Copyright IBM Corp. 2015
//
// 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.
//-------------------------------------------------------------------------------

'use strict';

var pipesSDK = require('simple-data-pipe-sdk');
var connectorExt = pipesSDK.connectorExt;
var _ = require('lodash');

/**
 * Sample connector using a few JSON records
 */
function demoConnector( parentDirPath ){

	// TODO: Replace 'template' with a unique connector id (Should match the value of property "simple_data_pipe"."name" in package.json)
	var connectorID = 'template';

	// Call constructor from super class

	// TODO: Replace 'Sample data source' with the desired cnnector display name
	// TODO: Customize connector options
	connectorExt.call(this,
					 connectorID,
					 'Sample data source',
					 {
					  recreateTargetDb: true // if set (default: false) all data from the staging database is cleared prior to data load
					 });

	/*
	 * @return list of data sets (also referred to as tables for legacy reasons) from which the user can choose from
	 */
	this.getTables = function(){

		var dataSets = [];

		// dataSets.push({name:'dataSetName', labelPlural:'dataSetName'}); // assign the name (display name) to each property

		// in this sample the data source contains two static data sets, named 'sample data set 1' and 'sample data set 2'

		var dataSetName = 'sample data set 1';
		dataSets.push({name:dataSetName, labelPlural:dataSetName});

		dataSetName = 'sample data set 2';
		dataSets.push({name:dataSetName, labelPlural:dataSetName});

		return dataSets;
	};

	/*
	 * Customization optional.
	 */
	this.getTablePrefix = function(){
		// The prefix is used to generate names for the Cloudant staging databases that hold your data.
		return connectorID;
	};

	/*
	 * @param pipe - data pipe configuration
	 */
	this.fetchRecords = function( dataSet, pushRecordFn, done, pipeRunStep, pipeRunStats, logger, pipe, pipeRunner ){

		// The data set is typically selected by the user in the "Filter Data" panel during the pipe configuration step
		// dataSet: {name: 'data set name'}

		// Bunyan logging - https://github.com/trentm/node-bunyan
		logger.debug('Fetching data set ' + dataSet.name + ' from cloud data source.');

		// TODO: fetch data from source
		// in this sample the data source contains two static data sets that can be retrieved

		var dataSet1Data = 	[
		 						{'firstname': 'George', 'lastname' : 'Clooney', 'address': 'hollywood blv', 'age': 57 },
		   				  		{'firstname': 'Will', 'lastname' : 'Smith', 'address': 'Rodeo drive', 'age': 45 },
		   				  		{'firstname': 'Brad', 'lastname' : 'Pitt', 'address': 'Beverly hills', 'age': 47 }
        					];

		var dataSet2Data = 	[
		 						{'firstname': 'Kevin', 'lastname' : 'Bacon', 'address': 'Hollywood blv', 'age': 47 },
		   				  		{'firstname': 'Sandra', 'lastname' : 'Bullock', 'address': 'Sunset Heights', 'age': 45 },
		   				  		{'firstname': 'Leonardo', 'lastname' : 'DiCaprio', 'address': 'Sunrise Hills', 'age': 42 },
		   				  		{'firstname': 'Jennifer', 'lastname' : 'Lawrence', 'address': 'Sunny Side', 'age': 26 },
        					];

		var records = dataSet1Data;
		if(dataSet.name === 'sample data set 2') {
			records = dataSet2Data;
		}

        logger.info('Enriching data.');

		// TODO: optional; enrich data
		_.forEach(records, function(record){
				record.username = record.firstname + '_' + record.lastname;

		});

		// TODO: invoke pushRecordFn to store records in Cloudant;
		//       the total number of records is automatically calculated if this function is invoked multiple times
		// Parameter: pass a single record or a set of records to be persisted
		//
		pushRecordFn(records);

		// Invoke done callback function after data processing is complete.
		// Accepts an optional parameter string, which is displayed to the end user, along with the record count
		// after the data pipe run completed
		return done('This is a static data set.');

	};
}

//Extend event Emitter
require('util').inherits(demoConnector, connectorExt);

module.exports = new demoConnector();<commit_msg>multi data source<commit_after>//-------------------------------------------------------------------------------
// Copyright IBM Corp. 2015
//
// 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.
//-------------------------------------------------------------------------------

'use strict';

var pipesSDK = require('simple-data-pipe-sdk');
var connectorExt = pipesSDK.connectorExt;
var _ = require('lodash');

/**
 * Sample connector that stores a few JSON records in Cloudant
 * Build your own connector by following the TODO instructions
 */
function demoConnector( parentDirPath ){

	 /*
	  * Customization is mandatory
	  */

	// TODO:
	//   Replace 'template' with a unique connector id (Should match the value of property "simple_data_pipe"."name" in package.json)
	//   Replace 'Sample Data Source' with the desired display name of the data source (e.g. reddit) from which data will be loaded
	var connectorInfo = {
						  id: 'template',				// internal connector ID
						  name: 'Sample Data Source'	// connector display name
						};

	// TODO
	var connectorOptions = {
					  		recreateTargetDb: true, // if set (default: false) all data currently stored in the staging database is removed prior to data load
					  		useCustomTables: true   // keep true (default: false)
						   };

	// Call constructor from super class;
	connectorExt.call(this,
					 connectorInfo.id,
					 connectorInfo.name,
					 connectorOptions
					 );

	/*
	 * Customization is mandatory!
	 * @return list of data sets (also referred to as tables for legacy reasons) from which the user can choose from
	 */
	this.getTables = function(){

		var dataSets = [];

		// TODO: 'Define' the data set or data sets that can be loaded from the data source. The user gets to choose one.
		// dataSets.push({name:'dataSetName', labelPlural:'dataSetName'}); // assign the name to each property

		/*
		 * In this example the data source contains two static data sets, named 'sample data set 1' and 'sample data set 2'.
		 */

			// data set 1
			var dataSetName = 'sample data set 1';
		    // dataSets.push({name:'dataSetName', labelPlural:'dataSetName'}); // assign the name to each property
			dataSets.push({name:dataSetName, labelPlural:dataSetName});

			// data set 2
			dataSetName = 'sample data set 2';
			dataSets.push({name:dataSetName, labelPlural:dataSetName});

			// In the UI the user gets to choose from:
			//  -> sample data set 1
			//  -> sample data set 2

			// Sometimes you might want to provide the user with the option to load all data sets concurrently
			// To enable that feature, define a single data set that contains only property 'labelPlural'
			dataSets.push({labelPlural:'All data sets'});

			// In the UI the user gets to choose from:
			//  -> All data sets
			//  -> sample data set 1
			//  -> sample data set 2

		// sort list; if present, the ALL_DATA option should be displayed first
		return dataSets.sort(function (dataSet1, dataSet2) {

															if(! dataSet1.name)	// ALL_DATA (only property labelPlural is defined)
																return -1;

															if(! dataSet2.name) // ALL_DATA (only property labelPlural is defined)
																return 1;

															return dataSet1.name - dataSet2.name;
														   });
	}; // getTables

	/*
	 * Customization is not needed.
	 */
	this.getTablePrefix = function(){
		// The prefix is used to generate names for the Cloudant staging databases that hold your data. The recommended
		// value is the connector ID to assure unqiueness.
		return connectorInfo.id;
	};

	/*
	 * Customization is mandatory!
	 * @param pipe - data pipe configuration
	 */
	this.fetchRecords = function( dataSet, pushRecordFn, done, pipeRunStep, pipeRunStats, logger, pipe, pipeRunner ){

		// The data set is typically selected by the user in the "Filter Data" panel during the pipe configuration step
		// dataSet: {name: 'data set name'}. However, if you enabled the ALL option (see get Tables)

		// Bunyan logging - https://github.com/trentm/node-bunyan
		logger.debug('Fetching data set ' + dataSet.name + ' from cloud data source.');

		// TODO: fetch data from cloud data source
		// in this sample the data source contains two static data sets that can be retrieved

		var dataSet1Data = 	[
		 						{'firstname': 'George', 'lastname' : 'Clooney', 'address': 'hollywood blv', 'age': 57 },
		   				  		{'firstname': 'Will', 'lastname' : 'Smith', 'address': 'Rodeo drive', 'age': 45 },
		   				  		{'firstname': 'Brad', 'lastname' : 'Pitt', 'address': 'Beverly hills', 'age': 47 }
        					];

		var dataSet2Data = 	[
		 						{'firstname': 'Kevin', 'lastname' : 'Bacon', 'address': 'Hollywood blv', 'age': 47 },
		   				  		{'firstname': 'Sandra', 'lastname' : 'Bullock', 'address': 'Sunset Heights', 'age': 45 },
		   				  		{'firstname': 'Leonardo', 'lastname' : 'DiCaprio', 'address': 'Sunrise Hills', 'age': 42 },
		   				  		{'firstname': 'Jennifer', 'lastname' : 'Lawrence', 'address': 'Sunny Side', 'age': 26 },
        					];

		var records = dataSet1Data;
		if(dataSet.name === 'sample data set 2') {
			records = dataSet2Data;
		}

        logger.info('Enriching data.');

		// TODO: optional; enrich data
		_.forEach(records, function(record){
				record.username = record.firstname + '_' + record.lastname;

		});

		// TODO: invoke pushRecordFn to store records in Cloudant;
		//       the total number of records is automatically calculated if this function is invoked multiple times
		// Parameter: pass a single record or a set of records to be persisted
		//
		pushRecordFn(records);

		// Invoke done callback function after data processing is complete.
		// Accepts an optional parameter string, which is displayed to the end user, along with the record count
		// after the data pipe run completed.
		return done('This is a static data set.');

	};
}

//Extend event Emitter
require('util').inherits(demoConnector, connectorExt);

module.exports = new demoConnector();<|endoftext|>


<commit_before>// Import Dependencies.
var gulp = require("gulp");
var webpack = require('webpack');
var webpackStream = require("webpack-stream");
var path = require("path");
var processShaders = require("../helpers/gulp-processShaders");
var uncommentShaders = require('../helpers/gulp-removeShaderComments');

// Read the full config.
var config = require("../config.json");

/**
 * Watch ts files and fire repective tasks.
 */
gulp.task("watchLibraries", function startWatch() {
    var tasks = [];

    config.modules.map(function(module) {
        var settings = config[module].build;
        if (!config[module].isCore && settings && settings.webpack) {
            for (var index = 0; index < config[module].libraries.length; index++) {
                var library = config[module].libraries[index];
                if (library.preventLoadLibrary) {
                    continue;
                }

                let wpConfig = require(settings.webpack);
                // watch on.
                wpConfig.watch = true;
                // dev mode and absolute path sourcemaps for debugging
                wpConfig.mode = "development";
                wpConfig.devtool = "nosources-source-map";

                var rootPath = path.resolve(__dirname, "../../../");
                var absoluteSrc = path.resolve(__dirname, "../", settings.srcDirectory);
                wpConfig.output.devtoolModuleFilenameTemplate = (info) => {
                    info.resourcePath = path.normalize(info.resourcePath);

                    if (!path.isAbsolute(info.resourcePath)) {
                        info.resourcePath = path.join(absoluteSrc, info.resourcePath);
                    }

                    return `"../../../${path.relative(rootPath, info.resourcePath).replace(/\\/g, "/")}`;
                };

                tasks.push(
                    gulp.src(settings.srcDirectory + "**/*.fx")
                        .pipe(uncommentShaders())
                        .pipe(processShaders(false))
                );

                var outputDirectory = config.build.tempDirectory + config.build.localDevUMDFolderName + settings.distOutputDirectory;
                tasks.push(
                    webpackStream(wpConfig, webpack).pipe(gulp.dest(outputDirectory))
                );

                tasks.push(
                    gulp.watch(settings.srcDirectory + "**/*.fx", { interval: 1000 }, function() {
                        console.log(library.output + ": Shaders.");
                        return gulp.src(settings.srcDirectory + "**/*.fx")
                            .pipe(uncommentShaders())
                            .pipe(processShaders(false));
                    })
                );
            }
        }
    });

    return Promise.resolve();
});<commit_msg>Fix Watch<commit_after>// Import Dependencies.
var gulp = require("gulp");
var webpack = require('webpack');
var webpackStream = require("webpack-stream");
var path = require("path");
var processShaders = require("../helpers/gulp-processShaders");
var uncommentShaders = require('../helpers/gulp-removeShaderComments');

// Read the full config.
var config = require("../config.json");

/**
 * Watch ts files and fire repective tasks.
 */
gulp.task("watchLibraries", function startWatch() {
    var tasks = [];

    config.modules.map(function(module) {
        var settings = config[module].build;
        if (!config[module].isCore && settings && settings.webpack) {
            for (var index = 0; index < config[module].libraries.length; index++) {
                var library = config[module].libraries[index];
                if (library.preventLoadLibrary) {
                    continue;
                }

                let wpConfig = require(settings.webpack);
                // watch on.
                wpConfig.watch = true;
                // dev mode and absolute path sourcemaps for debugging
                wpConfig.mode = "development";
                wpConfig.devtool = "nosources-source-map";

                var rootPath = path.resolve(__dirname, "../../../");
                var absoluteSrc = path.resolve(__dirname, "../", settings.srcDirectory);
                wpConfig.output.devtoolModuleFilenameTemplate = (info) => {
                    info.resourcePath = path.normalize(info.resourcePath);

                    if (!path.isAbsolute(info.resourcePath)) {
                        info.resourcePath = path.join(absoluteSrc, info.resourcePath);
                    }

                    return `../../../${path.relative(rootPath, info.resourcePath).replace(/\\/g, "/")}`;
                };

                tasks.push(
                    gulp.src(settings.srcDirectory + "**/*.fx")
                        .pipe(uncommentShaders())
                        .pipe(processShaders(false))
                );

                var outputDirectory = config.build.tempDirectory + config.build.localDevUMDFolderName + settings.distOutputDirectory;
                tasks.push(
                    webpackStream(wpConfig, webpack).pipe(gulp.dest(outputDirectory))
                );

                tasks.push(
                    gulp.watch(settings.srcDirectory + "**/*.fx", { interval: 1000 }, function() {
                        console.log(library.output + ": Shaders.");
                        return gulp.src(settings.srcDirectory + "**/*.fx")
                            .pipe(uncommentShaders())
                            .pipe(processShaders(false));
                    })
                );
            }
        }
    });

    return Promise.resolve();
});<|endoftext|>


<commit_before>var _require = require
var mongoskin = _require('mongoskin');

var metaOperators = {
  $comment: true
, $explain: true
, $hint: true
, $maxScan: true
, $max: true
, $min: true
, $orderby: true
, $returnKey: true
, $showDiskLoc: true
, $snapshot: true
};

var cursorOperators = {
  $limit: 'limit'
, $skip: 'skip'
};

// mongo is a mongoskin client. Create with:
// mongo.db('localhost:27017/tx?auto_reconnect', safe:true)
exports = module.exports = function() {
  var mongo = mongoskin.db.apply(mongoskin.db, arguments);
  return new LiveDbMongo(mongo);
};

exports.LiveDbMongo = LiveDbMongo;

function LiveDbMongo(mongo) {
  this.mongo = mongo;
  this.closed = false;
}

LiveDbMongo.prototype.name = 'mongo';

LiveDbMongo.prototype.close = function(callback) {
  if (this.closed) return callback('db already closed');
  this.mongo.close(callback);
  this.closed = true;
};

LiveDbMongo.prototype.getSnapshot = function(cName, docName, callback) {
  if (this.closed) return callback('db already closed');
  this.mongo.collection(cName).findOne({_id: docName}, function(err, doc) {
    callback(err, castToSnapshot(doc));
  });
};

LiveDbMongo.prototype.setSnapshot = function(cName, docName, data, callback) {
  if (this.closed) return callback('db already closed');
  var doc = castToDoc(docName, data);
  this.mongo.collection(cName).update({_id: docName}, doc, {upsert: true}, callback);
};

LiveDbMongo.prototype.query = function(livedb, cName, inputQuery, callback) {
  if (this.closed) return callback('db already closed');

  var query = normalizeQuery(inputQuery);
  var cursorMethods = extractCursorMethods(query);

  this.mongo.collection(cName).find(query, function(err, cursor) {
    if (err) return callback(err);

    for (var i = 0; i < cursorMethods.length; i++) {
      var item = cursorMethods[i];
      var method = item[0];
      var arg = item[1];
      cursor[method](arg);
    }

    cursor.toArray(function(err, results) {
      results = results && results.map(castToSnapshot);
      callback(err, results);
    });
  });
};

LiveDbMongo.prototype.queryDoc = function(livedb, index, cName, docName, inputQuery, callback) {
  if (this.closed) return callback('db already closed');
  var query = normalizeQuery(inputQuery);

  if (query.$query._id) {
    if (query.$query._id !== docName) return callback();
  } else {
    query.$query._id = docName;
  }

  this.mongo.collection(cName).findOne(query, function(err, doc) {
    callback(err, castToSnapshot(doc));
  });
};

// Test whether an operation will make the document its applied to match the
// specified query. This function doesn't really have enough information to know
// in all cases, but if we can determine whether a query matches based on just
// the operation, it saves doing extra DB calls.
//
// currentStatus is true or false depending on whether the query currently
// matches. return true or false if it knows, or null if the function doesn't
// have enough information to tell.
LiveDbMongo.prototype.willOpMakeDocMatchQuery = function(currentStatus, query, op) {
  return null;
};

// Does the query need to be rerun against the database with every edit?
LiveDbMongo.prototype.queryNeedsPollMode = function(query) {
  return query.hasOwnProperty('$orderby') ||
    query.hasOwnProperty('$limit') ||
    query.hasOwnProperty('$skip');
};

function extractCursorMethods(query) {
  var out = [];
  for (var key in query) {
    if (cursorOperators[key]) {
      out.push([cursorOperators[key], query[key]]);
      delete query[key];
    }
  }
  return out;
}

function normalizeQuery(inputQuery) {
  // Box queries inside of a $query and clone so that we know where to look
  // for selctors and can modify them without affecting the original object
  var query;
  if (inputQuery.$query) {
    query = shallowClone(inputQuery);
    query.$query = shallowClone(query.$query);
  } else {
    query = {$query: {}};
    for (var key in inputQuery) {
      if (metaOperators[key] || cursorOperators[key]) {
        query[key] = inputQuery[key];
      } else {
        query.$query[key] = inputQuery[key];
      }
    }
  }

  // Deleted documents are kept around so that we can start their version from
  // the last version if they get recreated. When they are deleted, their type
  // is set to null, so don't return any documents with a null type.
  if (!query.$query._type) query.$query._type = {$ne: null};

  return query;
}

function castToDoc(docName, data) {
  var doc = (
    typeof data.data === 'object' &&
    data.data !== null &&
    !Array.isArray(data.data)
  ) ?
    shallowClone(data.data) :
    {_data: (data.data === void 0) ? null : data.data};
  doc._type = data.type || null;
  doc._v = data.v;
  doc._id = docName;
  return doc;
}

function castToSnapshot(doc) {
  if (!doc) return;
  var type = doc._type;
  var v = doc._v;
  var docName = doc._id;
  var data = doc._data;
  if (data === void 0) {
    doc = shallowClone(doc);
    delete doc._type;
    delete doc._v;
    delete doc._id;
    return {
      data: doc
    , type: type
    , v: v
    , docName: docName
    };
  }
  return {
    data: data
  , type: type
  , v: v
  , docName: docName
  };
}

function shallowClone(object) {
  var out = {};
  for (var key in object) {
    out[key] = object[key];
  }
  return out;
}
<commit_msg>fix to support queries that involve a complex _id parameter<commit_after>var _require = require
var mongoskin = _require('mongoskin');

var metaOperators = {
  $comment: true
, $explain: true
, $hint: true
, $maxScan: true
, $max: true
, $min: true
, $orderby: true
, $returnKey: true
, $showDiskLoc: true
, $snapshot: true
};

var cursorOperators = {
  $limit: 'limit'
, $skip: 'skip'
};

// mongo is a mongoskin client. Create with:
// mongo.db('localhost:27017/tx?auto_reconnect', safe:true)
exports = module.exports = function() {
  var mongo = mongoskin.db.apply(mongoskin.db, arguments);
  return new LiveDbMongo(mongo);
};

exports.LiveDbMongo = LiveDbMongo;

function LiveDbMongo(mongo) {
  this.mongo = mongo;
  this.closed = false;
}

LiveDbMongo.prototype.name = 'mongo';

LiveDbMongo.prototype.close = function(callback) {
  if (this.closed) return callback('db already closed');
  this.mongo.close(callback);
  this.closed = true;
};

LiveDbMongo.prototype.getSnapshot = function(cName, docName, callback) {
  if (this.closed) return callback('db already closed');
  this.mongo.collection(cName).findOne({_id: docName}, function(err, doc) {
    callback(err, castToSnapshot(doc));
  });
};

LiveDbMongo.prototype.setSnapshot = function(cName, docName, data, callback) {
  if (this.closed) return callback('db already closed');
  var doc = castToDoc(docName, data);
  this.mongo.collection(cName).update({_id: docName}, doc, {upsert: true}, callback);
};

LiveDbMongo.prototype.query = function(livedb, cName, inputQuery, callback) {
  if (this.closed) return callback('db already closed');

  var query = normalizeQuery(inputQuery);
  var cursorMethods = extractCursorMethods(query);

  this.mongo.collection(cName).find(query, function(err, cursor) {
    if (err) return callback(err);

    for (var i = 0; i < cursorMethods.length; i++) {
      var item = cursorMethods[i];
      var method = item[0];
      var arg = item[1];
      cursor[method](arg);
    }

    cursor.toArray(function(err, results) {
      results = results && results.map(castToSnapshot);
      callback(err, results);
    });
  });
};

LiveDbMongo.prototype.queryDoc = function(livedb, index, cName, docName, inputQuery, callback) {
  if (this.closed) return callback('db already closed');
  var query = normalizeQuery(inputQuery);

  // Run the query against a particular mongo document by adding an _id filter
  var queryId = query.$query._id;
  if (queryId) {
    delete query.$query._id;
    query.$query.$and = [{_id: docName}, {_id: queryId}];
  } else {
    query.$query._id = docName;
  }

  this.mongo.collection(cName).findOne(query, function(err, doc) {
    callback(err, castToSnapshot(doc));
  });
};

// Test whether an operation will make the document its applied to match the
// specified query. This function doesn't really have enough information to know
// in all cases, but if we can determine whether a query matches based on just
// the operation, it saves doing extra DB calls.
//
// currentStatus is true or false depending on whether the query currently
// matches. return true or false if it knows, or null if the function doesn't
// have enough information to tell.
LiveDbMongo.prototype.willOpMakeDocMatchQuery = function(currentStatus, query, op) {
  return null;
};

// Does the query need to be rerun against the database with every edit?
LiveDbMongo.prototype.queryNeedsPollMode = function(query) {
  return query.hasOwnProperty('$orderby') ||
    query.hasOwnProperty('$limit') ||
    query.hasOwnProperty('$skip');
};

function extractCursorMethods(query) {
  var out = [];
  for (var key in query) {
    if (cursorOperators[key]) {
      out.push([cursorOperators[key], query[key]]);
      delete query[key];
    }
  }
  return out;
}

function normalizeQuery(inputQuery) {
  // Box queries inside of a $query and clone so that we know where to look
  // for selctors and can modify them without affecting the original object
  var query;
  if (inputQuery.$query) {
    query = shallowClone(inputQuery);
    query.$query = shallowClone(query.$query);
  } else {
    query = {$query: {}};
    for (var key in inputQuery) {
      if (metaOperators[key] || cursorOperators[key]) {
        query[key] = inputQuery[key];
      } else {
        query.$query[key] = inputQuery[key];
      }
    }
  }

  // Deleted documents are kept around so that we can start their version from
  // the last version if they get recreated. When they are deleted, their type
  // is set to null, so don't return any documents with a null type.
  if (!query.$query._type) query.$query._type = {$ne: null};

  return query;
}

function castToDoc(docName, data) {
  var doc = (
    typeof data.data === 'object' &&
    data.data !== null &&
    !Array.isArray(data.data)
  ) ?
    shallowClone(data.data) :
    {_data: (data.data === void 0) ? null : data.data};
  doc._type = data.type || null;
  doc._v = data.v;
  doc._id = docName;
  return doc;
}

function castToSnapshot(doc) {
  if (!doc) return;
  var type = doc._type;
  var v = doc._v;
  var docName = doc._id;
  var data = doc._data;
  if (data === void 0) {
    doc = shallowClone(doc);
    delete doc._type;
    delete doc._v;
    delete doc._id;
    return {
      data: doc
    , type: type
    , v: v
    , docName: docName
    };
  }
  return {
    data: data
  , type: type
  , v: v
  , docName: docName
  };
}

function shallowClone(object) {
  var out = {};
  for (var key in object) {
    out[key] = object[key];
  }
  return out;
}
<|endoftext|>


<commit_before>'use strict';

const CronJob = require('cron').CronJob;
const fetch = require('isomorphic-fetch');
const notifier = require('node-notifier');
const constants = require('../constants');

const httpRequest = (path, method, body = undefined) => {
  return fetch(path, {
    method,
    headers: {
      'Content-Type': 'application/json'
    },
    body
  })
  .then((res) => {
    if (res.status >= 400) {
      throw new Error("Bad response from server")
    }
    return res.json();
  });
};

const getWaterLevelURL = (country, prefecture, river) => {
  return `/production/water-level/countries/${ country }/prefectures/${ prefecture }/rivers/${ river }`;
};

const getRainFallURL = () => {

};

const setTrayIconForWaterLevel = (waterLevel, appIcon = null) => {
  const embankmentHeight = waterLevel.height;
  const currentWaterLevel = waterLevel.latestDate['4_10'].dataStr;
  const levelOfWaterLevel= (currentWaterLevel / embankmentHeight) * 100;

  let trayIcon;
  if (levelOfWaterLevel >= 0 && levelOfWaterLevel < 20) {
    trayIcon = constants.trayIcon1;
  } else if (levelOfWaterLevel >= 20 && levelOfWaterLevel < 40) {
    trayIcon = constants.trayIcon2;
  } else if (levelOfWaterLevel >= 40 && levelOfWaterLevel < 60) {
    trayIcon = constants.trayIcon3;
    this.generateNotify(); // TODO: 水位 or 降水量の遷移によって通知を出し分ける
  } else if (levelOfWaterLevel >= 60 && levelOfWaterLevel < 80) {
    trayIcon = constants.trayIcon4;
    this.generateNotify(); // TODO: 水位 or 降水量の遷移によって通知を出し分ける
  } else if (levelOfWaterLevel >= 80 && levelOfWaterLevel < 100) {
    trayIcon = constants.trayIcon5;
    this.generateNotify(); // TODO: 水位or 降水量の遷移によって通知を出し分ける
  } else {
    throw new Error(`Fault levelOfWaterLevel. levelOfWaterLevel: ${levelOfWaterLevel}`);
  }

  if (appIcon) {
    appIcon.setImage(trayIcon);
  }
};

const generateNotify = () => {
  return notifier.notify({
    'title': '警告',
    'message': '水位が急上昇しています!',
    'icon': constants.pushIcon,
  });
};

// export functions
module.exports = {
  polling: (func, params, cronTime) => {
    const job = new CronJob({
      cronTime,
      onTick: () => func(...params),
      start: true,
    });
    job.start();
  },
  requestWaterLevel: (country, prefecture, river, param) => {
    httpRequest(constants.host + getWaterLevelURL(country, prefecture, river), 'GET')
      .then((res) => {
        try {
          setTrayIconForWaterLevel(res, param);
        } catch (err) {
          throw err;
        }
      })
      .catch((err) => {
        console.error(err.stack);
      });
  },
  getData: (current) => {
    console.log(current) // Location number
    return {
      precipitation: Math.floor(Math.random() * 999), // example data
      trendencyPr: Math.floor(Math.random() * 5), // example data
      trendencyWl: Math.floor(Math.random() * 5) // example data
    };
  },
  getLocation: () => {
    return [
      'Japan, Ishikawa, Asano river',
      'Japan, Tokyo, Sumida river'
    ];
  },
}
<commit_msg>fix: create url<commit_after>'use strict';

const CronJob = require('cron').CronJob;
const fetch = require('isomorphic-fetch');
const notifier = require('node-notifier');
const constants = require('../constants');

const httpRequest = (path, method, body = undefined) => {
  return fetch(path, {
    method,
    headers: {
      'Content-Type': 'application/json'
    },
    body
  })
  .then((res) => {
    if (res.status >= 400) {
      throw new Error("Bad response from server")
    }
    return res.json();
  });
};

const getWaterLevelURL = (country, prefecture, river) => {
  return `/production/water-level/countries/${ country }/prefectures/${ prefecture }/rivers/${ river }`;
};

const getRainFallURL = () => {

};

const setTrayIconForWaterLevel = (waterLevel, appIcon = null) => {
  const embankmentHeight = waterLevel.height;
  const currentWaterLevel = waterLevel.latestDate['4_10'].dataStr;
  const levelOfWaterLevel= (currentWaterLevel / embankmentHeight) * 100;

  let trayIcon;
  if (levelOfWaterLevel >= 0 && levelOfWaterLevel < 20) {
    trayIcon = constants.trayIcon1;
  } else if (levelOfWaterLevel >= 20 && levelOfWaterLevel < 40) {
    trayIcon = constants.trayIcon2;
  } else if (levelOfWaterLevel >= 40 && levelOfWaterLevel < 60) {
    trayIcon = constants.trayIcon3;
    this.generateNotify(); // TODO: 水位 or 降水量の遷移によって通知を出し分ける
  } else if (levelOfWaterLevel >= 60 && levelOfWaterLevel < 80) {
    trayIcon = constants.trayIcon4;
    this.generateNotify(); // TODO: 水位 or 降水量の遷移によって通知を出し分ける
  } else if (levelOfWaterLevel >= 80 && levelOfWaterLevel < 100) {
    trayIcon = constants.trayIcon5;
    this.generateNotify(); // TODO: 水位or 降水量の遷移によって通知を出し分ける
  } else {
    throw new Error(`Fault levelOfWaterLevel. levelOfWaterLevel: ${levelOfWaterLevel}`);
  }

  if (appIcon) {
    appIcon.setImage(trayIcon);
  }
};

const generateNotify = () => {
  return notifier.notify({
    'title': '警告',
    'message': '水位が急上昇しています!',
    'icon': constants.pushIcon,
  });
};

// export functions
module.exports = {
  polling: (func, params, cronTime) => {
    const job = new CronJob({
      cronTime,
      onTick: () => func(...params),
      start: true,
    });
    job.start();
  },
  requestWaterLevel: (country, prefecture, river, param) => {
    httpRequest(`https://${ constants.host }${ getWaterLevelURL(country, prefecture, river) }`, 'GET')
      .then((res) => {
        try {
          setTrayIconForWaterLevel(res, param);
        } catch (err) {
          throw err;
        }
      })
      .catch((err) => {
        console.error(err.stack);
      });
  },
  getData: (current) => {
    console.log(current) // Location number
    return {
      precipitation: Math.floor(Math.random() * 999), // example data
      trendencyPr: Math.floor(Math.random() * 5), // example data
      trendencyWl: Math.floor(Math.random() * 5) // example data
    };
  },
  getLocation: () => {
    return [
      'Japan, Ishikawa, Asano river',
      'Japan, Tokyo, Sumida river'
    ];
  },
}
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');

var VERSION = '0.12.0';
var BASE = 'https://github.com/facebook/flow/releases/download/v' + VERSION + '/';

module.exports = new BinWrapper()
	.src(BASE + 'flow-osx-v' + VERSION + '.zip', 'darwin')
	.src(BASE + 'flow-linux64-v' + VERSION + '.zip', 'linux', 'x64')
	.dest(path.join(__dirname, '../vendor'))
	.use('flow');
<commit_msg>Update binary to v0.13.1<commit_after>'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');

var VERSION = '0.13.1';
var BASE = 'https://github.com/facebook/flow/releases/download/v' + VERSION + '/';

module.exports = new BinWrapper()
	.src(BASE + 'flow-osx-v' + VERSION + '.zip', 'darwin')
	.src(BASE + 'flow-linux64-v' + VERSION + '.zip', 'linux', 'x64')
	.dest(path.join(__dirname, '../vendor'))
	.use('flow');
<|endoftext|>


<commit_before>"use strict";

const isUndefined = require("is-undefined")
    , EventEmitter = require("events").EventEmitter
    , spawn = require("spawno")
    , isWin = require("is-win")
    ;

const EXE_NAME = `powershell${isWin() ? ".exe" : ""}`;

module.exports = class PowerShell extends EventEmitter {
    /**
     * PowerShell
     *
     * @name PowerShell
     * @function
     * @param {String} input The command or PowerShell script ro execute.
     * @param {Object} opt An object containing the following fields:
     *
     *  - `debug` (Boolean): Turn on/off the debug messages (default: `false`).
     *  - `noprofile` (Boolean): Turn on/off noprofile parameter (default: `true`).
     *  - `executionpolicy` (Enum): Run powershell with specified executionpolicy (default: System default). Valid enum values are `Restricted`, `AllSigned`, `RemoteSigned`, `Unrestricted`, `Bypass`, `Undefined`.
     *
     * @param {Function} cb The callback function (optional).
     */
    constructor (input, opt, cb){

        super();

        opt = opt || {};
        opt.debug = isUndefined(opt.debug) ? false : opt.debug;
        opt.noprofile = isUndefined(opt.noprofile) ? true : opt.noprofile;

        let args = [];

        if (opt.noprofile) {
            args.push("-NoProfile");
        }

        if(!isUndefined(opt.executionpolicy)) {
            args.push("-ExecutionPolicy", opt.executionpolicy);
        }

        args.push("-Command", "& {" + input + "}");

        let _proc = spawn(
            EXE_NAME
          , args
          , { stdio: ["ignore", "pipe", "pipe" ] }
          , cb
        );

        _proc.stdout.setEncoding("utf8");
        _proc.stderr.setEncoding("utf8");
        _proc.on("error", err => this.emit("error", err));

        if(opt.debug){
            console.log(`<${EXE_NAME}> Starting ${_proc.pid} on ${process.platform}`);
        }

        _proc.stdout.on("data", data => this.emit("output", data));
        _proc.stderr.on("data", err => this.emit("error-output", err));
        _proc.on("close", code => {
            if(opt.debug) {
                console.log(`<${EXE_NAME}> Process ${_proc.pid} exited with code ${code}`);
            }

            this.emit("end", code);
        });
    }
};
<commit_msg>Update index.js<commit_after>"use strict";

const isUndefined = require("is-undefined")
    , EventEmitter = require("events").EventEmitter
    , spawn = require("spawno")
    , isWin = require("is-win")
    ;

const EXE_NAME = `powershell${isWin() ? ".exe" : ""}`;

module.exports = class PowerShell extends EventEmitter {
    /**
     * PowerShell
     *
     * @name PowerShell
     * @function
     * @param {String} input The command or PowerShell script ro execute.
     * @param {Object} opt An object containing the following fields:
     *
     *  - `debug` (Boolean): Turn on/off the debug messages (default: `false`).
     *  - `noprofile` (Boolean): Turn on/off noprofile parameter (default: `true`).
     *  - `executionpolicy` (Enum): Run powershell with specified executionpolicy (default: System default). Valid enum values are `Restricted`, `AllSigned`, `RemoteSigned`, `Unrestricted`, `Bypass`, `Undefined`.
     *
     * @param {Function} cb The callback function (optional).
     */
    constructor (input, opt, cb){

        super();

        opt = opt || {};
        opt.debug = isUndefined(opt.debug) ? false : opt.debug;
        opt.noprofile = isUndefined(opt.noprofile) ? true : opt.noprofile;

        let args = [];

        if (opt.noprofile) {
            args.push("-NoProfile");
        }

        if(!isUndefined(opt.executionpolicy)) {
            args.push("-ExecutionPolicy", opt.executionpolicy);
        }

        args.push("-Command", "& {" + input + "}");

        let _proc = spawn(
            EXE_NAME
          , args
          , { stdio: ["ignore", "pipe", "pipe" ] }
          , cb
        );

        _proc.stdout.setEncoding("utf8");
        _proc.stderr.setEncoding("utf8");
        _proc.on("error", err => this.emit("error", err));

        if(opt.debug){
            console.log(`<${EXE_NAME}> Starting ${_proc.pid} on ${process.platform}`);
        }

        let chunks = [];
        _proc.stdout.on("data", chunk => { chunks.push(chunk); });
        _proc.stderr.on("data", err => this.emit("error-output", err));
        _proc.on("close", code => {
            if(opt.debug) {
                console.log(`<${EXE_NAME}> Process ${_proc.pid} exited with code ${code}`);
            }

            this.emit("output", chunks.join())
            this.emit("end", code);
        });
    }
};
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const svgicons2svgfont = require('svgicons2svgfont');
const svg2ttf = require('svg2ttf');
const ejs = require('ejs');
const MemoryStream = require('memory-stream');
const converters = {
	woff: require('ttf2woff'),
	woff2: require('ttf2woff2'),
	eot: require('ttf2eot')
};

function runConverters(svgFont, output) {
	let ttf = svg2ttf(svgFont, {});

	fs.writeFileSync(output + '.ttf', new Buffer(ttf.buffer));
	console.log(`- ${output}.ttf`);

	Object.keys(converters).forEach((key) => {
		fs.writeFileSync(`${output}.${key}`, converters[key](ttf.buffer));
		console.log(`- ${output}.${key}`);
	});
}

function decode(char) {
	let buf = [];

	char = new String(char);
	for (let i = 0; i < char.length; i++) {
		buf[i] = char.charCodeAt(i).toString(16);
	}
	return buf.join('');
}

function generateSpecimen(font, output) {
	font.decode = decode;
	ejs.renderFile('tpl.ejs', font, {}, function (err, str) {
		if (err) {
			console.log(err);
		} else {
			fs.writeFileSync(output + '-specimen' + '.html', str);
		}
	});
}

function convert(fontConfig, glyphsPath) {
	return new Promise((resolve, reject) => {
		let ms = new MemoryStream();
		let fontStream = svgicons2svgfont({
			fontName: fontConfig.name,
			normalize: true
		});

		fontStream.pipe(ms).on('finish', () => {
			resolve(ms.toString());
		}).on('error', function (err) {
			console.log(err);
		});
		console.log(`${fontConfig.name}: ${fontConfig.glyphs.length} glyphs found`);
		fontConfig.glyphs.forEach((glyphData) => {
			const glyphPath = `${glyphsPath}/${glyphData.file}.svg`;

			if (fs.existsSync(glyphPath)) {
				const glyph = fs.createReadStream(glyphPath);

				glyph.metadata = glyphData;
				fontStream.write(glyph);
			} else {
				console.warn(`${glyphPath} not found!`);
			}
		});
		fontStream.end();
	});
}

function fetchConfig(iconFolder) {
	let config = {name: 'All', glyphs: []};
	let files = fs.readdirSync(iconFolder);

	files.forEach((file, index) => {
		config.glyphs.push({
			'unicode': [
				String.fromCharCode(index)
			],
			'name': file,
			'file': file.replace(/\.svg/, '')
		});
	});
	return config;

}

exports.generate = function (param) {
	let fontConfig = param.fontConfig;
	let outputPath = param.outputPath;
	let glyphsPath = param.glyphsPath;

	fontConfig.name = fontConfig.name || 'font';
	convert(fontConfig, glyphsPath).then((svgFont) => {
		let output = path.join(outputPath, fontConfig.name);

		if (!fs.existsSync(outputPath)) {
			fs.mkdirSync(output);
		}

		runConverters(svgFont, output);
		if (param.fontSpecimen) {
			generateSpecimen(fontConfig, output);
		}
		console.log(`Font "${fontConfig.name}" created!`);
	});
};

exports.generateAll = function (param) {
	let outputPath = param.outputPath;

	convert(fetchConfig(param.glyphsPath), './icons').then((svgFont) => {
		let output = `${outputPath}/${fontConfig.name}`;

		if (!fs.existsSync(outputPath)) {
			fs.mkdirSync(outputPath);
		}
		runConverters(svgFont, output);
		generateSpecimen(fontConfig, output);
		console.log(`Font "${fontConfig.name}" created!`);
	});
};
<commit_msg>Grrr.....<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const svgicons2svgfont = require('svgicons2svgfont');
const svg2ttf = require('svg2ttf');
const ejs = require('ejs');
const MemoryStream = require('memory-stream');
const converters = {
	woff: require('ttf2woff'),
	woff2: require('ttf2woff2'),
	eot: require('ttf2eot')
};

function runConverters(svgFont, output) {
	let ttf = svg2ttf(svgFont, {});

	fs.writeFileSync(output + '.ttf', new Buffer(ttf.buffer));
	console.log(`- ${output}.ttf`);

	Object.keys(converters).forEach((key) => {
		fs.writeFileSync(`${output}.${key}`, converters[key](ttf.buffer));
		console.log(`- ${output}.${key}`);
	});
}

function decode(char) {
	let buf = [];

	char = new String(char);
	for (let i = 0; i < char.length; i++) {
		buf[i] = char.charCodeAt(i).toString(16);
	}
	return buf.join('');
}

function generateSpecimen(font, output) {
	font.decode = decode;
	ejs.renderFile('tpl.ejs', font, {}, function (err, str) {
		if (err) {
			console.log(err);
		} else {
			fs.writeFileSync(output + '-specimen' + '.html', str);
		}
	});
}

function convert(fontConfig, glyphsPath) {
	return new Promise((resolve, reject) => {
		let ms = new MemoryStream();
		let fontStream = svgicons2svgfont({
			fontName: fontConfig.name,
			normalize: true
		});

		fontStream.pipe(ms).on('finish', () => {
			resolve(ms.toString());
		}).on('error', function (err) {
			console.log(err);
		});
		console.log(`${fontConfig.name}: ${fontConfig.glyphs.length} glyphs found`);
		fontConfig.glyphs.forEach((glyphData) => {
			const glyphPath = `${glyphsPath}/${glyphData.file}.svg`;

			if (fs.existsSync(glyphPath)) {
				const glyph = fs.createReadStream(glyphPath);

				glyph.metadata = glyphData;
				fontStream.write(glyph);
			} else {
				console.warn(`${glyphPath} not found!`);
			}
		});
		fontStream.end();
	});
}

function fetchConfig(iconFolder) {
	let config = {name: 'All', glyphs: []};
	let files = fs.readdirSync(iconFolder);

	files.forEach((file, index) => {
		config.glyphs.push({
			'unicode': [
				String.fromCharCode(index)
			],
			'name': file,
			'file': file.replace(/\.svg/, '')
		});
	});
	return config;

}

exports.generate = function (param) {
	let fontConfig = param.fontConfig;
	let outputPath = param.outputPath;
	let glyphsPath = param.glyphsPath;

	fontConfig.name = fontConfig.name || 'font';
	convert(fontConfig, glyphsPath).then((svgFont) => {
		let output = path.join(outputPath, fontConfig.name);

		if (!fs.existsSync(outputPath)) {
			fs.mkdirSync(outputPath);
		}

		runConverters(svgFont, output);
		if (param.fontSpecimen) {
			generateSpecimen(fontConfig, output);
		}
		console.log(`Font "${fontConfig.name}" created!`);
	});
};

exports.generateAll = function (param) {
	let outputPath = param.outputPath;

	convert(fetchConfig(param.glyphsPath), './icons').then((svgFont) => {
		let output = `${outputPath}/${fontConfig.name}`;

		if (!fs.existsSync(outputPath)) {
			fs.mkdirSync(outputPath);
		}
		runConverters(svgFont, output);
		generateSpecimen(fontConfig, output);
		console.log(`Font "${fontConfig.name}" created!`);
	});
};
<|endoftext|>


<commit_before>Ti.include('cocoafish.js');
var Events = {};
/*
 *  <property name="acs-oauth-secret-development" type="string">GxvXXCNnjESPojJkCXvGBGdjOJD5kc8k</property>
 *  <property name="acs-oauth-key-development" type="string">1iHEqePuYFs3SFXcaVwNIB4nAx3G99Ld</property>
 *  <property name="acs-api-key-development" type="string">1PlafvOb0KsfJhWw68tWkGiVt3IkhjxR</property>
 */
var sdk = new Cocoafish('1iHEqePuYFs3SFXcaVwNIB4nAx3G99Ld','GxvXXCNnjESPojJkCXvGBGdjOJD5kc8k');
Events.create = function(_data){
  var custom_field = {club:_data.club};
  _data.custom_fields = JSON.stringify(custom_field);
  sdk.sendRequest('events/create.json', 'POST', _data, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'createEvent') {
      	  Ti.API.log(data.response);
        }
      }
    }
  });

};

Events.queryClub = function(_club,_callback){
  var whereString = JSON.stringify({_club: _club});
  var query = {
    where: whereString
  };
  sdk.sendRequest('events/query.json', 'GET', query, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'queryEvents') {
          var events = data.response.events;
          Ti.API.log(events);
          _callback(events);
        }
      }
    }
  });

};

Events.deleteEvent = function(_id){
  var postData = {event_id : _id};
  sdk.sendRequest('events/delete.json', 'DELETE', postData, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'createEvent') {
      	  Ti.API.log(data.response);
        }
      }
    }
  });
}

<commit_msg>changed wherestring format<commit_after>Ti.include('cocoafish.js');
var Events = {};
/*
 *  <property name="acs-oauth-secret-development" type="string">GxvXXCNnjESPojJkCXvGBGdjOJD5kc8k</property>
 *  <property name="acs-oauth-key-development" type="string">1iHEqePuYFs3SFXcaVwNIB4nAx3G99Ld</property>
 *  <property name="acs-api-key-development" type="string">1PlafvOb0KsfJhWw68tWkGiVt3IkhjxR</property>
 */
var sdk = new Cocoafish('1iHEqePuYFs3SFXcaVwNIB4nAx3G99Ld','GxvXXCNnjESPojJkCXvGBGdjOJD5kc8k');
Events.create = function(_data){
  var custom_field = {club:_data.club};
  _data.custom_fields = JSON.stringify(custom_field);
  sdk.sendRequest('events/create.json', 'POST', _data, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'createEvent') {
      	  Ti.API.log(data.response);
        }
      }
    }
  });

};

Events.queryClub = function(_club,_callback){
  var whereString = JSON.stringify(Util.createSet([_club]));
  var query = {
    where: whereString
  };
  sdk.sendRequest('events/query.json', 'GET', query, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'queryEvents') {
          var events = data.response.events;
          Ti.API.log(events);
          _callback(events);
        }
      }
    }
  });

};

Events.deleteEvent = function(_id){
  var postData = {event_id : _id};
  sdk.sendRequest('events/delete.json', 'DELETE', postData, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'createEvent') {
      	  Ti.API.log(data.response);
        }
      }
    }
  });
}

<|endoftext|>


<commit_before>'use strict';

var autoPlug = require('auto-plug'),
    glob = require('glob'),
    path = require('path');

function Plug(gulp) {
    this.gulp = gulp;
    this.parentDir = path.dirname(module.parent.filename);
    this.dir = path.join(this.parentDir, '.gulpplug');
    this.tasksDir = path.join(this.dir, 'tasks');
    this.taskGlob = '**/*.js';
    this.help = true;
    this.autoPlug = true;
    this.tasks = {};
    this.plugins = {};
}

Plug.prototype.addTasks = function() {
    glob.sync(this.taskGlob, {
        cwd: this.tasksDir
    }).forEach(function(filepath) {
        this.addTask({
            file: filepath,
            name: this.getTasknameFromFilepath(filepath)
        });
    }.bind(this));
    return this;
};

Plug.prototype.addTask = function(task) {
    if (task.name === '' || this.tasks.hasOwnProperty(task.name)) {
        return this;
    }
    if (!task.hasOwnProperty('fn')) {
        task = this.requireTask(task);
    }
    if (typeof task.fn === 'function') {
        task.fn(task.name, this.gulp, this, this.plugins);
        this.tasks[task.name] = task;
    }
    return this;
};

Plug.prototype.requireTask = function(task) {
    var taskModule = require(path.join(this.tasksDir, task.file));
    if (Array.isArray(taskModule) && taskModule.length === 2) {
        task.description = taskModule[0];
        task.fn = taskModule[1];
    } else {
        task.fn = taskModule;
    }
    return task;
};

Plug.prototype.getTasks = function() {
    return Object.keys(this.tasks).reduce(function(tasks, taskName) {
        tasks.push(this.tasks[taskName]);
        return tasks;
    }.bind(this), []);
};

Plug.prototype.addHelpTask = function() {
    this.addTask({
        name: 'help',
        fn: helpTask,
        description: 'display help message'
    });
    if (!this.gulp.hasTask('default')) {
        this.gulp.task('default', ['help']);
    }
    return this;
};

function helpTask(taskName, gulp, plug) {
    var gutil = require('gulp-util'),
        chalk = gutil.colors;
    gulp.task(taskName, function(done) {
        gutil.log(chalk.yellow('=================================================='));
        gutil.log(chalk.yellow('Available Tasks:'));
        plug.getTasks().forEach(function(task) {
            gutil.log(
                chalk.cyan(task.name) + chalk.gray(' ➜ ') +
                (task.description ? chalk.white(task.description) : chalk.gray('(no description)'))
            );
        });
        gutil.log(chalk.yellow('=================================================='));
        done();
    });
}

Plug.prototype.getTasknameFromFilepath = function(filepath) {
    return filepath//.toLowerCase()
        .replace(/([^a-z0-9_\.\/-]+)|(\.[^\.]+$)/gi, '')
        .replace(new RegExp(path.sep, 'g'), ':');
};

Plug.prototype.loadPlugins = function(autoPlugOptions) {
    autoPlugOptions = autoPlugOptions || {};
    autoPlugOptions.prefix = 'gulp';
    autoPlugOptions.config = require(path.join(this.parentDir, 'package.json'));
    this.plugins = autoPlug(autoPlugOptions);
    return this;
};

module.exports = new Plug();
<commit_msg>remove commented code<commit_after>'use strict';

var autoPlug = require('auto-plug'),
    glob = require('glob'),
    path = require('path');

function Plug(gulp) {
    this.gulp = gulp;
    this.parentDir = path.dirname(module.parent.filename);
    this.dir = path.join(this.parentDir, '.gulpplug');
    this.tasksDir = path.join(this.dir, 'tasks');
    this.taskGlob = '**/*.js';
    this.help = true;
    this.autoPlug = true;
    this.tasks = {};
    this.plugins = {};
}

Plug.prototype.addTasks = function() {
    glob.sync(this.taskGlob, {
        cwd: this.tasksDir
    }).forEach(function(filepath) {
        this.addTask({
            file: filepath,
            name: this.getTasknameFromFilepath(filepath)
        });
    }.bind(this));
    return this;
};

Plug.prototype.addTask = function(task) {
    if (task.name === '' || this.tasks.hasOwnProperty(task.name)) {
        return this;
    }
    if (!task.hasOwnProperty('fn')) {
        task = this.requireTask(task);
    }
    if (typeof task.fn === 'function') {
        task.fn(task.name, this.gulp, this, this.plugins);
        this.tasks[task.name] = task;
    }
    return this;
};

Plug.prototype.requireTask = function(task) {
    var taskModule = require(path.join(this.tasksDir, task.file));
    if (Array.isArray(taskModule) && taskModule.length === 2) {
        task.description = taskModule[0];
        task.fn = taskModule[1];
    } else {
        task.fn = taskModule;
    }
    return task;
};

Plug.prototype.getTasks = function() {
    return Object.keys(this.tasks).reduce(function(tasks, taskName) {
        tasks.push(this.tasks[taskName]);
        return tasks;
    }.bind(this), []);
};

Plug.prototype.addHelpTask = function() {
    this.addTask({
        name: 'help',
        fn: helpTask,
        description: 'display help message'
    });
    if (!this.gulp.hasTask('default')) {
        this.gulp.task('default', ['help']);
    }
    return this;
};

function helpTask(taskName, gulp, plug) {
    var gutil = require('gulp-util'),
        chalk = gutil.colors;
    gulp.task(taskName, function(done) {
        gutil.log(chalk.yellow('=================================================='));
        gutil.log(chalk.yellow('Available Tasks:'));
        plug.getTasks().forEach(function(task) {
            gutil.log(
                chalk.cyan(task.name) + chalk.gray(' ➜ ') +
                (task.description ? chalk.white(task.description) : chalk.gray('(no description)'))
            );
        });
        gutil.log(chalk.yellow('=================================================='));
        done();
    });
}

Plug.prototype.getTasknameFromFilepath = function(filepath) {
    return filepath
        .replace(/([^a-z0-9_\.\/-]+)|(\.[^\.]+$)/gi, '')
        .replace(new RegExp(path.sep, 'g'), ':');
};

Plug.prototype.loadPlugins = function(autoPlugOptions) {
    autoPlugOptions = autoPlugOptions || {};
    autoPlugOptions.prefix = 'gulp';
    autoPlugOptions.config = require(path.join(this.parentDir, 'package.json'));
    this.plugins = autoPlug(autoPlugOptions);
    return this;
};

module.exports = new Plug();
<|endoftext|>


<commit_before>const traverse = require('traverse')
const functionOrigin = require('function-origin')

function scoutFunction(fn) {
  const origin = functionOrigin(fn)
  origin.name = fn.name
  origin.line = origin.line + 1
  return origin
}

/**
 * Scouts all functions in the provided object by traversing it.
 *
 * It returns an array of all functions found as `functions` and
 * the cloned object with all functions replaced with their information
 * as `scouted`
 *
 * A `functions` value looks like this:
 *
 * ```
 *  { path: [ '_events', 'end', '1' ],
 *    key: '1',
 *    level: 3,
 *    info:
 *    FunctionOrigin {
 *      file: '/Volumes/d/dev/js/async-hooks/function-scout/examples/readStream.js',
 *      line: 10,
 *      column: 14,
 *      inferredName: '',
 *      name: 'onend' } }
 * ```
 *
 * The `level, path` and `key` provide information about where in the object each
 * function was found.
 *
 * The `scouted` functions look the same except they don't have any `level, path, key`
 * information since they are still attached to the object.
 * The `scouted` object only is returned if `mutate=true` and has the resolved functions
 * attached to the paths of the object at which they were originally found.
 * By default `mutate=false` and thus only `functions` are returned.
 *
 * @name functionScout
 * @function
 * @param {Object} object the object which functions to scout
 *
 * @param {Object} $0 configure how functions are scouted
 *
 * @param {boolean} [$0.mutate=false] if `true` the `object` is cloned and then
 * the are functions replaced with the scouted versions on the returned
 * `scouted` object.
 *
 * @param {boolean} [$0.referenceFunction=false] if `true` a reference to the function is
 * included with each of the function infos. Make sure to not hold on to it as it would
 * prevent the function and anything it closes over to be garbage collected
 *
 * @return {Object} with properties `scouted` (if `mutate=true`) and
 * `functions` explained above
 */
module.exports = function functionScout(object, { mutate = false, referenceFunction = false } = {}) {
  const functions = []

  function processNode(n) {
    const node = this.node
    if (typeof node !== 'function') return
    const info = scoutFunction(node)
    functions.push({ path: this.path, key: this.key, level: this.level, info: info })
    if (referenceFunction) info.function = node
    if (mutate) this.update(info)
  }

  // we don't mutate by default
  if (!mutate) {
    traverse(object).forEach(processNode)
    return { functions }
  }

  // mutate
  const scouted = traverse(object).map(processNode)
  return { scouted, functions }
}
<commit_msg>core: improving function reference code<commit_after>const traverse = require('traverse')
const functionOrigin = require('function-origin')

function scoutFunction(fn, referenceFunction) {
  const origin = functionOrigin(fn)
  origin.name = fn.name
  origin.line = origin.line + 1
  if (referenceFunction) origin.function = fn
  return origin
}

/**
 * Scouts all functions in the provided object by traversing it.
 *
 * It returns an array of all functions found as `functions` and
 * the cloned object with all functions replaced with their information
 * as `scouted`
 *
 * A `functions` value looks like this:
 *
 * ```
 *  { path: [ '_events', 'end', '1' ],
 *    key: '1',
 *    level: 3,
 *    info:
 *    FunctionOrigin {
 *      file: '/Volumes/d/dev/js/async-hooks/function-scout/examples/readStream.js',
 *      line: 10,
 *      column: 14,
 *      inferredName: '',
 *      name: 'onend' } }
 * ```
 *
 * The `level, path` and `key` provide information about where in the object each
 * function was found.
 *
 * The `scouted` functions look the same except they don't have any `level, path, key`
 * information since they are still attached to the object.
 * The `scouted` object only is returned if `mutate=true` and has the resolved functions
 * attached to the paths of the object at which they were originally found.
 * By default `mutate=false` and thus only `functions` are returned.
 *
 * @name functionScout
 * @function
 * @param {Object} object the object which functions to scout
 *
 * @param {Object} $0 configure how functions are scouted
 *
 * @param {boolean} [$0.mutate=false] if `true` the `object` is cloned and then
 * the are functions replaced with the scouted versions on the returned
 * `scouted` object.
 *
 * @param {boolean} [$0.referenceFunction=false] if `true` a reference to the function is
 * included with each of the function infos. Make sure to not hold on to it as it would
 * prevent the function and anything it closes over to be garbage collected
 *
 * @return {Object} with properties `scouted` (if `mutate=true`) and
 * `functions` explained above
 */
module.exports = function functionScout(object, { mutate = false, referenceFunction = false } = {}) {
  const functions = []

  function processNode(n) {
    const node = this.node
    if (typeof node !== 'function') return
    const info = scoutFunction(node, referenceFunction)
    functions.push({ path: this.path, key: this.key, level: this.level, info: info })
    if (mutate) this.update(info)
  }

  // we don't mutate by default
  if (!mutate) {
    traverse(object).forEach(processNode)
    return { functions }
  }

  // mutate
  const scouted = traverse(object).map(processNode)
  return { scouted, functions }
}
<|endoftext|>