<commit_before>import {
  GraphQLBoolean,
  GraphQLInt,
  GraphQLInterfaceType,
  GraphQLNonNull,
  GraphQLObjectType,
  GraphQLString,
} from 'graphql';
import { GraphQLDateTime } from 'graphql-iso-date';

import orderStatus from '../../../constants/order_status';
import models from '../../../models';
import * as TransactionLib from '../../common/transactions';
import { TransactionType } from '../enum/TransactionType';
import { getIdEncodeResolver, idEncode, IDENTIFIER_TYPES } from '../identifiers';
import { Amount } from '../object/Amount';
import { Expense } from '../object/Expense';
import { Order } from '../object/Order';
import { PaymentMethod } from '../object/PaymentMethod';

import { Account } from './Account';

const TransactionPermissions = new GraphQLObjectType({
  name: 'TransactionPermissions',
  description: 'Fields for the user permissions on an transaction',
  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLString),
      resolve: getIdEncodeResolver(IDENTIFIER_TYPES.TRANSACTION),
    },
    canRefund: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: 'Whether the current user can edit the transaction',
      resolve: TransactionLib.canRefund,
    },
    canDownloadInvoice: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: "Whether the current user can download this transaction's invoice",
      resolve: TransactionLib.canDownloadInvoice,
    },
    canReject: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: 'Whether the current user can reject the transaction',
      resolve: TransactionLib.canReject,
    },
  }),
});

export const Transaction = new GraphQLInterfaceType({
  name: 'Transaction',
  description: 'Transaction interface shared by all kind of transactions (Debit, Credit)',
  fields: () => {
    return {
      id: {
        type: new GraphQLNonNull(GraphQLString),
      },
      legacyId: {
        type: new GraphQLNonNull(GraphQLInt),
      },
      uuid: {
        type: GraphQLString,
      },
      type: {
        type: TransactionType,
      },
      description: {
        type: GraphQLString,
      },
      amount: {
        type: new GraphQLNonNull(Amount),
      },
      amountInHostCurrency: {
        type: new GraphQLNonNull(Amount),
      },
      netAmount: {
        type: new GraphQLNonNull(Amount),
      },
      taxAmount: {
        type: new GraphQLNonNull(Amount),
      },
      platformFee: {
        type: new GraphQLNonNull(Amount),
      },
      hostFee: {
        type: Amount,
      },
      paymentProcessorFee: {
        type: Amount,
      },
      host: {
        type: Account,
      },
      fromAccount: {
        type: Account,
      },
      toAccount: {
        type: Account,
      },
      giftCardEmitterAccount: {
        type: Account,
      },
      createdAt: {
        type: GraphQLDateTime,
      },
      updatedAt: {
        type: GraphQLDateTime,
      },
      expense: {
        type: Expense,
      },
      order: {
        type: Order,
      },
      isRefunded: {
        type: GraphQLBoolean,
      },
      isRefund: {
        type: GraphQLBoolean,
      },
      paymentMethod: {
        type: PaymentMethod,
      },
      permissions: {
        type: TransactionPermissions,
      },
      isOrderRejected: {
        type: new GraphQLNonNull(GraphQLBoolean),
      },
      refundTransaction: {
        type: Transaction,
      },
    };
  },
});

export const TransactionFields = () => {
  return {
    id: {
      type: new GraphQLNonNull(GraphQLString),
      resolve(transaction) {
        return idEncode(transaction.id, 'transaction');
      },
    },
    legacyId: {
      type: new GraphQLNonNull(GraphQLInt),
      resolve(transaction) {
        return transaction.id;
      },
    },
    uuid: {
      type: GraphQLString,
    },
    type: {
      type: TransactionType,
      resolve(transaction) {
        return transaction.type;
      },
    },
    description: {
      type: GraphQLString,
      resolve(transaction) {
        return transaction.description;
      },
    },
    amount: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return { value: transaction.amount, currency: transaction.currency };
      },
    },
    amountInHostCurrency: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return { value: transaction.amountInHostCurrency, currency: transaction.hostCurrency };
      },
    },
    netAmount: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return {
          value: transaction.netAmountInCollectiveCurrency,
          currency: transaction.currency,
        };
      },
    },
    taxAmount: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return {
          value: Math.abs(transaction.taxAmount),
          currency: transaction.currency,
        };
      },
    },
    platformFee: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return {
          value: transaction.platformFeeInHostCurrency || 0,
          currency: transaction.hostCurrency,
        };
      },
    },
    hostFee: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return {
          value: transaction.hostFeeInHostCurrency || 0,
          currency: transaction.hostCurrency,
        };
      },
    },
    paymentProcessorFee: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return {
          value: transaction.paymentProcessorFeeInHostCurrency || 0,
          currency: transaction.hostCurrency,
        };
      },
    },
    host: {
      type: Account,
      resolve(transaction) {
        return transaction.getHostCollective();
      },
    },
    createdAt: {
      type: GraphQLDateTime,
      resolve(transaction) {
        return transaction.createdAt;
      },
    },
    updatedAt: {
      type: GraphQLDateTime,
      resolve(transaction) {
        // Transactions are immutable right?
        return transaction.createdAt;
      },
    },
    expense: {
      type: Expense,
      resolve(transaction, _, req) {
        if (transaction.ExpenseId) {
          return req.loaders.Expense.byId.load(transaction.ExpenseId);
        } else {
          return null;
        }
      },
    },
    order: {
      type: Order,
      resolve(transaction, _, req) {
        if (transaction.OrderId) {
          return req.loaders.Order.byId.load(transaction.OrderId);
        } else {
          return null;
        }
      },
    },
    isRefunded: {
      type: GraphQLBoolean,
      resolve(transaction) {
        return transaction.RefundTransactionId !== null;
      },
    },
    isRefund: {
      type: GraphQLBoolean,
    },
    paymentMethod: {
      type: PaymentMethod,
      resolve(transaction) {
        return models.PaymentMethod.findByPk(transaction.PaymentMethodId);
      },
    },
    permissions: {
      type: new GraphQLNonNull(TransactionPermissions),
      description: 'The permissions given to current logged in user for this transaction',
      async resolve(transaction) {
        return transaction; // Individual fields are set by TransactionPermissions's resolvers
      },
    },
    giftCardEmitterAccount: {
      type: Account,
      description: 'Account that emitted the gift card used for this transaction (if any)',
      async resolve(transaction, _, req) {
        return transaction.UsingGiftCardFromCollectiveId
          ? await req.loaders.Collective.byId.load(transaction.UsingGiftCardFromCollectiveId)
          : null;
      },
    },
    isOrderRejected: {
      type: new GraphQLNonNull(GraphQLBoolean),
      async resolve(transaction, _, req) {
        if (transaction.OrderId) {
          const order = await req.loaders.Order.byId.load(transaction.OrderId);
          return order.status === orderStatus.REJECTED;
        } else {
          return false;
        }
      },
    },
    refundTransaction: {
      type: Transaction,
      resolve(transaction) {
        return transaction.getRefundTransaction();
      },
    },
  };
};
<commit_msg>feat: add transaction.kind to Transaction interface<commit_after>import {
  GraphQLBoolean,
  GraphQLInt,
  GraphQLInterfaceType,
  GraphQLNonNull,
  GraphQLObjectType,
  GraphQLString,
} from 'graphql';
import { GraphQLDateTime } from 'graphql-iso-date';

import orderStatus from '../../../constants/order_status';
import models from '../../../models';
import * as TransactionLib from '../../common/transactions';
import { TransactionKind } from '../enum/TransactionKind';
import { TransactionType } from '../enum/TransactionType';
import { getIdEncodeResolver, idEncode, IDENTIFIER_TYPES } from '../identifiers';
import { Amount } from '../object/Amount';
import { Expense } from '../object/Expense';
import { Order } from '../object/Order';
import { PaymentMethod } from '../object/PaymentMethod';

import { Account } from './Account';

const TransactionPermissions = new GraphQLObjectType({
  name: 'TransactionPermissions',
  description: 'Fields for the user permissions on an transaction',
  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLString),
      resolve: getIdEncodeResolver(IDENTIFIER_TYPES.TRANSACTION),
    },
    canRefund: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: 'Whether the current user can edit the transaction',
      resolve: TransactionLib.canRefund,
    },
    canDownloadInvoice: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: "Whether the current user can download this transaction's invoice",
      resolve: TransactionLib.canDownloadInvoice,
    },
    canReject: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: 'Whether the current user can reject the transaction',
      resolve: TransactionLib.canReject,
    },
  }),
});

export const Transaction = new GraphQLInterfaceType({
  name: 'Transaction',
  description: 'Transaction interface shared by all kind of transactions (Debit, Credit)',
  fields: () => {
    return {
      id: {
        type: new GraphQLNonNull(GraphQLString),
      },
      legacyId: {
        type: new GraphQLNonNull(GraphQLInt),
      },
      uuid: {
        type: GraphQLString,
      },
      type: {
        type: TransactionType,
      },
      kind: {
        type: TransactionKind,
      },
      description: {
        type: GraphQLString,
      },
      amount: {
        type: new GraphQLNonNull(Amount),
      },
      amountInHostCurrency: {
        type: new GraphQLNonNull(Amount),
      },
      netAmount: {
        type: new GraphQLNonNull(Amount),
      },
      taxAmount: {
        type: new GraphQLNonNull(Amount),
      },
      platformFee: {
        type: new GraphQLNonNull(Amount),
      },
      hostFee: {
        type: Amount,
      },
      paymentProcessorFee: {
        type: Amount,
      },
      host: {
        type: Account,
      },
      fromAccount: {
        type: Account,
      },
      toAccount: {
        type: Account,
      },
      giftCardEmitterAccount: {
        type: Account,
      },
      createdAt: {
        type: GraphQLDateTime,
      },
      updatedAt: {
        type: GraphQLDateTime,
      },
      expense: {
        type: Expense,
      },
      order: {
        type: Order,
      },
      isRefunded: {
        type: GraphQLBoolean,
      },
      isRefund: {
        type: GraphQLBoolean,
      },
      paymentMethod: {
        type: PaymentMethod,
      },
      permissions: {
        type: TransactionPermissions,
      },
      isOrderRejected: {
        type: new GraphQLNonNull(GraphQLBoolean),
      },
      refundTransaction: {
        type: Transaction,
      },
    };
  },
});

