<commit_before>let SettingsView = null
let settingsView = null

let statusView = null

const {CompositeDisposable} = require('atom')

const PackageManager = require('./package-manager')
let packageManager = null

const SnippetsProvider = {
  getSnippets() { return atom.config.scopedSettingsStore.propertySets }
}

const CONFIG_URI = 'atom://config'
const uriRegex = /config\/([a-z]+)\/?([a-zA-Z0-9_-]+)?/i

const openPanel = (settingsView, panelName, uri) => {
  const match = uriRegex.exec(uri)

  const options = {uri}
  if (match) {
    const panel = match[1]
    const detail = match[2]
    if (panel === 'packages' && detail != null) {
      panelName = detail
      options.pack = {name: detail}
      if (atom.packages.getLoadedPackage(detail)) options.back = 'Packages'
    }
  }

  settingsView.showPanel(panelName, options)
}

module.exports = {
  handleURI(parsed) {
    switch (parsed.pathname) {
      case '/show-package': this.showPackage(parsed.query.package)
    }
  },

  showPackage(packageName) {
    atom.workspace.open(`atom://config/packages/${packageName}`)
  },

  activate() {
    this.disposables = new ComositeDisposable()

    this.disposables.add(atom.workspace.addOpener(uri => {
      if (uri.startsWith(CONFIG_URI)) {
        if (settingsView == null || settingsView.destroyed) {
          settingsView = this.createSettingsView({uri})
        }

        const match = uriRegex.exec(uri)
        if (match) {
          let panelName = match[1]
          panelName = panelName[0].toUpperCase() + panelName.slice(1)
          openPanel(settingsView, panelName, uri)
        }
        return settingsView
      }
    }))

    this.dispsoables.add(atom.commands.add('atom-workspace', {
      'settings-view:open'() { atom.workspace.open(CONFIG_URI) },
      'settings-view:core'() { atom.workspace.open(`${CONFIG_URI}/core`) },
      'settings-view:editor'() { atom.workspace.open(`${CONFIG_URI}/editor`) },
      'settings-view:show-keybindings'() { atom.workspace.open(`${CONFIG_URI}/keybindings`) },
      'settings-view:change-themes'() { atom.workspace.open(`${CONFIG_URI}/themes`) },
      'settings-view:install-packages-and-themes'() { atom.workspace.open(`${CONFIG_URI}/install`) },
      'settings-view:view-installed-themes'() { atom.workspace.open(`${CONFIG_URI}/themes`) },
      'settings-view:uninstall-themes'() { atom.workspace.open(`${CONFIG_URI}/themes`) },
      'settings-view:view-installed-packages'() { atom.workspace.open(`${CONFIG_URI}/packages`) },
      'settings-view:uninstall-packages'() { atom.workspace.open(`${CONFIG_URI}/packages`) },
      'settings-view:check-for-package-updates'() { atom.workspace.open(`${CONFIG_URI}/updates`) }
    }))

    if (process.platform === 'win32' && require('atom').WinShell != null) {
      this.disposables.add(atom.commands.add('atom-workspace', {'settings-view:system'() { atom.workspace.open(`${CONFIG_URI}/system`) }}))
    }

    if (!localStorage.getItem('hasSeenDeprecatedNotification')) {
      if (packageManager == null) packageManager = new PackageManager()
      packageManager.getInstalled().then(packages => {
        if (packages.user && packages.user.length) this.showDeprecatedNotification(packages)
      })
    }
  },

  deactivate() {
    if (this.disposables) this.disposables.dispose()
    if (settingsView) settingsView.destroy()
    if (packageManager) packageManager.destroy()
    if (statusView) statusView.destroy()
    this.disposables = null
    settingsView = null
    packageManager = null
    statusView = null
  },

  consumeStatusBar(statusBar) {
    if (packageManager == null) packageManager = new PackageManager()
    packageManager.getOutdated().then(updates => {
      if (packageManager) {
        const PackageUpdatesStatusView = require('./package-updates-status-view')
        statusView = new PackageUpdatesStatusView()
        statusView.initialize(statusBar, packageManager, updates)
      }
    })
  },

  consumeSnippets(snippets) {
    if (typeof snippets.getUnparsedSnippets === 'function') {
      SnippetsProvider.getSnippets = snippets.getUnparsedSnippets.bind(snippets)
    }
  },

  createSettingsView(params) {
    if (SettingsView == null) SettingsView = require('./settings-view')
    if (packageManager == null) packageManager = new PackageManager()
    params.packageManager = packageManager
    params.snippetsProvider = SnippetsProvider
    settingsView = new SettingsView(params)
    return settingsView
  },

  showDeprecatedNotification(packages) {
    localStorage.setItem('hasSeenDeprecatedNotification', true)

    const deprecatedPackages = packages.user.filter(({name, version}) => atom.packages.isDeprecatedPackage(name, version))
    if (!deprecatedPackages.length) return

    let were = 'were'
    let have = 'have'
    let packageText = 'packages'
    if (packages.length === 1) {
      packageText = 'package'
      were = 'was'
      have = 'has'
    }

    const notification = atom.notifications.addWarning(`${deprecatedPackages.length} ${packageText} ${have} deprecations and ${were} not loaded.`, {
      description: 'This message will show only one time. Deprecated packages can be viewed in the settings view.',
      detail: (deprecatedPackages.map(pack => pack.name)).join(', '),
      dismissable: true,
      buttons: [{
        text: 'View Deprecated Packages',
        onDidClick() {
          atom.commands.dispatch(atom.views.getView(atom.workspace), 'settings-view:view-installed-packages')
          notification.dismiss()
        }
      }]
    })
  }
}
<commit_msg>:abc:<commit_after>let SettingsView = null
let settingsView = null

let statusView = null

const {CompositeDisposable} = require('atom')

const PackageManager = require('./package-manager')
let packageManager = null

const SnippetsProvider = {
  getSnippets() { return atom.config.scopedSettingsStore.propertySets }
}

const CONFIG_URI = 'atom://config'
const uriRegex = /config\/([a-z]+)\/?([a-zA-Z0-9_-]+)?/i

const openPanel = (settingsView, panelName, uri) => {
  const match = uriRegex.exec(uri)

  const options = {uri}
  if (match) {
    const panel = match[1]
    const detail = match[2]
    if (panel === 'packages' && detail != null) {
      panelName = detail
      options.pack = {name: detail}
      if (atom.packages.getLoadedPackage(detail)) options.back = 'Packages'
    }
  }

  settingsView.showPanel(panelName, options)
}

