<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const DependencyGraph = require('../node-haste');

const declareOpts = require('../lib/declareOpts');
const defaults = require('../../../defaults');
const pathJoin = require('path').join;

const validateOpts = declareOpts({
  projectRoots: {
    type: 'array',
    required: true,
  },
  blacklistRE: {
    type: 'object', // typeof regex is object
  },
  polyfillModuleNames: {
    type: 'array',
    default: [],
  },
  moduleFormat: {
    type: 'string',
    default: 'haste',
  },
  watch: {
    type: 'boolean',
    default: false,
  },
  assetExts: {
    type: 'array',
    required: true,
  },
  cache: {
    type: 'object',
    required: true,
  },
  transformCode: {
    type: 'function',
  },
  transformCacheKey: {
    type: 'string',
  },
  extraNodeModules: {
    type: 'object',
    required: false,
  },
  minifyCode: {
    type: 'function',
  },
  resetCache: {
    type: 'boolean',
    default: false,
  },
});

const getDependenciesValidateOpts = declareOpts({
  dev: {
    type: 'boolean',
    default: true,
  },
  platform: {
    type: 'string',
    required: false,
  },
  unbundle: {
    type: 'boolean',
    default: false,
  },
  recursive: {
    type: 'boolean',
    default: true,
  },
});

class Resolver {

  constructor(options) {
    const opts = validateOpts(options);

    this._depGraph = new DependencyGraph({
      roots: opts.projectRoots,
      assetExts: opts.assetExts,
      ignoreFilePath: function(filepath) {
        return filepath.indexOf('__tests__') !== -1 ||
          (opts.blacklistRE && opts.blacklistRE.test(filepath));
      },
      providesModuleNodeModules: defaults.providesModuleNodeModules,
      platforms: defaults.platforms,
      preferNativePlatform: true,
      watch: opts.watch,
      cache: opts.cache,
      shouldThrowOnUnresolvedErrors: (_, platform) => platform !== 'android',
      transformCode: opts.transformCode,
      transformCacheKey: opts.transformCacheKey,
      extraNodeModules: opts.extraNodeModules,
      assetDependencies: ['react-native/Libraries/Image/AssetRegistry'],
      resetCache: options.resetCache,
      moduleOptions: {
        cacheTransformResults: true,
        resetCache: options.resetCache,
      },
    });

    this._minifyCode = opts.minifyCode;
    this._polyfillModuleNames = opts.polyfillModuleNames || [];

    this._depGraph.load().catch(err => {
      console.error(err.message + '\n' + err.stack);
      process.exit(1);
    });
  }

  getShallowDependencies(entryFile, transformOptions) {
    return this._depGraph.getShallowDependencies(entryFile, transformOptions);
  }

  stat(filePath) {
    return this._depGraph.getFS().stat(filePath);
  }

  getModuleForPath(entryFile) {
    return this._depGraph.getModuleForPath(entryFile);
  }

  getDependencies(entryPath, options, transformOptions, onProgress, getModuleId) {
    const {platform, recursive} = getDependenciesValidateOpts(options);
    return this._depGraph.getDependencies({
      entryPath,
      platform,
      transformOptions,
      recursive,
      onProgress,
    }).then(resolutionResponse => {
      this._getPolyfillDependencies().reverse().forEach(
        polyfill => resolutionResponse.prependDependency(polyfill)
      );

      resolutionResponse.getModuleId = getModuleId;
      return resolutionResponse.finalize();
    });
  }

  getModuleSystemDependencies(options) {
    const opts = getDependenciesValidateOpts(options);

    const prelude = opts.dev
        ? pathJoin(__dirname, 'polyfills/prelude_dev.js')
        : pathJoin(__dirname, 'polyfills/prelude.js');

    const moduleSystem = defaults.moduleSystem;

    return [
      prelude,
      moduleSystem,
    ].map(moduleName => this._depGraph.createPolyfill({
      file: moduleName,
      id: moduleName,
      dependencies: [],
    }));
  }

  _getPolyfillDependencies() {
    const polyfillModuleNames = defaults.polyfills.concat(this._polyfillModuleNames);

    return polyfillModuleNames.map(
      (polyfillModuleName, idx) => this._depGraph.createPolyfill({
        file: polyfillModuleName,
        id: polyfillModuleName,
        dependencies: polyfillModuleNames.slice(0, idx),
      })
    );
  }