export const TransactionFields = () => {
  return {
    id: {
      type: new GraphQLNonNull(GraphQLString),
      resolve(transaction) {
        return idEncode(transaction.id, 'transaction');
      },
    },
    legacyId: {
      type: new GraphQLNonNull(GraphQLInt),
      resolve(transaction) {
        return transaction.id;
      },
    },
    uuid: {
      type: GraphQLString,
    },
    type: {
      type: TransactionType,
      resolve(transaction) {
        return transaction.type;
      },
    },
    kind: {
      type: TransactionKind,
      resolve(transaction) {
        return transaction.kind;
      },
    },
    description: {
      type: GraphQLString,
      resolve(transaction) {
        return transaction.description;
      },
    },
    amount: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return { value: transaction.amount, currency: transaction.currency };
      },
    },
    amountInHostCurrency: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return { value: transaction.amountInHostCurrency, currency: transaction.hostCurrency };
      },
    },
    netAmount: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return {
          value: transaction.netAmountInCollectiveCurrency,
          currency: transaction.currency,
        };
      },
    },
    taxAmount: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return {
          value: Math.abs(transaction.taxAmount),
          currency: transaction.currency,
        };
      },
    },
    platformFee: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return {
          value: transaction.platformFeeInHostCurrency || 0,
          currency: transaction.hostCurrency,
        };
      },
    },
    hostFee: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return {
          value: transaction.hostFeeInHostCurrency || 0,
          currency: transaction.hostCurrency,
        };
      },
    },
    paymentProcessorFee: {
      type: new GraphQLNonNull(Amount),
      resolve(transaction) {
        return {
          value: transaction.paymentProcessorFeeInHostCurrency || 0,
          currency: transaction.hostCurrency,
        };
      },
    },
    host: {
      type: Account,
      resolve(transaction) {
        return transaction.getHostCollective();
      },
    },
    createdAt: {
      type: GraphQLDateTime,
      resolve(transaction) {
        return transaction.createdAt;
      },
    },
    updatedAt: {
      type: GraphQLDateTime,
      resolve(transaction) {
        // Transactions are immutable right?
        return transaction.createdAt;
      },
    },
    expense: {
      type: Expense,
      resolve(transaction, _, req) {
        if (transaction.ExpenseId) {
          return req.loaders.Expense.byId.load(transaction.ExpenseId);
        } else {
          return null;
        }
      },
    },
    order: {
      type: Order,
      resolve(transaction, _, req) {
        if (transaction.OrderId) {
          return req.loaders.Order.byId.load(transaction.OrderId);
        } else {
          return null;
        }
      },
    },
    isRefunded: {
      type: GraphQLBoolean,
      resolve(transaction) {
        return transaction.RefundTransactionId !== null;
      },
    },
    isRefund: {
      type: GraphQLBoolean,
    },
    paymentMethod: {
      type: PaymentMethod,
      resolve(transaction) {
        return models.PaymentMethod.findByPk(transaction.PaymentMethodId);
      },
    },
    permissions: {
      type: new GraphQLNonNull(TransactionPermissions),
      description: 'The permissions given to current logged in user for this transaction',
      async resolve(transaction) {
        return transaction; // Individual fields are set by TransactionPermissions's resolvers
      },
    },
    giftCardEmitterAccount: {
      type: Account,
      description: 'Account that emitted the gift card used for this transaction (if any)',
      async resolve(transaction, _, req) {
        return transaction.UsingGiftCardFromCollectiveId
          ? await req.loaders.Collective.byId.load(transaction.UsingGiftCardFromCollectiveId)
          : null;
      },
    },
    isOrderRejected: {
      type: new GraphQLNonNull(GraphQLBoolean),
      async resolve(transaction, _, req) {
        if (transaction.OrderId) {
          const order = await req.loaders.Order.byId.load(transaction.OrderId);
          return order.status === orderStatus.REJECTED;
        } else {
          return false;
        }
      },
    },
    refundTransaction: {
      type: Transaction,
      resolve(transaction) {
        return transaction.getRefundTransaction();
      },
    },
  };
};
<|endoftext|>


<commit_before>const express = require('express')
const queryHelper = require('../../utilities/query')
const router = express.Router()

router.get('/number-of-student-by-year', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select convert(substr(student_id, 1, 2), unsigned integer)-54 as student_year,
          count(*) as student_count from students
          where convert(substr(student_id, 1, 2), unsigned integer)-54<=4
	        group by substr(student_id, 1, 2)`,
    req: req,
    res: res
  })
})

router.get('/average-gpax-by-year', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select convert(substr(student_id, 1, 2), unsigned integer)-54 as academic_year,
	        avg(gpax) as avg_gpax from students
          where convert(substr(student_id, 1, 2), unsigned integer)-54 <= 4
          group by SUBSTRING(student_id, 1, 2);`,
    req: req,
    res: res
  })
})

router.get('/average-gpax-all', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select avg(gpax) as avg_gpax from students;`,
    req: req,
    res: res
  })
})

router.get('/leave-student', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select count(*) as leave_count from leaves
	        left join students on leaves.sid = students.sid
          where semester=2 and year=2016`,
    req: req,
    res: res
  })
})

router.get('/overtime-student', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select substr(student_id, 1, 2) as academic_year,
	        count(*) as student_count from students
          where convert(substr(student_id, 1, 2), unsigned integer)<56 and status!='G';`,
    req: req,
    res: res
  })
})

router.get('/student-activity-by-name', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select activity_name, count(*) as student_count from students_activities
	        left join activities on activities.activity_id = students_activities.activity_id
          group by activity_name`,
    req: req,
    res: res
  })
})

router.get('/student-activity-by-year', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select substr(student_id, 1, 2) as academic_year, count(*) as student_count
          from students_activities
	        left join students on students.sid = students_activities.sid
          group by substr(student_id, 1, 2)`,
    req: req,
    res: res
  })
})

router.get('/number-of-student-history', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select substr(student_id, 1, 2) as academic_year,
	        count(*) as student_count from students
          group by substr(student_id, 1, 2)`,
    req: req,
    res: res
  })
})

module.exports = router
<commit_msg>Add student comprtition to dash board<commit_after>const express = require('express')
const queryHelper = require('../../utilities/query')
const router = express.Router()

router.get('/number-of-student-by-year', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select convert(substr(student_id, 1, 2), unsigned integer)-54 as student_year,
          count(*) as student_count from students
          where convert(substr(student_id, 1, 2), unsigned integer)-54<=4
	        group by substr(student_id, 1, 2)`,
    req: req,
    res: res
  })
})

router.get('/average-gpax-by-year', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select convert(substr(student_id, 1, 2), unsigned integer)-54 as academic_year,
	        avg(gpax) as avg_gpax from students
          where convert(substr(student_id, 1, 2), unsigned integer)-54 <= 4
          group by SUBSTRING(student_id, 1, 2);`,
    req: req,
    res: res
  })
})

router.get('/average-gpax-all', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select avg(gpax) as avg_gpax from students;`,
    req: req,
    res: res
  })
})

router.get('/leave-student', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select count(*) as leave_count from leaves
	        left join students on leaves.sid = students.sid
          where semester=2 and year=2016`,
    req: req,
    res: res
  })
})

router.get('/overtime-student', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select substr(student_id, 1, 2) as academic_year,
	        count(*) as student_count from students
          where convert(substr(student_id, 1, 2), unsigned integer)<56 and status!='G';`,
    req: req,
    res: res
  })
})

router.get('/student-activity-by-name', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select activity_name, count(*) as student_count from students_activities
	        left join activities on activities.activity_id = students_activities.activity_id
          group by activity_name`,
    req: req,
    res: res
  })
})