module.exports = {
  handleURI(parsed) {
    switch (parsed.pathname) {
      case '/show-package': this.showPackage(parsed.query.package)
    }
  },

  showPackage(packageName) {
    atom.workspace.open(`atom://config/packages/${packageName}`)
  },

  activate() {
    this.disposables = new CompositeDisposable()

    this.disposables.add(atom.workspace.addOpener(uri => {
      if (uri.startsWith(CONFIG_URI)) {
        if (settingsView == null || settingsView.destroyed) {
          settingsView = this.createSettingsView({uri})
        }

        const match = uriRegex.exec(uri)
        if (match) {
          let panelName = match[1]
          panelName = panelName[0].toUpperCase() + panelName.slice(1)
          openPanel(settingsView, panelName, uri)
        }
        return settingsView
      }
    }))

    this.disposables.add(atom.commands.add('atom-workspace', {
      'settings-view:open'() { atom.workspace.open(CONFIG_URI) },
      'settings-view:core'() { atom.workspace.open(`${CONFIG_URI}/core`) },
      'settings-view:editor'() { atom.workspace.open(`${CONFIG_URI}/editor`) },
      'settings-view:show-keybindings'() { atom.workspace.open(`${CONFIG_URI}/keybindings`) },
      'settings-view:change-themes'() { atom.workspace.open(`${CONFIG_URI}/themes`) },
      'settings-view:install-packages-and-themes'() { atom.workspace.open(`${CONFIG_URI}/install`) },
      'settings-view:view-installed-themes'() { atom.workspace.open(`${CONFIG_URI}/themes`) },
      'settings-view:uninstall-themes'() { atom.workspace.open(`${CONFIG_URI}/themes`) },
      'settings-view:view-installed-packages'() { atom.workspace.open(`${CONFIG_URI}/packages`) },
      'settings-view:uninstall-packages'() { atom.workspace.open(`${CONFIG_URI}/packages`) },
      'settings-view:check-for-package-updates'() { atom.workspace.open(`${CONFIG_URI}/updates`) }
    }))

    if (process.platform === 'win32' && require('atom').WinShell != null) {
      this.disposables.add(atom.commands.add('atom-workspace', {'settings-view:system'() { atom.workspace.open(`${CONFIG_URI}/system`) }}))
    }

    if (!localStorage.getItem('hasSeenDeprecatedNotification')) {
      if (packageManager == null) packageManager = new PackageManager()
      packageManager.getInstalled().then(packages => {
        if (packages.user && packages.user.length) this.showDeprecatedNotification(packages)
      })
    }
  },

  deactivate() {
    if (this.disposables) this.disposables.dispose()
    if (settingsView) settingsView.destroy()
    if (packageManager) packageManager.destroy()
    if (statusView) statusView.destroy()
    this.disposables = null
    settingsView = null
    packageManager = null
    statusView = null
  },

  consumeStatusBar(statusBar) {
    if (packageManager == null) packageManager = new PackageManager()
    packageManager.getOutdated().then(updates => {
      if (packageManager) {
        const PackageUpdatesStatusView = require('./package-updates-status-view')
        statusView = new PackageUpdatesStatusView()
        statusView.initialize(statusBar, packageManager, updates)
      }
    })
  },

  consumeSnippets(snippets) {
    if (typeof snippets.getUnparsedSnippets === 'function') {
      SnippetsProvider.getSnippets = snippets.getUnparsedSnippets.bind(snippets)
    }
  },

  createSettingsView(params) {
    if (SettingsView == null) SettingsView = require('./settings-view')
    if (packageManager == null) packageManager = new PackageManager()
    params.packageManager = packageManager
    params.snippetsProvider = SnippetsProvider
    settingsView = new SettingsView(params)
    return settingsView
  },

  showDeprecatedNotification(packages) {
    localStorage.setItem('hasSeenDeprecatedNotification', true)

    const deprecatedPackages = packages.user.filter(({name, version}) => atom.packages.isDeprecatedPackage(name, version))
    if (!deprecatedPackages.length) return

    let were = 'were'
    let have = 'have'
    let packageText = 'packages'
    if (packages.length === 1) {
      packageText = 'package'
      were = 'was'
      have = 'has'
    }

    const notification = atom.notifications.addWarning(`${deprecatedPackages.length} ${packageText} ${have} deprecations and ${were} not loaded.`, {
      description: 'This message will show only one time. Deprecated packages can be viewed in the settings view.',
      detail: (deprecatedPackages.map(pack => pack.name)).join(', '),
      dismissable: true,
      buttons: [{
        text: 'View Deprecated Packages',
        onDidClick() {
          atom.commands.dispatch(atom.views.getView(atom.workspace), 'settings-view:view-installed-packages')
          notification.dismiss()
        }
      }]
    })
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */

// Public node modules.
const _ = require('lodash');
const { ApolloServer } = require('apollo-server-koa');
const depthLimit = require('graphql-depth-limit');
const loadConfigs = require('./load-config');

module.exports = strapi => {
  const { appPath, installedPlugins } = strapi.config;

  return {
    beforeInitialize: async function() {
      // Try to inject this hook just after the others hooks to skip the router processing.
      if (!_.get(strapi.config.hook.load, 'after')) {
        _.set(strapi.config.hook.load, 'after', []);
      }

      strapi.config.hook.load.after.push('graphql');
      // Load core utils.

      const { api, plugins, extensions } = await loadConfigs({
        appPath,
        installedPlugins,
      });
      _.merge(strapi, { api, plugins });

      /*
       * Create a merge of all the GraphQL configuration.
       */
      const apisSchemas = Object.keys(strapi.api || {}).map(key =>
        _.get(strapi.api[key], 'config.schema.graphql', {})
      );

      const pluginsSchemas = Object.keys(strapi.plugins || {}).map(key =>
        _.get(strapi.plugins[key], 'config.schema.graphql', {})
      );

      const extensionsSchemas = Object.keys(extensions || {}).map(key =>
        _.get(extensions[key], 'config.schema.graphql', {})
      );

      // save the final schema in the plugin's config
      _.set(
        strapi,
        ['plugins', 'graphql', 'config', '_schema', 'graphql'],
        mergeSchemas([...apisSchemas, ...pluginsSchemas, ...extensionsSchemas])
      );
    },

    initialize: function() {
      const {
        typeDefs,
        resolvers,
      } = strapi.plugins.graphql.services.schema.generateSchema();

      if (_.isEmpty(typeDefs)) {
        strapi.log.warn(
          'The GraphQL schema has not been generated because it is empty'
        );

        return;
      }

      const serverParams = {
        typeDefs,
        resolvers,
        context: ({ ctx }) => {
          // Initiliase loaders for this request.
          // TODO: set loaders in the context not globally
          strapi.plugins.graphql.services.loaders.initializeLoader();

          return {
            context: ctx,
          };
        },
        validationRules: [depthLimit(strapi.plugins.graphql.config.depthLimit)],
        tracing: _.get(strapi.plugins.graphql, 'config.tracing', false),
        playground: false,
        cors: false,
        bodyParserConfig: true,
      };

      // Disable GraphQL Playground in production environment.
      if (
        strapi.config.environment !== 'production' ||
        strapi.plugins.graphql.config.playgroundAlways
      ) {
        serverParams.playground = {
          endpoint: strapi.plugins.graphql.config.endpoint,
          shareEnabled: strapi.plugins.graphql.config.shareEnabled
        };

        serverParams.introspection = true;
      }

      const server = new ApolloServer(serverParams);

      server.applyMiddleware({
        app: strapi.app,
        path: strapi.plugins.graphql.config.endpoint,
      });
    },
  };
};

/**
 * Merges a  list of schemas
 * @param {Array<Object>} schemas - The list of schemas to merge
 */
const mergeSchemas = schemas => {
  return schemas.reduce((acc, el) => {
    const { definition, query, mutation, type, resolver } = el;

    return _.merge(acc, {
      definition: `${acc.definition || ''} ${definition || ''}`,
      query: `${acc.query || ''} ${query || ''}`,
      mutation: `${acc.mutation || ''} ${mutation || ''}`,
      type,
      resolver,
    });
  }, {});
};
<commit_msg>Updated ApolloServer configuration for introspection queries (#4660)<commit_after>'use strict';

/**
 * Module dependencies
 */

// Public node modules.
const _ = require('lodash');
const { ApolloServer } = require('apollo-server-koa');
const depthLimit = require('graphql-depth-limit');
const loadConfigs = require('./load-config');

module.exports = strapi => {
  const { appPath, installedPlugins } = strapi.config;

  return {
    beforeInitialize: async function() {
      // Try to inject this hook just after the others hooks to skip the router processing.
      if (!_.get(strapi.config.hook.load, 'after')) {
        _.set(strapi.config.hook.load, 'after', []);
      }

      strapi.config.hook.load.after.push('graphql');
      // Load core utils.

      const { api, plugins, extensions } = await loadConfigs({
        appPath,
        installedPlugins,
      });
      _.merge(strapi, { api, plugins });

      /*
       * Create a merge of all the GraphQL configuration.
       */
      const apisSchemas = Object.keys(strapi.api || {}).map(key =>
        _.get(strapi.api[key], 'config.schema.graphql', {})
      );

      const pluginsSchemas = Object.keys(strapi.plugins || {}).map(key =>
        _.get(strapi.plugins[key], 'config.schema.graphql', {})
      );

      const extensionsSchemas = Object.keys(extensions || {}).map(key =>
        _.get(extensions[key], 'config.schema.graphql', {})
      );

      // save the final schema in the plugin's config
      _.set(
        strapi,
        ['plugins', 'graphql', 'config', '_schema', 'graphql'],
        mergeSchemas([...apisSchemas, ...pluginsSchemas, ...extensionsSchemas])
      );
    },

    initialize: function() {
      const {
        typeDefs,
        resolvers,
      } = strapi.plugins.graphql.services.schema.generateSchema();

      if (_.isEmpty(typeDefs)) {
        strapi.log.warn(
          'The GraphQL schema has not been generated because it is empty'
        );

        return;
      }

      const serverParams = {
        typeDefs,
        resolvers,
        context: ({ ctx }) => {
          // Initiliase loaders for this request.
          // TODO: set loaders in the context not globally
          strapi.plugins.graphql.services.loaders.initializeLoader();

          return {
            context: ctx,
          };
        },
        validationRules: [depthLimit(strapi.plugins.graphql.config.depthLimit)],
        tracing: _.get(strapi.plugins.graphql, 'config.tracing', false),
        playground: false,
        cors: false,
        bodyParserConfig: true,
        introspection: _.get(
          strapi.plugins.graphql,
          'config.introspection',
          true
        ),
      };

      // Disable GraphQL Playground in production environment.
      if (
        strapi.config.environment !== 'production' ||
        strapi.plugins.graphql.config.playgroundAlways
      ) {
        serverParams.playground = {
          endpoint: strapi.plugins.graphql.config.endpoint,
          shareEnabled: strapi.plugins.graphql.config.shareEnabled,
        };
      }

      const server = new ApolloServer(serverParams);

      server.applyMiddleware({
        app: strapi.app,
        path: strapi.plugins.graphql.config.endpoint,
      });
    },
  };
};

/**
 * Merges a  list of schemas
 * @param {Array<Object>} schemas - The list of schemas to merge
 */
const mergeSchemas = schemas => {
  return schemas.reduce((acc, el) => {
    const { definition, query, mutation, type, resolver } = el;

    return _.merge(acc, {
      definition: `${acc.definition || ''} ${definition || ''}`,
      query: `${acc.query || ''} ${query || ''}`,
      mutation: `${acc.mutation || ''} ${mutation || ''}`,
      type,
      resolver,
    });
  }, {});
};
<|endoftext|>


<commit_before>"use strict";

const Handler = require('../../router/handler');
const isEmptyObject = require('../../../util/isEmptyObject');

class SessionHandler extends Handler {
  async init(context) {
    let Session = context.engine.pluginRegistry.get('Session');

    // Use a Promise just to clean up the code execution flow.
    // TODO: Rework.
    await new Promise(async(accept, reject) => {
      let currentTime = Math.round(new Date().getTime() / 1000),
          newExpiration = currentTime + Session.sessionLifetime;

      // Try to load a session if it exists.
      await Session.sessionReader(context.request, context.response);

      if ((!context.request.sessionId) || (!context.request.sessionId.id)) {
        // No session exists, so create one.
        await Session.generateSession(context);
        return accept();
      }

      // The connection claims a session.  Is it already loaded?
      if (Session.sessions[context.request.sessionId.id]) {
        let session = Session.sessions[context.request.sessionId.id];
        // Has the session expired?
        if (currentTime > session.expire) {
          delete Session.sessions[session.id];
          await Session.deleteSessionFile(session.id);
          await Session.generateSession(context);
          return accept();
        }
        // Update the session.
        session.expire = newExpiration;
        await Session.writeSessionFile(session);
        context.session = session;
        return accept();
      }

      // The session does not exist in memory.  Try to load it from a file.
      let session = await Session.readSessionFile(context.request.sessionId.id);
      if (!session || isEmptyObject(session)) {
        await Session.generateSession(context);
        return accept();
      }

      // Has the session expired?
      if (currentTime > session.expire) {
        await Session.deleteSessionFile(session.id);
        await Session.generateSession(context);
        return accept();
      }

      // The session exists.  Update it.
      Session.sessions[session.id] = session;
      session.expire = newExpiration;
      await Session.writeSessionFile(session);
      context.session = session;
    });

    // Set the volatile session object.
    if (!Session.volatile[context.session.id]) {
      Session.volatile[context.session.id] = {};
    }
    context.volatile = Session.volatile[context.session.id];
  }
}

SessionHandler.id = 'Session.SessionHandler';
SessionHandler.path = '';
SessionHandler.weight = -550;

module.exports = SessionHandler;
<commit_msg>Bugfix: missing Promise accept() in Session<commit_after>"use strict";

const Handler = require('../../router/handler');
const isEmptyObject = require('../../../util/isEmptyObject');

class SessionHandler extends Handler {
  async init(context) {
    let Session = context.engine.pluginRegistry.get('Session');

    // Use a Promise just to clean up the code execution flow.
    // TODO: Rework.
    await new Promise(async(accept, reject) => {
      let currentTime = Math.round(new Date().getTime() / 1000),
          newExpiration = currentTime + Session.sessionLifetime;

      // Try to load a session if it exists.
      await Session.sessionReader(context.request, context.response);

      if ((!context.request.sessionId) || (!context.request.sessionId.id)) {
        // No session exists, so create one.
        await Session.generateSession(context);
        return accept();
      }

      // The connection claims a session.  Is it already loaded?
      if (Session.sessions[context.request.sessionId.id]) {
        let session = Session.sessions[context.request.sessionId.id];
        // Has the session expired?
        if (currentTime > session.expire) {
          delete Session.sessions[session.id];
          await Session.deleteSessionFile(session.id);
          await Session.generateSession(context);
          return accept();
        }
        // Update the session.
        session.expire = newExpiration;
        await Session.writeSessionFile(session);
        context.session = session;
        return accept();
      }

      // The session does not exist in memory.  Try to load it from a file.
      let session = await Session.readSessionFile(context.request.sessionId.id);
      if (!session || isEmptyObject(session)) {
        await Session.generateSession(context);
        return accept();
      }

      // Has the session expired?
      if (currentTime > session.expire) {
        await Session.deleteSessionFile(session.id);
        await Session.generateSession(context);
        return accept();
      }

      // The session exists.  Update it.
      Session.sessions[session.id] = session;
      session.expire = newExpiration;
      await Session.writeSessionFile(session);
      context.session = session;
      return accept();
    });

    // Set the volatile session object.
    if (!Session.volatile[context.session.id]) {
      Session.volatile[context.session.id] = {};
    }
    context.volatile = Session.volatile[context.session.id];
  }
}

SessionHandler.id = 'Session.SessionHandler';
SessionHandler.path = '';
SessionHandler.weight = -550;

module.exports = SessionHandler;
<|endoftext|>


<commit_before>/*
* Created by: Master Float.
* Edited by: Kevinxzllz
*/

'use strict';

let fs = require('fs');
let path = require('path');
let selectors;

function writeIconCSS() {
	fs.appendFile('config/custom.css', selectors);
}

function logMoney(message) {
	if (!message) return;
	let file = path.join(__dirname, '../logs/money.txt');
	let date = "[" + new Date().toUTCString() + "] ";
	let msg = message + "\n";
	fs.appendFile(file, date + msg);
}

exports.commands = {
	seticon: function (target, room, user) {
		if (!this.can('ban')) return this.errorReply("Access denied.");

		let args = target.split(',');
		if (args.length < 3) return this.parse('/help seticon');
		let username = toId(args.shift());
		let image = 'background: rgba(244, 244, 244, 0.8) url("' + args.shift().trim() + '") right no-repeat;';
		selectors = '\n\n' + '  #' + toId(args.shift()) + '-userlist-user-' + username;
		args.forEach(function (room) {
			selectors += ', #' + toId(room) + '-userlist-user-' + username;
		});
		selectors += ' { \n' + '    ' + image +  '\n  }';

		logMoney(user.name + " has set an icon to " + username + ".");
		this.privateModCommand("(" + user.name + " has set an icon to  " + username + ")");
		Rooms('staff').add('|raw|' + user.name + " has set an icon to " + username +  ".").update();
		writeIconCSS();
	},
	seticonhelp: ["/seticon [username], [image], [room 1], [room 2], etc. - Sets an icon to a user in chosen rooms."],
};
<commit_msg>Update seticon.js<commit_after>/*
* Created by: Master Float.
* Edited by: Kevinxzllz
*/

'use strict';

let fs = require('fs');
let path = require('path');
let selectors;

function writeIconCSS() {
	fs.appendFile('config/custom.css', selectors);
}

function logMoney(message) {
	if (!message) return;
	let file = path.join(__dirname, '../logs/money.txt');
	let date = "[" + new Date().toUTCString() + "] ";
	let msg = message + "\n";
	fs.appendFile(file, date + msg);
}

exports.commands = {
	seticon: function (target, room, user) {
		if (!this.can('ban')) return this.errorReply("Access denied.");

		let args = target.split(',');
		if (args.length < 3) return this.parse('/help seticon');
		let username = toId(args.shift());
		let image = 'background: rgba(153, 0, 0, 0.3) url("' + args.shift().trim() + '") right no-repeat;';
		selectors = '\n\n' + '  #' + toId(args.shift()) + '-userlist-user-' + username;
		args.forEach(function (room) {
			selectors += ', #' + toId(room) + '-userlist-user-' + username;
		});
		selectors += ' { \n' + '    ' + image +  '\n  }';

		logMoney(user.name + " has set an icon to " + username + ".");
		this.privateModCommand("(" + user.name + " has set an icon to  " + username + ")");
		Rooms('staff').add('|raw|' + user.name + " has set an icon to " + username +  ".").update();
		writeIconCSS();
	},
	seticonhelp: ["/seticon [username], [image], [room 1], [room 2], etc. - Sets an icon to a user in chosen rooms."],
};
<|endoftext|>


<commit_before>import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import {reducer as reduxAsyncConnect} from 'redux-connect';
import blog from './blog.js';
import monitor from './monitor.js';
import statistics from './statistics.js';

export default combineReducers({
  routing: routerReducer,
  reduxAsyncConnect,
  blog,
  monitor
});
<commit_msg>Removed statistics reference in reducer.<commit_after>import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import {reducer as reduxAsyncConnect} from 'redux-connect';
import blog from './blog.js';
import monitor from './monitor.js';

export default combineReducers({
  routing: routerReducer,
  reduxAsyncConnect,
  blog,
  monitor
});
<|endoftext|>


<commit_before>'use strict';
var self = require('sdk/self');
var notifications = require('sdk/notifications');

exports.main = function() {
    require('sdk/page-mod').PageMod({
        include: [
        /.*memrise\.com\/course\/\d{1,}\/.*\/edit\/database\/.*/
        ],
        contentScriptFile: [
            self.data.url('zepto.min.js'),
            self.data.url('page-mod/addInput.js'),
            self.data.url('page-mod/jsonTool.js'),
            self.data.url('page-mod/upload.js')
        ],
        onAttach: function (worker) {
            console.log('prova andata bene');
            worker.port.on('upload', function () {
                worker.port.emit('filetype');
            });
            worker.port.on('audio', function () {
                worker.port.emit('upload', {
                    'tipo' : '.audio'
                });
            });
            worker.port.on('image', function () {
                worker.port.emit('upload', {
                    'tipo' : '.image'
                });
            });

            worker.port.on('list populated', function (obj) {
                worker.port.emit('list_avaiable', obj);
            });
            worker.port.on('list empty', function () {
                notifications.notify({
                        title: 'No words detected',
                        text: 'Please add words to your database',
                        iconURL: self.data.url('img/memrise-icon-32.ico')
                });
            });
            worker.port.on('Uploaded', function () {
                    notifications.notify({
                        title: 'Uploaded',
                        text: 'Matching files have been uploaded.',
                        iconURL: self.data.url('img/memrise-icon-32.ico')
                });
            });
            worker.port.on('No appropriate column', function () {
                var notifications = require('sdk/notifications');
                    notifications.notify({
                        title: 'No audio column detected',
                        text: 'Please add the correct column to your database.',
                        iconURL: self.data.url('img/memrise-icon-32.ico')
                });
            });
            worker.port.on('help', function () {
                require('sdk/tabs').open(self.data.url('index.html'));
            });
        }
    });
};<commit_msg>from data/zepto.min.js to data/zepto/zepto.min.js<commit_after>'use strict';
var self = require('sdk/self');
var notifications = require('sdk/notifications');

exports.main = function() {
    require('sdk/page-mod').PageMod({
        include: [
        /.*memrise\.com\/course\/\d{1,}\/.*\/edit\/database\/.*/
        ],
        contentScriptFile: [
            self.data.url('zepto/zepto.min.js'),
            self.data.url('page-mod/addInput.js'),
            self.data.url('page-mod/jsonTool.js'),
            self.data.url('page-mod/upload.js')
        ],
        onAttach: function (worker) {
            console.log('prova andata bene');
            worker.port.on('upload', function () {
                worker.port.emit('filetype');
            });
            worker.port.on('audio', function () {
                worker.port.emit('upload', {
                    'tipo' : '.audio'
                });
            });
            worker.port.on('image', function () {
                worker.port.emit('upload', {
                    'tipo' : '.image'
                });
            });

            worker.port.on('list populated', function (obj) {
                worker.port.emit('list_avaiable', obj);
            });
            worker.port.on('list empty', function () {
                notifications.notify({
                        title: 'No words detected',
                        text: 'Please add words to your database',
                        iconURL: self.data.url('img/memrise-icon-32.ico')
                });
            });
            worker.port.on('Uploaded', function () {
                    notifications.notify({
                        title: 'Uploaded',
                        text: 'Matching files have been uploaded.',
                        iconURL: self.data.url('img/memrise-icon-32.ico')
                });
            });
            worker.port.on('No appropriate column', function () {
                var notifications = require('sdk/notifications');
                    notifications.notify({
                        title: 'No audio column detected',
                        text: 'Please add the correct column to your database.',
                        iconURL: self.data.url('img/memrise-icon-32.ico')
                });
            });
            worker.port.on('help', function () {
                require('sdk/tabs').open(self.data.url('index.html'));
            });
        }
    });
};<|endoftext|>


<commit_before>(function (window, $) {

    function resizeCanvas(canvas) {
        var ratio =  window.devicePixelRatio || 1;
        canvas.width = canvas.offsetWidth * ratio;
        canvas.height = canvas.offsetHeight * ratio;
        canvas.getContext("2d").scale(ratio, ratio);
    }

    $.fn.signatureWidget = function (options) {
        return this.each(function () {
            var input = $(this);
            var ts = Date.now();

            options = $.extend({
                'canvasClass' :  'signaturePad',
                'modal' : {
                    'title' : 'Sign Below',
                    'buttons' : [
                        '<button type="button" class="btn btn-default sig-clear">Clear</button>',
                        '<button type="button" class="btn btn-primary sig-save">Save</button>',
                    ]
                },
            }, options);

            var toggleContent =  "Click here to sign";

            var tpl = [
                "",
                toggleContent,
                "",
                "
",
                "
",
                "
",
                "
",
                "<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">×</button>",
                "
"+options.modal.title+"
",
                "
",
                "
",
                "<canvas id=\""+ts+"_canvas\" class=\""+options.canvasClass+"\" />",
                "
",
                "
",
                options.modal.buttons.join(' '),
                "

"
            ];

            input.after(tpl.join(' '));

            var modal = $('#'+ts+'_modal');
            var canvas = modal.find('canvas').get(0);
            var signaturePad = new SignaturePad(canvas);
            var toggle = $('#'+ts+'_toggle');

            modal.data('initialized', false);
            /**
             * When modal is shown
             */
            modal.on('shown.bs.modal', function () {
                if (modal.data('initialized') == false) {
                    resizeCanvas(canvas);
                }
                var value = input.val();
                if (value && 0 < value.length) {
                    signaturePad.fromDataURL(input.val());
                }
            });

            /**
             * Click the save button
             */
            modal.delegate('.sig-save', 'click', function (e) {
                if (!signaturePad.isEmpty()) {
                    var data = signaturePad.toDataURL();
                    input.val(data);
                    toggle.html('');
                }

                modal.modal('hide');
            });

            /**
             * Click the clear button
             */
            modal.delegate('.sig-clear', 'click', function (e) {
                signaturePad.clear();
                input.val('');
                toggle.html(toggleContent);
            });

            modal.on('hide.bs.modal', function () {
                signaturePad.clear();
            });
        });
    };
})(window, jQuery);<commit_msg>Fixing bug - signature wasnt being displayed on page load<commit_after>(function (window, $) {

    function resizeCanvas(canvas) {
        var ratio =  window.devicePixelRatio || 1;
        canvas.width = canvas.offsetWidth * ratio;
        canvas.height = canvas.offsetHeight * ratio;
        canvas.getContext("2d").scale(ratio, ratio);
    }

    $.fn.signatureWidget = function (options) {
        return this.each(function () {
            var input = $(this);
            var ts = Date.now();
            var data = input.val();
            var toggleContent = "Click here to sign";

            options = $.extend({
                'canvasClass' :  'signaturePad',
                'modal' : {
                    'title' : 'Sign Below',
                    'buttons' : [
                        '<button type="button" class="btn btn-default sig-clear">Clear</button>',
                        '<button type="button" class="btn btn-primary sig-save">Save</button>',
                    ]
                },
            }, options);

            var tpl = [
                "",
                (data !== '' && data.length > 0) ? '' : toggleContent,
                "",
                "
",
                "
",
                "
",
                "
",
                "<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">×</button>",
                "
"+options.modal.title+"
",
                "
",
                "
",
                "<canvas id=\""+ts+"_canvas\" class=\""+options.canvasClass+"\" />",
                "
",
                "
",
                options.modal.buttons.join(' '),
                "

"
            ];

            input.after(tpl.join(' '));

            var modal = $('#'+ts+'_modal');
            var canvas = modal.find('canvas').get(0);
            var signaturePad = new SignaturePad(canvas);
            var toggle = $('#'+ts+'_toggle');

            modal.data('initialized', false);
            /**
             * When modal is shown
             */
            modal.on('shown.bs.modal', function () {
                if (modal.data('initialized') == false) {
                    resizeCanvas(canvas);
                }
                var value = input.val();
                if (value && 0 < value.length) {
                    signaturePad.fromDataURL(input.val());
                }
            });

            /**
             * Click the save button
             */
            modal.delegate('.sig-save', 'click', function (e) {
                if (!signaturePad.isEmpty()) {
                    var data = signaturePad.toDataURL();
                    input.val(data);
                    toggle.html('');
                }

                modal.modal('hide');
            });

            /**
             * Click the clear button
             */
            modal.delegate('.sig-clear', 'click', function (e) {
                signaturePad.clear();
                input.val('');
                toggle.html(toggleContent);
            });

            modal.on('hide.bs.modal', function () {
                signaturePad.clear();
            });
        });
    };
})(window, jQuery);<|endoftext|>


<commit_before>// Load in dependencies
var EventEmitter = require('events').EventEmitter;
var inherits = require('inherits');
var Keyboard = require('./keyboard');
var Mouse = require('./mouse');

// Define bind method
function bind(context, fn) {
  return function bindFn () {
    return fn.apply(context, arguments);
  };
}

// Define our constructor
function GoogleMusic(win) {
  // If win was not provided, complain
  if (!win) {
    throw new Error('`win` was not provided to the `GoogleMusic` constructor');
  }

  // Inherit from EventEmitter
  EventEmitter.call(this);

  // Localize reference to window and document
  this.win = win;
  this.doc = win.document;

  // Initialize a keyboard and mouse
  this.keyboard = new Keyboard(win);
  this.mouse = new Mouse(win);

  // For each of the prototype sections
  var proto = GoogleMusic._protoObj;
  for (var protoKey in proto) {
    if (proto.hasOwnProperty(protoKey)) {
      // Define a key on our object
      this[protoKey] = {};

      // For each of the keys on the section, define a function that invokes on this original context
      var section = proto[protoKey];
      for (var sectionKey in section) {
        if (section.hasOwnProperty(sectionKey)) {
          this[protoKey][sectionKey] = bind(this, section[sectionKey]);
        }
      }

      // If there was an `init` method, run it
      if (this[protoKey].init) {
        this[protoKey].init();
      }
    }
  }
}
// Inherit from EventEmitter normally
inherits(GoogleMusic, EventEmitter);

// Define a "prototype" that will have magical invocation
var proto = GoogleMusic._protoObj = {};

// Create a volume API
proto.volume = {
  // Query required elements
  init: function () {
    this.volume._sliderEl = this.doc.querySelector('#vslider');
  },

  // Get the current volume level.
  getVolume: function () {
    return parseInt(this.volume._sliderEl.getAttribute('aria-valuenow'), 10);
  },

  // Set the volume level (0 - 100).
  setVolume: function (vol) {
    var current = this.volume.getVolume();

    if (vol > current) {
      this.volume.increaseVolume(vol - current);
    } else if (vol < current) {
      this.volume.decreaseVolume(current - vol);
    }
  },

  // Increase the volume by an amount (default of 1)
  increaseVolume: function (amount) {
    if (amount === undefined) {
      amount = 1;
    }

    for (var i = 0; i < amount; i++) {
      this.keyboard.sendKey(this.volume._sliderEl, Keyboard.KEY_UP);
    }
  },

  // Decrease the volume by an amount (default of 1)
  decreaseVolume: function (amount) {
    if (amount === undefined) {
      amount = 1;
    }

    for (var i = 0; i < amount; i++) {
      this.keyboard.sendKey(this.volume._sliderEl, Keyboard.KEY_DOWN);
    }
  }
};

// Create a playback API and constants
GoogleMusic.Playback = {
  // Playback states
  STOPPED: 0,
  PAUSED: 1,
  PLAYING: 2,

  // Repeat modes
  LIST_REPEAT: 'LIST_REPEAT',
  SINGLE_REPEAT: 'SINGLE_REPEAT',
  NO_REPEAT: 'NO_REPEAT',

  // Shuffle modes
  ALL_SHUFFLE: 'ALL_SHUFFLE',
  NO_SHUFFLE: 'NO_SHUFFLE'
};
proto.playback = {
  // Query references to the media playback elements
  init: function () {
    this.playback._sliderEl = this.doc.getElementById('slider');
    this.playback._playPauseEl = this.doc.querySelector('button[data-id="play-pause"]');
    this.playback._forwardEl = this.doc.querySelector('button[data-id="forward"]');
    this.playback._rewindEl = this.doc.querySelector('button[data-id="rewind"]');
    this.playback._shuffleEl = this.doc.querySelector('button[data-id="shuffle"]');
    this.playback._repeatEl = this.doc.querySelector('button[data-id="repeat"]');
  },

  // Time functions
  getPlaybackTime: function () {
    return parseInt(this.playback._sliderEl.getAttribute('aria-valuenow'), 10);
  },

  setPlaybackTime: function (milliseconds) {
    var percent = milliseconds / parseFloat(this.playback._sliderEl.getAttribute('aria-valuemax'));
    var lower = this.playback._sliderEl.offsetLeft + 6;
    var upper = this.playback._sliderEl.offsetLeft + this.playback._sliderEl.clientWidth - 6;
    var x = lower + percent * (upper - lower);

    this.mouse.clickAtLocation(this.playback._sliderEl, x, 0);
  },

  // Playback functions
  playPause: function () { this.playback._playPauseEl.click(); },
  forward: function () { this.playback._forwardEl.click(); },
  rewind: function () { this.playback._rewindEl.click(); },

  getShuffle: function () { return this.playback._shuffleEl.value; },
  toggleShuffle: function () { this.playback._shuffleEl.click(); },

  getRepeat: function () {
    return this.playback._repeatEl.value;
  },

  toggleRepeat: function (mode) {
    if (!mode) {
      // Toggle between repeat modes once
      this.playback._repeatEl.click();
    } else {
      // Toggle between repeat modes until the desired mode is activated
      while (this.playback.getRepeat() !== mode) {
        this.playback._repeatEl.click();
      }
    }
  },

  // Taken from the Google Play Music page
  toggleVisualization: function () {
    this.win.SJBpost('toggleVisualization');
  }
};

// Create a rating API
proto.rating = {
  // Determine whether the rating system is thumbs or stars
  isStarsRatingSystem: function () {
    return this.doc.querySelector('.rating-container.stars') !== null;
  },

  // Get current rating
  getRating: function () {
    var el = this.doc.querySelector('.player-rating-container li.selected');

    if (el) {
      return el.getAttribute('data-rating');
    } else {
      return 0;
    }
  },

  // Thumbs up
  toggleThumbsUp: function () {
    var el = this.doc.querySelector('.player-rating-container li[data-rating="5"]');

    if (el) {
      el.click();
    }
  },

  // Thumbs down
  toggleThumbsDown: function () {
    var el = this.doc.querySelector('.player-rating-container li[data-rating="1"]');

    if (el) {
      el.click();
    }
  },

  // Set a star rating
  setStarRating: function (rating) {
    var el = this.doc.querySelector('.player-rating-container li[data-rating="' + rating + '"]');

    if (el) {
      el.click();
    }
  }
};

// Miscellaneous functions
proto.extras = {
  // Get a shareable URL of the song on Google Play Music
  getSongURL: function () {
    var albumEl = this.doc.querySelector('.player-album');
    var artistEl = this.doc.querySelector('.player-artist');

    var urlTemplate = 'https://play.google.com/music/m/';
    var url = null;

    var parseID = function (id) {
      return id.substring(0, id.indexOf('/'));
    };

    if (albumEl === null && artistEl === null) {
      return null;
    }

    var albumId = parseID(albumEl.dataset.id);
    var artistId = parseID(artistEl.dataset.id);

    if (albumId) {
      url = urlTemplate + albumId;
    } else if (artistId) {
      url = urlTemplate + artistId;
    }

    return url;
  }
};

proto.hooks = {
  init: function () {
    // Save context for bindings
    var that = this;

    // Define mutation observer for reuse
    var MutationObserver = this.win.MutationObserver || this.win.WebKitMutationObserver;

    var lastTitle = '';
    var lastArtist = '';
    var lastAlbum = '';

    var addObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        for (var i = 0; i < m.addedNodes.length; i++) {
          var target = m.addedNodes[i];
          var name = target.id || target.className;

          if (name === 'text-wrapper')  {
            var title = that.doc.querySelector('#playerSongTitle');
            var artist = that.doc.querySelector('#player-artist');
            var album = that.doc.querySelector('.player-album');
            var art = that.doc.querySelector('#playingAlbumArt');
            var duration = parseInt(that.doc.querySelector('#player #slider').getAttribute('aria-valuemax'), 10);

            title = (title) ? title.innerText : 'Unknown';
            artist = (artist) ? artist.innerText : 'Unknown';
            album = (album) ? album.innerText : 'Unknown';
            art = (art) ? art.src : null;

            // The art may be a protocol-relative URL, so normalize it to HTTPS
            if (art && art.slice(0, 2) === '//') {
              art = 'https:' + art;
            }

            // Make sure that this is the first of the notifications for the
            // insertion of the song information elements.
            if (lastTitle !== title || lastArtist !== artist || lastAlbum !== album) {
              that.emit('change:song', {
                title: title,
                artist: artist,
                album: album,
                art: art,
                duration: duration
              });

              lastTitle = title;
              lastArtist = artist;
              lastAlbum = album;
            }
          }
        }
      });
    });

    var shuffleObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        var target = m.target;
        var id = target.dataset.id;

        if (id === 'shuffle') {
          that.emit('change:shuffle', target.value);
        }
      });
    });

    var repeatObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        var target = m.target;
        var id = target.dataset.id;

        if (id === 'repeat') {
          that.emit('change:repeat', target.value);
        }
      });
    });

    var playbackObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        var target = m.target;
        var id = target.dataset.id;

        if (id === 'play-pause') {
          var mode;
          var playing = target.classList.contains('playing');

          if (playing) {
            mode = GoogleMusic.Playback.PLAYING;
          } else {
            // If there is a current song, then the player is paused
            if (that.doc.querySelector('#playerSongInfo').childNodes.length) {
              mode = GoogleMusic.Playback.PAUSED;
            } else {
              mode = GoogleMusic.Playback.STOPPED;
            }
          }

          that.emit('change:playback', mode);
        }
      });
    });

    var playbackTimeObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        var target = m.target;
        var id = target.id;

        if (id === 'slider') {
          var currentTime = parseInt(target.getAttribute('aria-valuenow'), 10);
          var totalTime = parseInt(target.getAttribute('aria-valuemax'), 10);
          that.emit('change:playback-time', {current: currentTime, total: totalTime});
        }
      });
    });

    var ratingObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        var target = m.target;

        if (target.classList.contains('selected')) {
          that.emit('change:rating', target.dataset.rating);
        }
      });
    });

    addObserver.observe(this.doc.querySelector('#playerSongInfo'), {
      childList: true,
      subtree: true
    });
    shuffleObserver.observe(this.doc.querySelector('#player button[data-id="shuffle"]'), {
      attributes: true
    });
    repeatObserver.observe(this.doc.querySelector('#player button[data-id="repeat"]'), {
      attributes: true
    });
    playbackObserver.observe(this.doc.querySelector('#player button[data-id="play-pause"]'), {
      attributes: true
    });
    playbackTimeObserver.observe(this.doc.querySelector('#player #slider'), {
      attributes: true
    });
    ratingObserver.observe(this.doc.querySelector('#player .player-rating-container'), {
      attributes: true,
      subtree: true
    });
  }
};