  resolveRequires(resolutionResponse, module, code, dependencyOffsets = []) {
    const resolvedDeps = Object.create(null);

    // here, we build a map of all require strings (relative and absolute)
    // to the canonical ID of the module they reference
    resolutionResponse.getResolvedDependencyPairs(module)
      .forEach(([depName, depModule]) => {
        if (depModule) {
          resolvedDeps[depName] = resolutionResponse.getModuleId(depModule);
        }
      });

    // if we have a canonical ID for the module imported here,
    // we use it, so that require() is always called with the same
    // id for every module.
    // Example:
    // -- in a/b.js:
    //    require('./c') => require(3);
    // -- in b/index.js:
    //    require('../a/c') => require(3);
    const replaceModuleId = (codeMatch, quote, depName) =>
      depName in resolvedDeps
        ? `${JSON.stringify(resolvedDeps[depName])} /* ${depName} */`
        : codeMatch;

    code = dependencyOffsets.reduceRight((codeBits, offset) => {
      const first = codeBits.shift();
      codeBits.unshift(
        first.slice(0, offset),
        first.slice(offset).replace(/(['"])([^'"']*)\1/, replaceModuleId),
      );
      return codeBits;
    }, [code]);

    return code.join('');
  }

  wrapModule({
    resolutionResponse,
    module,
    name,
    map,
    code,
    meta = {},
    dev = true,
    minify = false,
  }) {
    if (module.isJSON()) {
      code = `module.exports = ${code}`;
    }

    if (module.isPolyfill()) {
      code = definePolyfillCode(code);
    } else {
      const moduleId = resolutionResponse.getModuleId(module);
      code = this.resolveRequires(
        resolutionResponse,
        module,
        code,
        meta.dependencyOffsets
      );
      code = defineModuleCode(moduleId, code, name, dev);
    }

    return minify
      ? this._minifyCode(module.path, code, map)
      : Promise.resolve({code, map});
  }

  minifyModule({path, code, map}) {
    return this._minifyCode(path, code, map);
  }

  getDependencyGraph() {
    return this._depGraph;
  }
}

function defineModuleCode(moduleName, code, verboseName = '', dev = true) {
  return [
    `__d(/* ${verboseName} */`,
    'function(global, require, module, exports) {', // module factory
      code,
    '\n}, ',
    `${JSON.stringify(moduleName)}`, // module id, null = id map. used in ModuleGraph
    dev ? `, null, ${JSON.stringify(verboseName)}` : '',
    ');',
  ].join('');
}

function definePolyfillCode(code,) {
  return [
    '(function(global) {',
    code,
    `\n})(typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this);`,
  ].join('');
}

module.exports = Resolver;
<commit_msg>Stop silently failing for requires on Android<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';

const DependencyGraph = require('../node-haste');

const declareOpts = require('../lib/declareOpts');
const defaults = require('../../../defaults');
const pathJoin = require('path').join;

const validateOpts = declareOpts({
  projectRoots: {
    type: 'array',
    required: true,
  },
  blacklistRE: {
    type: 'object', // typeof regex is object
  },
  polyfillModuleNames: {
    type: 'array',
    default: [],
  },
  moduleFormat: {
    type: 'string',
    default: 'haste',
  },
  watch: {
    type: 'boolean',
    default: false,
  },
  assetExts: {
    type: 'array',
    required: true,
  },
  cache: {
    type: 'object',
    required: true,
  },
  transformCode: {
    type: 'function',
  },
  transformCacheKey: {
    type: 'string',
  },
  extraNodeModules: {
    type: 'object',
    required: false,
  },
  minifyCode: {
    type: 'function',
  },
  resetCache: {
    type: 'boolean',
    default: false,
  },
});

const getDependenciesValidateOpts = declareOpts({
  dev: {
    type: 'boolean',
    default: true,
  },
  platform: {
    type: 'string',
    required: false,
  },
  unbundle: {
    type: 'boolean',
    default: false,
  },
  recursive: {
    type: 'boolean',
    default: true,
  },
});

class Resolver {

  constructor(options) {
    const opts = validateOpts(options);

    this._depGraph = new DependencyGraph({
      roots: opts.projectRoots,
      assetExts: opts.assetExts,
      ignoreFilePath: function(filepath) {
        return filepath.indexOf('__tests__') !== -1 ||
          (opts.blacklistRE && opts.blacklistRE.test(filepath));
      },
      providesModuleNodeModules: defaults.providesModuleNodeModules,
      platforms: defaults.platforms,
      preferNativePlatform: true,
      watch: opts.watch,
      cache: opts.cache,
      shouldThrowOnUnresolvedErrors: () => true,
      transformCode: opts.transformCode,
      transformCacheKey: opts.transformCacheKey,
      extraNodeModules: opts.extraNodeModules,
      assetDependencies: ['react-native/Libraries/Image/AssetRegistry'],
      resetCache: options.resetCache,
      moduleOptions: {
        cacheTransformResults: true,
        resetCache: options.resetCache,
      },
    });

    this._minifyCode = opts.minifyCode;
    this._polyfillModuleNames = opts.polyfillModuleNames || [];

    this._depGraph.load().catch(err => {
      console.error(err.message + '\n' + err.stack);
      process.exit(1);
    });
  }

  getShallowDependencies(entryFile, transformOptions) {
    return this._depGraph.getShallowDependencies(entryFile, transformOptions);
  }

  stat(filePath) {
    return this._depGraph.getFS().stat(filePath);
  }

  getModuleForPath(entryFile) {
    return this._depGraph.getModuleForPath(entryFile);
  }

  getDependencies(entryPath, options, transformOptions, onProgress, getModuleId) {
    const {platform, recursive} = getDependenciesValidateOpts(options);
    return this._depGraph.getDependencies({
      entryPath,
      platform,
      transformOptions,
      recursive,
      onProgress,
    }).then(resolutionResponse => {
      this._getPolyfillDependencies().reverse().forEach(
        polyfill => resolutionResponse.prependDependency(polyfill)
      );

      resolutionResponse.getModuleId = getModuleId;
      return resolutionResponse.finalize();
    });
  }

  getModuleSystemDependencies(options) {
    const opts = getDependenciesValidateOpts(options);

    const prelude = opts.dev
        ? pathJoin(__dirname, 'polyfills/prelude_dev.js')
        : pathJoin(__dirname, 'polyfills/prelude.js');

    const moduleSystem = defaults.moduleSystem;

    return [
      prelude,
      moduleSystem,
    ].map(moduleName => this._depGraph.createPolyfill({
      file: moduleName,
      id: moduleName,
      dependencies: [],
    }));
  }

  _getPolyfillDependencies() {
    const polyfillModuleNames = defaults.polyfills.concat(this._polyfillModuleNames);

    return polyfillModuleNames.map(
      (polyfillModuleName, idx) => this._depGraph.createPolyfill({
        file: polyfillModuleName,
        id: polyfillModuleName,
        dependencies: polyfillModuleNames.slice(0, idx),
      })
    );
  }

  resolveRequires(resolutionResponse, module, code, dependencyOffsets = []) {
    const resolvedDeps = Object.create(null);

    // here, we build a map of all require strings (relative and absolute)
    // to the canonical ID of the module they reference
    resolutionResponse.getResolvedDependencyPairs(module)
      .forEach(([depName, depModule]) => {
        if (depModule) {
          resolvedDeps[depName] = resolutionResponse.getModuleId(depModule);
        }
      });

    // if we have a canonical ID for the module imported here,
    // we use it, so that require() is always called with the same
    // id for every module.
    // Example:
    // -- in a/b.js:
    //    require('./c') => require(3);
    // -- in b/index.js:
    //    require('../a/c') => require(3);
    const replaceModuleId = (codeMatch, quote, depName) =>
      depName in resolvedDeps
        ? `${JSON.stringify(resolvedDeps[depName])} /* ${depName} */`
        : codeMatch;

    code = dependencyOffsets.reduceRight((codeBits, offset) => {
      const first = codeBits.shift();
      codeBits.unshift(
        first.slice(0, offset),
        first.slice(offset).replace(/(['"])([^'"']*)\1/, replaceModuleId),
      );
      return codeBits;
    }, [code]);

    return code.join('');
  }

  wrapModule({
    resolutionResponse,
    module,
    name,
    map,
    code,
    meta = {},
    dev = true,
    minify = false,
  }) {
    if (module.isJSON()) {
      code = `module.exports = ${code}`;
    }

    if (module.isPolyfill()) {
      code = definePolyfillCode(code);
    } else {
      const moduleId = resolutionResponse.getModuleId(module);
      code = this.resolveRequires(
        resolutionResponse,
        module,
        code,
        meta.dependencyOffsets
      );
      code = defineModuleCode(moduleId, code, name, dev);
    }

    return minify
      ? this._minifyCode(module.path, code, map)
      : Promise.resolve({code, map});
  }

  minifyModule({path, code, map}) {
    return this._minifyCode(path, code, map);
  }

  getDependencyGraph() {
    return this._depGraph;
  }
}

function defineModuleCode(moduleName, code, verboseName = '', dev = true) {
  return [
    `__d(/* ${verboseName} */`,
    'function(global, require, module, exports) {', // module factory
      code,
    '\n}, ',
    `${JSON.stringify(moduleName)}`, // module id, null = id map. used in ModuleGraph
    dev ? `, null, ${JSON.stringify(verboseName)}` : '',
    ');',
  ].join('');
}

function definePolyfillCode(code,) {
  return [
    '(function(global) {',
    code,
    `\n})(typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this);`,
  ].join('');
}

module.exports = Resolver;
<|endoftext|>


<commit_before>/*
Convert CoffeeScript classes that extend other classes into `superClass.extend` calls.

Example:

```coffeescript
class Todo extends Backbone.Model
```

```javascript
Todo = Backbone.Model.extend({

});
```

Assumptions:
- Every time a method receives `superClass` as an argument we assume it's body
  to be a CoffeeScript class.
- `extend`, `bind` and `hasProp` are expected to be variables that are only used
  by CoffeeScript classes (we remove them in this transform).
- Each triply nested memberExpression with `__super__` is replaced by
  `superClass.prototype.METHOD.apply()`

FIXME:
- This transform is pretty big on its assumptions. Ideally we should find a way to
  convert CoffeeScript classes into ES2015 classes, but because of the nature of
  the HackerOne codebase (all classes are Backbone Models/Collections) I decided
  to go with the easy route first.
*/

import removeVariableDeclarator from "./util/remove-variable-declarator";

module.exports = (file, api) => {
  const j = api.jscodeshift;
  const isConstructor = bodyElement =>
    bodyElement.type === "FunctionDeclaration";

  const isPrototypeMethod = bodyElement =>
    bodyElement.type === "ExpressionStatement" &&
        bodyElement.expression.left &&
        bodyElement.expression.left.type === "MemberExpression" &&
        bodyElement.expression.left.object.type === "MemberExpression" &&
        bodyElement.expression.left.object.property.name === "prototype";

  const transformConstructorBody = bodyElement => {
    j(bodyElement)
      .find(j.AssignmentExpression, {
        left: {
          type: "MemberExpression",
          object: {
            type: "ThisExpression",
          },
        },
        right: {
          type: "CallExpression",
          callee: {
            type: "Identifier",
            name: "bind",
          },
        },
      })
      .replaceWith(exp =>
        j.assignmentExpression(
          "=",
          exp.value.left,
          j.callExpression(
            j.memberExpression(
              exp.value.right.arguments[0],
              j.identifier("bind")
            ),
            exp.value.right.arguments.slice(1)
          )
        )
      );

    return bodyElement;
  };

  const transformBodyElementToProperty = bodyElement => {
    if (isConstructor(bodyElement) && bodyElement.body.body.length > 1) {
      return j.property(
        "init",
        j.identifier("constructor"),
        j.functionExpression(
          null,
          [],
          transformConstructorBody(bodyElement.body)
        )
      );
    } else if (isPrototypeMethod(bodyElement)) {
      return j.property(
        "init",
        j.identifier(bodyElement.expression.left.property.name),
        bodyElement.expression.right
      );
    }
  };

  const transformSuperCalls = (classBody, superClass) =>
    j(classBody)
      .find(j.CallExpression, {
        callee: {
          type: "MemberExpression",
          object: {
            type: "MemberExpression",
            object: {
              type: "MemberExpression",
              object: { type: "Identifier" },
              property: { type: "Identifier", name: "__super__" },
            },
            property: { type: "Identifier" },
          },
          property: { type: "Identifier", name: "apply" },
        },
      })
      .replaceWith(exp =>
        j.callExpression(
          j.memberExpression(
            j.memberExpression(
              superClass,
              j.memberExpression(
                j.identifier("prototype"),
                exp.value.callee.object.property
              )
            ),
            j.identifier("apply")
          ),
          exp.value.arguments
        )
      );

  const hasStaticProp = exp =>
    exp.value.callee.body.body.find(bodyElement =>
      bodyElement.type === "ExpressionStatement" &&
      bodyElement.expression.type === "AssignmentExpression" &&
      bodyElement.expression.left.type === "MemberExpression" &&
      bodyElement.expression.left.object.type === "Identifier"
    );

  return j(file.source)
    .find(j.CallExpression, {
      callee: {
        type: "FunctionExpression",
      },
    })
    .filter(exp =>
      exp.value.callee.params.length === 1 &&
      exp.value.callee.params[0].name === "superClass"
    )
    .filter(exp => !hasStaticProp(exp))
    .replaceWith(exp => {
      const callee = exp.value.callee;
      const superClass = exp.value.arguments[0];
      const newBody = [];

      callee.body.body.forEach(bodyElement => {
        const property = transformBodyElementToProperty(bodyElement);

        if (property) {
          if (property.value.type === "FunctionExpression") {
            property.method = true;
          }

          newBody.push(property);
        }
      });

      removeVariableDeclarator("extend", exp.scope.path, api);
      removeVariableDeclarator("hasProp", exp.scope.path, api);
      removeVariableDeclarator("bind", exp.scope.path, api);

      transformSuperCalls(newBody, superClass);

      return j.callExpression(
        j.memberExpression(superClass, j.identifier("extend")),
        [
          j.objectExpression(newBody),
        ]
      );
    })
    .toSource();
};
<commit_msg>Fix constructor calls in backbone-classes<commit_after>/*
Convert CoffeeScript classes that extend other classes into `superClass.extend` calls.

Example:

```coffeescript
class Todo extends Backbone.Model
```

```javascript
Todo = Backbone.Model.extend({

});
```

Assumptions:
- Every time a method receives `superClass` as an argument we assume it's body
  to be a CoffeeScript class.
- `extend`, `bind` and `hasProp` are expected to be variables that are only used
  by CoffeeScript classes (we remove them in this transform).
- Each triply nested memberExpression with `__super__` is replaced by
  `superClass.prototype.METHOD.apply()`

FIXME:
- This transform is pretty big on its assumptions. Ideally we should find a way to
  convert CoffeeScript classes into ES2015 classes, but because of the nature of
  the HackerOne codebase (all classes are Backbone Models/Collections) I decided
  to go with the easy route first.
*/

import removeVariableDeclarator from "./util/remove-variable-declarator";

module.exports = (file, api) => {
  const j = api.jscodeshift;
  const isConstructor = bodyElement =>
    bodyElement.type === "FunctionDeclaration";

  const isPrototypeMethod = bodyElement =>
    bodyElement.type === "ExpressionStatement" &&
        bodyElement.expression.left &&
        bodyElement.expression.left.type === "MemberExpression" &&
        bodyElement.expression.left.object.type === "MemberExpression" &&
        bodyElement.expression.left.object.property.name === "prototype";

  const transformConstructorBody = bodyElement => {
    j(bodyElement)
      .find(j.AssignmentExpression, {
        left: {
          type: "MemberExpression",
          object: {
            type: "ThisExpression",
          },
        },
        right: {
          type: "CallExpression",
          callee: {
            type: "Identifier",
            name: "bind",
          },
        },
      })
      .replaceWith(exp =>
        j.assignmentExpression(
          "=",
          exp.value.left,
          j.callExpression(
            j.memberExpression(
              exp.value.right.arguments[0],
              j.identifier("bind")
            ),
            exp.value.right.arguments.slice(1)
          )
        )
      );

    return bodyElement;
  };

  const transformBodyElementToProperty = bodyElement => {
    if (isConstructor(bodyElement) && bodyElement.body.body.length > 1) {
      return j.property(
        "init",
        j.identifier("constructor"),
        j.functionExpression(
          null,
          [],
          transformConstructorBody(bodyElement.body)
        )
      );
    } else if (isPrototypeMethod(bodyElement)) {
      return j.property(
        "init",
        j.identifier(bodyElement.expression.left.property.name),
        bodyElement.expression.right
      );
    }
  };

  const transformSuperCalls = (classBody, superClass) =>
    j(classBody)
      .find(j.CallExpression, {
        callee: {
          type: "MemberExpression",
          object: {
            type: "MemberExpression",
            object: {
              type: "MemberExpression",
              object: { type: "Identifier" },
              property: { type: "Identifier", name: "__super__" },
            },
            property: { type: "Identifier" },
          },
          property: { type: "Identifier", name: "apply" },
        },
      })
      .replaceWith(exp =>
        j.callExpression(
          j.memberExpression(
            j.memberExpression(
              j.memberExpression(
                superClass,
                j.identifier("prototype")
              ),
              exp.value.callee.object.property
            ),
            j.identifier("apply")
          ),
          exp.value.arguments
        )
      );

  const hasStaticProp = exp =>
    exp.value.callee.body.body.find(bodyElement =>
      bodyElement.type === "ExpressionStatement" &&
      bodyElement.expression.type === "AssignmentExpression" &&
      bodyElement.expression.left.type === "MemberExpression" &&
      bodyElement.expression.left.object.type === "Identifier"
    );

  return j(file.source)
    .find(j.CallExpression, {
      callee: {
        type: "FunctionExpression",
      },
    })
    .filter(exp =>
      exp.value.callee.params.length === 1 &&
      exp.value.callee.params[0].name === "superClass"
    )
    .filter(exp => !hasStaticProp(exp))
    .replaceWith(exp => {
      const callee = exp.value.callee;
      const superClass = exp.value.arguments[0];
      const newBody = [];

      callee.body.body.forEach(bodyElement => {
        const property = transformBodyElementToProperty(bodyElement);

        if (property) {
          if (property.value.type === "FunctionExpression") {
            property.method = true;
          }

          newBody.push(property);
        }
      });

      removeVariableDeclarator("extend", exp.scope.path, api);
      removeVariableDeclarator("hasProp", exp.scope.path, api);
      removeVariableDeclarator("bind", exp.scope.path, api);

      transformSuperCalls(newBody, superClass);

      return j.callExpression(
        j.memberExpression(superClass, j.identifier("extend")),
        [
          j.objectExpression(newBody),
        ]
      );
    })
    .toSource();
};
<|endoftext|>


<commit_before>function defaultNotificationFormat(txt){
    if(txt.substr(0,txt.indexOf("[")-1) == 0)
      return txt.substring(txt.indexOf("]:")+2);
    return txt.substr(0,txt.indexOf("[")-1) + ": " + txt.substring(txt.indexOf("]:")+2);
}
var templateToLoad;
templateToLoad = templateToLoad || "https://rawgit.com/ocbaker/SMFPack-Chatbox-Tools/settings-update/settingsTemplate.html";
var notificationSettings = {
    phrases: ["ocbaker", "oliver", "admin", "mods", "moderator", "baker", "swear", "language"],
    general: true,
    mentions: true,
    generalTimeout: 5 * 1000,
    mentionTimeout: 10 * 1000,
    notifyWhenChatActive: false,
    generalFormat: defaultNotificationFormat,
    mentionFormat: defaultNotificationFormat
};
function loadChatbox(){
    Shoutbox_PutMsgs = function Shoutbox_PutMsgs(XMLDoc)
    {
        if (Shoutbox.msgs !== false)
            window.clearTimeout(Shoutbox.msgs);
        if (XMLDoc && XMLDoc.getElementsByTagName("banned")[0])
        {
            setOuterHTML(document.getElementById("shoutbox_banned"), '');
            document.getElementById("shoutbox_status").style.visibility = 'hidden';
            document.getElementById("shoutbox_message").value = '';
            document.getElementById("shoutbox_message").disabled = true;
            return window.alert(Shoutbox.lang.banned);
        }
        var error = false;
        if (XMLDoc && XMLDoc.getElementsByTagName("error")[0])
            error = XMLDoc.getElementsByTagName("error")[0].childNodes[0].nodeValue;
        if (!XMLDoc || !XMLDoc.getElementsByTagName("msgs")[0])
        {
            if (!Shoutbox.hide)
            {
                Shoutbox.msgs = window.setTimeout("Shoutbox_GetMsgs();", Shoutbox.refresh);
                Shoutbox.loading = false;
            }
            document.getElementById("shoutbox_status").style.visibility = 'hidden';
            if (error)
                window.alert(error);
            Shoutbox.first = false;
            return;
        }
        var toReset = !Shoutbox.first && XMLDoc.getElementsByTagName("reset")[0];
        if (!Shoutbox.ie)
        {
            if (toReset)
            {
                if (Shoutbox.msgdown)
                    setInnerHTML(document.getElementById("shoutbox_banned"), '

');
                else
                    setInnerHTML(document.getElementById("shoutbox_banned"), '

');
            }
            setOuterHTML(document.getElementById("shoutbox_msgs"), XMLDoc.getElementsByTagName("msgs")[0].childNodes[0].nodeValue);
        }
        else
        {
            var msgs = '';
            if (Shoutbox.msgdown)
            {
                msgs += '

';
                msgs += (toReset ? '' : getInnerHTML(document.getElementById("shoutbox_table"))) + XMLDoc.getElementsByTagName("msgs")[0].childNodes[0].nodeValue;
                msgs += '

';
            }
            else
            {
                msgs += '
';
                msgs += XMLDoc.getElementsByTagName("msgs")[0].childNodes[0].nodeValue + (toReset ? '' : getInnerHTML(document.getElementById("shoutbox_table")));
                msgs += '
';
            }
            setInnerHTML(document.getElementById("shoutbox_banned"), msgs);
        }
        if (toReset)
        {
            Shoutbox.currentmsg = 1;
            Shoutbox.countmsgs = Shoutbox.maxmsgs = 0;
        }
        var count = parseInt(XMLDoc.getElementsByTagName("count")[0].childNodes[0].nodeValue);
        if (Shoutbox.countmsgs + count > Shoutbox.keepmsgs)
        {
            for (var i = Shoutbox.currentmsg; i < Shoutbox.currentmsg + Shoutbox.countmsgs + count - Shoutbox.keepmsgs; i++)
                document.getElementById("shoutbox_row" + i).parentNode.removeChild(document.getElementById("shoutbox_row" + i));
            Shoutbox.currentmsg += Shoutbox.countmsgs + count - Shoutbox.keepmsgs;
        }
        Shoutbox.maxmsgs += count;
        Shoutbox.countmsgs = Shoutbox.countmsgs + count > Shoutbox.keepmsgs ? Shoutbox.keepmsgs : Shoutbox.countmsgs + count;
        if (!Shoutbox.hide)
        {
            Shoutbox.msgs = window.setTimeout("Shoutbox_GetMsgs();", Shoutbox.refresh);
            Shoutbox.loading = false;
        }
        document.getElementById("shoutbox_status").style.visibility = 'hidden';
        if (Shoutbox.msgdown && (document.getElementById("shoutbox_banned").scrollTop >= Shoutbox.scroll || Shoutbox.scroll == 0))
        {
            document.getElementById("shoutbox_banned").scrollTop = document.getElementById("shoutbox_banned").scrollHeight;
            document.getElementById("shoutbox_banned").scrollTop = document.getElementById("shoutbox_banned").scrollHeight;
            Shoutbox.scroll = document.getElementById("shoutbox_banned").scrollTop;
        }
        if (error)
            window.alert(error);
        if (!Shoutbox.first && XMLDoc.getElementsByTagName("newmsgs")[0]) {
            var msgs = $(XMLDoc.getElementsByTagName("msgs")[0].childNodes[0].nodeValue);
            if ((notificationSettings.notifyWhenChatActive || isHidden()) && (notificationSettings.general || notificationSettings.mentions))
                msgs.each(function(a, b, c) {
                    var txt = $(b).text();
                    if (txt != "") {
                        var stxt = txt.toLowerCase();
                        var found = false;
                        notificationSettings.phrases.forEach(function(phrase, i) {
                            if (!found && stxt.indexOf(phrase.toLowerCase()) != -1)
                                found = true;
                        });

                        if (found && notificationSettings.mentions)
                            notifyMe("LoE Chat Mention", notificationSettings.mentionFormat(txt), notificationSettings.mentionTimeout);
                        if (!(found && notificationSettings.mentions) && notificationSettings.general)
                            notifyMe("LoE Chat", notificationSettings.generalFormat(txt), notificationSettings.generalTimeout);
                    }

                });
            Shoutbox_NewMsgs();
        }
        Shoutbox.first = false;
    };
}

notifyMe = function notifyMe(title, msg, timeout) {
    // Let's check if the browser supports notifications
    if (!("Notification" in window)) {
        alert("This browser does not support desktop notification");
    }

    // Let's check whether notification permissions have alredy been granted
    else if (Notification.permission === "granted") {
        // If it's okay let's create a notification
        var notification = new Notification(title, {body: msg,icon: "https://pbs.twimg.com/profile_images/1910794026/LoE_Web_Logo2_400x400.png"});
        if (timeout != 0)
            setTimeout(function() {
                notification.close();
            }, timeout);
    }

    // Otherwise, we need to ask the user for permission
    else if (Notification.permission !== 'denied') {
        Notification.requestPermission(function(permission) {
            // If the user accepts, let's create a notification
            if (permission === "granted") {
                var notification = new Notification(title, {body: msg,icon: "https://pbs.twimg.com/profile_images/1910794026/LoE_Web_Logo2_400x400.png"});
                if (timeout != 0)
                    setTimeout(function() {
                        notification.close();
                    }, timeout);
            }
        });
    }

// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them any more.
}
function getHiddenProp() {
    var prefixes = ['webkit', 'moz', 'ms', 'o'];

    // if 'hidden' is natively supported just return it
    if ('hidden' in document)
        return 'hidden';

    // otherwise loop over all the known prefixes until we find one
    for (var i = 0; i < prefixes.length; i++) {
        if ((prefixes[i] + 'Hidden') in document)
            return prefixes[i] + 'Hidden';
    }

    // otherwise it's not supported
    return null;
}
function isHidden() {
    var prop = getHiddenProp();
    if (!prop)
        return false;

    return document[prop];
}

function loadSettings(localStorageService){

}

function loadAngular() {

    angular.module('Foo', ['LocalStorageModule'], function($controllerProvider) {
        controllerProvider = $controllerProvider;
    });
    // Bootstrap Foo
    angular.bootstrap($('#shoutbox'), ['Foo']);

    // .. time passes ..

    // Load javascript file with Ctrl controller
    var myApp = angular.module('Foo');
    myApp.config(function(localStorageServiceProvider) {
        localStorageServiceProvider
        .setPrefix('myApp')
        .setStorageType('localStorage')
        .setNotify(true, true)
    });
    myApp.controller('Ctrl', function($scope, $rootScope, localStorageService) {
        console.log(localStorageService);
        $scope.settings = notificationSettings;
        console.log($scope);
        loadChatbox();
        notifyMe("LoE Chat", "Loaded Notifications", 10000);
    });
    // Load html file with content that uses Ctrl controller
    $('
').appendTo('#shoutbox .content');
    $('#nSettings').load(templateToLoad, function() {
        registerController("Foo", "Ctrl");
        // compile the new element
        $('#shoutbox .content').injector().invoke(function($compile, $rootScope, localStorageService) {
            $compile($('#ctrl'))($rootScope);
            $rootScope.$apply();
        });
    });
}

var controllerProvider = null;

jQuery.getScript("//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.min.js", function() {
    jQuery.getScript("https://rawgit.com/grevory/angular-local-storage/master/dist/angular-local-storage.js", function() {
        loadAngular();
    });
});

// Register Ctrl controller manually
// If you can reference the controller function directly, just run:
// $controllerProvider.register(controllerName, controllerFunction);
// Note: I haven't found a way to get $controllerProvider at this stage
//    so I keep a reference from when I ran my module config
function registerController(moduleName, controllerName) {
    // Here I cannot get the controller function directly so I
    // need to loop through the module's _invokeQueue to get it
    var queue = angular.module(moduleName)._invokeQueue;
    for (var i = 0; i < queue.length; i++) {
        var call = queue[i];
        if (call[0] == "$controllerProvider" &&
        call[1] == "register" &&
        call[2][0] == controllerName) {
            controllerProvider.register(controllerName, call[2][1]);
        }
    }
}

<commit_msg>Added functionality for changing the chat size<commit_after>function defaultNotificationFormat(txt){
    if(txt.substr(0,txt.indexOf("[")-1) == 0)
      return txt.substring(txt.indexOf("]:")+2);
    return txt.substr(0,txt.indexOf("[")-1) + ": " + txt.substring(txt.indexOf("]:")+2);
}
var templateToLoad;
templateToLoad = templateToLoad || "https://rawgit.com/ocbaker/SMFPack-Chatbox-Tools/settings-update/settingsTemplate.html";
var notificationSettings = {
    phrases: ["ocbaker", "oliver", "admin", "mods", "moderator", "baker", "swear", "language"],
    general: true,
    mentions: true,
    generalTimeout: 5 * 1000,
    mentionTimeout: 10 * 1000,
    notifyWhenChatActive: false,
    generalFormat: defaultNotificationFormat,
    mentionFormat: defaultNotificationFormat,
    chatHeight: 180
};
function loadChatbox(){
    Shoutbox_PutMsgs = function Shoutbox_PutMsgs(XMLDoc)
    {
        if (Shoutbox.msgs !== false)
            window.clearTimeout(Shoutbox.msgs);
        if (XMLDoc && XMLDoc.getElementsByTagName("banned")[0])
        {
            setOuterHTML(document.getElementById("shoutbox_banned"), '');
            document.getElementById("shoutbox_status").style.visibility = 'hidden';
            document.getElementById("shoutbox_message").value = '';
            document.getElementById("shoutbox_message").disabled = true;
            return window.alert(Shoutbox.lang.banned);
        }
        var error = false;
        if (XMLDoc && XMLDoc.getElementsByTagName("error")[0])
            error = XMLDoc.getElementsByTagName("error")[0].childNodes[0].nodeValue;
        if (!XMLDoc || !XMLDoc.getElementsByTagName("msgs")[0])
        {
            if (!Shoutbox.hide)
            {
                Shoutbox.msgs = window.setTimeout("Shoutbox_GetMsgs();", Shoutbox.refresh);
                Shoutbox.loading = false;
            }
            document.getElementById("shoutbox_status").style.visibility = 'hidden';
            if (error)
                window.alert(error);
            Shoutbox.first = false;
            return;
        }
        var toReset = !Shoutbox.first && XMLDoc.getElementsByTagName("reset")[0];
        if (!Shoutbox.ie)
        {
            if (toReset)
            {
                if (Shoutbox.msgdown)
                    setInnerHTML(document.getElementById("shoutbox_banned"), '

');
                else
                    setInnerHTML(document.getElementById("shoutbox_banned"), '

');
            }
            setOuterHTML(document.getElementById("shoutbox_msgs"), XMLDoc.getElementsByTagName("msgs")[0].childNodes[0].nodeValue);
        }
        else
        {
            var msgs = '';
            if (Shoutbox.msgdown)
            {
                msgs += '

';
                msgs += (toReset ? '' : getInnerHTML(document.getElementById("shoutbox_table"))) + XMLDoc.getElementsByTagName("msgs")[0].childNodes[0].nodeValue;
                msgs += '

';
            }
            else
            {
                msgs += '
';
                msgs += XMLDoc.getElementsByTagName("msgs")[0].childNodes[0].nodeValue + (toReset ? '' : getInnerHTML(document.getElementById("shoutbox_table")));
                msgs += '
';
            }
            setInnerHTML(document.getElementById("shoutbox_banned"), msgs);
        }
        if (toReset)
        {
            Shoutbox.currentmsg = 1;
            Shoutbox.countmsgs = Shoutbox.maxmsgs = 0;
        }
        var count = parseInt(XMLDoc.getElementsByTagName("count")[0].childNodes[0].nodeValue);
        if (Shoutbox.countmsgs + count > Shoutbox.keepmsgs)
        {
            for (var i = Shoutbox.currentmsg; i < Shoutbox.currentmsg + Shoutbox.countmsgs + count - Shoutbox.keepmsgs; i++)
                document.getElementById("shoutbox_row" + i).parentNode.removeChild(document.getElementById("shoutbox_row" + i));
            Shoutbox.currentmsg += Shoutbox.countmsgs + count - Shoutbox.keepmsgs;
        }
        Shoutbox.maxmsgs += count;
        Shoutbox.countmsgs = Shoutbox.countmsgs + count > Shoutbox.keepmsgs ? Shoutbox.keepmsgs : Shoutbox.countmsgs + count;
        if (!Shoutbox.hide)
        {
            Shoutbox.msgs = window.setTimeout("Shoutbox_GetMsgs();", Shoutbox.refresh);
            Shoutbox.loading = false;
        }
        document.getElementById("shoutbox_status").style.visibility = 'hidden';
        if (Shoutbox.msgdown && (document.getElementById("shoutbox_banned").scrollTop >= Shoutbox.scroll || Shoutbox.scroll == 0))
        {
            document.getElementById("shoutbox_banned").scrollTop = document.getElementById("shoutbox_banned").scrollHeight;
            document.getElementById("shoutbox_banned").scrollTop = document.getElementById("shoutbox_banned").scrollHeight;
            Shoutbox.scroll = document.getElementById("shoutbox_banned").scrollTop;
        }
        if (error)
            window.alert(error);
        if (!Shoutbox.first && XMLDoc.getElementsByTagName("newmsgs")[0]) {
            var msgs = $(XMLDoc.getElementsByTagName("msgs")[0].childNodes[0].nodeValue);
            if ((notificationSettings.notifyWhenChatActive || isHidden()) && (notificationSettings.general || notificationSettings.mentions))
                msgs.each(function(a, b, c) {
                    var txt = $(b).text();
                    if (txt != "") {
                        var stxt = txt.toLowerCase();
                        var found = false;
                        notificationSettings.phrases.forEach(function(phrase, i) {
                            if (!found && stxt.indexOf(phrase.toLowerCase()) != -1)
                                found = true;
                        });

                        if (found && notificationSettings.mentions)
                            notifyMe("LoE Chat Mention", notificationSettings.mentionFormat(txt), notificationSettings.mentionTimeout);
                        if (!(found && notificationSettings.mentions) && notificationSettings.general)
                            notifyMe("LoE Chat", notificationSettings.generalFormat(txt), notificationSettings.generalTimeout);
                    }

                });
            Shoutbox_NewMsgs();
        }
        Shoutbox.first = false;
    };
}

notifyMe = function notifyMe(title, msg, timeout) {
    // Let's check if the browser supports notifications
    if (!("Notification" in window)) {
        alert("This browser does not support desktop notification");
    }

    // Let's check whether notification permissions have alredy been granted
    else if (Notification.permission === "granted") {
        // If it's okay let's create a notification
        var notification = new Notification(title, {body: msg,icon: "https://pbs.twimg.com/profile_images/1910794026/LoE_Web_Logo2_400x400.png"});
        if (timeout != 0)
            setTimeout(function() {
                notification.close();
            }, timeout);
    }

    // Otherwise, we need to ask the user for permission
    else if (Notification.permission !== 'denied') {
        Notification.requestPermission(function(permission) {
            // If the user accepts, let's create a notification
            if (permission === "granted") {
                var notification = new Notification(title, {body: msg,icon: "https://pbs.twimg.com/profile_images/1910794026/LoE_Web_Logo2_400x400.png"});
                if (timeout != 0)
                    setTimeout(function() {
                        notification.close();
                    }, timeout);
            }
        });
    }

// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them any more.
}
function getHiddenProp() {
    var prefixes = ['webkit', 'moz', 'ms', 'o'];

    // if 'hidden' is natively supported just return it
    if ('hidden' in document)
        return 'hidden';

    // otherwise loop over all the known prefixes until we find one
    for (var i = 0; i < prefixes.length; i++) {
        if ((prefixes[i] + 'Hidden') in document)
            return prefixes[i] + 'Hidden';
    }

    // otherwise it's not supported
    return null;
}
function isHidden() {
    var prop = getHiddenProp();
    if (!prop)
        return false;

    return document[prop];
}

function loadSettings(localStorageService){

}

function loadAngular() {

    angular.module('Foo', ['LocalStorageModule'], function($controllerProvider) {
        controllerProvider = $controllerProvider;
    });
    // Bootstrap Foo
    angular.bootstrap($('#shoutbox'), ['Foo']);

    // .. time passes ..

    // Load javascript file with Ctrl controller
    var myApp = angular.module('Foo');
    myApp.config(function(localStorageServiceProvider) {
        localStorageServiceProvider
        .setPrefix('myApp')
        .setStorageType('localStorage')
        .setNotify(true, true)
    });
    myApp.controller('Ctrl', function($scope, $rootScope, localStorageService) {
        console.log(localStorageService);
        $scope.settings = notificationSettings;
        $scope.getChatStyle = function(){
            return {'height': $scope.settings.chatHeight + 'px', 'max-height': $scope.settings.chatHeight + 'px'};
        };
        console.log($scope);
        loadChatbox();
        notifyMe("LoE Chat", "Loaded Notifications", 10000);
    });
    // Load html file with content that uses Ctrl controller
    $('
').appendTo('#shoutbox .content');
    $('#shoutbox .content').attr("ng-controller","Ctrl");
    $('#shoutbox .content').attr("id","ctrl");
    $('#shoutbox_banned').attr("ng-style","getChatStyle()");
    $('#nSettings').load(templateToLoad, function() {
        registerController("Foo", "Ctrl");
        // compile the new element
        $('#shoutbox .content').injector().invoke(function($compile, $rootScope, localStorageService) {
            $compile($('#ctrl'))($rootScope);
            $rootScope.$apply();
        });
    });
}

var controllerProvider = null;

jQuery.getScript("//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.min.js", function() {
    jQuery.getScript("https://rawgit.com/grevory/angular-local-storage/master/dist/angular-local-storage.js", function() {
        loadAngular();
    });
});

// Register Ctrl controller manually
// If you can reference the controller function directly, just run:
// $controllerProvider.register(controllerName, controllerFunction);
// Note: I haven't found a way to get $controllerProvider at this stage
//    so I keep a reference from when I ran my module config
function registerController(moduleName, controllerName) {
    // Here I cannot get the controller function directly so I
    // need to loop through the module's _invokeQueue to get it
    var queue = angular.module(moduleName)._invokeQueue;
    for (var i = 0; i < queue.length; i++) {
        var call = queue[i];
        if (call[0] == "$controllerProvider" &&
        call[1] == "register" &&
        call[2][0] == controllerName) {
            controllerProvider.register(controllerName, call[2][1]);
        }
    }
}

<|endoftext|>


<commit_before>import _ from 'lodash';

const defaultMeta = { connected: true };

export default class PipeDescriptor {
  constructor() {
    // Interface
    this.type;
    this.pipe;
    this.inTransformer;
    this.outTransformer;
    this.errTransformer;
    this.meta;
  }

  setup(settings) {
    _.merge(this, settings);
    return this;
  }

  create(type, pipe, inTransformer, outTransformer, errTransformer, extra = {}) {
    const meta = { ...extra, ...defaultMeta}; // Additional info

    return this.setup({
      type,
      pipe,
      inTransformer,
      outTransformer,
      errTransformer,
      meta,
    });
  }

  args(newSetup = {}) {
    const {
      type,
      pipe,
      inTransformer,
      outTransformer,
      errTransformer,
      meta,
    } = _.merge({}, this, newSetup);

    return [type, pipe, inTransformer, outTransformer, errTransformer, meta];
  }

  replicate(customization = {}) {
    return new PipeDescriptor().setup(this).setup(customization);
  }
}

export const isPipeDescriptor = ref => ref instanceof PipeDescriptor;
<commit_msg>Improve PipeDescriptor transformers<commit_after>import _ from 'lodash';
import { pick } from './transformers/in';
import { append } from './transformers/out';

const defaultMeta = { connected: true };

function resolveInTransformer(transformer) {
  return _.isString(transformer) ? pick(transformer) : transformer;
}

function resolveOutTransformer(transformer) {
  return _.isString(transformer) ? append(transformer) : transformer;
}

export default class PipeDescriptor {
  constructor() {
    // Interface
    this.type;
    this.pipe;
    this.inTransformer;
    this.outTransformer;
    this.errTransformer;
    this.meta;
  }

  setup(settings) {
    _.merge(this, settings);
    return this;
  }

  /**
   * Create Pipe descriptor.
   * Process arguments optional values to required type.
   *
   * @param type {string}
   * @param pipe {function | Pipeline}
   * @param inTransformer {string | function}
   *  A string is converted to the pick transformer, a function is left as is.
   * @param outTransformerArg {string | function(result, stream)}
   *  A string is converted to the append transformer, a function is left as is.
   * @param errTransformerArg {string | function}
   *  Same as the outTransformer.
   * @param extra {object}
   * @returns {PipeDescriptor}
   */
  create(type, pipe, inTransformerArg, outTransformerArg, errTransformerArg, extra = {}) {
    const meta = { ...extra, ...defaultMeta}; // Additional info

    const inTransformer = resolveInTransformer(inTransformerArg);
    const outTransformer = resolveOutTransformer(outTransformerArg);
    const errTransformer = resolveOutTransformer(errTransformerArg);

    return this.setup({
      type,
      pipe,
      inTransformer,
      outTransformer,
      errTransformer,
      meta,
    });
  }

  args(newSetup = {}) {
    const {
      type,
      pipe,
      inTransformer,
      outTransformer,
      errTransformer,
      meta,
    } = _.merge({}, this, newSetup);

    return [type, pipe, inTransformer, outTransformer, errTransformer, meta];
  }

  replicate(customization = {}) {
    return new PipeDescriptor().setup(this).setup(customization);
  }
}

export const isPipeDescriptor = ref => ref instanceof PipeDescriptor;
<|endoftext|>


<commit_before>function swapImage(imageName, type)  {
  var newImage = "";

  if (type == "on")  {
    newImage = imageName + "-on";
  }
  else  {
    newImage = imageName + "-off";
  }

  if (document.images)  {
    document.images[imageName].src = 'images/' + newImage + '.gif';
  }
}
<commit_msg>javascript for dynamic menu.  Make uPortal website menu consistent with jasig.org<commit_after>function swapImage(imageName, type)  {
  var newImage = "";

  if (type == "on")  {
    newImage = imageName + "-on";
  }
  else  {
    newImage = imageName + "-off";
  }

  if (document.images)  {
    document.images[imageName].src = "images/" + newImage + ".gif";
  }
}<|endoftext|>


<commit_before>// 1. 두 수를 입력받아 큰 수를 반환하는 함수

// 1번째 안
/*
function bigger(a, b){ // 두개의 숫자를 비교하는 조건문 함수를 사용하여
  if (a > b) { //  a가 b보다 크다면
    console.log(a); // a를 출력한다.
  }else if (a === b){ // a와 b가 같은 수 라면
    console.log(a + "와" + b + "는 같은 수입니다."); // 'a와 b는 같은 수입니다.'를 출력한다.
  }
  else{ // 그렇지 않으면 ( a가 b보다 크지도 않고 같지도 않다면)
    console.log(b); // b를 출력한다.
  }
}
bigger(3, 3);
*/

function bigger(a, b){ // 두개의 숫자를 비교하는 조건문 함수를 사용하여
  if (a > b) { //  a가 b보다 크다면
    console.log(a); // a를 출력한다.
  } else{ // 그렇지 않으면 (a가 b보다 크지도 않고 같지도 않다면)
    console.log(b); // b를 출력한다.
  }
}
bigger(3, 7);

/*

// 2번째 안
// 두 수를 입력받아 큰 수를 반환하는 함수

function bigger(c, d) { // 두개의 숫자를 비교하는 조건문 함수를 사용하여
  var result;
  if (c > d) { // c가 d보다 크다면
    result = c; // c 이다.
  }

   // else if(c === d){ // 두개의 숫자가 같다면
   //   result = "입력한 수는" + c + "로 같은 수를 비교하였습니다."; // 같은 수를 입력하여 비교함을 알려준다. 리턴값에 문자열이 섞이면 오류가 날 확률이 크므로 일반적인 사용방법은 아니다. 수정필요함.
   //   }

  else{ // c가 d보다 작거나 같다면
    result = d; // d이다.
  }
  return result; // 결과를 반환한다.
}
console.log(bigger(3, 9)); // 숫자를 입력하여 결과값을 확인한다.

// bigger(3, 8); // 숫자를 입력하여 결과값을 확인한다.
<commit_msg> add solve another case<commit_after>// 1. 두 수를 입력받아 큰 수를 반환하는 함수

// 1번째 안
/*
function bigger(a, b){ // 두개의 숫자를 비교하는 조건문 함수를 사용하여
  if (a > b) { //  a가 b보다 크다면
    console.log(a); // a를 출력한다.
  }else if (a === b){ // a와 b가 같은 수 라면
    console.log(a + "와" + b + "는 같은 수입니다."); // 'a와 b는 같은 수입니다.'를 출력한다.
  }
  else{ // 그렇지 않으면 ( a가 b보다 크지도 않고 같지도 않다면)
    console.log(b); // b를 출력한다.
  }
}
bigger(3, 3);
*/

function bigger(a, b){ // 두개의 숫자를 비교하는 조건문 함수를 사용하여
  if (a > b) { //  a가 b보다 크다면
    console.log(a); // a를 출력한다.
  } else{ // 그렇지 않으면 (a가 b보다 크지도 않고 같지도 않다면)
    console.log(b); // b를 출력한다.
  }
}
bigger(3, 7);

// 2번째 안
// 두 수를 입력받아 큰 수를 반환하는 함수

function bigger(c, d) { // 두개의 숫자를 비교하는 조건문 함수를 사용하여
  var result;
  if (c > d) { // c가 d보다 크다면
    result = c; // c 이다.
  }

   // else if(c === d){ // 두개의 숫자가 같다면
   //   result = "입력한 수는" + c + "로 같은 수를 비교하였습니다."; // 같은 수를 입력하여 비교함을 알려준다. 리턴값에 문자열이 섞이면 오류가 날 확률이 크므로 일반적인 사용방법은 아니다. 수정필요함.
   //   }

  else{ // c가 d보다 작거나 같다면
    result = d; // d이다.
  }
  return result; // 결과를 반환한다.
}
console.log(bigger(3, 9)); // 숫자를 입력하여 결과값을 확인한다.

// bigger(3, 8); // 숫자를 입력하여 결과값을 확인한다.

// Math.max() Math 객체를 이용

console.log(Math.max(5, 9)); // 빌트인 함수 이용. 완료.

<|endoftext|>


<commit_before>/**
 * window.c.ProjectSuggestedContributions component
 * A Project-show page helper to show suggested amounts of contributions
 *
 * Example of use:
 * view: () => {
 *   ...
 *   m.component(c.ProjectSuggestedContributions, {project: project})
 *   ...
 * }
 */
import m from 'mithril';
import _ from 'underscore';
import projectVM from '../vms/project-vm';

const projectSuggestedContributions = {
    view: function({attrs}) {
        const project = attrs.project();

        const subscriptionSuggestionUrl = amount => `/projects/${project.project_id}/subscriptions/start?value=${amount * 100}`,
            contributionSuggestionUrl = amount => `/projects/${project.project_id}/contributions/new?value=${amount * 100}`,
            suggestionUrl = projectVM.isSubscription(project) ? subscriptionSuggestionUrl : contributionSuggestionUrl,
            suggestedValues = [10, 25, 50, 100];

        return m('#suggestions', _.map(suggestedValues, amount => project ? m(`${project.open_for_contributions ? `a[href="${suggestionUrl(amount)}"].card-reward` : ''}.card-big.card-secondary.u-marginbottom-20`, [
            m('.fontsize-larger', `R$ ${amount}`)
        ]) : ''));
    }
};

export default projectSuggestedContributions;
<commit_msg>Add center and increase suggested value font size<commit_after>/**
 * window.c.ProjectSuggestedContributions component
 * A Project-show page helper to show suggested amounts of contributions
 *
 * Example of use:
 * view: () => {
 *   ...
 *   m.component(c.ProjectSuggestedContributions, {project: project})
 *   ...
 * }
 */
import m from 'mithril';
import _ from 'underscore';
import projectVM from '../vms/project-vm';

const projectSuggestedContributions = {
    view: function({attrs}) {
        const project = attrs.project();

        const subscriptionSuggestionUrl = amount => `/projects/${project.project_id}/subscriptions/start?value=${amount * 100}`,
            contributionSuggestionUrl = amount => `/projects/${project.project_id}/contributions/new?value=${amount * 100}`,
            suggestionUrl = projectVM.isSubscription(project) ? subscriptionSuggestionUrl : contributionSuggestionUrl,
            suggestedValues = [10, 25, 50, 100];

        return m('#suggestions', _.map(suggestedValues, amount => project ? m(`${project.open_for_contributions ? `a[href="${suggestionUrl(amount)}"].card-reward` : ''}.card-big.u-text-center.card-secondary.u-marginbottom-20`, [
            m('.fontsize-jumbo', `R$ ${amount}`)
        ]) : ''));
    }
};

export default projectSuggestedContributions;
<|endoftext|>


<commit_before>//http://jsperf.com/isblank2
(function(_) {
  _.mixin({
    isBlank: function( val ) {
      if ( _.isNumber(val) && !_.isNaN(val) ) return false;
      if ( _.isDate(val) || _.isFunction(val) || _.isRegExp(val) ) return false;
      if ( _.isString(val) || _.isObject(val) ) return _.isEmpty(val);

      return (val ? false : true);
    },

    isPresent: function(val) {
      return !_.isBlank(val);
    }
  });
})(this._);
<commit_msg>FIX firefox _.isBlank isElement verification issue.<commit_after>//http://jsperf.com/isblank2
(function(_) {
  function validateObjectsWith(fn, val) {
    if ( _.isString(val) || (_.isArray(val) || fn(val)) ) return _.isEmpty(val);
  }

  _.mixin({
    isBlank: function( val ) {
      var objectValidation;

      if ( _.isNumber(val) && !_.isNaN(val) ) return false;

      if ( _.isPlainObject ) {
        objectValidation = validateObjectsWith(_.isPlainObject, val);
      } else {
        if ( _.isDate(val) || _.isFunction(val) || _.isRegExp(val) || _.isElement(val) ) return false;

        objectValidation = validateObjectsWith(_.isObject, val);
      }

      return ( objectValidation || (val ? false : true) );
    },

    isPresent: function(val) {
      return !_.isBlank(val);
    }
  });
})(this._);
<|endoftext|>


<commit_before>var mongo = require('mongodb');

exports.weather = function (context, entities) {
  exports.reply(context, "It's sunny, bitch.", 'sunny');
};

mongo.connect(process.env.MONGOLAB_URI, {}, function(error, db) {
  console.log('MongoLAB connected:', error);
  db.collection('users', function (err, users) {

    exports.set_service_username = function (context, entities) {
      if (!entities.service) {
        return exports.reply(context, 'Dude name a service');
      } else if (!entities.username) {
        return exports.reply(context, "I didn't catch your username");
      }

      var doc = { user_id: context.user_id, user_name: context.user_name };
      doc[entities.service.value] = entities.username.value;

      users.findAndModify({user_id: context.user_id}, doc, {upsert: true}, function (err, item) {
        if (err) {
          exports.reply(context, 'Error saving to mongo :(');
        } else {
          exports.reply(context, 'I gotcha, @' + context.user_name + '! ' +
              entities.username.value + ' on ' + entities.service.value);
        }
      });
    };

  });
});
<commit_msg>Add more identity intents<commit_after>var mongo = require('mongodb');

exports.weather = function (context, entities) {
  exports.reply(context, "It's sunny, bitch.", 'sunny');
};

mongo.connect(process.env.MONGOLAB_URI, {}, function(error, db) {
  console.log('MongoLAB connected:', error);
  db.collection('users', function (err, users) {

    exports.set_service_username = function (context, entities) {
      if (!entities.service) {
        return exports.reply(context, 'Dude name a service');
      } else if (!entities.username) {
        return exports.reply(context, "I didn't catch your username");
      }

      var doc = { user_id: context.user_id, user_name: context.user_name };
      doc['usernames.' + entities.service.value] = entities.username.value;

      users.update({user_id: context.user_id}, {$set:doc}, {upsert: true}, function (err, item) {
        if (err) {
          exports.reply(context, 'Error saving to mongo :(');
          console.log(err);
        } else {
          exports.reply(context, 'I gotcha, @' + context.user_name + '! ' +
              entities.username.value + ' on ' + entities.service.value);
        }
      });
    };

    exports.get_identity = function (context, entities) {
      users.findOne({user_id: context.user_id}, function (err, item) {
        if (err) {
          exports.reply(context, 'Error reading from mongo :(');
          console.log(err);
        } else if (!item || !item.usernames) {
          exports.reply(context, "I have no dirt on you, bro.");
        } else if (!entities.service) {
          exports.reply(context, "Your accounts: " + JSON.stringify(item.usernames));
        } else if (!item.usernames[entities.service.value]) {
          exports.reply(context, "You never told me your " + entities.service.value);
        } else {
          exports.reply(context, "Your " + entities.service.value + " is " + item.usernames[entities.service.value]);
        }
      });
    };

    exports.get_someones_username = function (context, entities) {
      if (!entities.service) {
        return exports.reply(context, 'Dude what service?');
      } else if (!entities.username) {
        return exports.reply(context, "I didn't catch a username");
      }

      users.findOne({user_name: entities.username.value}, function (err, item) {
        if (err) {
          exports.reply(context, 'Error reading from mongo :(');
          console.log(err);
        } else if (!item || !item.usernames) {
          exports.reply(context, "I have no dirt on " + entities.username.value + ", bro.");
        } else if (!item.usernames[entities.service.value]) {
          exports.reply(context, "No idea what " + entities.username.value + "'s " + entities.service.value + " is.");
        } else {
          exports.reply(context, entities.username.value + "'s " + entities.service.value + " is " + item.usernames[entities.service.value]);
        }
      });
    };
  });
});
<|endoftext|>


<commit_before>// To eliminate hard coding paths for require, we are modifying the NODE_PATH to include our lib folder
var oldpath = '';
if(process.env['NODE_PATH']!==undefined)
{
    oldpath = process.env['NODE_PATH'];
}

// Just in case already been set, leave it alone
process.env['NODE_PATH'] = ( __dirname + '/modules:' + __dirname + '/platforms:' + oldpath );
require('module').Module._initPaths();

var path 			= require( "path" );
var Promise			= require( "bluebird" );
var fs				= Promise.promisifyAll( require( "fs" ) );

var BoardInterface 	= require( "BoardInterface.js" );
var CPUInterface 	= require( "CPUInterface.js" );

var PlatformManager = function( name, deps )
{
	var self = this;

	this.platform = {};
	this.platform.systemDirectory = deps.config.systemDirectory;

	this.platform.board = new BoardInterface( deps );
	this.platform.cpu 	= new CPUInterface( deps );

	console.log( "PLATFORM: Loading platform interfaces..." );

	Promise.try( function()
	{
		// Load interfaces
		return Promise.try( function()
		{
			return LoadPlatformName( self.platform );
		} )
		// .then( LoadCPUInterface )
		// .then( LoadBoardInterface )
		// .then( function( platform )
		// {
		// 	console.log( "PLATFORM: Successfully loaded configuration for a supported platform." );
		// 	deps.globalEventLoop.emit( "platform.supported" );
		// })
		.catch( function( error )
		{
			//deps.globalEventLoop.emit( "platform.unsupported", error );
			console.error( "PLATFORM: Failed to load platform details for this system: " + error );
			throw new Error( "Failed to load platform details for this system: " + error );
		} );
	} )
	.catch(  function( error )
	{
		console.error( "What: " + JSON.stringify( err ) );
	} );
}

function LoadPlatformName( platform )
{
	console.log( "PLATFORM: Fetching platform name..." );

	if( process.env.PLATFORM !== undefined )
	{
		// Allow shortcut
		platform.name = process.env.PLATFORM;
		console.log( "PLATFORM: Platform shortcut set to: " + platform.name );

		return platform;
	}
	else
	{
		var platConfPath = path.resolve( platform.systemDirectory + "/config/platform.conf" );

		console.log( "PLATFORM: Opening platform conf file: " + platConfPath );

		return fs.readFileAsync( platConfPath, 'utf8' )
		.then( function( data )
		{
			console.log( "PLATFORM: Parsing platform conf" );

			// Parse platform info from configuration file
			var platInfo 	= JSON.parse( data );
			platform.name 	= platInfo.platform;

			console.log( "PLATFORM: Platform name: " + platform.name );

			return platform;
		} )
		.catch( function( err )
		{
			console.error( "Failed to load platform name: " + JSON.stringify( err ) );

			// Can't proceed if we can't determine the platform
			throw new Error( "Failed to load platform name: " + JSON.stringify( err ) );
		})
	}
};

// function LoadCPUInterface( platform )
// {
// 	console.log( "PLATFORM: Loading CPU interface..." );

// 	var CPUInterfaceLoader = require( "./platforms/" + platform.name + "/cpu.js" );

// 	return CPUInterfaceLoader.Compose( platform )
// 			.catch( function( err )
// 			{
// 				console.error( "Failed to load CPU interface: " + JSON.stringify( err ) );
// 				throw new Error( "Failed to load CPU interface: " + JSON.stringify( err ) );
// 			})
// 			.then( function()
// 			{
// 				return platform;
// 			})
// };

// function LoadBoardInterface( platform )
// {
// 	console.log( "PLATFORM: Loading Board interface..." );

// 	var BoardInterfaceLoader = require( "./platforms/" + platform.name + "/board.js" );

// 	return BoardInterfaceLoader.Compose( platform )
// 			.catch( function( err )
// 			{
// 				console.error( "Failed to load board interface: " + JSON.stringify( err ) );

// 				// Continue anyway. Board is optional to operation of cockpit
// 			} )
// 			.then( function()
// 			{
// 				return platform;
// 			});
// };

// Export provides the public interface
module.exports = function (name, deps)
{
	return new PlatformManager(name,deps);
};

<commit_msg>Modified catch in load platform name<commit_after>// To eliminate hard coding paths for require, we are modifying the NODE_PATH to include our lib folder
var oldpath = '';
if(process.env['NODE_PATH']!==undefined)
{
    oldpath = process.env['NODE_PATH'];
}

// Just in case already been set, leave it alone
process.env['NODE_PATH'] = ( __dirname + '/modules:' + __dirname + '/platforms:' + oldpath );
require('module').Module._initPaths();

var path 			= require( "path" );
var Promise			= require( "bluebird" );
var fs				= Promise.promisifyAll( require( "fs" ) );

var BoardInterface 	= require( "BoardInterface.js" );
var CPUInterface 	= require( "CPUInterface.js" );

var PlatformManager = function( name, deps )
{
	var self = this;

	this.platform = {};
	this.platform.systemDirectory = deps.config.systemDirectory;

	this.platform.board = new BoardInterface( deps );
	this.platform.cpu 	= new CPUInterface( deps );

	console.log( "PLATFORM: Loading platform interfaces..." );

	Promise.try( function()
	{
		// Load interfaces
		return Promise.try( function()
		{
			return LoadPlatformName( self.platform );
		} )
		// .then( LoadCPUInterface )
		// .then( LoadBoardInterface )
		// .then( function( platform )
		// {
		// 	console.log( "PLATFORM: Successfully loaded configuration for a supported platform." );
		// 	deps.globalEventLoop.emit( "platform.supported" );
		// })
		.catch( function( error )
		{
			//deps.globalEventLoop.emit( "platform.unsupported", error );
			console.error( "PLATFORM: Failed to load platform details for this system: " + error );
			throw new Error( "Failed to load platform details for this system: " + error );
		} );
	} )
	.catch(  function( error )
	{
		console.error( "What: " + JSON.stringify( err ) );
	} );
}

function LoadPlatformName( platform )
{
	console.log( "PLATFORM: Fetching platform name..." );

	if( process.env.PLATFORM !== undefined )
	{
		// Allow shortcut
		platform.name = process.env.PLATFORM;
		console.log( "PLATFORM: Platform shortcut set to: " + platform.name );

		return platform;
	}
	else
	{
		var platConfPath = path.resolve( platform.systemDirectory + "/config/platform.conf" );

		console.log( "PLATFORM: Opening platform conf file: " + platConfPath );

		return fs.readFileAsync( platConfPath, 'utf8' )
		.then( function( data )
		{
			console.log( "PLATFORM: Parsing platform conf" );

			// Parse platform info from configuration file
			var platInfo 	= JSON.parse( data );
			platform.name 	= platInfo.platform;

			console.log( "PLATFORM: Platform name: " + platform.name );

			return platform;
		} )
		.catch( function( err )
		{
			console.error( "Failed to load platform name: " );

			// Can't proceed if we can't determine the platform
			throw new Error( "Failed to load platform name: " );
		});
	}
};

// function LoadCPUInterface( platform )
// {
// 	console.log( "PLATFORM: Loading CPU interface..." );

// 	var CPUInterfaceLoader = require( "./platforms/" + platform.name + "/cpu.js" );

// 	return CPUInterfaceLoader.Compose( platform )
// 			.catch( function( err )
// 			{
// 				console.error( "Failed to load CPU interface: " + JSON.stringify( err ) );
// 				throw new Error( "Failed to load CPU interface: " + JSON.stringify( err ) );
// 			})
// 			.then( function()
// 			{
// 				return platform;
// 			})
// };

// function LoadBoardInterface( platform )
// {
// 	console.log( "PLATFORM: Loading Board interface..." );

// 	var BoardInterfaceLoader = require( "./platforms/" + platform.name + "/board.js" );

// 	return BoardInterfaceLoader.Compose( platform )
// 			.catch( function( err )
// 			{
// 				console.error( "Failed to load board interface: " + JSON.stringify( err ) );

// 				// Continue anyway. Board is optional to operation of cockpit
// 			} )
// 			.then( function()
// 			{
// 				return platform;
// 			});
// };

// Export provides the public interface
module.exports = function (name, deps)
{
	return new PlatformManager(name,deps);
};

<|endoftext|>


<commit_before>(function(){

    // Base class for Raphael charts
    // -----------------------------

    var RaphaelChart = Datawrapper.Visualizations.RaphaelChart = function() {};

    _.extend(RaphaelChart.prototype, Datawrapper.Visualizations.Base, {

        init: function() {
            this.__seriesElements = {};
            this.__seriesLabels = {};

            $('body').append('

');
        },

        setRoot: function(el) {
            this.__root = el;
            el.css({
                position: 'relative'
            });
        },

        initCanvas: function(canvas) {
            var me = this, el = me.__root, w = $(document).width();
            canvas = _.extend({
                w: w,
                h: me.getMaxChartHeight(el),
                rpad: me.theme.padding.right,
                lpad: me.theme.padding.left,
                bpad: me.theme.padding.bottom,
                tpad: me.theme.padding.top
            }, canvas);

            if (w <= 300) {
                canvas.bpad = canvas.tpad = canvas.lpad = canvas.rpad = 5;
            }

            canvas.root = el;
            canvas.paper = Raphael(el[0], canvas.w, canvas.h+2);
            //console.log(w, w-canvas.lpad-canvas.rpad);
            //canvas.paper.rect(canvas.lpad, canvas.tpad, canvas.w - canvas.lpad - canvas.rpad, canvas.h - canvas.tpad - canvas.bpad);
            el.height(canvas.h);
            $('.tooltip').hide();
            me.__canvas = canvas;
            return canvas;
        },

        onMouseMove: function(e) {
            var me = this,
                x = e.pageX,
                y = e.pageY,
                series = this.getSeriesByPoint(x, y),
                row = this.getDataRowByPoint(x, y);

            if (!series) {
                // nothing hovered
                clearTimeout(me.__mouseOverTimer);
                me.__mouseOutTimer = setTimeout(function() {
                    clearTimeout(me.__mouseOverTimer);
                    clearTimeout(me.__mouseOutTimer);
                    if (me.theme.hover) me.hoverSeries();
                    if (me.theme.tooltip) me.hideTooltip();
                }, 200);
            } else {
                if (me.__mouseOutTimer) clearTimeout(me.__mouseOutTimer);
                me.__mouseOverTimer = setTimeout(function() {
                    clearTimeout(me.__mouseOverTimer);
                    clearTimeout(me.__mouseOutTimer);
                    if (me.theme.hover) me.hoverSeries(series);
                    if (me.theme.tooltip) me.showTooltip(series, row, x, y);
                }, 100);
            }
        },

        registerSeriesElement: function(el, series) {
            el.data('series', series);
            if (!this.__seriesElements[series.name]) {
                this.__seriesElements[series.name] = [];
            }
            this.__seriesElements[series.name].push(el);
        },

        registerSeriesLabel: function(lbl, series) {
            lbl.data('series', series);
            if (!this.__seriesLabels[series.name]) {
                this.__seriesLabels[series.name] = [];
            }
            this.__seriesLabels[series.name].push(lbl);
        },

        hoverSeries: function(series) {
            var seriesElements = this.__seriesElements;
            _.each(seriesElements, function(elements, key) {
                var h = !series || key == series.name;
                _.each(elements, function(el) {
                    el.attr({ opacity: h ? 1 : 0.1 });
                });
            });

            var seriesLabels = this.__seriesLabels;
            _.each(seriesLabels, function(labels, key) {
                var h = !series || key == series.name;
                _.each(labels, function(lbl) {
                    lbl.css({ opacity: h ? 1 : 0.1 });
                    if (h) lbl.addClass('highlighted');
                });
            });
        },

        path: function(pathdata, className) {
            var p = this.__canvas.paper.path(pathdata);
            if (className && Raphael.svg) {
                $(p.node).attr('class', className);
            }
            return p;
        },

        label: function(x, y, txt, attrs) {
            var l, w, align, h, va;
            if (attrs === undefined) attrs = {};
            if (attrs.rotate == -90) {
                l = $('
'+txt+'
');
                w = 60;
                l.css({
                    position: 'absolute',
                    left: (x-w*0.5)+'px',
                    top: (y+12),
                    width: w,
                    height: 20,
                    'text-align': 'right'
                });
                l.css({
                    '-moz-transform': 'rotate(-90deg)',
                    '-webkit-transform': 'rotate(-90deg)',
                    '-ms-transform': 'rotate(-90deg)',
                    '-o-transform': 'rotate(-90deg)',
                    'filter': 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)'
                });
                this.__canvas.root.append(l);
            } else {
                va = attrs.valign;
                l = $('
'+txt+'
');
                w = attrs.w ? attrs.w : this.labelWidth(txt, attrs.cl);
                align = attrs.align ? attrs.align : 'left';
                x = align == 'left' ? x : align == 'center' ? x - w * 0.5 : x - w;
                l.css({
                    position: 'absolute',
                    left: x+'px',
                    'text-align': align
                });
                if (attrs.w) {
                    l.css({ width: w+'px' });
                }
                this.__canvas.root.append(l);
                h = attrs.h ? attrs.h : l.height();
                if (!va) va = 'middle';
                l.css({
                    top: (y-h*(va == 'top' ? 0 : va == 'middle' ? 0.5 : 1))+'px'
                });
            }
            return l;
        },

        labelWidth: function(txt, className) {
            // returns the width of a label
            var l = $('
'+txt+'
');
            this.__root.append(l);
            var w = $('span', l).width();
            l.remove();
            return w;
        },

        orderSeriesElements: function() {
            // put highlighted lines on top
            var me = this;
            _.each(me.chart.dataSeries(), function(series) {
                if (me.chart.isHighlighted(series)) {
                    _.each(me.__seriesElements[series.name], function(el) {
                        el.toFront();
                    });
                }
            });
        },

        getSeriesByPoint: function(x, y) {
            var el = this.__canvas.paper.getElementByPoint(x, y);
            return el && el.data('series') ? el.data('series') : null;
        },

        getDataRowByPoint: function(x, y) {
            // needs to be implemented by each visualization
            throw 'getDataRowByPoint() needs to be implemented by each visualization';
        },

        getSeriesColor: function(series, row, useNegativeColor) {
            var me = this,
                main = useNegativeColor && series.data[row] < 0 ? 'negative' : 'main',
                highlight = useNegativeColor && series.data[row] < 0 ? 'highlight-negative' : 'highlight';
            if (!me.chart.hasHighlight()) return me.theme.colors[main];
            return me.theme.colors[me.chart.isHighlighted(series) ? highlight : main];
        },

        getYTicks: function(h) {
            var me = this,
                yscale = me.__scales.y,
                ticks = yscale.ticks(h / 80),
                domain = me.__domain,
                bt = yscale(ticks[0]),
                tt = yscale(ticks[ticks.length-1]);

            if (Math.abs(yscale(domain[0]) - bt) < 30) ticks.shift();
            if (Math.abs(tt - yscale(domain[1])) < 30) ticks.pop();

            ticks.unshift(domain[0]);
            ticks.push(domain[1]);

            return ticks;
        }

    });

}).call(this);<commit_msg>line-charts: added x-value to tooltips<commit_after>(function(){

    // Base class for Raphael charts
    // -----------------------------

    var RaphaelChart = Datawrapper.Visualizations.RaphaelChart = function() {};

    _.extend(RaphaelChart.prototype, Datawrapper.Visualizations.Base, {

        init: function() {
            this.__seriesElements = {};
            this.__seriesLabels = {};

            $('body').append('

');
        },

        setRoot: function(el) {
            this.__root = el;
            el.css({
                position: 'relative'
            });
        },

        initCanvas: function(canvas) {
            var me = this, el = me.__root, w = $(document).width();
            canvas = _.extend({
                w: w,
                h: me.getMaxChartHeight(el),
                rpad: me.theme.padding.right,
                lpad: me.theme.padding.left,
                bpad: me.theme.padding.bottom,
                tpad: me.theme.padding.top
            }, canvas);

            if (w <= 300) {
                canvas.bpad = canvas.tpad = canvas.lpad = canvas.rpad = 5;
            }

            canvas.root = el;
            canvas.paper = Raphael(el[0], canvas.w, canvas.h+2);
            //console.log(w, w-canvas.lpad-canvas.rpad);
            //canvas.paper.rect(canvas.lpad, canvas.tpad, canvas.w - canvas.lpad - canvas.rpad, canvas.h - canvas.tpad - canvas.bpad);
            el.height(canvas.h);
            $('.tooltip').hide();
            me.__canvas = canvas;
            return canvas;
        },

        onMouseMove: function(e) {
            var me = this,
                x = e.pageX,
                y = e.pageY,
                series = this.getSeriesByPoint(x, y),
                row = this.getDataRowByPoint(x, y);

            if (!series) {
                // nothing hovered
                clearTimeout(me.__mouseOverTimer);
                me.__mouseOutTimer = setTimeout(function() {
                    clearTimeout(me.__mouseOverTimer);
                    clearTimeout(me.__mouseOutTimer);
                    if (me.theme.hover) me.hoverSeries();
                    if (me.theme.tooltip) me.hideTooltip();
                }, 200);
            } else {
                if (me.__mouseOutTimer) clearTimeout(me.__mouseOutTimer);
                me.__mouseOverTimer = setTimeout(function() {
                    clearTimeout(me.__mouseOverTimer);
                    clearTimeout(me.__mouseOutTimer);
                    if (me.theme.hover) me.hoverSeries(series);
                    if (me.theme.tooltip) me.showTooltip(series, row, x, y);
                }, 100);
            }
        },

        registerSeriesElement: function(el, series) {
            el.data('series', series);
            if (!this.__seriesElements[series.name]) {
                this.__seriesElements[series.name] = [];
            }
            this.__seriesElements[series.name].push(el);
        },

        registerSeriesLabel: function(lbl, series) {
            lbl.data('series', series);
            if (!this.__seriesLabels[series.name]) {
                this.__seriesLabels[series.name] = [];
            }
            this.__seriesLabels[series.name].push(lbl);
        },

        hoverSeries: function(series) {
            var seriesElements = this.__seriesElements;
            _.each(seriesElements, function(elements, key) {
                var h = !series || key == series.name;
                _.each(elements, function(el) {
                    el.attr({ opacity: h ? 1 : 0.1 });
                });
            });

            var seriesLabels = this.__seriesLabels;
            _.each(seriesLabels, function(labels, key) {
                var h = !series || key == series.name;
                _.each(labels, function(lbl) {
                    lbl.css({ opacity: h ? 1 : 0.1 });
                    if (h) lbl.addClass('highlighted');
                });
            });
        },

        path: function(pathdata, className) {
            var p = this.__canvas.paper.path(pathdata);
            if (className && Raphael.svg) {
                $(p.node).attr('class', className);
            }
            return p;
        },

        label: function(x, y, txt, attrs) {
            var l, w, align, h, va;
            if (attrs === undefined) attrs = {};
            if (attrs.rotate == -90) {
                l = $('
'+txt+'
');
                w = 60;
                l.css({
                    position: 'absolute',
                    left: (x-w*0.5)+'px',
                    top: (y+12),
                    width: w,
                    height: 20,
                    'text-align': 'right'
                });
                l.css({
                    '-moz-transform': 'rotate(-90deg)',
                    '-webkit-transform': 'rotate(-90deg)',
                    '-ms-transform': 'rotate(-90deg)',
                    '-o-transform': 'rotate(-90deg)',
                    'filter': 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)'
                });
                this.__canvas.root.append(l);
            } else {
                va = attrs.valign;
                l = $('
'+txt+'
');
                w = attrs.w ? attrs.w : this.labelWidth(txt, attrs.cl);
                align = attrs.align ? attrs.align : 'left';
                x = align == 'left' ? x : align == 'center' ? x - w * 0.5 : x - w;
                l.css({
                    position: 'absolute',
                    left: x+'px',
                    'text-align': align
                });
                if (attrs.w) {
                    l.css({ width: w+'px' });
                }
                this.__canvas.root.append(l);
                h = attrs.h ? attrs.h : l.height();
                if (!va) va = 'middle';
                l.css({
                    top: (y-h*(va == 'top' ? 0 : va == 'middle' ? 0.5 : 1))+'px'
                });
            }
            return l;
        },

        labelWidth: function(txt, className) {
            // returns the width of a label
            var l = $('
'+txt+'
');
            this.__root.append(l);
            var w = $('span', l).width();
            l.remove();
            return w;
        },

        orderSeriesElements: function() {
            // put highlighted lines on top
            var me = this;
            _.each(me.chart.dataSeries(), function(series) {
                if (me.chart.isHighlighted(series)) {
                    _.each(me.__seriesElements[series.name], function(el) {
                        el.toFront();
                    });
                }
            });
        },

        getSeriesByPoint: function(x, y) {
            var el = this.__canvas.paper.getElementByPoint(x, y);
            return el && el.data('series') ? el.data('series') : null;
        },

        getDataRowByPoint: function(x, y) {
            // needs to be implemented by each visualization
            throw 'getDataRowByPoint() needs to be implemented by each visualization';
        },

        getSeriesColor: function(series, row, useNegativeColor) {
            var me = this,
                main = useNegativeColor && series.data[row] < 0 ? 'negative' : 'main',
                highlight = useNegativeColor && series.data[row] < 0 ? 'highlight-negative' : 'highlight';
            if (!me.chart.hasHighlight()) return me.theme.colors[main];
            return me.theme.colors[me.chart.isHighlighted(series) ? highlight : main];
        },

        getYTicks: function(h) {
            var me = this,
                yscale = me.__scales.y,
                ticks = yscale.ticks(h / 80),
                domain = me.__domain,
                bt = yscale(ticks[0]),
                tt = yscale(ticks[ticks.length-1]);

            if (Math.abs(yscale(domain[0]) - bt) < 30) ticks.shift();
            if (Math.abs(tt - yscale(domain[1])) < 30) ticks.pop();

            ticks.unshift(domain[0]);
            ticks.push(domain[1]);

            return ticks;
        }

    });

}).call(this);<|endoftext|>


<commit_before>window.firebaseURL = "https://techfugees2015.firebaseio.com/"<commit_msg>Don't want this here.<commit_after><|endoftext|>


<commit_before>Ext.namespace('Kwf.Utils.YoutubePlayer');
Kwf.Utils.YoutubePlayer.isLoaded = false;
Kwf.Utils.YoutubePlayer.isCallbackCalled = false;
Kwf.Utils.YoutubePlayer.callbacks = [];

Kwf.Utils.YoutubePlayer.load = function(callback, scope)
{
    if (Kwf.Utils.YoutubePlayer.isCallbackCalled) {
        callback.call(scope || window);
        return;
    }
    Kwf.Utils.YoutubePlayer.callbacks.push({
        callback: callback,
        scope: scope
    });
    if (Kwf.Utils.YoutubePlayer.isLoaded) return;

    Kwf.Utils.YoutubePlayer.isLoaded = true;

    //workaround mediaelementjs also defining onYouTubePlayerAPIReady
    //placed here in load() so we are called after mediaelementjs
    var origOnYouTubePlayerAPIReady = window.onYouTubePlayerAPIReady;
    window.onYouTubePlayerAPIReady = function() {
        if (origOnYouTubePlayerAPIReady) origOnYouTubePlayerAPIReady();
        Kwf.Utils.YoutubePlayer.isCallbackCalled = true;
        Kwf.Utils.YoutubePlayer.callbacks.forEach(function(i) {
            i.callback.call(i.scope || window);
        });
    };

    var tag = document.createElement('script');
    tag.setAttribute('type', 'text/javascript');
    tag.setAttribute('src', 'http://www.youtube.com/iframe_api');
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
};

<commit_msg>get dynamicly if https or http is supported for youtube iframe api<commit_after>Ext.namespace('Kwf.Utils.YoutubePlayer');
Kwf.Utils.YoutubePlayer.isLoaded = false;
Kwf.Utils.YoutubePlayer.isCallbackCalled = false;
Kwf.Utils.YoutubePlayer.callbacks = [];

Kwf.Utils.YoutubePlayer.load = function(callback, scope)
{
    if (Kwf.Utils.YoutubePlayer.isCallbackCalled) {
        callback.call(scope || window);
        return;
    }
    Kwf.Utils.YoutubePlayer.callbacks.push({
        callback: callback,
        scope: scope
    });
    if (Kwf.Utils.YoutubePlayer.isLoaded) return;

    Kwf.Utils.YoutubePlayer.isLoaded = true;

    //workaround mediaelementjs also defining onYouTubePlayerAPIReady
    //placed here in load() so we are called after mediaelementjs
    var origOnYouTubePlayerAPIReady = window.onYouTubePlayerAPIReady;
    window.onYouTubePlayerAPIReady = function() {
        if (origOnYouTubePlayerAPIReady) origOnYouTubePlayerAPIReady();
        Kwf.Utils.YoutubePlayer.isCallbackCalled = true;
        Kwf.Utils.YoutubePlayer.callbacks.forEach(function(i) {
            i.callback.call(i.scope || window);
        });
    };

    var tag = document.createElement('script');
    tag.setAttribute('type', 'text/javascript');
    tag.setAttribute('src', '//www.youtube.com/iframe_api');
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
};

<|endoftext|>


<commit_before>const render = require('../../render')
const test = require('tape')
const parse = require('parse-element')
const strip = require('strip-formatting')
const s = require('brisky-struct')

test('any - sort', t => {
  const app = {
    types: {
      special: {
        type: 'style',
        fontSize: '40px',
        textAlign: 'center',
        padding: '5px',
        background: 'rgb(51, 51, 51)',
        color: 'rgb(238, 238, 238)',
        opacity: 1
      },
      holder: {
        style: {
          borderTop: '1px solid rgb(51, 51, 51)',
          padding: '50px',
          textAlign: 'center'
        },
        $: 'collection.$any',
        $any: (keys, state) => keys.concat().sort(
          (a, b) => state.get(a).compute() > state.get(b).compute() ? -1 : 1
        ).slice(0, 3),
        props: {
          default: {
            style: {
              type: 'special',
              display: 'inline-block',
              borderRadius: '50%',
              margin: '15px',
              width: '50px',
              height: '50px',
              color: { $: 'color' },
              something: { $: 'blurf' },
              fontWeight: { $: 'styles.weight' },
              transition: 'transform 0.5s',
              transform: {
                scale: { $: true, $transform: val => (5 + val) / 10 }
              }
            },
            text: { $: true },
            text2: { type: 'text', $: 'root.james' }
          }
        }
      }
    },
    props: {
      default: {
        type: 'holder'
      }
    },
    a: {},
    b: {},
    c: {
      $any: (keys, state) => keys.filter(val => state.get(val).compute() > 4)
    },
    hello: {
      type: 'element',
      hello: {
        $: 'query',
        style: {
          type: 'special'
        },
        text: { $: 'root.james' }
      }
    },
    d: {
      $any: {
        val: (keys, state) => {

          var x = keys.filter(
          val => {
            console.log('??????', val, state[val].compute(), state.root().query.compute() == state[val].compute(), state.root().james.compute() == state[val].compute())
            return state.root().query.compute() == state[val].compute() || state.root().james.compute() == state[val].compute()
          }
        )

          console.log(x)
          return x
        },
        root: {
          query: true,
          james: true
        },
        color: {
          val: true,
          smurf: true
        },
        blurf: 1,
        styles: { val: true }
        // same as well -- need to test
      }
    }
  }

  const state = s({
    collection: [ 1, 2, 3, 4, 5 ],
    query: 1,
    james: '!'
  })

  state.collection.set(state.collection.map(val => ({ val: val.compute(), color: 'rgb(' + val.compute() * 20 + ', 100, 100)' })))

  const elem = render(app, state, (a, b, c, s, t) => {
    if (s) console.warn(t, s.path())
  })

  var cnt = 0
  const defer = (val) => new Promise(resolve => {
    setTimeout(() => console.log('\nset!') || resolve(val), (++cnt))
  })

  state.collection.set(defer({ 0: 6 }))
  state.collection.set(defer({ 3: 7 }))
  state.collection.set(defer({ 4: 1 }))
  state.collection.set(defer({ 0: 1 }))
  state.query.set(defer(7))
  state.james.set(defer(1))

  if (document.body) {
    document.body.appendChild(elem)
  }

  const result = strip(`

71

31

21

71

31

21

71

1

11

71

11

`)

  state.james.once(1, () => {
    setTimeout(() => {
      t.equal(
        parse(elem),
        result
      )
      t.end()
    })
  })
})
<commit_msg>removed logs<commit_after>const render = require('../../render')
const test = require('tape')
const parse = require('parse-element')
const strip = require('strip-formatting')
const s = require('brisky-struct')

test('any - sort', t => {
  const app = {
    types: {
      special: {
        type: 'style',
        fontSize: '40px',
        textAlign: 'center',
        padding: '5px',
        background: 'rgb(51, 51, 51)',
        color: 'rgb(238, 238, 238)',
        opacity: 1
      },
      holder: {
        style: {
          borderTop: '1px solid rgb(51, 51, 51)',
          padding: '50px',
          textAlign: 'center'
        },
        $: 'collection.$any',
        $any: (keys, state) => keys.concat().sort(
          (a, b) => state.get(a).compute() > state.get(b).compute() ? -1 : 1
        ).slice(0, 3),
        props: {
          default: {
            style: {
              type: 'special',
              display: 'inline-block',
              borderRadius: '50%',
              margin: '15px',
              width: '50px',
              height: '50px',
              color: { $: 'color' },
              something: { $: 'blurf' },
              fontWeight: { $: 'styles.weight' },
              transition: 'transform 0.5s',
              transform: {
                scale: { $: true, $transform: val => (5 + val) / 10 }
              }
            },
            text: { $: true },
            text2: { type: 'text', $: 'root.james' }
          }
        }
      }
    },
    props: {
      default: {
        type: 'holder'
      }
    },
    a: {},
    b: {},
    c: {
      $any: (keys, state) => keys.filter(val => state.get(val).compute() > 4)
    },
    hello: {
      type: 'element',
      hello: {
        $: 'query',
        style: {
          type: 'special'
        },
        text: { $: 'root.james' }
      }
    },
    d: {
      $any: {
        val: (keys, state) => {
          var x = keys.filter(
            val => {
              return state.root().query.compute() == state[val].compute() || state.root().james.compute() == state[val].compute() //eslint-disable-line
            }
          )
          return x
        },
        root: {
          query: true,
          james: true
        },
        color: {
          val: true,
          smurf: true
        },
        blurf: 1,
        styles: { val: true }
        // same as well -- need to test
      }
    }
  }

  const state = s({
    collection: [ 1, 2, 3, 4, 5 ],
    query: 1,
    james: '!'
  })

  state.collection.set(state.collection.map(val => ({ val: val.compute(), color: 'rgb(' + val.compute() * 20 + ', 100, 100)' })))

  const elem = render(app, state)

  var cnt = 0
  const defer = (val) => new Promise(resolve => {
    setTimeout(() => resolve(val), (++cnt))
  })

  state.collection.set(defer({ 0: 6 }))
  state.collection.set(defer({ 3: 7 }))
  state.collection.set(defer({ 4: 1 }))
  state.collection.set(defer({ 0: 1 }))
  state.query.set(defer(7))
  state.james.set(defer(1))

  if (document.body) {
    document.body.appendChild(elem)
  }

  const result = strip(`

71

31

21

71

31

21

71

1

11

71

11

`)

  state.james.once(1, () => {
    setTimeout(() => {
      t.equal(
        parse(elem),
        result
      )
      t.end()
    })
  })
})
<|endoftext|>