router.get('/student-activity-by-year', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select substr(student_id, 1, 2) as academic_year, count(*) as student_count
          from students_activities
	        left join students on students.sid = students_activities.sid
          group by substr(student_id, 1, 2)`,
    req: req,
    res: res
  })
})

router.get('/number-of-student-history', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `select substr(student_id, 1, 2) as academic_year,
	        count(*) as student_count from students
          group by substr(student_id, 1, 2)`,
    req: req,
    res: res
  })
})

router.get('/student-competition-by-year', (req, res) => {
  queryHelper.queryAndResponse({
    sql: `SELECT count(*) as student_count,
	        convert(substr(student_id, 1, 2), unsigned integer)-54 as student_year FROM (
	        SELECT competition_name, T1.team_id, sid FROM competitions as T1
		      LEFT JOIN teams_students as T2 ON T1.team_id = T2.team_id) as T12
			    LEFT JOIN students as T3 ON T12.sid = T3.sid
	        where convert(substr(student_id, 1, 2), unsigned integer)-54<=4
          group by convert(substr(student_id, 1, 2), unsigned integer)-54`,
    req: req,
    res: res
  })
})

module.exports = router
<|endoftext|>


<commit_before>module.exports = (responseFromWatson) => {

    //  All the intents
    const { intents } = responseFromWatson;
    // //  All the entities
    const { entites } = responseFromWatson;

    //  Take the highest matching intent
    const intent = intents.sort((first, second) => {
        return -(first.confidence - second.confidence);
    })[0];

    //  Return the object of intent and entities
    return { intent, entites };

};
<commit_msg>sorting<commit_after>module.exports = (responseFromWatson) => {

    //  All the intents
    const { intents } = responseFromWatson;
    // //  All the entities
    const { entites } = responseFromWatson;

    //  Take the highest matching intent
    const intent = intents.sort((first, second) => {
        if(first && second) return -(first.confidence - second.confidence);
        return 0;
    })[0];

    //  Return the object of intent and entities
    return { intent, entites };

};
<|endoftext|>


<commit_before>/**
 * Created by guntars on 11/10/2014.
 */
/*globals setTimeout, define*/
// ### Requirejs plugin
// For to simplify `widget/Constructor` Class
// Usage Example
//
//      `<cp-widget src="widget/parser!widget.html"></cp-widget>`
//
//  This savining to create extra unnecessary javascript file.
//
//      define([
//          'templating/parser!widget.html',
//          'widget/Constructor'
//      ], function (template, Constructor) {
//          var Widget = Constructor.extend({
//              template: template
//          });
//          return Widget;
//      });

define(function () {
    function getName(fileName) {
        return (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined;
    }

    return {
        version: "0.1.0",
        load: function (moduleName, req, onLoad, config) {
            moduleName = (getName(moduleName) !== undefined) ? moduleName : moduleName + '.html';
            if (config.isBuild) {
                req([
                    'templating/parser!' + moduleName,
                ], function (template) {
                    template;
                    onLoad();
                });
                return;
            }
            req([
                'templating/parser!' + moduleName,
                'widget/Constructor'
            ], function (template, Constructor) {
                var Widget = Constructor.extend({
                    template: template
                });
                onLoad(Widget);
            });
        },
        write: function (pluginName, moduleName, write) {
            var Name = (getName(moduleName) !== undefined) ? moduleName : moduleName + '.html';
            write('define("' + pluginName + '!' + moduleName + '", ' +
                  '[' +
                  '"templating/parser!' + Name + '",' +
                  '"widget/Constructor"' +
                  '], function(template, Constructor){ return Constructor.extend({' +
                  'template: template' +
                  '});' +
                  '});\n');
        }
    }
});<commit_msg>Fixed dependency problem for wifget/parser<commit_after>/**
 * Created by guntars on 11/10/2014.
 */
/*globals setTimeout, define*/
// ### Requirejs plugin
// For to simplify `widget/Constructor` Class
// Usage Example
//
//      `<cp-widget src="widget/parser!widget.html"></cp-widget>`
//
//  This savining to create extra unnecessary javascript file.
//
//      define([
//          'templating/parser!widget.html',
//          'widget/Constructor'
//      ], function (template, Constructor) {
//          var Widget = Constructor.extend({
//              template: template
//          });
//          return Widget;
//      });

define(function () {
    function getName(fileName) {
        return (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined;
    }

    return {
        version: "0.1.0",
        load: function (moduleName, req, onLoad, config) {
            moduleName = (getName(moduleName) !== undefined) ? moduleName : moduleName + '.html';
            define('widget/parser!' + moduleName,
                [
                    'templating/parser!' + moduleName,
                    'widget/Constructor'
                ], function (template, Constructor) {
                    var Widget = Constructor.extend({
                        template: template
                    });
                    return Widget;
                });
            req(['widget/parser!' + moduleName], function (Widget) {
                onLoad(Widget);
            });
        },
        write: function (pluginName, moduleName, write) {
            var Name = (getName(moduleName) !== undefined) ? moduleName : moduleName + '.html';
            write('define("' + pluginName + '!' + moduleName + '", ' +
                  '[' +
                  '"templating/parser!' + Name + '",' +
                  '"widget/Constructor"' +
                  '], function(template, Constructor){ return Constructor.extend({' +
                  'template: template' +
                  '});' +
                  '});\n');
        }
    }
});<|endoftext|>


<commit_before>(function (global) {

  var TEMPLATE = '

 정진영
Last active 1 hour ago

The maximum upload size is 40MB

 <textarea id="txMessage" placeholder="Write a reply…"></textarea>

';

  var root = global;

  // 1. private variable (using this scope)
  var version = '1.0';
  var _CONFIG = {
    user: 'guest',
    admin: undefined,
    div: undefined,
    app_id: undefined,
    server_url: 'http://chat.stalk.io:8000',
    css_url: 'http://static.stalk.io/widget.css',
    height: '200px',
    width: '300px',
    fontFamily: undefined,
    titleColor: undefined,
    channel: undefined,
    message: {
      title: 'Online : {title}',
      welcome: 'Welcome !'
    },
    _isCreate: false
  };

  var _STATUS = {
    last: '',
    current: '',
    timestamp: {
      admin: 0,
      user: 0
    }
  };

  var div_root = document.createElement('div');
  div_root.id = 'stalk';
  div_root.innerHTML = TEMPLATE;

  var _root = document.getElementsByTagName('body')[0];
  _root.appendChild(div_root);

  var divLauncher = document.getElementById('stalk-launcher');
  var btnLauncher = document.getElementById('stalk-launcher-button');
  var divChatbox = document.getElementById('stalk-chatbox');

  var txMessage = document.getElementById('txMessage');

  var utils = {
    getEscapeHtml: function (html) {
      return String(html)
        .replace(/&/g, '&')
        .replace(/"/g, '"')
        .replace(/'/g, ''')
        .replace(/</g, '<')
        .replace(/>/g, '>');
    },
    getHashCode: function (s) {
      var hash = 0;
      if (s.length === 0) return hash;
      for (var i = 0; i < s.length; i++) {
        var char1 = s.charCodeAt(i);
        hash = ((hash << 5) - hash) + char1;
        hash = hash & hash;
      }
      return hash;
    },
    loadScript: function (url, callback) {
      var script = document.createElement("script");
      script.type = "text/javascript";
      if (script.readyState) {  //IE
        script.onreadystatechange = function () {
          if (script.readyState == "loaded" ||
            script.readyState == "complete") {
            callback();
          }
        };
      } else {  //Others
        script.onload = function () {
          callback();
        };
      }
      script.src = url;
      document.getElementsByTagName("head")[0].appendChild(script);
    },
    loadCss: function (url) {
      var link = document.createElement('link');
      link.type = 'text/css';
      link.rel = 'stylesheet';
      link.href = url;
      document.getElementsByTagName('head')[0].appendChild(link);
      return link;
    },
    loadJson: function (url, callbackStr) {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.charset = "utf-8";
      script.id = this.getHashCode(url);
      if (script.readyState) {  //IE
        script.onreadystatechange = function () {
          if (script.readyState == "loaded" ||
            script.readyState == "complete") {
          }
        };
      } else {
        script.onload = function () {
          // DO Something?
        };
      }
      script.src = url + '&callback=' + callbackStr + '&_noCacheIE=' + (new Date()).getTime();
      document.getElementsByTagName("head")[0].appendChild(script);
    },
    hasClass: function (el, val) {
      var pattern = new RegExp("(^|\\s)" + val + "(\\s|$)");
      return pattern.test(el.className);
    },
    addClass: function (ele, cls) {
      if (!this.hasClass(ele, cls)) ele.className += " " + cls;
    },
    removeClass: function (ele, cls) {
      if (this.hasClass(ele, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
      }
    },
    isIE: function () {
      return (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
    },
    mergeConfig: function (obj1, obj2) {

      for (var p in obj2) {
        try {
          if (obj2[p].constructor == Object) {
            obj1[p] = this.mergeConfig(obj1[p], obj2[p]);
          } else {
            obj1[p] = obj2[p];
          }
        } catch (e) {
          obj1[p] = obj2[p];

        }
      }
      return obj1;
    },
    initXMLhttp: function () {
      var xmlhttp;
      if (window.XMLHttpRequest) {
        //code for IE7,firefox chrome and above
        xmlhttp = new XMLHttpRequest();
      } else {
        //code for Internet Explorer
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      return xmlhttp;
    },
    minAjax: function (config) {

      if (!config.url) {
        if (config.debugLog == true)
          console.log("No Url!");
        return;
      }

      if (!config.type) {
        if (config.debugLog == true)
          console.log("No Default type (GET/POST) given!");
        return;
      }

      if (!config.method) {
        config.method = true;
      }

      if (!config.debugLog) {
        config.debugLog = false;
      }

      var xmlhttp = this.initXMLhttp();

      xmlhttp.onreadystatechange = function () {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

          if (config.success) {
            config.success(xmlhttp.responseText, xmlhttp.readyState);
          }

          if (config.debugLog == true)
            console.log("SuccessResponse");
          if (config.debugLog == true)
            console.log("Response Data:" + xmlhttp.responseText);

        } else {

          if (config.debugLog == true)
            console.log("FailureResponse --> State:" + xmlhttp.readyState + "Status:" + xmlhttp.status);
        }
      };

      var sendString = [],
        sendData = config.data;
      if (typeof sendData === "string") {
        var tmpArr = String.prototype.split.call(sendData, '&');
        for (var i = 0, j = tmpArr.length; i < j; i++) {
          var datum = tmpArr[i].split('=');
          sendString.push(encodeURIComponent(datum[0]) + "=" + encodeURIComponent(datum[1]));
        }
      } else if (typeof sendData === 'object' && !( sendData instanceof String || (FormData && sendData instanceof FormData) )) {
        for (var k in sendData) {
          var datum = sendData[k];
          if (Object.prototype.toString.call(datum) == "[object Array]") {
            for (var i = 0, j = datum.length; i < j; i++) {
              sendString.push(encodeURIComponent(k) + "[]=" + encodeURIComponent(datum[i]));
            }
          } else {
            sendString.push(encodeURIComponent(k) + "=" + encodeURIComponent(datum));
          }
        }
      }
      sendString = sendString.join('&');

      if (config.type == "GET") {
        xmlhttp.open("GET", config.url + "?" + sendString, config.method);
        xmlhttp.send();

        if (config.debugLog == true)
          console.log("GET fired at:" + config.url + "?" + sendString);
      }
      if (config.type == "POST") {
        xmlhttp.open("POST", config.url, config.method);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send(sendString);

        if (config.debugLog == true)
          console.log("POST fired at:" + config.url + " || Data:" + sendString);
      }
    },
    requestAdminInfo: function (_callback) {

      if(!_CONFIG.server_url || !_CONFIG.app_id){
        console.error('error on initiation.'); // @ TODO console logging !
        return false;
      }

      this.minAjax({
        url: _CONFIG.server_url + '/user/list/active',
        type: "POST",
        data: {
          A: _CONFIG.app_id
        },
        //method: "true",
        //debugLog: "true",
        success: _callback
      });
    },
    requestServerInfo: function (_callback) {

      if(!_CONFIG.server_url || !_CONFIG.app_id || !_CONFIG.channel){
        console.error('error on initiation.'); // @ TODO console logging !
        return false;
      }

      this.minAjax({
        url: _CONFIG.server_url + '/node/' + encodeURIComponent(_CONFIG.app_id) + '/' + encodeURIComponent(_CONFIG.channel),
        type: "GET",
        success: _callback
      });
    }

  };

  var layout = {
    open: function () {
      utils.removeClass(divLauncher, 'stalk-launcher-active');
      utils.addClass(divLauncher, 'stalk-launcher-inactive');
      divChatbox.style.display = 'block';
    },
    close: function () {
      utils.removeClass(divLauncher, 'stalk-launcher-inactive');
      utils.addClass(divLauncher, 'stalk-launcher-active');
      divChatbox.style.display = 'none';
    },
    addMessage: function (message, type) {

      var div_message = document.getElementById('stalk-message');

      _STATUS.current = 'admin';
      if (type == _CONFIG.user) {
        _STATUS.current = 'user';
      }

      var msgHtml = '

' +
        message + '

';

      var classStr = 'stalk-conversation-part stalk-conversation-part-grouped';
      if (_STATUS.last != _STATUS.current) {
        if(_STATUS.current == 'admin'){ // add avatar image (on the first admin message)
          msgHtml = '' + msgHtml;
        }
        classStr = classStr + '-first';
      }

      var chatDiv = document.createElement("div");
      chatDiv.className = classStr;
      chatDiv.innerHTML = msgHtml;

      div_message.appendChild(chatDiv);
      div_message.scrollTop = div_message.scrollHeight;

      _STATUS.last = _STATUS.current;

    }
  };

  // element event handlers
  btnLauncher.onclick = function (e) {
    STALK._start();
    layout.open();
  };

  document.getElementById('btnClose').onclick = function (e) {
    layout.close();
  };

  txMessage.onkeydown = function (e) {

    e = root.event || e;
    var keyCode = (e.which) ? e.which : e.keyCode;

    if (keyCode == 13 && !e.shiftKey) {

      if (e.preventDefault) {
        e.preventDefault();
      } else {
        e.returnValue = false;
      }

      var message = txMessage.value.toString().trim();
      message = utils.getEscapeHtml(message.replace(/^\s+|\s+$/g, ''));

      if (message !== "") {

        STALK.sendMessage(message);

        txMessage.value = "";
      }

      return false;
    }
  };

  /************************************************************/

  if (_CONFIG.isReady) return false;

  var STALK;
  if (typeof exports !== 'undefined') {
    STALK = exports;
  } else {
    STALK = root.STALK = {};
  }

  if (root.stalkConfig) {
    _CONFIG = utils.mergeConfig(_CONFIG, root.stalkConfig);
  }
  _CONFIG.app_id = 'STALK:' + _CONFIG.app_id; // append prefix ('STALK')

  if (!_CONFIG.channel) _CONFIG.channel = encodeURIComponent(/*location.hostname + */ location.pathname);

  STALK._start = function () {

    utils.loadCss(_CONFIG.css_url);

    utils.requestAdminInfo(function (data) {
      data = JSON.parse(data);
      if (data.status == 'ok' && data.result.length > 0) {

        _CONFIG.admin = data.result[0].U; // @ TODO U is not user real name (just user id)

        utils.requestServerInfo(STALK._callbackInit);
      }
    });

  };

  STALK._callbackInit = function (data) {

    data = JSON.parse(data);

    if (
      _CONFIG.isReady ||
      data.status != 'ok' || !data.result.server
    ) return false;

    var query =
      'A=' + _CONFIG.app_id + '&' +
      'U=' + _CONFIG.user + '&' +
      'D=' + '_' + '&' +
      'C=' + _CONFIG.channel + '&' +
        //'DT=' + JSON.stringify(_CONFIG.user) + '&' +
      'S=' + data.result.server.name;

    _CONFIG._socket = io.connect(data.result.server.url + '/channel?' + query);

    _CONFIG._socket.on('connect', function () {

      if (!_CONFIG._isCreate) {

        // TODO 나중에 개발해야 함
        //layout.initWin();

        var initMessage = _CONFIG.message.welcome;
        // TODO welcome 메시지 보여줄 것.
      }
      _CONFIG._isCreate = true;
      _CONFIG.isReady = true;

    });

    _CONFIG._socket.on('_event', function (data) {
      if (data.event == 'CONNECTION') {
        //layout.setTitleBar('title', data.count);
      } else if (data.event == 'DISCONNECT') {
        //layout.setTitleBar('title', data.count);
      }
    });

    _CONFIG._socket.on('message', function (data) {

      console.log(data);

      layout.addMessage(data.message, data.user);
    });

  };

  STALK.sendMessage = function (msg) {
    var param = {
      A: _CONFIG.app_id,
      C: _CONFIG.channel,
      NM: 'message',
      DT: {
        user: _CONFIG.user,
        message: msg
      }
    };
    _CONFIG._socket.emit('send', param, function (data) {
    });
  };

  STALK.getVersion = function () {
    return version;
  };

}(this));<commit_msg>add dummy console object for IE<commit_after>(function (global) {

  if (!window.console) console = {
    log: function () {
    },
    error: function () {
    }
  };

  var TEMPLATE = '

 정진영
Last active 1 hour ago

The maximum upload size is 40MB

 <textarea id="txMessage" placeholder="Write a reply…"></textarea>

';

  var root = global;

  // 1. private variable (using this scope)
  var version = '1.0';
  var _CONFIG = {
    user: 'guest',
    admin: undefined,
    div: undefined,
    app_id: undefined,
    server_url: 'http://chat.stalk.io:8000',
    css_url: 'http://static.stalk.io/widget.css',
    height: '200px',
    width: '300px',
    fontFamily: undefined,
    titleColor: undefined,
    channel: undefined,
    message: {
      title: 'Online : {title}',
      welcome: 'Welcome !'
    },
    _isCreate: false
  };

  var _STATUS = {
    last: '',
    current: '',
    timestamp: {
      admin: 0,
      user: 0
    }
  };

  var div_root = document.createElement('div');
  div_root.id = 'stalk';
  div_root.innerHTML = TEMPLATE;

  var _root = document.getElementsByTagName('body')[0];
  _root.appendChild(div_root);

  var divLauncher = document.getElementById('stalk-launcher');
  var btnLauncher = document.getElementById('stalk-launcher-button');
  var divChatbox = document.getElementById('stalk-chatbox');

  var txMessage = document.getElementById('txMessage');

  var utils = {
    getEscapeHtml: function (html) {
      return String(html)
        .replace(/&/g, '&')
        .replace(/"/g, '"')
        .replace(/'/g, ''')
        .replace(/</g, '<')
        .replace(/>/g, '>');
    },
    getHashCode: function (s) {
      var hash = 0;
      if (s.length === 0) return hash;
      for (var i = 0; i < s.length; i++) {
        var char1 = s.charCodeAt(i);
        hash = ((hash << 5) - hash) + char1;
        hash = hash & hash;
      }
      return hash;
    },
    loadScript: function (url, callback) {
      var script = document.createElement("script");
      script.type = "text/javascript";
      if (script.readyState) {  //IE
        script.onreadystatechange = function () {
          if (script.readyState == "loaded" ||
            script.readyState == "complete") {
            callback();
          }
        };
      } else {  //Others
        script.onload = function () {
          callback();
        };
      }
      script.src = url;
      document.getElementsByTagName("head")[0].appendChild(script);
    },
    loadCss: function (url) {
      var link = document.createElement('link');
      link.type = 'text/css';
      link.rel = 'stylesheet';
      link.href = url;
      document.getElementsByTagName('head')[0].appendChild(link);
      return link;
    },
    loadJson: function (url, callbackStr) {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.charset = "utf-8";
      script.id = this.getHashCode(url);
      if (script.readyState) {  //IE
        script.onreadystatechange = function () {
          if (script.readyState == "loaded" ||
            script.readyState == "complete") {
          }
        };
      } else {
        script.onload = function () {
          // DO Something?
        };
      }
      script.src = url + '&callback=' + callbackStr + '&_noCacheIE=' + (new Date()).getTime();
      document.getElementsByTagName("head")[0].appendChild(script);
    },
    hasClass: function (el, val) {
      var pattern = new RegExp("(^|\\s)" + val + "(\\s|$)");
      return pattern.test(el.className);
    },
    addClass: function (ele, cls) {
      if (!this.hasClass(ele, cls)) ele.className += " " + cls;
    },
    removeClass: function (ele, cls) {
      if (this.hasClass(ele, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
      }
    },
    isIE: function () {
      return (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
    },
    mergeConfig: function (obj1, obj2) {

      for (var p in obj2) {
        try {
          if (obj2[p].constructor == Object) {
            obj1[p] = this.mergeConfig(obj1[p], obj2[p]);
          } else {
            obj1[p] = obj2[p];
          }
        } catch (e) {
          obj1[p] = obj2[p];

        }
      }
      return obj1;
    },
    initXMLhttp: function () {
      var xmlhttp;
      if (window.XMLHttpRequest) {
        //code for IE7,firefox chrome and above
        xmlhttp = new XMLHttpRequest();
      } else {
        //code for Internet Explorer
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      return xmlhttp;
    },
    minAjax: function (config) {

      if (!config.url) {
        if (config.debugLog == true)
          console.log("No Url!");
        return;
      }

      if (!config.type) {
        if (config.debugLog == true)
          console.log("No Default type (GET/POST) given!");
        return;
      }

      if (!config.method) {
        config.method = true;
      }

      if (!config.debugLog) {
        config.debugLog = false;
      }

      var xmlhttp = this.initXMLhttp();

      xmlhttp.onreadystatechange = function () {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

          if (config.success) {
            config.success(xmlhttp.responseText, xmlhttp.readyState);
          }

          if (config.debugLog == true)
            console.log("SuccessResponse");
          if (config.debugLog == true)
            console.log("Response Data:" + xmlhttp.responseText);

        } else {

          if (config.debugLog == true)
            console.log("FailureResponse --> State:" + xmlhttp.readyState + "Status:" + xmlhttp.status);
        }
      };

      var sendString = [],
        sendData = config.data;
      if (typeof sendData === "string") {
        var tmpArr = String.prototype.split.call(sendData, '&');
        for (var i = 0, j = tmpArr.length; i < j; i++) {
          var datum = tmpArr[i].split('=');
          sendString.push(encodeURIComponent(datum[0]) + "=" + encodeURIComponent(datum[1]));
        }
      } else if (typeof sendData === 'object' && !( sendData instanceof String || (FormData && sendData instanceof FormData) )) {
        for (var k in sendData) {
          var datum = sendData[k];
          if (Object.prototype.toString.call(datum) == "[object Array]") {
            for (var i = 0, j = datum.length; i < j; i++) {
              sendString.push(encodeURIComponent(k) + "[]=" + encodeURIComponent(datum[i]));
            }
          } else {
            sendString.push(encodeURIComponent(k) + "=" + encodeURIComponent(datum));
          }
        }
      }
      sendString = sendString.join('&');

      if (config.type == "GET") {
        xmlhttp.open("GET", config.url + "?" + sendString, config.method);
        xmlhttp.send();

        if (config.debugLog == true)
          console.log("GET fired at:" + config.url + "?" + sendString);
      }
      if (config.type == "POST") {
        xmlhttp.open("POST", config.url, config.method);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send(sendString);

        if (config.debugLog == true)
          console.log("POST fired at:" + config.url + " || Data:" + sendString);
      }
    },
    requestAdminInfo: function (_callback) {

      if (!_CONFIG.server_url || !_CONFIG.app_id) {
        console.error('error on initiation.'); // @ TODO console logging !
        return false;
      }

      this.minAjax({
        url: _CONFIG.server_url + '/user/list/active',
        type: "POST",
        data: {
          A: _CONFIG.app_id
        },
        //method: "true", debugLog: "true",
        success: _callback
      });
    },
    requestServerInfo: function (_callback) {

      if (!_CONFIG.server_url || !_CONFIG.app_id || !_CONFIG.channel) {
        console.error('error on initiation.'); // @ TODO console logging !
        return false;
      }

      this.minAjax({
        url: _CONFIG.server_url + '/node/' + encodeURIComponent(_CONFIG.app_id) + '/' + encodeURIComponent(_CONFIG.channel),
        type: "GET",
        //method: "true", debugLog: "true",
        success: _callback
      });
    }

  };

  var layout = {
    open: function () {
      utils.removeClass(divLauncher, 'stalk-launcher-active');
      utils.addClass(divLauncher, 'stalk-launcher-inactive');
      divChatbox.style.display = 'block';
    },
    close: function () {
      utils.removeClass(divLauncher, 'stalk-launcher-inactive');
      utils.addClass(divLauncher, 'stalk-launcher-active');
      divChatbox.style.display = 'none';
    },
    addMessage: function (message, type) {

      var div_message = document.getElementById('stalk-message');

      _STATUS.current = 'admin';
      if (type == _CONFIG.user) {
        _STATUS.current = 'user';
      }

      var msgHtml = '

' +
        message + '

';

      var classStr = 'stalk-conversation-part stalk-conversation-part-grouped';
      if (_STATUS.last != _STATUS.current) {
        if (_STATUS.current == 'admin') { // add avatar image (on the first admin message)
          msgHtml = '' + msgHtml;
        }
        classStr = classStr + '-first';
      }

      var chatDiv = document.createElement("div");
      chatDiv.className = classStr;
      chatDiv.innerHTML = msgHtml;

      div_message.appendChild(chatDiv);
      div_message.scrollTop = div_message.scrollHeight;

      _STATUS.last = _STATUS.current;

    }
  };

  // element event handlers
  btnLauncher.onclick = function (e) {
    STALK._start();
    layout.open();
  };

  document.getElementById('btnClose').onclick = function (e) {
    layout.close();
  };

  txMessage.onkeydown = function (e) {

    e = root.event || e;
    var keyCode = (e.which) ? e.which : e.keyCode;

    if (keyCode == 13 && !e.shiftKey) {

      if (e.preventDefault) {
        e.preventDefault();
      } else {
        e.returnValue = false;
      }

      var message = txMessage.value.toString().trim();
      message = utils.getEscapeHtml(message.replace(/^\s+|\s+$/g, ''));

      if (message !== "") {

        STALK.sendMessage(message);

        txMessage.value = "";
      }

      return false;
    }
  };

  /************************************************************/

  if (_CONFIG.isReady) return false;

  var STALK;
  if (typeof exports !== 'undefined') {
    STALK = exports;
  } else {
    STALK = root.STALK = {};
  }

  if (root.stalkConfig) {
    _CONFIG = utils.mergeConfig(_CONFIG, root.stalkConfig);
  }
  _CONFIG.app_id = 'STALK:' + _CONFIG.app_id; // append prefix ('STALK')

  if (!_CONFIG.channel) _CONFIG.channel = encodeURIComponent(/*location.hostname + */ location.pathname);

  STALK._start = function () {

    utils.loadCss(_CONFIG.css_url);

    utils.requestAdminInfo(function (data) {
      data = JSON.parse(data);
      if (data.status == 'ok' && data.result.length > 0) {

        _CONFIG.admin = data.result[0].U; // @ TODO U is not user real name (just user id)

        utils.requestServerInfo(STALK._callbackInit);
      }
    });

  };

  STALK._callbackInit = function (data) {

    data = JSON.parse(data);

    if (
      _CONFIG.isReady ||
      data.status != 'ok' || !data.result.server
    ) return false;

    var query =
      'A=' + _CONFIG.app_id + '&' +
      'U=' + _CONFIG.user + '&' +
      'D=' + '_' + '&' +
      'C=' + _CONFIG.channel + '&' +
        //'DT=' + JSON.stringify(_CONFIG.user) + '&' +
      'S=' + data.result.server.name;

    _CONFIG._socket = io.connect(data.result.server.url + '/channel?' + query);

    _CONFIG._socket.on('connect', function () {

      if (!_CONFIG._isCreate) {

        // TODO 나중에 개발해야 함
        //layout.initWin();

        var initMessage = _CONFIG.message.welcome;
        // TODO welcome 메시지 보여줄 것.
      }
      _CONFIG._isCreate = true;
      _CONFIG.isReady = true;

    });

    _CONFIG._socket.on('_event', function (data) {
      if (data.event == 'CONNECTION') {
        //layout.setTitleBar('title', data.count);
      } else if (data.event == 'DISCONNECT') {
        //layout.setTitleBar('title', data.count);
      }
    });

    _CONFIG._socket.on('message', function (data) {
      layout.addMessage(data.message, data.user);
    });

  };

  STALK.sendMessage = function (msg) {
    var param = {
      A: _CONFIG.app_id,
      C: _CONFIG.channel,
      NM: 'message',
      DT: {
        user: _CONFIG.user,
        message: msg
      }
    };
    _CONFIG._socket.emit('send', param, function (data) {
    });
  };

  STALK.getVersion = function () {
    return version;
  };

}(this));<|endoftext|>


<commit_before>import CheckboxWidget from './checkbox-widget.vue'
import ErrorWidget from './error-widget.vue'
import FileWidget from './file-widget.vue'
import FormWidget from './form-widget.vue'
import InputWidget from './input-widget.vue'
import TextareaWidget from './textarea-widget.vue'
import WrapperWidget from './wrapper-widget.vue'

export {
  CheckboxWidget,
  InputWidget,
  WrapperWidget,
  TextareaWidget,
  ErrorWidget,
  FormWidget,
  FileWidget
}
<commit_msg>fix(v-form): error widget footsteps :D<commit_after>import CheckboxWidget from './checkbox-widget.vue'
import FileWidget from './file-widget.vue'
import FormWidget from './form-widget.vue'
import InputWidget from './input-widget.vue'
import TextareaWidget from './textarea-widget.vue'
import WrapperWidget from './wrapper-widget.vue'

export {
  CheckboxWidget,
  InputWidget,
  WrapperWidget,
  TextareaWidget,
  FormWidget,
  FileWidget
}
<|endoftext|>


<commit_before>'use strict';

var api = require('../core/api'),
    _ = require('../tools/tools'),
    aplazameVersion = require('../../.tmp/aplazame-version'),
    lastScrollTop;

function modal (content, options) {

  // if( !modal.cached ) {
  //   return _.http.noCache( api.baseUrl + 'widgets/modal/modal.html' ).then(function (response) {
  //     modal.cached = _.template.compile( response.data.replace(/\n/g, '').replace(/<head\>/, '<head><base href="' + api.baseUrl + '" />') );
  //     modal(data, options);
  //   });
  // }

  if( modal.iframe ) {
    document.body.removeChild(modal.iframe);
  }

  options = options || {};

  modal.iframe = _.getIFrame({
        top: 0,
        left: 0,
        width: '100%',
        height: '0',
        background: 'transparent',
        'z-index': 2147483647
      });

  modal.iframe.className = 'aplazame-modal';

  modal.iframe.content = content;

  // lastScrollTop = _.scrollTop();
  // console.log('scrollTop', lastScrollTop );
  // _.cssHack('modal').hack(true);

  // var cssBlur = _.cssHack('blur'),
  //     cssModal = _.cssHack('modal');

  // modal.iframe.overflow = document.body.style.overflow;

  document.body.appendChild(modal.iframe);
  modal.iframe.src = api.baseUrl + 'widgets/modal/modal.html?v=' + encodeURI(aplazameVersion);
  // _.writeIframe(modal.iframe, modal.cached(content || {}) );

  // document.body.style.overflow = 'hidden';
}

_.onMessage('modal', function (e, message) {

  console.log('message', 'modal', message);

  switch( message.event ) {
    case 'open':
      modal.referrer = e.source;
      modal.message = message;
      modal(message.data);
      break;
    case 'opened':
      lastScrollTop = _.scrollTop();
      _.cssHack('modal').hack(true);
      e.source.postMessage({
        aplazame: 'modal',
        event: 'content',
        content: modal.iframe.content
      }, '*');
      break;
    case 'resolved':
      modal.referrer.postMessage({
        aplazame: 'modal',
        event: 'resolved',
        name: modal.message.name,
        value: message.value
      }, '*');
      delete modal.referrer;
      break;
    case 'closing':
      document.body.style.overflow = modal.iframe.overflow;
      break;
    case 'close':
      _.cssHack('modal').hack(false);
      setTimeout(function () {
        _.scrollTop(lastScrollTop);
      }, 0);
      if( modal.iframe ) {
        document.body.removeChild(modal.iframe);

        if( modal.referrer ) {
          modal.referrer.postMessage({
            aplazame: 'modal',
            event: 'dismiss',
            name: modal.message.name
          }, '*');
          delete modal.referrer;
        }

        if( modal.message ) {
          delete modal.message;
        }
        delete modal.iframe;
      }
      break;
  }

});

module.exports = modal;
<commit_msg>removing unnecessary logs<commit_after>'use strict';

var api = require('../core/api'),
    _ = require('../tools/tools'),
    aplazameVersion = require('../../.tmp/aplazame-version'),
    lastScrollTop;

function modal (content, options) {

  // if( !modal.cached ) {
  //   return _.http.noCache( api.baseUrl + 'widgets/modal/modal.html' ).then(function (response) {
  //     modal.cached = _.template.compile( response.data.replace(/\n/g, '').replace(/<head\>/, '<head><base href="' + api.baseUrl + '" />') );
  //     modal(data, options);
  //   });
  // }

  if( modal.iframe ) {
    document.body.removeChild(modal.iframe);
  }

  options = options || {};

  modal.iframe = _.getIFrame({
        top: 0,
        left: 0,
        width: '100%',
        height: '0',
        background: 'transparent',
        'z-index': 2147483647
      });

  modal.iframe.className = 'aplazame-modal';

  modal.iframe.content = content;

  // lastScrollTop = _.scrollTop();
  // console.log('scrollTop', lastScrollTop );
  // _.cssHack('modal').hack(true);

  // var cssBlur = _.cssHack('blur'),
  //     cssModal = _.cssHack('modal');

  // modal.iframe.overflow = document.body.style.overflow;

  document.body.appendChild(modal.iframe);
  modal.iframe.src = api.baseUrl + 'widgets/modal/modal.html?v=' + encodeURI(aplazameVersion);
  // _.writeIframe(modal.iframe, modal.cached(content || {}) );

  // document.body.style.overflow = 'hidden';
}

_.onMessage('modal', function (e, message) {

  // console.log('message', 'modal', message);

  switch( message.event ) {
    case 'open':
      modal.referrer = e.source;
      modal.message = message;
      modal(message.data);
      break;
    case 'opened':
      lastScrollTop = _.scrollTop();
      _.cssHack('modal').hack(true);
      e.source.postMessage({
        aplazame: 'modal',
        event: 'content',
        content: modal.iframe.content
      }, '*');
      break;
    case 'resolved':
      modal.referrer.postMessage({
        aplazame: 'modal',
        event: 'resolved',
        name: modal.message.name,
        value: message.value
      }, '*');
      delete modal.referrer;
      break;
    case 'closing':
      document.body.style.overflow = modal.iframe.overflow;
      break;
    case 'close':
      _.cssHack('modal').hack(false);
      setTimeout(function () {
        _.scrollTop(lastScrollTop);
      }, 0);
      if( modal.iframe ) {
        document.body.removeChild(modal.iframe);

        if( modal.referrer ) {
          modal.referrer.postMessage({
            aplazame: 'modal',
            event: 'dismiss',
            name: modal.message.name
          }, '*');
          delete modal.referrer;
        }

        if( modal.message ) {
          delete modal.message;
        }
        delete modal.iframe;
      }
      break;
  }

});

module.exports = modal;
<|endoftext|>


<commit_before>import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';

let component;

function set(keyValuePairs) {
  Ember.run(component, function() {
    component.setProperties(keyValuePairs);
  });
}

moduleForComponent('travis-status', 'Unit | Component | travis status', {
  unit: true,

  beforeEach: function() {
    component = this.subject();
  },
});

test('the property bindings are correct', function(assert) {
  // let className = component.get('className');
  // let status = 'passing';

  // assert.expect(8);

  Ember.run(function() {

    assert.equal(component._state, 'preRender',
      'The component instance should be created');

  });

  // set({ status });

  // assert.equal(component.get('statusClassName'), `${className}-${status}`,
  //   'The status class name should reflect the new status');

  // assert.ok(!component.get('isFailing'),
  //   "isFailing should be false when the returned status is 'passing'");

  // assert.ok(component.get('isPassing'),
  //   "isPassing should be true when the returned status is 'passing'");

  // className = 'travis-widget';
  // status = 'failing';

  // set({
  //   className,
  //   status
  // });

  // assert.equal(component.get('statusClassName'), `${className}-${status}`,
  //   'The status class name should reflect the new class name and status');

  // assert.ok(component.get('isFailing'),
  //   "isFailing should be true when the returned status is 'failing'");

  // assert.ok(!component.get('isPassing'),
  //   "isPassing should be false when the returned status is 'failing'");

  // this.render();

  // assert.equal(component._state, 'inDOM',
  //   'The component should be inserted into the DOM');

});
<commit_msg>travis debug 8<commit_after>import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';

let component;

function set(keyValuePairs) {
  Ember.run(component, function() {
    component.setProperties(keyValuePairs);
  });
}

moduleForComponent('travis-status', 'Unit | Component | travis status', {
  unit: true,

  beforeEach: function() {
    component = this.subject();
  },
});

test('the property bindings are correct', function(assert) {
  const done = assert.async();
  // let className = component.get('className');
  // let status = 'passing';

  // assert.expect(8);

  Ember.run(function() {

    assert.equal(component._state, 'preRender',
      'The component instance should be created');

    done();

  });

  // set({ status });

  // assert.equal(component.get('statusClassName'), `${className}-${status}`,
  //   'The status class name should reflect the new status');

  // assert.ok(!component.get('isFailing'),
  //   "isFailing should be false when the returned status is 'passing'");

  // assert.ok(component.get('isPassing'),
  //   "isPassing should be true when the returned status is 'passing'");

  // className = 'travis-widget';
  // status = 'failing';

  // set({
  //   className,
  //   status
  // });

  // assert.equal(component.get('statusClassName'), `${className}-${status}`,
  //   'The status class name should reflect the new class name and status');

  // assert.ok(component.get('isFailing'),
  //   "isFailing should be true when the returned status is 'failing'");

  // assert.ok(!component.get('isPassing'),
  //   "isPassing should be false when the returned status is 'failing'");

  // this.render();

  // assert.equal(component._state, 'inDOM',
  //   'The component should be inserted into the DOM');

});
<|endoftext|>


<commit_before>/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 2015 SIRAP SAS All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/*global tinymce:true */

tinymce.PluginManager.add('forminputs', function(editor) {

  function insertCheckbox(evt){
    // console.log(evt);

    var body = editor.getBody();
    var selection = editor.selection.getNode();
    var inputElement = editor.dom.create('input', {type:'checkbox'});
    var labelElement = editor.dom.create('label', null, 'ma case à cocher');

    editor.dom.add(labelElement,inputElement);
    editor.dom.add(selection,labelElement);

  }

    });

  editor.addMenuItem('forminputs', {
    separator: 'before',
    text: 'Form',
    context: 'insert',
    menu: [
      // {text: 'Text', onclick: null, onPostRender: null},
      {text: 'Checkbox', onclick: insertCheckbox, onPostRender: null},
      // {text: 'Radio buttons', onclick: null, onPostRender: null}
    ]
  });

});
<commit_msg>prompt for label to insert a checkbox<commit_after>/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 2015 SIRAP SAS All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/*global tinymce:true */

tinymce.PluginManager.add('forminputs', function(editor) {

  function insertCheckbox(evt){
    // console.log(evt);

    var body = editor.getBody();
    var selection = editor.selection.getNode();
    var inputElement = editor.dom.create('input', {type:'checkbox'});
    var labelElement = editor.dom.create('label', null, prompt('Saisir un label pour la case à chocher'));

    editor.dom.add(labelElement,inputElement);
    editor.dom.add(selection,labelElement);

  }

    });

  editor.addMenuItem('forminputs', {
    separator: 'before',
    text: 'Form',
    context: 'insert',
    menu: [
      // {text: 'Text', onclick: null, onPostRender: null},
      {text: 'Checkbox', onclick: insertCheckbox, onPostRender: null},
      // {text: 'Radio buttons', onclick: null, onPostRender: null}
    ]
  });

});
<|endoftext|>


<commit_before>/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 2015 SIRAP SAS All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/*global tinymce:true */

tinymce.PluginManager.add('forminputs', function(editor) {

  function insertCheckbox(evt){
    var body = editor.getBody();
    var selection = editor.selection.getNode();
    var inputElement = editor.dom.create('input', {type:'checkbox'});
    var labelElement = editor.dom.create('label', null, prompt('Saisir un label pour la case à chocher'));

    editor.dom.add(labelElement,inputElement);
    editor.dom.add(selection,labelElement);
  }

  function onCheckboxClick(){
    $(this).attr('checked',!!!$(this).attr('checked'));
    editor.fire('NodeChange');
  }

  function updateCheckboxesClickHandlers(){
    $(':checkbox',editor.getDoc())
    .off('click').on('click',onCheckboxClick);
  }

  editor.on('init change SetContent',updateCheckboxesClickHandlers);

  editor.addMenuItem('forminputs', {
    separator: 'before',
    text: 'Form',
    context: 'insert',
    menu: [
      // {text: 'Text', onclick: null, onPostRender: null},
      {text: 'Checkbox', onclick: insertCheckbox, onPostRender: null},
      // {text: 'Radio buttons', onclick: null, onPostRender: null}
    ]
  });

});
<commit_msg>clean forminputs menu item propeties definition<commit_after>/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 2015 SIRAP SAS All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/*global tinymce:true */

tinymce.PluginManager.add('forminputs', function(editor) {

  function insertCheckbox(evt){
    var body = editor.getBody();
    var selection = editor.selection.getNode();
    var inputElement = editor.dom.create('input', {type:'checkbox'});
    var labelElement = editor.dom.create('label', null, prompt('Saisir un label pour la case à chocher'));

    editor.dom.add(labelElement,inputElement);
    editor.dom.add(selection,labelElement);
  }

  function onCheckboxClick(){
    $(this).attr('checked',!!!$(this).attr('checked'));
    editor.fire('NodeChange');
  }

  function updateCheckboxesClickHandlers(){
    $(':checkbox',editor.getDoc())
    .off('click').on('click',onCheckboxClick);
  }

  editor.on('init change SetContent',updateCheckboxesClickHandlers);

  editor.addMenuItem('forminputs', {
    separator: 'before',
    text: 'Form',
    context: 'insert',
    menu: [{
      text: 'Checkbox',
      onclick: insertCheckbox,
      onPostRender: null
    }]
  });

});
<|endoftext|>


<commit_before>var fs = require('fs');

var DemoPlugin = function(output, options) {
  this.output = output;
  this.options = options;
};

module.exports = DemoPlugin;

DemoPlugin.prototype.apply = function(compiler) {

  compiler.plugin('compilation', function(compilation) {

    compilation.plugin("optimize-modules", function(modules) {
      //iterate over modules
        //check if filepath ends in css
          //split at ! and fs
          //concat file path to css array
          //check if module is first css
            //if not, splice out module
        //check if filepath does not contain node_modules
          //concat path to content array
      //pass css and content array into kenny's function
      //store result in uncss string
      //go back to first css module and splice in our code

  }); //end compiler.plugin

};<commit_msg>update roadmap in plugin.js to compare each css individually<commit_after>var fs = require('fs');

var DemoPlugin = function(output, options) {
  this.output = output;
  this.options = options;
};

module.exports = DemoPlugin;

DemoPlugin.prototype.apply = function(compiler) {

  compiler.plugin('compilation', function(compilation) {

    compilation.plugin("optimize-modules", function(modules) {
      //iterate over modules
        //check if filepath ends in css
          //split at ! and fs
          //concat file path to css array
        //check if filepath does not contain node_modules
          //concat path to content array
      //pass css and content array into kenny's function
      //store results in uncss array
      //update css modules accordingly

  }); //end compiler.plugin

};<|endoftext|>


<commit_before>module.exports = {
  onPostBuild({ utils: { status: { show } } }) {
    show({ summary: 'Test' })
  }
}
<commit_msg>Revert "Test"<commit_after>module.exports = {
  onSuccess({ utils: { status: { show } } }) {
    show({ summary: 'Test' })
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2012 Google, Inc. All Rights Reserved.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

/**
 * @fileoverview Library-private utilties.
 *
 * @author benvanik@google.com (Ben Vanik)
 */

goog.provide('wtf.util');

goog.require('goog.asserts');
/** @suppress {extraRequire} */
goog.require('goog.debug.ErrorHandler');
goog.require('goog.string');
goog.require('goog.userAgent.product');

/**
 * Pads a number with leading zeros.
 * @param {number|string} value Value to pad.
 * @param {number} count Length to pad to.
 * @return {string} Padded number.
 */
wtf.util.pad0 = function(value, count) {
  value = String(value);
  while (value.length < count) {
    value = '0' + value;
  }
  return value;
};

/**
 * Formats a time value, rounding to ms at 3 decimal places.
 * @param {number} value Time value.
 * @return {string} Formatted time string.
 */
wtf.util.formatTime = function(value) {
  return value.toFixed(3) + 'ms';
};

/**
 * Formats a time value, rounding to ms and to ms at 3 decimal places if <1.
 * @param {number} value Time value.
 * @return {string} Formatted time string, plus units.
 */
wtf.util.formatSmallTime = function(value) {
  if (value == 0) {
    return '0ms';
  } else if (value < 1) {
    return value.toFixed(3) + 'ms';
  } else if (value < 10) {
    return value.toFixed(2) + 'ms';
  }
  return value.toFixed(0) + 'ms';
};

/**
 * Formats time in the standard format.
 * @param {number} value Wall-time.
 * @return {string} Formatted time string.
 */
wtf.util.formatWallTime = function(value) {
  // Format time: 05:33:28.105.25530
  var dt = new Date(value);
  return '' +
      goog.string.padNumber(dt.getHours(), 2) + ':' +
      goog.string.padNumber(dt.getMinutes(), 2) + ':' +
      goog.string.padNumber(dt.getSeconds(), 2) + '.' +
      String((dt.getMilliseconds() / 1000).toFixed(3)).slice(2, 5) + '.' +
      goog.string.padNumber(Math.floor((value - Math.floor(value)) * 10000), 4);
};

// TODO(benvanik): replace with fancy tooltip formatting.
/**
 * Adds event argument lines to the line list.
 * @param {!Array.<string>} lines List of lines that will be added to.
 * @param {Object} data Argument data object.
 */
wtf.util.addArgumentLines = function(lines, data) {
  if (!data) {
    return;
  }

  for (var argName in data) {
    var argValue = data[argName];
    if (argValue === undefined) {
      continue;
    }
    if (argValue === null) {
      argValue = 'null';
    } else if (goog.isArray(argValue)) {
      argValue = '[' + argValue + ']';
    } else if (argValue.buffer && argValue.buffer instanceof ArrayBuffer) {
      // TODO(benvanik): better display of big data blobs.
      var argString = '[';
      var maxCount = 16;
      for (var n = 0; n < Math.min(argValue.length, maxCount); n++) {
        if (n) {
          argString += ',';
        }
        argString += argValue[n];
      }
      if (argValue.length > maxCount) {
        argString += ' ...';
      }
      argString += ']';
      argValue = argString;
    } else if (goog.isObject(argValue)) {
      // TODO(benvanik): prettier object printing.
      argValue = goog.global.JSON.stringify(argValue, undefined, 2);
    }
    lines.push(argName + ': ' + argValue);
  }
};

/**
 * Gets the compiled name of a member on an object.
 * This looks up by member value, so only use with known-good values.
 * @param {!Object} obj Representative object.
 * @param {*} memberValue Member value.
 * @return {string?} Member name, if found.
 */
wtf.util.getCompiledMemberName = function(obj, memberValue) {
  // This does not early-exit to ensure that duplicates throw errors instead of
  // behaving unpredictably.
  var foundName = null;
  for (var name in obj) {
    if (obj[name] === memberValue) {
      if (foundName) {
        goog.asserts.fail('duplicate members found');
        return null;
      }
      foundName = name;
    }
  }
  return foundName;
};

/**
 * Calls a function when the DOM is ready.
 * The callback may be issued immediately if the DOM is already ready.
 * @param {!Function} callback Function to call.
 * @param {Object=} opt_scope Scope to call the function in.
 * @param {Document=} opt_document Document, if not the current one.
 */
wtf.util.callWhenDomReady = function(callback, opt_scope, opt_document) {
  var doc = opt_document || goog.global.document;

  // TODO(benvanik): prevent leaking these events.
  if (doc.readyState == 'complete' ||
      doc.readyState == 'interactive') {
    callback.call(opt_scope);
  } else {
    if (doc.addEventListener) {
      var listener = function() {
        doc.removeEventListener('DOMContentLoaded', listener, false);
        callback.call(opt_scope);
      };
      listener['__wtf_ignore__'] = true;
      doc.addEventListener('DOMContentLoaded', listener, false);
    } else if (doc.attachEvent) {
      var listener = function() {
        doc.detachEvent('onload', listener);
        callback.call(opt_scope);
      };
      listener['__wtf_ignore__'] = true;
      doc.attachEvent('onload', listener);
    }
  }
};

/**
 * Converts an ASCII string into a byte array.
 * This is very unsafe and should only be used when the content is known-ASCII.
 * @param {string} value Source string.
 * @return {!Uint8Array} Resulting array buffer.
 */
wtf.util.convertAsciiStringToUint8Array = function(value) {
  var buffer = new Uint8Array(value.length);
  for (var n = 0; n < buffer.length; n++) {
    buffer[n] = value.charCodeAt(n) & 0xFF;
  }
  return buffer;
};

/**
 * Converts a byte array into an ASCII string.
 * This is very unsafe and should only be used when the content is known-ASCII.
 * @param {!Uint8Array} value Source buffer.
 * @return {string} Resulting string.
 */
wtf.util.convertUint8ArrayToAsciiString = function(value) {
  // TODO(benvanik): evaluate not using a temp array
  var out = new Array(value.length);
  for (var n = 0; n < value.length; n++) {
    out[n] = String.fromCharCode(value[n]);
  }
  return out.join('');
};

/**
 * Generates an XPath expression that tries to uniquely identify a DOM element.
 * @param {Element|Object} targetElement DOM element.
 * @return {?string} XPath string or null if not possible.
 */
wtf.util.getElementXPath = function(targetElement) {
  if (!targetElement) {
    // No element is null.
    return null;
  } else if (targetElement == goog.global) {
    return 'window';
  } else if (targetElement.id) {
    // Element has an ID - easy.
    return '//*[@id="' + targetElement.id + '"]';
  }

  // TODO(benvanik): evaluate caching this string instance. We could check the
  //     cached copy on the element by walking up the tree - if it doesn't match
  //     (meaning the element has moved) we regenerate then. This would remove
  //     allocations in the common case.

  // Slow path - build a full xpath string.
  // We build the list of parts in reverse and then flip before joining.
  var paths = [];
  for (var el = targetElement;
      el && el.nodeType == Node.ELEMENT_NODE; el = el.parentNode) {
    var index = 0;
    for (var sibling = el.previousSibling; sibling;
        sibling = sibling.previousSibling) {
      if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) {
        continue;
      }
      if (sibling.nodeName == el.nodeName) {
        index++;
      }
    }
    paths.push(el.nodeName + '[' + (index + 1) + ']');
  }
  if (!paths.length) {
    return null;
  }

  // Add a leading '' to force a leading /.
  paths.push('');

  // Reverse the paths.
  wtf.util.reverse(paths);

  return paths.join('/');
};

/**
 * Attempts to find an element int he DOM by XPath.
 * @param {string?} path XPath query string.
 * @param {Document=} opt_document Document to query.
 * @return {Element|Object} Element, if found.
 */
wtf.util.findElementByXPath = function(path, opt_document) {
  var doc = opt_document || goog.global['document'];
  if (!path) {
    return null;
  } else if (path == 'window') {
    return doc['defaultView'];
  }
  var result = doc.evaluate(
      path,
      doc,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null);
  return result.singleNodeValue;
};

/**
 * Reverses the contents of the array inline.
 * This is up to 2x faster than the native browser reverse() in Chrome, but
 * slower in most other browsers.
 * @param {!Array} array Array to reverse.
 */
wtf.util.reverse = goog.userAgent.product.CHROME ? function(array) {
  var length = array.length;
  var halfLength = length >> 1;
  for (var n = 0; n < halfLength; n++) {
    var m = length - n - 1;
    var tmp = array[n];
    array[n] = array[m];
    array[m] = tmp;
  }
} : function(array) {
  array.reverse();
};

/**
 * Property name used to store the cache on the global object.
 * @type {string}
 * @const
 * @private
 */
wtf.util.GLOBAL_CACHE_KEY_ = 'wtf_util_global_cache';

/**
 * Gets a global cache object that can be used to store *cache only* data.
 * Use this instead of stashing properties on the global object yourself.
 * Since anything placed on here essentially leaks, it should only be used for
 * non-reference data (strings/numbers/etc) that is used for identity lookups
 * and such.
 *
 *
 * var stash = wtf.util.getGlobalCacheObject('foo');
 * stash.someId = 53;
 *
 *
 * @param {string} key Application-unique key.
 * @param {Object=} opt_global Global object to use instead of
 *     {@code goog.global}.
 * @return {!Object} An object that can be used to stash values.
 */
wtf.util.getGlobalCacheObject = function(key, opt_global) {
  var global = opt_global || goog.global;
  var root = global[wtf.util.GLOBAL_CACHE_KEY_];
  if (!root) {
    root = global[wtf.util.GLOBAL_CACHE_KEY_] = {};
  }
  var stash = root[key];
  if (!stash) {
    stash = root[key] = {};
  }
  return stash;
};

goog.exportSymbol(
    'wtf.util.formatTime',
    wtf.util.formatTime);
goog.exportSymbol(
    'wtf.util.formatSmallTime',
    wtf.util.formatSmallTime);
goog.exportSymbol(
    'wtf.util.formatWallTime',
    wtf.util.formatWallTime);
<commit_msg>Fixing document ready code for IE10.<commit_after>/**
 * Copyright 2012 Google, Inc. All Rights Reserved.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

/**
 * @fileoverview Library-private utilties.
 *
 * @author benvanik@google.com (Ben Vanik)
 */

goog.provide('wtf.util');

goog.require('goog.asserts');
/** @suppress {extraRequire} */
goog.require('goog.debug.ErrorHandler');
goog.require('goog.string');
goog.require('goog.userAgent.product');

/**
 * Pads a number with leading zeros.
 * @param {number|string} value Value to pad.
 * @param {number} count Length to pad to.
 * @return {string} Padded number.
 */
wtf.util.pad0 = function(value, count) {
  value = String(value);
  while (value.length < count) {
    value = '0' + value;
  }
  return value;
};

/**
 * Formats a time value, rounding to ms at 3 decimal places.
 * @param {number} value Time value.
 * @return {string} Formatted time string.
 */
wtf.util.formatTime = function(value) {
  return value.toFixed(3) + 'ms';
};

/**
 * Formats a time value, rounding to ms and to ms at 3 decimal places if <1.
 * @param {number} value Time value.
 * @return {string} Formatted time string, plus units.
 */
wtf.util.formatSmallTime = function(value) {
  if (value == 0) {
    return '0ms';
  } else if (value < 1) {
    return value.toFixed(3) + 'ms';
  } else if (value < 10) {
    return value.toFixed(2) + 'ms';
  }
  return value.toFixed(0) + 'ms';
};

/**
 * Formats time in the standard format.
 * @param {number} value Wall-time.
 * @return {string} Formatted time string.
 */
wtf.util.formatWallTime = function(value) {
  // Format time: 05:33:28.105.25530
  var dt = new Date(value);
  return '' +
      goog.string.padNumber(dt.getHours(), 2) + ':' +
      goog.string.padNumber(dt.getMinutes(), 2) + ':' +
      goog.string.padNumber(dt.getSeconds(), 2) + '.' +
      String((dt.getMilliseconds() / 1000).toFixed(3)).slice(2, 5) + '.' +
      goog.string.padNumber(Math.floor((value - Math.floor(value)) * 10000), 4);
};

// TODO(benvanik): replace with fancy tooltip formatting.
/**
 * Adds event argument lines to the line list.
 * @param {!Array.<string>} lines List of lines that will be added to.
 * @param {Object} data Argument data object.
 */
wtf.util.addArgumentLines = function(lines, data) {
  if (!data) {
    return;
  }

  for (var argName in data) {
    var argValue = data[argName];
    if (argValue === undefined) {
      continue;
    }
    if (argValue === null) {
      argValue = 'null';
    } else if (goog.isArray(argValue)) {
      argValue = '[' + argValue + ']';
    } else if (argValue.buffer && argValue.buffer instanceof ArrayBuffer) {
      // TODO(benvanik): better display of big data blobs.
      var argString = '[';
      var maxCount = 16;
      for (var n = 0; n < Math.min(argValue.length, maxCount); n++) {
        if (n) {
          argString += ',';
        }
        argString += argValue[n];
      }
      if (argValue.length > maxCount) {
        argString += ' ...';
      }
      argString += ']';
      argValue = argString;
    } else if (goog.isObject(argValue)) {
      // TODO(benvanik): prettier object printing.
      argValue = goog.global.JSON.stringify(argValue, undefined, 2);
    }
    lines.push(argName + ': ' + argValue);
  }
};

/**
 * Gets the compiled name of a member on an object.
 * This looks up by member value, so only use with known-good values.
 * @param {!Object} obj Representative object.
 * @param {*} memberValue Member value.
 * @return {string?} Member name, if found.
 */
wtf.util.getCompiledMemberName = function(obj, memberValue) {
  // This does not early-exit to ensure that duplicates throw errors instead of
  // behaving unpredictably.
  var foundName = null;
  for (var name in obj) {
    if (obj[name] === memberValue) {
      if (foundName) {
        goog.asserts.fail('duplicate members found');
        return null;
      }
      foundName = name;
    }
  }
  return foundName;
};

/**
 * Calls a function when the DOM is ready.
 * The callback may be issued immediately if the DOM is already ready.
 * @param {!Function} callback Function to call.
 * @param {Object=} opt_scope Scope to call the function in.
 * @param {Document=} opt_document Document, if not the current one.
 */
wtf.util.callWhenDomReady = function(callback, opt_scope, opt_document) {
  var doc = opt_document || goog.global.document;

  // TODO(benvanik): prevent leaking these events.
  if (doc.readyState == 'complete') {
    callback.call(opt_scope);
  } else {
    var hasFired = false;
    if (doc.addEventListener) {
      var listener = function() {
        if (hasFired) {
          return;
        }
        hasFired = true;
        doc.removeEventListener('DOMContentLoaded', listener, false);
        doc.removeEventListener('load', listener, false);
        callback.call(opt_scope);
      };
      listener['__wtf_ignore__'] = true;
      doc.addEventListener('DOMContentLoaded', listener, false);
      goog.global.addEventListener('load', listener, false);
    } else if (doc.attachEvent) {
      var listener = function() {
        if (hasFired) {
          return;
        }
        hasFired = true;
        doc.detachEvent('onload', listener);
        goog.global.detachEvent('load', listener);
        callback.call(opt_scope);
      };
      listener['__wtf_ignore__'] = true;
      doc.attachEvent('onload', listener);
      goog.global.attachEvent('load', listener);
    }
  }
};

/**
 * Converts an ASCII string into a byte array.
 * This is very unsafe and should only be used when the content is known-ASCII.
 * @param {string} value Source string.
 * @return {!Uint8Array} Resulting array buffer.
 */
wtf.util.convertAsciiStringToUint8Array = function(value) {
  var buffer = new Uint8Array(value.length);
  for (var n = 0; n < buffer.length; n++) {
    buffer[n] = value.charCodeAt(n) & 0xFF;
  }
  return buffer;
};

/**
 * Converts a byte array into an ASCII string.
 * This is very unsafe and should only be used when the content is known-ASCII.
 * @param {!Uint8Array} value Source buffer.
 * @return {string} Resulting string.
 */
wtf.util.convertUint8ArrayToAsciiString = function(value) {
  // TODO(benvanik): evaluate not using a temp array
  var out = new Array(value.length);
  for (var n = 0; n < value.length; n++) {
    out[n] = String.fromCharCode(value[n]);
  }
  return out.join('');
};

/**
 * Generates an XPath expression that tries to uniquely identify a DOM element.
 * @param {Element|Object} targetElement DOM element.
 * @return {?string} XPath string or null if not possible.
 */
wtf.util.getElementXPath = function(targetElement) {
  if (!targetElement) {
    // No element is null.
    return null;
  } else if (targetElement == goog.global) {
    return 'window';
  } else if (targetElement.id) {
    // Element has an ID - easy.
    return '//*[@id="' + targetElement.id + '"]';
  }

  // TODO(benvanik): evaluate caching this string instance. We could check the
  //     cached copy on the element by walking up the tree - if it doesn't match
  //     (meaning the element has moved) we regenerate then. This would remove
  //     allocations in the common case.

  // Slow path - build a full xpath string.
  // We build the list of parts in reverse and then flip before joining.
  var paths = [];
  for (var el = targetElement;
      el && el.nodeType == Node.ELEMENT_NODE; el = el.parentNode) {
    var index = 0;
    for (var sibling = el.previousSibling; sibling;
        sibling = sibling.previousSibling) {
      if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) {
        continue;
      }
      if (sibling.nodeName == el.nodeName) {
        index++;
      }
    }
    paths.push(el.nodeName + '[' + (index + 1) + ']');
  }
  if (!paths.length) {
    return null;
  }

  // Add a leading '' to force a leading /.
  paths.push('');

  // Reverse the paths.
  wtf.util.reverse(paths);

  return paths.join('/');
};

/**
 * Attempts to find an element int he DOM by XPath.
 * @param {string?} path XPath query string.
 * @param {Document=} opt_document Document to query.
 * @return {Element|Object} Element, if found.
 */
wtf.util.findElementByXPath = function(path, opt_document) {
  var doc = opt_document || goog.global['document'];
  if (!path) {
    return null;
  } else if (path == 'window') {
    return doc['defaultView'];
  }
  var result = doc.evaluate(
      path,
      doc,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null);
  return result.singleNodeValue;
};

/**
 * Reverses the contents of the array inline.
 * This is up to 2x faster than the native browser reverse() in Chrome, but
 * slower in most other browsers.
 * @param {!Array} array Array to reverse.
 */
wtf.util.reverse = goog.userAgent.product.CHROME ? function(array) {
  var length = array.length;
  var halfLength = length >> 1;
  for (var n = 0; n < halfLength; n++) {
    var m = length - n - 1;
    var tmp = array[n];
    array[n] = array[m];
    array[m] = tmp;
  }
} : function(array) {
  array.reverse();
};

/**
 * Property name used to store the cache on the global object.
 * @type {string}
 * @const
 * @private
 */
wtf.util.GLOBAL_CACHE_KEY_ = 'wtf_util_global_cache';

/**
 * Gets a global cache object that can be used to store *cache only* data.
 * Use this instead of stashing properties on the global object yourself.
 * Since anything placed on here essentially leaks, it should only be used for
 * non-reference data (strings/numbers/etc) that is used for identity lookups
 * and such.
 *
 *
 * var stash = wtf.util.getGlobalCacheObject('foo');
 * stash.someId = 53;
 *
 *
 * @param {string} key Application-unique key.
 * @param {Object=} opt_global Global object to use instead of
 *     {@code goog.global}.
 * @return {!Object} An object that can be used to stash values.
 */
wtf.util.getGlobalCacheObject = function(key, opt_global) {
  var global = opt_global || goog.global;
  var root = global[wtf.util.GLOBAL_CACHE_KEY_];
  if (!root) {
    root = global[wtf.util.GLOBAL_CACHE_KEY_] = {};
  }
  var stash = root[key];
  if (!stash) {
    stash = root[key] = {};
  }
  return stash;
};

goog.exportSymbol(
    'wtf.util.formatTime',
    wtf.util.formatTime);
goog.exportSymbol(
    'wtf.util.formatSmallTime',
    wtf.util.formatSmallTime);
goog.exportSymbol(
    'wtf.util.formatWallTime',
    wtf.util.formatWallTime);
<|endoftext|>