// Export our constructor
module.exports = GoogleMusic;
<commit_msg>Updated setStarRating to support setRating<commit_after>// Load in dependencies
var EventEmitter = require('events').EventEmitter;
var inherits = require('inherits');
var Keyboard = require('./keyboard');
var Mouse = require('./mouse');

// Define bind method
function bind(context, fn) {
  return function bindFn () {
    return fn.apply(context, arguments);
  };
}

// Define our constructor
function GoogleMusic(win) {
  // If win was not provided, complain
  if (!win) {
    throw new Error('`win` was not provided to the `GoogleMusic` constructor');
  }

  // Inherit from EventEmitter
  EventEmitter.call(this);

  // Localize reference to window and document
  this.win = win;
  this.doc = win.document;

  // Initialize a keyboard and mouse
  this.keyboard = new Keyboard(win);
  this.mouse = new Mouse(win);

  // For each of the prototype sections
  var proto = GoogleMusic._protoObj;
  for (var protoKey in proto) {
    if (proto.hasOwnProperty(protoKey)) {
      // Define a key on our object
      this[protoKey] = {};

      // For each of the keys on the section, define a function that invokes on this original context
      var section = proto[protoKey];
      for (var sectionKey in section) {
        if (section.hasOwnProperty(sectionKey)) {
          this[protoKey][sectionKey] = bind(this, section[sectionKey]);
        }
      }

      // If there was an `init` method, run it
      if (this[protoKey].init) {
        this[protoKey].init();
      }
    }
  }
}
// Inherit from EventEmitter normally
inherits(GoogleMusic, EventEmitter);

// Define a "prototype" that will have magical invocation
var proto = GoogleMusic._protoObj = {};

// Create a volume API
proto.volume = {
  // Query required elements
  init: function () {
    this.volume._sliderEl = this.doc.querySelector('#vslider');
  },

  // Get the current volume level.
  getVolume: function () {
    return parseInt(this.volume._sliderEl.getAttribute('aria-valuenow'), 10);
  },

  // Set the volume level (0 - 100).
  setVolume: function (vol) {
    var current = this.volume.getVolume();

    if (vol > current) {
      this.volume.increaseVolume(vol - current);
    } else if (vol < current) {
      this.volume.decreaseVolume(current - vol);
    }
  },

  // Increase the volume by an amount (default of 1)
  increaseVolume: function (amount) {
    if (amount === undefined) {
      amount = 1;
    }

    for (var i = 0; i < amount; i++) {
      this.keyboard.sendKey(this.volume._sliderEl, Keyboard.KEY_UP);
    }
  },

  // Decrease the volume by an amount (default of 1)
  decreaseVolume: function (amount) {
    if (amount === undefined) {
      amount = 1;
    }

    for (var i = 0; i < amount; i++) {
      this.keyboard.sendKey(this.volume._sliderEl, Keyboard.KEY_DOWN);
    }
  }
};

// Create a playback API and constants
GoogleMusic.Playback = {
  // Playback states
  STOPPED: 0,
  PAUSED: 1,
  PLAYING: 2,

  // Repeat modes
  LIST_REPEAT: 'LIST_REPEAT',
  SINGLE_REPEAT: 'SINGLE_REPEAT',
  NO_REPEAT: 'NO_REPEAT',

  // Shuffle modes
  ALL_SHUFFLE: 'ALL_SHUFFLE',
  NO_SHUFFLE: 'NO_SHUFFLE'
};
proto.playback = {
  // Query references to the media playback elements
  init: function () {
    this.playback._sliderEl = this.doc.getElementById('slider');
    this.playback._playPauseEl = this.doc.querySelector('button[data-id="play-pause"]');
    this.playback._forwardEl = this.doc.querySelector('button[data-id="forward"]');
    this.playback._rewindEl = this.doc.querySelector('button[data-id="rewind"]');
    this.playback._shuffleEl = this.doc.querySelector('button[data-id="shuffle"]');
    this.playback._repeatEl = this.doc.querySelector('button[data-id="repeat"]');
  },

  // Time functions
  getPlaybackTime: function () {
    return parseInt(this.playback._sliderEl.getAttribute('aria-valuenow'), 10);
  },

  setPlaybackTime: function (milliseconds) {
    var percent = milliseconds / parseFloat(this.playback._sliderEl.getAttribute('aria-valuemax'));
    var lower = this.playback._sliderEl.offsetLeft + 6;
    var upper = this.playback._sliderEl.offsetLeft + this.playback._sliderEl.clientWidth - 6;
    var x = lower + percent * (upper - lower);

    this.mouse.clickAtLocation(this.playback._sliderEl, x, 0);
  },

  // Playback functions
  playPause: function () { this.playback._playPauseEl.click(); },
  forward: function () { this.playback._forwardEl.click(); },
  rewind: function () { this.playback._rewindEl.click(); },

  getShuffle: function () { return this.playback._shuffleEl.value; },
  toggleShuffle: function () { this.playback._shuffleEl.click(); },

  getRepeat: function () {
    return this.playback._repeatEl.value;
  },

  toggleRepeat: function (mode) {
    if (!mode) {
      // Toggle between repeat modes once
      this.playback._repeatEl.click();
    } else {
      // Toggle between repeat modes until the desired mode is activated
      while (this.playback.getRepeat() !== mode) {
        this.playback._repeatEl.click();
      }
    }
  },

  // Taken from the Google Play Music page
  toggleVisualization: function () {
    this.win.SJBpost('toggleVisualization');
  }
};

// Create a rating API
proto.rating = {
  // Determine whether the rating system is thumbs or stars
  isStarsRatingSystem: function () {
    return this.doc.querySelector('.rating-container.stars') !== null;
  },

  // Get current rating
  getRating: function () {
    var el = this.doc.querySelector('.player-rating-container li.selected');

    if (el) {
      return el.getAttribute('data-rating');
    } else {
      return 0;
    }
  },

  // Thumbs up
  toggleThumbsUp: function () {
    var el = this.doc.querySelector('.player-rating-container li[data-rating="5"]');

    if (el) {
      el.click();
    }
  },

  // Thumbs down
  toggleThumbsDown: function () {
    var el = this.doc.querySelector('.player-rating-container li[data-rating="1"]');

    if (el) {
      el.click();
    }
  },

  // Set a rating
  setRating: function (rating) {
    var el = this.doc.querySelector('.player-rating-container li[data-rating="' + rating + '"]');

    if (el && !el.classList.contains('selected')) {
      el.click();
    }
  }
};

// Miscellaneous functions
proto.extras = {
  // Get a shareable URL of the song on Google Play Music
  getSongURL: function () {
    var albumEl = this.doc.querySelector('.player-album');
    var artistEl = this.doc.querySelector('.player-artist');

    var urlTemplate = 'https://play.google.com/music/m/';
    var url = null;

    var parseID = function (id) {
      return id.substring(0, id.indexOf('/'));
    };

    if (albumEl === null && artistEl === null) {
      return null;
    }

    var albumId = parseID(albumEl.dataset.id);
    var artistId = parseID(artistEl.dataset.id);

    if (albumId) {
      url = urlTemplate + albumId;
    } else if (artistId) {
      url = urlTemplate + artistId;
    }

    return url;
  }
};

proto.hooks = {
  init: function () {
    // Save context for bindings
    var that = this;

    // Define mutation observer for reuse
    var MutationObserver = this.win.MutationObserver || this.win.WebKitMutationObserver;

    var lastTitle = '';
    var lastArtist = '';
    var lastAlbum = '';

    var addObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        for (var i = 0; i < m.addedNodes.length; i++) {
          var target = m.addedNodes[i];
          var name = target.id || target.className;

          if (name === 'text-wrapper')  {
            var title = that.doc.querySelector('#playerSongTitle');
            var artist = that.doc.querySelector('#player-artist');
            var album = that.doc.querySelector('.player-album');
            var art = that.doc.querySelector('#playingAlbumArt');
            var duration = parseInt(that.doc.querySelector('#player #slider').getAttribute('aria-valuemax'), 10);

            title = (title) ? title.innerText : 'Unknown';
            artist = (artist) ? artist.innerText : 'Unknown';
            album = (album) ? album.innerText : 'Unknown';
            art = (art) ? art.src : null;

            // The art may be a protocol-relative URL, so normalize it to HTTPS
            if (art && art.slice(0, 2) === '//') {
              art = 'https:' + art;
            }

            // Make sure that this is the first of the notifications for the
            // insertion of the song information elements.
            if (lastTitle !== title || lastArtist !== artist || lastAlbum !== album) {
              that.emit('change:song', {
                title: title,
                artist: artist,
                album: album,
                art: art,
                duration: duration
              });

              lastTitle = title;
              lastArtist = artist;
              lastAlbum = album;
            }
          }
        }
      });
    });

    var shuffleObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        var target = m.target;
        var id = target.dataset.id;

        if (id === 'shuffle') {
          that.emit('change:shuffle', target.value);
        }
      });
    });

    var repeatObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        var target = m.target;
        var id = target.dataset.id;

        if (id === 'repeat') {
          that.emit('change:repeat', target.value);
        }
      });
    });

    var playbackObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        var target = m.target;
        var id = target.dataset.id;

        if (id === 'play-pause') {
          var mode;
          var playing = target.classList.contains('playing');

          if (playing) {
            mode = GoogleMusic.Playback.PLAYING;
          } else {
            // If there is a current song, then the player is paused
            if (that.doc.querySelector('#playerSongInfo').childNodes.length) {
              mode = GoogleMusic.Playback.PAUSED;
            } else {
              mode = GoogleMusic.Playback.STOPPED;
            }
          }

          that.emit('change:playback', mode);
        }
      });
    });

    var playbackTimeObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        var target = m.target;
        var id = target.id;

        if (id === 'slider') {
          var currentTime = parseInt(target.getAttribute('aria-valuenow'), 10);
          var totalTime = parseInt(target.getAttribute('aria-valuemax'), 10);
          that.emit('change:playback-time', {current: currentTime, total: totalTime});
        }
      });
    });

    var ratingObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (m) {
        var target = m.target;

        if (target.classList.contains('selected')) {
          that.emit('change:rating', target.dataset.rating);
        }
      });
    });

    addObserver.observe(this.doc.querySelector('#playerSongInfo'), {
      childList: true,
      subtree: true
    });
    shuffleObserver.observe(this.doc.querySelector('#player button[data-id="shuffle"]'), {
      attributes: true
    });
    repeatObserver.observe(this.doc.querySelector('#player button[data-id="repeat"]'), {
      attributes: true
    });
    playbackObserver.observe(this.doc.querySelector('#player button[data-id="play-pause"]'), {
      attributes: true
    });
    playbackTimeObserver.observe(this.doc.querySelector('#player #slider'), {
      attributes: true
    });
    ratingObserver.observe(this.doc.querySelector('#player .player-rating-container'), {
      attributes: true,
      subtree: true
    });
  }
};

// Export our constructor
module.exports = GoogleMusic;
<|endoftext|>


<commit_before>"use babel"

let {BufferedProcess, CompositeDisposable} = require('atom')
let URL                 = require('url')
PodPreviewView          = require('./pod-preview')
Perl6Linter             = require('./syntax-check-linter')
Perl6Builder            = require('./builder')
Perl6Hyperclick         = require('./help-hyperclick')
Perl6FileIconsProvider  = require('./file-icons')

module.exports = {
  activate(state) {
    // Install package-deps section in package.json without user intervention
    require('atom-package-deps').install()
      .then( () => { console.log("All deps are installed, it's good to go") } )

    // Disable language-perl if it is enabled!
    if (! atom.packages.isPackageDisabled("language-perl")) {
      atom.packages.disablePackage("language-perl")
      atom.notifications.addInfo("language-perl has been disabled for a more Perl 6 fun editing experience")
    }

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable

    // Register command that toggles this view
    this.subscriptions.add(
      atom.commands.add('atom-workspace', { 'main:pod-preview': () => { return module.exports.podPreview() } } )
    )

    atom.workspace.addOpener( (uriToOpen) => {
      let {protocol, host, pathname} = URL.parse(uriToOpen)

      if(protocol != 'pod-preview:') {
        return
      }

      try {
        if (pathname) {
          pathname = decodeURI(pathname)
        }
      } catch(error) {
        console.error(error)
        return
      }

      if(host == 'editor') {
        return new PodPreviewView( { editorId: pathname.substring(1) } )
      } else {
        return new PodPreviewView( { filePath: pathname } )
      }
    })
  },

  run_tests() {
    // TODO take command from config parameter
    command   = 'prove'
    args      = ['-v', '-e', 'perl6']

    // Find project directory for the text editor provided
    // and revert to first project path if otherwise
    textEditor = atom.workspace.getActiveTextEditor()
    projectDirs = atom.project.getDirectories()
    projectDir = projectDirs.find(
      (dir) => {
        return textEditor && dir.contains(textEditor.getPath() )
      }
    )
    projectDir = projectDir.path ? projectDir.path : projectDir[0];

    options = {
      cwd: cwd = atom.project.getDirectories()[0].path,
      env: process.env
    }

    stdout  = (text) => {
      atom.notifications.addSuccess(text)
      return
    }

    stderr  = (text) => {
      atom.notifications.addError(text)
      return
    }

    exit    = (code) => {
      atom.notifications.addInfo(`'${command} ${args.join(" ")}' exited with ${code}`)
      return
    }

    // Run `prove -v -e "perl6 -Ilib"`
    atom.notifications.addInfo(`Starting running ${command} ${args.join(" ")}'...`)
    new BufferedProcess({command, args, options, stdout, stderr, exit})
  },

  podPreview() {
    // Open POD Preview on a valid editor and warn if otherwise
    editor = atom.workspace.getActiveTextEditor()
    if (!editor) {
      atom.notifications.addWarning("No editor found. Aborting...")
      return
    }

    // Open POD Preview only on a valid Perl6 editor and warn if otherwise
    grammar = editor.getGrammar()
    if (!  (grammar && grammar.scopeName && grammar.scopeName.startsWith("source.perl6")) ) {
      atom.notifications.addWarning("No Perl 6 editor found. Aborting...")
      return
    }

    // Open POD Preview only if Pod::To::HTML is installed and warn if otherwise
    module.exports.checkForPodToHtml( () => { module.exports.openPodPreview(editor) } )

    return
  },

  openPodPreview(editor) {
    // Double check that the editor is valid
    if(!editor) {
      return
    }

    uri = `pod-preview://editor/${editor.id}`

    previewPane = atom.workspace.paneForURI(uri)
    if(previewPane) {
      previewPane.destroyItem(previewPane.itemForURI(uri))
      return
    }

    previousActivePane = atom.workspace.getActivePane()
    atom.workspace.open(uri, { split: 'right', searchAllPanes: true} ).done( (podPreviewView) => {
      if (podPreviewView instanceof PodPreviewView) {
        podPreviewView.renderHTML()
        previousActivePane.activate()
      }
    });
  },

  deactivate: () => {
    this.subscriptions.dispose()
  },

  checkForPodToHtml(onSuccess) {
    // TODO take command from config parameter
    command   = 'perl6'
    args      = ["-e use Pod::To::HTML; 0"]

    exit    = (code) => {
      if (code == 0) {
        onSuccess()
      } else {
        atom.notifications.addWarning(
          `Pod::To::HTML is not installed.

Please type the following in your command line:

panda install Pod::To::HTML
`,
          { dismissable: true }
        )
      }
      return
    }

    // Run perl6 -e 'use Pod::To::HTML'
    process   = new BufferedProcess({command, args, exit})
  },

  // Perl 6 linter
  provideLinter() {
    return new Perl6Linter
  },

  // Perl 6 builder
  provideBuilder() {
    return Perl6Builder
  },

  // Perl 6 context-sensitive help
  provideHyperclick() {
    return new Perl6Hyperclick
  },

  // Perl 6 file icons
  provideFileIcons() {
    return new Perl6FileIconsProvider
  }
}<commit_msg>Activate the plugin once the dependencies are properly installed by atom-package-deps<commit_after>"use babel"

let {BufferedProcess, CompositeDisposable} = require('atom')
let URL                 = require('url')
PodPreviewView          = require('./pod-preview')
Perl6Linter             = require('./syntax-check-linter')
Perl6Builder            = require('./builder')
Perl6Hyperclick         = require('./help-hyperclick')
Perl6FileIconsProvider  = require('./file-icons')

module.exports = {

  // This is called on plugin activation by the Atom environment
  activate(state) {
    // Install package-deps section in package.json without user intervention
    require('atom-package-deps')
      .install()
      .then( () => {
        // All dependencies are now installed, let's roll
        this.activateAfterDepsCheck()
      })
  },

  // This is called once the dependencies are properly installed
  activateAfterDepsCheck() {

    // Disable language-perl if it is enabled!
    if (! atom.packages.isPackageDisabled("language-perl")) {
      atom.packages.disablePackage("language-perl")
      atom.notifications.addInfo("language-perl has been disabled for a more Perl 6 fun editing experience")
    }

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable

    // Register command that toggles this view
    this.subscriptions.add(
      atom.commands.add('atom-workspace', { 'main:pod-preview': () => { return module.exports.podPreview() } } )
    )

    atom.workspace.addOpener( (uriToOpen) => {
      let {protocol, host, pathname} = URL.parse(uriToOpen)

      if(protocol != 'pod-preview:') {
        return
      }

      try {
        if (pathname) {
          pathname = decodeURI(pathname)
        }
      } catch(error) {
        console.error(error)
        return
      }

      if(host == 'editor') {
        return new PodPreviewView( { editorId: pathname.substring(1) } )
      } else {
        return new PodPreviewView( { filePath: pathname } )
      }
    })
  },

  run_tests() {
    // TODO take command from config parameter
    command   = 'prove'
    args      = ['-v', '-e', 'perl6']

    // Find project directory for the text editor provided
    // and revert to first project path if otherwise
    textEditor = atom.workspace.getActiveTextEditor()
    projectDirs = atom.project.getDirectories()
    projectDir = projectDirs.find(
      (dir) => {
        return textEditor && dir.contains(textEditor.getPath() )
      }
    )
    projectDir = projectDir.path ? projectDir.path : projectDir[0];

    options = {
      cwd: cwd = atom.project.getDirectories()[0].path,
      env: process.env
    }

    stdout  = (text) => {
      atom.notifications.addSuccess(text)
      return
    }

    stderr  = (text) => {
      atom.notifications.addError(text)
      return
    }

    exit    = (code) => {
      atom.notifications.addInfo(`'${command} ${args.join(" ")}' exited with ${code}`)
      return
    }

    // Run `prove -v -e "perl6 -Ilib"`
    atom.notifications.addInfo(`Starting running ${command} ${args.join(" ")}'...`)
    new BufferedProcess({command, args, options, stdout, stderr, exit})
  },

  podPreview() {
    // Open POD Preview on a valid editor and warn if otherwise
    editor = atom.workspace.getActiveTextEditor()
    if (!editor) {
      atom.notifications.addWarning("No editor found. Aborting...")
      return
    }

    // Open POD Preview only on a valid Perl6 editor and warn if otherwise
    grammar = editor.getGrammar()
    if (!  (grammar && grammar.scopeName && grammar.scopeName.startsWith("source.perl6")) ) {
      atom.notifications.addWarning("No Perl 6 editor found. Aborting...")
      return
    }

    // Open POD Preview only if Pod::To::HTML is installed and warn if otherwise
    module.exports.checkForPodToHtml( () => { module.exports.openPodPreview(editor) } )

    return
  },

  openPodPreview(editor) {
    // Double check that the editor is valid
    if(!editor) {
      return
    }

    uri = `pod-preview://editor/${editor.id}`

    previewPane = atom.workspace.paneForURI(uri)
    if(previewPane) {
      previewPane.destroyItem(previewPane.itemForURI(uri))
      return
    }

    previousActivePane = atom.workspace.getActivePane()
    atom.workspace.open(uri, { split: 'right', searchAllPanes: true} ).done( (podPreviewView) => {
      if (podPreviewView instanceof PodPreviewView) {
        podPreviewView.renderHTML()
        previousActivePane.activate()
      }
    });
  },

  deactivate: () => {
    this.subscriptions.dispose()
  },

  checkForPodToHtml(onSuccess) {
    // TODO take command from config parameter
    command   = 'perl6'
    args      = ["-e use Pod::To::HTML; 0"]

    exit    = (code) => {
      if (code == 0) {
        onSuccess()
      } else {
        atom.notifications.addWarning(
          `Pod::To::HTML is not installed.

Please type the following in your command line:

panda install Pod::To::HTML
`,
          { dismissable: true }
        )
      }
      return
    }

    // Run perl6 -e 'use Pod::To::HTML'
    process   = new BufferedProcess({command, args, exit})
  },

  // Perl 6 linter
  provideLinter() {
    return new Perl6Linter
  },

  // Perl 6 builder
  provideBuilder() {
    return Perl6Builder
  },

  // Perl 6 context-sensitive help
  provideHyperclick() {
    return new Perl6Hyperclick
  },

  // Perl 6 file icons
  provideFileIcons() {
    return new Perl6FileIconsProvider
  }
}<|endoftext|>


<commit_before>'use babel'
import { CompositeDisposable } from 'atom'
import path from 'path'

let subs = null
let toolbar = null
let juliaClient = null
let HTMLPreviewView = require('./html-preview.js')

export function activate () {
    subs = new CompositeDisposable()

    subs.add(atom.workspace.addOpener((uri) => {
        if (path.extname(uri) === '.html' && uri.startsWith('preview://')) {
            return new HTMLPreviewView(uri)
        }
    }))

    subs.add(atom.commands.add('atom-text-editor',
        'weave:weave-to-pdf', () => weave('pdf')))
    subs.add(atom.commands.add('atom-text-editor',
        'weave:weave-to-html', () => weave('html')))
}

function weave(format) {
    if (juliaClient === null) {
        atom.notifications.addError("Juno not installed", {
            description: "[Juno](http://junolab.org/) needs to be installed to weave files."
        })
        return
    }

    juliaClient.boot()

    ed = atom.workspace.getActiveTextEditor()
    pane = atom.workspace.getActivePane()
    if (!ed) {
        atom.notifications.addError("No editor selected", {
            description: "Select an editor to weave a file."
        })
        return
    }
    edpath = ed.getPath()
    if (!edpath) {
        atom.notifications.addError("File is not saved", {
            description: "Please save your file to weave it."
        })
        return
    }

    ed.save()

    if (process.platform === 'win32') {
        edpath = edpath.replace(/\\/g, "/")
    }
    outpath = edpath.split('.')
    outpath.pop()
    outpath = outpath.join('.') + '.' + format

    weaveCommand  = 'using Weave;'
    weaveCommand += 'try;'
    weaveCommand += `weave("${edpath}", doctype="md2${format}"); 1;`
    weaveCommand += 'catch err;'
    weaveCommand += '@error("Weaving failed.", error=err); 0;'
    weaveCommand += 'end'

    evalsimple = juliaClient.import({rpc: ['evalsimple']}).evalsimple
    evalsimple(weaveCommand).then((res) => {
        if (!atom.config.get('language-weave.showPreview')) return

        if (format === 'pdf' && !atom.packages.isPackageActive('pdf-view')) {
            atom.notifications.addError("Can't display PDF", {
                description: 'Please install the [pdf-view](https://github.com/izuzak/atom-pdf-view) package.'
            })
            return
        }

        if (res == 1) {
            if (format == 'html') {
                outpath = 'preview://' + outpath
            }
            atom.workspace.open(outpath, {
                searchAllPanes: true,
                split: 'right'
            }).then(() => {
                pane.activate()
                pane.activateItem(ed)
            })
        } else {
            atom.notifications.addError("Weaving file failed", {
                description: "See the REPL for details."
            })
        }
    })
}

export function consumeJuliaClient (client) {
    juliaClient = client
}

export function consumeToolBar (getToolBar) {
    if (!atom.config.get('julia-client.uiOptions.enableToolBar')) return
    toolbar = getToolBar()
    toolbar.addSpacer()
    toolbar.addButton({
        icon: 'social-html5',
        iconset: 'ion',
        callback: 'weave:weave-to-html',
        tooltip: 'Weave HTML'
    })
    toolbar.addButton({
        icon: 'file-pdf',
        iconset: 'fa',
        callback: 'weave:weave-to-pdf',
        tooltip: 'Weave PDF'
    })
    toolbar.addSpacer()
}

export var config = {
    showPreview: {
        type: 'boolean',
        default: true,
        title: 'Show Previews'
    }
}

export function deactivate () {
    if (toolbar) {
        toolbar.removeItems()
        toolbar = null
    }
    subs.dispose()
}

export function deserialize({filePath, uri}) {
    if (require('fs-plus').isFileSync(filePath)) {
        return new HTMLPreviewView(uri)
    }
}
<commit_msg>Add variable identifiers<commit_after>'use babel'
import { CompositeDisposable } from 'atom'
import path from 'path'

let subs = null
let toolbar = null
let juliaClient = null
let HTMLPreviewView = require('./html-preview.js')

export function activate () {
    subs = new CompositeDisposable()

    subs.add(atom.workspace.addOpener((uri) => {
        if (path.extname(uri) === '.html' && uri.startsWith('preview://')) {
            return new HTMLPreviewView(uri)
        }
    }))

    subs.add(atom.commands.add('atom-text-editor',
        'weave:weave-to-pdf', () => weave('pdf')))
    subs.add(atom.commands.add('atom-text-editor',
        'weave:weave-to-html', () => weave('html')))
}

function weave(format) {
    if (juliaClient === null) {
        atom.notifications.addError("Juno not installed", {
            description: "[Juno](http://junolab.org/) needs to be installed to weave files."
        })
        return
    }

    juliaClient.boot()

    const ed = atom.workspace.getActiveTextEditor()
    const pane = atom.workspace.getActivePane()
    if (!ed) {
        atom.notifications.addError("No editor selected", {
            description: "Select an editor to weave a file."
        })
        return
    }
    let edpath = ed.getPath()
    if (!edpath) {
        atom.notifications.addError("File is not saved", {
            description: "Please save your file to weave it."
        })
        return
    }

    ed.save()

    if (process.platform === 'win32') {
        edpath = edpath.replace(/\\/g, "/")
    }
    let outpath = edpath.split('.')
    outpath.pop()
    outpath = outpath.join('.') + '.' + format

    let weaveCommand  = ''
    weaveCommand += 'try;'
    weaveCommand += `weave("${edpath}", doctype="md2${format}"); 1;`
    weaveCommand += 'catch err;'
    weaveCommand += '@error("Weaving failed.", error=err); 0;'
    weaveCommand += 'end'

    const evalsimple = juliaClient.import({rpc: ['evalsimple']}).evalsimple
    evalsimple(weaveCommand).then((res) => {
        if (!atom.config.get('language-weave.showPreview')) return

        if (format === 'pdf' && !atom.packages.isPackageActive('pdf-view')) {
            atom.notifications.addError("Can't display PDF", {
                description: 'Please install the [pdf-view](https://github.com/izuzak/atom-pdf-view) package.'
            })
            return
        }

        if (res == 1) {
            if (format == 'html') {
                outpath = 'preview://' + outpath
            }
            atom.workspace.open(outpath, {
                searchAllPanes: true,
                split: 'right'
            }).then(() => {
                pane.activate()
                pane.activateItem(ed)
            })
        } else {
            atom.notifications.addError("Weaving file failed", {
                description: "See the REPL for details."
            })
        }
    })
}

export function consumeJuliaClient (client) {
    juliaClient = client
}

export function consumeToolBar (getToolBar) {
    if (!atom.config.get('julia-client.uiOptions.enableToolBar')) return
    toolbar = getToolBar()
    toolbar.addSpacer()
    toolbar.addButton({
        icon: 'social-html5',
        iconset: 'ion',
        callback: 'weave:weave-to-html',
        tooltip: 'Weave HTML'
    })
    toolbar.addButton({
        icon: 'file-pdf',
        iconset: 'fa',
        callback: 'weave:weave-to-pdf',
        tooltip: 'Weave PDF'
    })
    toolbar.addSpacer()
}

export var config = {
    showPreview: {
        type: 'boolean',
        default: true,
        title: 'Show Previews'
    }
}

export function deactivate () {
    if (toolbar) {
        toolbar.removeItems()
        toolbar = null
    }
    subs.dispose()
}

export function deserialize({filePath, uri}) {
    if (require('fs-plus').isFileSync(filePath)) {
        return new HTMLPreviewView(uri)
    }
}
<|endoftext|>


<commit_before>"use strict";

var aws = require('aws-sdk');
var exec = require('child_process').exec;
var fs = require('fs');
var os = require('os');
var packageJson = require('./../package.json');
var path = require('path');
var async = require('async');
var uuid = require('node-uuid');
var Lambda = function() {
  this.version = packageJson.version;

  return this;
};

Lambda.prototype._createSampleFile = function(file) {
  var exampleFile = process.cwd() + '/' + file;
  var boilerplateFile = __dirname + '/' + file + '.example';

  if (!fs.existsSync(exampleFile)) {
    fs.writeFileSync(exampleFile, fs.readFileSync(boilerplateFile));
    console.log(exampleFile + ' file successfully created');
  }

};

Lambda.prototype.setup = function() {
  console.log('Running setup.');
  this._createSampleFile('.env');
  this._createSampleFile('event.json');
  console.log('Setup done. Edit the .env and event.json files as needed.');
};

Lambda.prototype.run = function(program) {
  this._createSampleFile('event.json');

  var dir = program.directory;
  var splitHandler = program.handler.split('.');
  var filename = splitHandler[0] + '.js';
  var handlername = splitHandler[1];

  var handler = require(process.cwd() + '/' + filename)[handlername];
  var event = require(process.cwd() + '/event.json');

  this._runHandler(handler, event);
};

Lambda.prototype._runHandler = function(handler, event) {
  var context = {
    done: function() {
      process.exit(0);
    }
  };

  handler(event, context);
};

Lambda.prototype._zipfileTmpPath = function(program) {
  var ms_since_epoch = +new Date();
  var filename = program.functionName + '-' + ms_since_epoch + '.zip';
  var zipfile = path.join(os.tmpDir(), filename);

  return zipfile;
};

Lambda.prototype._params = function(program, buffer)  {
  var params = {
    FunctionName: program.functionName + '-' + program.environment,
    FunctionZip: buffer,
    Handler: program.handler,
    Mode: program.mode,
    Role: program.role,
    Runtime: program.runtime,
    Description: program.description,
    MemorySize: program.memorySize,
    Timeout: program.timeout
  };
  params.FunctionName += (program.version ? '-' + program.version.replace(/\./g, '-'): '');
  return params;
};

Lambda.prototype.deploy = function(program) {
  this._createSampleFile('.env');

  var _this = this;
  var zipfile = _this._zipfileTmpPath(program);
  var regions = program.region.split(',');

  // zip up but ignore .git, .dotfiles, .log files, and the event.json file.
  console.log('Generating zip file');
  exec( "zip -roq " + zipfile + " * -x '.git' -x '*/\.*' -x '*/\*.log' -x 'event.json'", function(err, stdout, stderr) {
    if (err) {
      throw err;
    }

    console.log('Reading zip file to memory');
    var buffer = fs.readFileSync(zipfile);
    var params = _this._params(program, buffer);

    async.map(regions, function(region, cb) {
      console.log('Working in region: ' + region);
      console.log('Uploading zip file to AWS Lambda with parameters:');
      console.log(params);

      aws.config.update({
        accessKeyId: program.accessKey,
        secretAccessKey: program.secretKey,
        region: region
      });

      var lambda = new aws.Lambda({ apiVersion: '2014-11-11' });

      lambda.uploadFunction(params, function(err, data) {
          cb(err, data);
      });

    }, function(err, results) {
      if (err) {
        console.log(err);
      } else {
        console.log('Zip file(s) done uploading. Results follow: ');
        console.log(results);
      }
    });
  });
};

module.exports = new Lambda();
<commit_msg>Remove function<commit_after>"use strict";

var aws = require('aws-sdk');
var exec = require('child_process').exec;
var fs = require('fs');
var os = require('os');
var packageJson = require('./../package.json');
var path = require('path');
var async = require('async');
var uuid = require('node-uuid');
var Lambda = function() {
  this.version = packageJson.version;

  return this;
};

Lambda.prototype._createSampleFile = function(file) {
  var exampleFile = process.cwd() + '/' + file;
  var boilerplateFile = __dirname + '/' + file + '.example';

  if (!fs.existsSync(exampleFile)) {
    fs.writeFileSync(exampleFile, fs.readFileSync(boilerplateFile));
    console.log(exampleFile + ' file successfully created');
  }

};

Lambda.prototype.setup = function() {
  console.log('Running setup.');
  this._createSampleFile('.env');
  this._createSampleFile('event.json');
  console.log('Setup done. Edit the .env and event.json files as needed.');
};

Lambda.prototype.run = function(program) {
  this._createSampleFile('event.json');

  var dir = program.directory;
  var splitHandler = program.handler.split('.');
  var filename = splitHandler[0] + '.js';
  var handlername = splitHandler[1];

  var handler = require(process.cwd() + '/' + filename)[handlername];
  var event = require(process.cwd() + '/event.json');

  this._runHandler(handler, event);
};

Lambda.prototype._runHandler = function(handler, event) {
  var context = {
    done: function() {
      process.exit(0);
    }
  };

  handler(event, context);
};

Lambda.prototype._params = function(program, buffer)  {
  var params = {
    FunctionName: program.functionName + '-' + program.environment,
    FunctionZip: buffer,
    Handler: program.handler,
    Mode: program.mode,
    Role: program.role,
    Runtime: program.runtime,
    Description: program.description,
    MemorySize: program.memorySize,
    Timeout: program.timeout
  };
  params.FunctionName += (program.version ? '-' + program.version.replace(/\./g, '-'): '');
  return params;
};

Lambda.prototype.deploy = function(program) {
  this._createSampleFile('.env');

  var _this = this;
  var zipfile = _this._zipfileTmpPath(program);
  var regions = program.region.split(',');

  // zip up but ignore .git, .dotfiles, .log files, and the event.json file.
  console.log('Generating zip file');
  exec( "zip -roq " + zipfile + " * -x '.git' -x '*/\.*' -x '*/\*.log' -x 'event.json'", function(err, stdout, stderr) {
    if (err) {
      throw err;
    }

    console.log('Reading zip file to memory');
    var buffer = fs.readFileSync(zipfile);
    var params = _this._params(program, buffer);

    async.map(regions, function(region, cb) {
      console.log('Working in region: ' + region);
      console.log('Uploading zip file to AWS Lambda with parameters:');
      console.log(params);

      aws.config.update({
        accessKeyId: program.accessKey,
        secretAccessKey: program.secretKey,
        region: region
      });

      var lambda = new aws.Lambda({ apiVersion: '2014-11-11' });

      lambda.uploadFunction(params, function(err, data) {
          cb(err, data);
      });

    }, function(err, results) {
      if (err) {
        console.log(err);
      } else {
        console.log('Zip file(s) done uploading. Results follow: ');
        console.log(results);
      }
    });
  });
};

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


<commit_before>"use babel";

export default {
    config: {
        executable: {
            type: "string",
            default: "gfortran"
        },
        gfortran_flags: {
            type: "string",
            default: "-Wall -Wextra"
        },
    },

    activate: () => {
        require("atom-package-deps").install("linter-gfortran");
    },

    provideLinter: () => {
        const helpers = require("atom-linter");
        const path = require('path')
        const regex = "(?<file>.+):(?<line>\\d+)[\.:](?<col>\\d+):((.|\\r|\\n)*?)(?<type>(Error|Warning|Note)):\\s*(?<message>.*)";
        const tmpdir = require('tmp').dirSync().name;
        return {
            name: "gfortran",
            grammarScopes: [
                "source.fortran.free",
                "source.fortran.fixed",
                "source.fortran.modern",
                "source.fortran.punchcard"
            ],
            scope: "project",
            lintOnFly: true,
            lint: (activeEditor) => {
              const command = atom.config.get("linter-gfortran.executable");
              const fileContents = activeEditor.getText()
              const filePath = activeEditor.getPath();

              // Split the users flag string and append flags to specific syntax checking and temporary file directory.
              const args = atom.config
                .get("linter-gfortran.gfortran_flags")
                .split(" ")
                .concat(["-fsyntax-only", "-J", tmpdir, file]);

              return helpers.tempFile(path.basename(filePath), fileContents, (tmpFilename) => {
                args.push(tmpFilename);
                return helpers.exec(command, args, { stream: "stderr"}).then(output => {
                    return helpers.parse(output, regex, { filePath : filePath });
                    });
                });
          }
        };
    }
};
<commit_msg>Fixed other errors.<commit_after>"use babel";

export default {
    config: {
        executable: {
            type: "string",
            default: "gfortran"
        },
        gfortran_flags: {
            type: "string",
            default: "-Wall -Wextra"
        },
    },

    activate: () => {
        require("atom-package-deps").install("linter-gfortran");
    },

    provideLinter: () => {
        const helpers = require("atom-linter");
        const path = require('path');
        const regex = ".+:(?<line>\\d+)[\.:](?<col>\\d+):((.|\\r|\\n)*?)(?<type>(Error|Warning|Note)):\\s*(?<message>.*)";
        const tmpdir = require('tmp').dirSync().name;
        return {
            name: "gfortran",
            grammarScopes: [
                "source.fortran.free",
                "source.fortran.fixed",
                "source.fortran.modern",
                "source.fortran.punchcard"
            ],
            scope: "project",
            lintOnFly: true,
            lint: (activeEditor) => {
              const command = atom.config.get("linter-gfortran.executable");
              const fileContents = activeEditor.getText()
              const filePath = activeEditor.getPath();

              // Split the users flag string and append flags to specific syntax checking and temporary file directory.
              const args = atom.config
                .get("linter-gfortran.gfortran_flags")
                .split(" ")
                .concat(["-fsyntax-only", "-J", tmpdir]);

              return helpers.tempFile(path.basename(filePath), fileContents, (tmpFilename) => {
                args.push(tmpFilename);
                return helpers.exec(command, args, { stream: "stderr"}).then(output => {
                    return helpers.parse(output, regex, { filePath : filePath });
                    });
                });
          }
        };
    }
};
<|endoftext|>


<commit_before>(function ( Backbone, _ ) {

  'use strict';

  var bbExtend = Backbone.Model.extend;

  function triggerPropChange( ctx, prop ) {
    return function () {
      ctx.trigger( 'change:' + prop, ctx, prop );
    };
  }

  function setupDepsListeners( ctx, prop, deps ) {
    deps = deps || [];
    var l = deps.length;
    while ( l-- ) {
      ctx.on( 'change:' + deps[ l ], triggerPropChange( ctx, prop ) );
    }
  }

  Backbone.Model.extend = function ( properties, classProperties ) {
    var prop, action, propSpec, deps;
    var parent = this;

    properties = properties || {};
    var computedProps = properties.properties;
    delete properties.properties;

    // Setup computed properties
    if ( computedProps ) {
      for ( prop in computedProps ) {
        if ( computedProps.hasOwnProperty( prop ) ) {
          propSpec = computedProps[ prop ];
          if ( propSpec instanceof Function ) {
            action = propSpec;
            deps = [];
          } else {
            action = propSpec.action;
            deps = propSpec.depends || [];
          }
          computedProps[ prop ] = {
            action: action,
            deps: deps
          };
        }
      }
    }

    // Override Boostrap's default constructor, setting up listeners for dependencies.
    properties.constructor = function () {
      var prop, deps, l;
      this._cachedProps = {};

      for ( prop in computedProps ) {
        if ( computedProps.hasOwnProperty( prop ) ) {
          setupDepsListeners( this, prop, computedProps[ prop ].deps );
        }
      }

      return parent.apply( this, arguments );
    };

    // Extend our class from Boostrap.Model
    var Class = bbExtend.call( this, properties, classProperties );

    // Override Bootstrap's default getter
    var get = Class.prototype.get;
    Class.prototype.get = function ( attr ) {
      var newValue;
      if ( computedProps[ attr ] ) {
        newValue = computedProps[ attr ].action.call( this );
        this._cachedProps[ attr ] = newValue;
        return newValue;
      }
      return get.apply( this, arguments );
    };

    // Override Bootstrap's default setter
    var set = Class.prototype.set;
    Class.prototype.set = function ( attr, value ) {
      var newValue;
      if ( computedProps[ attr ] ) {
        newValue = computedProps[ attr ].action.call( this, value );
        if ( this._cachedProps[ attr ] !== newValue ) {
          this._cachedProps[ attr ] = newValue;
          this.trigger( 'change:' + attr, this, attr );
        }
        return this;
      }
      return set.apply( this, arguments );
    };

    return Class;
  };

}( this.Backbone, this.underscore ));
<commit_msg>Reference underscore as '_'<commit_after>(function ( Backbone, _ ) {

  'use strict';

  var bbExtend = Backbone.Model.extend;

  function triggerPropChange( ctx, prop ) {
    return function () {
      ctx.trigger( 'change:' + prop, ctx, prop );
    };
  }

  function setupDepsListeners( ctx, prop, deps ) {
    deps = deps || [];
    var l = deps.length;
    while ( l-- ) {
      ctx.on( 'change:' + deps[ l ], triggerPropChange( ctx, prop ) );
    }
  }

  Backbone.Model.extend = function ( properties, classProperties ) {
    var prop, action, propSpec, deps;
    var parent = this;

    properties = properties || {};
    var computedProps = properties.properties;
    delete properties.properties;

    // Setup computed properties
    if ( computedProps ) {
      for ( prop in computedProps ) {
        if ( computedProps.hasOwnProperty( prop ) ) {
          propSpec = computedProps[ prop ];
          if ( propSpec instanceof Function ) {
            action = propSpec;
            deps = [];
          } else {
            action = propSpec.action;
            deps = propSpec.depends || [];
          }
          computedProps[ prop ] = {
            action: action,
            deps: deps
          };
        }
      }
    }

    // Override Boostrap's default constructor, setting up listeners for dependencies.
    properties.constructor = function () {
      var prop, deps, l;
      this._cachedProps = {};

      for ( prop in computedProps ) {
        if ( computedProps.hasOwnProperty( prop ) ) {
          setupDepsListeners( this, prop, computedProps[ prop ].deps );
        }
      }

      return parent.apply( this, arguments );
    };

    // Extend our class from Boostrap.Model
    var Class = bbExtend.call( this, properties, classProperties );

    // Override Bootstrap's default getter
    var get = Class.prototype.get;
    Class.prototype.get = function ( attr ) {
      var newValue;
      if ( computedProps[ attr ] ) {
        newValue = computedProps[ attr ].action.call( this );
        this._cachedProps[ attr ] = newValue;
        return newValue;
      }
      return get.apply( this, arguments );
    };

    // Override Bootstrap's default setter
    var set = Class.prototype.set;
    Class.prototype.set = function ( attr, value ) {
      var newValue;
      if ( computedProps[ attr ] ) {
        newValue = computedProps[ attr ].action.call( this, value );
        if ( this._cachedProps[ attr ] !== newValue ) {
          this._cachedProps[ attr ] = newValue;
          this.trigger( 'change:' + attr, this, attr );
        }
        return this;
      }
      return set.apply( this, arguments );
    };

    return Class;
  };

}( this.Backbone, this._ ));
<|endoftext|>