<commit_before>const path = require('path');
const validate = require('webpack-validator');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = validate({
   entry: {
      app: ['./src/index.js']
   },
   module: {
      preLoaders: [
         { test: /.js$/, exclude: /node_modules/, loader: 'eslint-loader' }
      ],
      loaders: [
         { test: /\.svg/, loader: 'svg-url-loader' },
         { test: /.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['es2015'] } },
         { test: /\.(ttf|woff)$|\.eot$/, loader: 'file', query: { name: 'fonts/[name].[ext]' }, },
         {
            test: /\.(jpe|jpg|woff|woff2|eot|ttf|svg)(\?.*$|$)/,
            exclude: /node_modules/,
            loader: 'url-loader?importLoaders=1&limit=100000'
         },
         { test: /\.scss$/, loaders: ['style', 'css?sourceMap', 'sass?sourceMap'] },
         { test: /\.html/, loader: 'html-loader' },
         { test: /\.json$/, loader: 'json-loader' }]
   },
   devtool: 'source-map',
   output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'js/[name].js'
   },
   devServer: {
      contentBase: './src'
   },
   resolve: {
      extensions: ['', '.js', '.json', '.scss', '.html']
   },
   plugins: [new HtmlWebpackPlugin({
      template: 'src/index.html'
   })]
});<commit_msg>KSBWI-743 imported settings from default.js<commit_after>const path = require('path');
const validate = require('webpack-validator');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const fs = require('fs');

module.exports = validate({
   entry: {
      app: ['./src/index.js']
   },
   module: {
      preLoaders: [
         { test: /.js$/, exclude: /widget-core-library/, loader: `eslint-loader?{configFile:"${path.join(__dirname, '.eslintrc')}"}` }
      ],
      loaders: [
         {test: /\.svg/, loader: 'svg-url-loader'},
         {test: /(\.ttf|\.woff2?|\.eot)/, loader: 'url-loader'},
         { test: /.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['es2015'] } },
         { test: /\.scss$/, loaders: ['style', 'css?sourceMap', 'sass?sourceMap'] },
         { test: /\.html/, loader: 'html-loader' },
         { test: /\.json$/, loader: 'json-loader' }]
   },
   resolveLoader: { root: fs.existsSync(path.join(__dirname, "node_modules")) ? path.join(__dirname, "node_modules") : path.resolve('./../') },
   devtool: 'source-map',
   output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'js/[name].js'
   },
   devServer: {
      contentBase: './src'
   },
   resolve: {
      extensions: ['', '.js', '.json', '.scss', '.html']
   },
   plugins: [
      new HtmlWebpackPlugin({template: 'src/index.html'}),
      new CopyWebpackPlugin([
         { from: './src/i18n', to: 'i18n' },
         { from: path.join(__dirname, 'widget_config', 'mockSetupData.json'), to: '.' }
      ])
   ]
});
<|endoftext|>


<commit_before>import webpack from 'webpack';
import baseConfig from './base.babel';

const host = 'localhost';
const port = 3000;

const baseDevConfig = {
  ...baseConfig,
  mode: 'development',
  devtool: 'inline-source-map',
  devServer: { host, port },
  output: {
    ...baseConfig.output,
    publicPath: `http://localhost:${port}/js/`,
  },
  module: {
    rules: [
      ...baseConfig.module.rules,
      {
        test: /\.css?$/,
        use: ['style-loader', 'raw-loader'],
      },
    ],
  },
  plugins: [
    ...baseConfig.plugins,
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development'),
    }),
  ],
};

const buildDevConfig = config => ({
  ...baseDevConfig,
  ...config,
});

export default [
  buildDevConfig({
    entry: './app/index',
    target: 'electron-renderer',
  }),
  buildDevConfig({
    entry: './app/worker/index.js',
    resolve: {
      ...baseDevConfig.resolve,
      aliasFields: ['browser'],
    },
    output: {
      ...baseDevConfig.output,
      filename: 'RNDebuggerWorker.js',
      libraryTarget: undefined,
    },
    target: 'webworker',
  }),
];
<commit_msg>Add disableHostCheck for dev server<commit_after>import webpack from 'webpack';
import baseConfig from './base.babel';

const host = 'localhost';
const port = 3000;

const baseDevConfig = {
  ...baseConfig,
  mode: 'development',
  devtool: 'inline-source-map',
  devServer: { host, port, disableHostCheck: true },
  output: {
    ...baseConfig.output,
    publicPath: `http://localhost:${port}/js/`,
  },
  module: {
    rules: [
      ...baseConfig.module.rules,
      {
        test: /\.css?$/,
        use: ['style-loader', 'raw-loader'],
      },
    ],
  },
  plugins: [
    ...baseConfig.plugins,
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development'),
    }),
  ],
};

const buildDevConfig = config => ({
  ...baseDevConfig,
  ...config,
});

export default [
  buildDevConfig({
    entry: './app/index',
    target: 'electron-renderer',
  }),
  buildDevConfig({
    entry: './app/worker/index.js',
    resolve: {
      ...baseDevConfig.resolve,
      aliasFields: ['browser'],
    },
    output: {
      ...baseDevConfig.output,
      filename: 'RNDebuggerWorker.js',
      libraryTarget: undefined,
    },
    target: 'webworker',
  }),
];
<|endoftext|>


<commit_before>import {assert} from 'chai';

import waitForPromise from '../../wait-for-promise';

export const elements = {
  loadingScreen: '.webex-teams-loading',
  recentsWidget: '.ciscospark-recents-widget',
  listContainer: '.ciscospark-spaces-list',
  noSpacesTitle: '.ciscospark-no-spaces-title',
  noSpacesMessage: '.ciscospark-no-spaces-message',
  firstSpace: '.ciscospark-spaces-list-item-0',
  title: '.cui-list-item__header',
  unreadIndicator: '.cui-list-item--unread',
  indicatorIcon: '.cui-list-item--unread .cui-list-item__right .cui-icon',
  lastActivity: '.space-last-activity',
  callButton: 'button[aria-label="Call Space"]',
  joinCallButton: 'button[aria-label="Join Call"]',
  answerButton: 'button[aria-label="Answer"]',
  searchInput: '#pillSearchInput',
  clearButton: 'button[aria-label="clear input"]',
  headerBar: '.ciscospark-recents-header',
  headerProfile: '.ciscospark-recents-header .ciscospark-recents-header-left button',
  headerSignout: '.ciscospark-recents-header-profile-menu-signout',
  headerAddButton: 'button[aria-label="Contact a person or create a space"]'
};

export * from './space-list-filter';

/**
 * Sends a message to a space and verifies that it is received and displayed
 *
 * @export
 * @param {object} aBrowser
 * @param {object} sender - Person with spark object
 * @param {object} conversation
 * @param {string} message
 * @param {boolean} [isOneOnOne=false]
 * @returns {undefined}
 */
export function displayIncomingMessage(aBrowser, sender, conversation, message, isOneOnOne = false) {
  const spaceTitle = isOneOnOne ? sender.displayName : conversation.displayName;

  waitForPromise(sender.spark.internal.conversation.post(conversation, {
    displayName: message
  }));
  aBrowser.waitUntil(() => aBrowser.element(`${elements.firstSpace} ${elements.title}`).isVisible()
    && aBrowser.element(`${elements.firstSpace} ${elements.title}`).getText() === spaceTitle);
  assert.isTrue(aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible(), 'does not have unread indicator');
}

/**
 * Sends a message to a space and verifies that it is received and displayed,
 * then marks it read.
 *
 * @export
 * @param {object} aBrowser
 * @param {object} sender - Person with spark object
 * @param {object} receiver - Person with spark object
 * @param {object} conversation
 * @param {string} message
 * @returns {undefined}
 */
export function displayAndReadIncomingMessage(aBrowser, sender, receiver, conversation, message) {
  let activity;

  waitForPromise(sender.spark.internal.conversation.post(conversation, {
    displayName: message
  }).then((a) => {
    activity = a;
  }));
  aBrowser.waitUntil(() => aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
  assert.isTrue(aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible(), 'does not have unread indicator');
  // Acknowledge the activity to mark it read
  waitForPromise(receiver.spark.internal.conversation.acknowledge(conversation, activity));
  aBrowser.waitUntil(() => !aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
}

/**
 * Sends a message to a space and verifies that it is received and muted icon is displayed,
 * then marks it read.
 *
 * @export
 * @param {object} aBrowser
 * @param {object} sender - Person with spark object
 * @param {object} receiver - Person with spark object
 * @param {object} conversation
 * @param {string} message
 * @returns {undefined}
 */
export function displayMutedIconAndReadIncomingMessage(aBrowser, sender, receiver, conversation, message) {
  let activity;

  waitForPromise(sender.spark.internal.conversation.post(conversation, {
    displayName: message
  }).then((a) => {
    activity = a;
  }));
  aBrowser.waitUntil(() => aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
  assert.isTrue(aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible(), 'does not have unread indicator');
  assert.exists(aBrowser.element(`${elements.indicatorIcon}`).getAttribute('name').match(/alert-muted(.*)/g), 'does not have muted indicator');

  // Acknowledge the activity to mark it read
  waitForPromise(receiver.spark.internal.conversation.acknowledge(conversation, activity));
  aBrowser.waitUntil(() => !aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
}

/**
 * Sends a message to a space and verifies that it is received and mention icon is displayed,
 * then marks it read.
 *
 * @export
 * @param {object} aBrowser
 * @param {object} sender - Person with spark object
 * @param {object} receiver - Person with spark object
 * @param {object} conversation
 * @param {string} message
 * @param {object} mentions
 * @returns {undefined}
 */
export function displayMentionIconAndReadIncomingMessage(aBrowser, sender, receiver, conversation, message, mentions) {
  let activity;

  waitForPromise(sender.spark.internal.conversation.post(conversation, {
    displayName: message,
    mentions
  }).then((a) => {
    activity = a;
  }));
  aBrowser.waitUntil(() => aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
  assert.isTrue(aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible(), 'does not have unread indicator');
  assert.exists(aBrowser.element(`${elements.indicatorIcon}`).getAttribute('name').match(/mention(.*)/g), 'does not have mention indicator');

  // Acknowledge the activity to mark it read
  waitForPromise(receiver.spark.internal.conversation.acknowledge(conversation, activity));
  aBrowser.waitUntil(() => !aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
}

/**
 * Creates a new space and posts a message to it, then verifies
 * space is displayed properly
 *
 * @export
 * @param {object} aBrowser
 * @param {object} sender
 * @param {array} participants
 * @param {string} roomTitle
 * @param {string} firstPost
 * @param {boolean} [isOneOnOne=false]
 * @returns {undefined}
 */
export function createSpaceAndPost(aBrowser, sender, participants, roomTitle, firstPost, isOneOnOne = false) {
  const spaceTitle = isOneOnOne ? sender.displayName : roomTitle;
  let conversation;
  const createOptions = {
    participants
  };

  if (roomTitle) {
    createOptions.displayName = roomTitle;
  }
  waitForPromise(sender.spark.internal.conversation.create(createOptions)
    .then((c) => {
      conversation = c;

      return sender.spark.internal.conversation.post(c, {
        displayName: firstPost
      });
    }));
  aBrowser.waitUntil(() => aBrowser.element(`${elements.firstSpace} ${elements.title}`).isVisible()
    && aBrowser.element(`${elements.firstSpace} ${elements.title}`).getText().includes(spaceTitle));

  return conversation;
}
<commit_msg>test(journeys): update recents selector for momentum-ui<commit_after>import {assert} from 'chai';

import waitForPromise from '../../wait-for-promise';

export const elements = {
  loadingScreen: '.webex-teams-loading',
  recentsWidget: '.ciscospark-recents-widget',
  listContainer: '.ciscospark-spaces-list',
  noSpacesTitle: '.ciscospark-no-spaces-title',
  noSpacesMessage: '.ciscospark-no-spaces-message',
  firstSpace: '.ciscospark-spaces-list-item-0',
  title: '.md-list-item__header',
  unreadIndicator: '.md-list-item--unread',
  indicatorIcon: '.md-list-item--unread .md-list-item__right .md-icon',
  lastActivity: '.space-last-activity',
  callButton: 'button[aria-label="Call Space"]',
  joinCallButton: 'button[aria-label="Join Call"]',
  answerButton: 'button[aria-label="Answer"]',
  searchInput: '#pillSearchInput',
  clearButton: 'button[aria-label="clear input"]',
  headerBar: '.ciscospark-recents-header',
  headerProfile: '.ciscospark-recents-header .ciscospark-recents-header-left button',
  headerSignout: '.ciscospark-recents-header-profile-menu-signout',
  headerAddButton: 'button[aria-label="Contact a person or create a space"]'
};

export * from './space-list-filter';

/**
 * Sends a message to a space and verifies that it is received and displayed
 *
 * @export
 * @param {object} aBrowser
 * @param {object} sender - Person with spark object
 * @param {object} conversation
 * @param {string} message
 * @param {boolean} [isOneOnOne=false]
 * @returns {undefined}
 */
export function displayIncomingMessage(aBrowser, sender, conversation, message, isOneOnOne = false) {
  const spaceTitle = isOneOnOne ? sender.displayName : conversation.displayName;

  waitForPromise(sender.spark.internal.conversation.post(conversation, {
    displayName: message
  }));
  aBrowser.waitUntil(() => aBrowser.element(`${elements.firstSpace} ${elements.title}`).isVisible()
    && aBrowser.element(`${elements.firstSpace} ${elements.title}`).getText() === spaceTitle);
  assert.isTrue(aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible(), 'does not have unread indicator');
}

/**
 * Sends a message to a space and verifies that it is received and displayed,
 * then marks it read.
 *
 * @export
 * @param {object} aBrowser
 * @param {object} sender - Person with spark object
 * @param {object} receiver - Person with spark object
 * @param {object} conversation
 * @param {string} message
 * @returns {undefined}
 */
export function displayAndReadIncomingMessage(aBrowser, sender, receiver, conversation, message) {
  let activity;

  waitForPromise(sender.spark.internal.conversation.post(conversation, {
    displayName: message
  }).then((a) => {
    activity = a;
  }));
  aBrowser.waitUntil(() => aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
  assert.isTrue(aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible(), 'does not have unread indicator');
  // Acknowledge the activity to mark it read
  waitForPromise(receiver.spark.internal.conversation.acknowledge(conversation, activity));
  aBrowser.waitUntil(() => !aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
}

/**
 * Sends a message to a space and verifies that it is received and muted icon is displayed,
 * then marks it read.
 *
 * @export
 * @param {object} aBrowser
 * @param {object} sender - Person with spark object
 * @param {object} receiver - Person with spark object
 * @param {object} conversation
 * @param {string} message
 * @returns {undefined}
 */
export function displayMutedIconAndReadIncomingMessage(aBrowser, sender, receiver, conversation, message) {
  let activity;

  waitForPromise(sender.spark.internal.conversation.post(conversation, {
    displayName: message
  }).then((a) => {
    activity = a;
  }));
  aBrowser.waitUntil(() => aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
  assert.isTrue(aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible(), 'does not have unread indicator');
  assert.exists(aBrowser.element(`${elements.indicatorIcon}`).getAttribute('name').match(/alert-muted(.*)/g), 'does not have muted indicator');

  // Acknowledge the activity to mark it read
  waitForPromise(receiver.spark.internal.conversation.acknowledge(conversation, activity));
  aBrowser.waitUntil(() => !aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
}

/**
 * Sends a message to a space and verifies that it is received and mention icon is displayed,
 * then marks it read.
 *
 * @export
 * @param {object} aBrowser
 * @param {object} sender - Person with spark object
 * @param {object} receiver - Person with spark object
 * @param {object} conversation
 * @param {string} message
 * @param {object} mentions
 * @returns {undefined}
 */
export function displayMentionIconAndReadIncomingMessage(aBrowser, sender, receiver, conversation, message, mentions) {
  let activity;

  waitForPromise(sender.spark.internal.conversation.post(conversation, {
    displayName: message,
    mentions
  }).then((a) => {
    activity = a;
  }));
  aBrowser.waitUntil(() => aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
  assert.isTrue(aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible(), 'does not have unread indicator');
  assert.exists(aBrowser.element(`${elements.indicatorIcon}`).getAttribute('name').match(/mention(.*)/g), 'does not have mention indicator');

  // Acknowledge the activity to mark it read
  waitForPromise(receiver.spark.internal.conversation.acknowledge(conversation, activity));
  aBrowser.waitUntil(() => !aBrowser.element(`${elements.firstSpace} ${elements.unreadIndicator}`).isVisible());
}

/**
 * Creates a new space and posts a message to it, then verifies
 * space is displayed properly
 *
 * @export
 * @param {object} aBrowser
 * @param {object} sender
 * @param {array} participants
 * @param {string} roomTitle
 * @param {string} firstPost
 * @param {boolean} [isOneOnOne=false]
 * @returns {undefined}
 */
export function createSpaceAndPost(aBrowser, sender, participants, roomTitle, firstPost, isOneOnOne = false) {
  const spaceTitle = isOneOnOne ? sender.displayName : roomTitle;
  let conversation;
  const createOptions = {
    participants
  };

  if (roomTitle) {
    createOptions.displayName = roomTitle;
  }
  waitForPromise(sender.spark.internal.conversation.create(createOptions)
    .then((c) => {
      conversation = c;

      return sender.spark.internal.conversation.post(c, {
        displayName: firstPost
      });
    }));
  aBrowser.waitUntil(() => aBrowser.element(`${elements.firstSpace} ${elements.title}`).isVisible()
    && aBrowser.element(`${elements.firstSpace} ${elements.title}`).getText().includes(spaceTitle));

  return conversation;
}
<|endoftext|>


<commit_before>jQuery(document).ready(function($){
  csetfilter = $("input[name=changeset]");
  function toggleRepositories() {
    $("input[name^=repo-]").parent().toggle();
  }
  csetfilter.click(toggleRepositories);
  if (csetfilter.checked())
    toggleRepositories();
});
<commit_msg>0.13dev: Merged [11038] from 0.12-stable<commit_after>jQuery(document).ready(function($){
  var csetfilter = $("input[name=changeset]");
  function toggleRepositories() {
    $("input[name^=repo-]").parent().toggle();
  }
  csetfilter.click(toggleRepositories);
  if (csetfilter.checked())
    toggleRepositories();
});
<|endoftext|>


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

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name binary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/binary}
*/
setReadOnly( ns, 'binary', require( '@stdlib/strided/base/binary' ) );

/**
* @name binaryAddonDispatch
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/binary-addon-dispatch}
*/
setReadOnly( ns, 'binaryAddonDispatch', require( '@stdlib/strided/base/binary-addon-dispatch' ) );

/**
* @name dmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dmap}
*/
setReadOnly( ns, 'dmap', require( '@stdlib/strided/base/dmap' ) );

/**
* @name dmap2
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dmap2}
*/
setReadOnly( ns, 'dmap2', require( '@stdlib/strided/base/dmap2' ) );

/**
* @name dmskmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dmskmap}
*/
setReadOnly( ns, 'dmskmap', require( '@stdlib/strided/base/dmskmap' ) );

/**
* @name dtypeEnum2Str
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-enum2str}
*/
setReadOnly( ns, 'dtypeEnum2Str', require( '@stdlib/strided/base/dtype-enum2str' ) );

/**
* @name dtypeResolveEnum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-resolve-enum}
*/
setReadOnly( ns, 'dtypeResolveEnum', require( '@stdlib/strided/base/dtype-resolve-enum' ) );

/**
* @name dtypeStr2Enum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-str2enum}
*/
setReadOnly( ns, 'dtypeStr2Enum', require( '@stdlib/strided/base/dtype-str2enum' ) );

/**
* @name mapBy
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/map-by}
*/
setReadOnly( ns, 'mapBy', require( '@stdlib/strided/base/map-by' ) );

/**
* @name metaDataProps
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/meta-data-props}
*/
setReadOnly( ns, 'metaDataProps', require( '@stdlib/strided/base/meta-data-props' ) );

/**
* @name mskunary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/mskunary}
*/
setReadOnly( ns, 'mskunary', require( '@stdlib/strided/base/mskunary' ) );

/**
* @name nullary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/nullary}
*/
setReadOnly( ns, 'nullary', require( '@stdlib/strided/base/nullary' ) );

/**
* @name quaternary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/quaternary}
*/
setReadOnly( ns, 'quaternary', require( '@stdlib/strided/base/quaternary' ) );

/**
* @name quinary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/quinary}
*/
setReadOnly( ns, 'quinary', require( '@stdlib/strided/base/quinary' ) );

/**
* @name smap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/smap}
*/
setReadOnly( ns, 'smap', require( '@stdlib/strided/base/smap' ) );

/**
* @name smskmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/smskmap}
*/
setReadOnly( ns, 'smskmap', require( '@stdlib/strided/base/smskmap' ) );

/**
* @name ternary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/ternary}
*/
setReadOnly( ns, 'ternary', require( '@stdlib/strided/base/ternary' ) );

/**
* @name unary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/unary}
*/
setReadOnly( ns, 'unary', require( '@stdlib/strided/base/unary' ) );

/**
* @name unaryAddonDispatch
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/unary-addon-dispatch}
*/
setReadOnly( ns, 'unaryAddonDispatch', require( '@stdlib/strided/base/unary-addon-dispatch' ) );

// EXPORTS //

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

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name binary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/binary}
*/
setReadOnly( ns, 'binary', require( '@stdlib/strided/base/binary' ) );

/**
* @name binaryAddonDispatch
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/binary-addon-dispatch}
*/
setReadOnly( ns, 'binaryAddonDispatch', require( '@stdlib/strided/base/binary-addon-dispatch' ) );

/**
* @name dmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dmap}
*/
setReadOnly( ns, 'dmap', require( '@stdlib/strided/base/dmap' ) );

/**
* @name dmap2
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dmap2}
*/
setReadOnly( ns, 'dmap2', require( '@stdlib/strided/base/dmap2' ) );

/**
* @name dmskmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dmskmap}
*/
setReadOnly( ns, 'dmskmap', require( '@stdlib/strided/base/dmskmap' ) );

/**
* @name dtypeEnum2Str
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-enum2str}
*/
setReadOnly( ns, 'dtypeEnum2Str', require( '@stdlib/strided/base/dtype-enum2str' ) );

/**
* @name dtypeResolveEnum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-resolve-enum}
*/
setReadOnly( ns, 'dtypeResolveEnum', require( '@stdlib/strided/base/dtype-resolve-enum' ) );

/**
* @name dtypeStr2Enum
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/dtype-str2enum}
*/
setReadOnly( ns, 'dtypeStr2Enum', require( '@stdlib/strided/base/dtype-str2enum' ) );

/**
* @name mapBy
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/map-by}
*/
setReadOnly( ns, 'mapBy', require( '@stdlib/strided/base/map-by' ) );

/**
* @name metaDataProps
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/meta-data-props}
*/
setReadOnly( ns, 'metaDataProps', require( '@stdlib/strided/base/meta-data-props' ) );

/**
* @name mskunary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/mskunary}
*/
setReadOnly( ns, 'mskunary', require( '@stdlib/strided/base/mskunary' ) );

/**
* @name nullary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/nullary}
*/
setReadOnly( ns, 'nullary', require( '@stdlib/strided/base/nullary' ) );

/**
* @name quaternary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/quaternary}
*/
setReadOnly( ns, 'quaternary', require( '@stdlib/strided/base/quaternary' ) );

/**
* @name quinary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/quinary}
*/
setReadOnly( ns, 'quinary', require( '@stdlib/strided/base/quinary' ) );

/**
* @name smap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/smap}
*/
setReadOnly( ns, 'smap', require( '@stdlib/strided/base/smap' ) );

/**
* @name smap2
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/smap2}
*/
setReadOnly( ns, 'smap2', require( '@stdlib/strided/base/smap2' ) );

/**
* @name smskmap
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/smskmap}
*/
setReadOnly( ns, 'smskmap', require( '@stdlib/strided/base/smskmap' ) );

/**
* @name ternary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/ternary}
*/
setReadOnly( ns, 'ternary', require( '@stdlib/strided/base/ternary' ) );

/**
* @name unary
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/unary}
*/
setReadOnly( ns, 'unary', require( '@stdlib/strided/base/unary' ) );

/**
* @name unaryAddonDispatch
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/strided/base/unary-addon-dispatch}
*/
setReadOnly( ns, 'unaryAddonDispatch', require( '@stdlib/strided/base/unary-addon-dispatch' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>/** @jsx React.DOM */
"use strict";

var React = require('react/addons');
var ReactGoogleMaps = require('../../');
var GoogleMapsAPI = window.google.maps;
var Map = ReactGoogleMaps.Map;
var Marker = ReactGoogleMaps.Marker;
var LatLng = GoogleMapsAPI.LatLng;

var GoogleMapWithMarkers = React.createClass({
  getInitialState: function() {
    return {
      center: new LatLng(-34.397, 150.644),
      zoom: 16,
      markers: [
        {position: new LatLng(-34.397, 150.644)}
      ]
    };
  },

  render: function() {
    return (
      <Map
        zoom={this.state.zoom}
        center={this.state.center}
        width={700}
        height={700}
        onZoomChange={this.handleZoomChange}
        onCenterChange={this.handleCenterChange}
        onClick={this.handleMapClick}>
        {this.state.markers.map(this.renderMarkers)}
      </Map>
      );
  },

  renderMarkers: function(state, i) {
    return (
      <Marker position={state.position} key={i} />
      );
  },

  handleMapClick: function(mapEvent) {
    var marker = {
      position: mapEvent.latLng
    };

    var markers = React.addons
      .update(this.state.markers, {$push: [marker]});

    this.setState({markers: markers});
  },

  handleZoomChange: function(map) {
    var zoom = map.getZoom();
    if (this.state.zoom > zoom) {
      this.setState({zoom: zoom});
    }
  },

  handleCenterChange: function(map) {
    var center = map.getCenter();
    this.setState({center: center});
  }
});

React.renderComponent(<GoogleMapWithMarkers />, document.getElementById('example'));
<commit_msg>Simplify example<commit_after>/** @jsx React.DOM */
"use strict";

var React = require('react/addons');
var ReactGoogleMaps = require('../../');
var GoogleMapsAPI = window.google.maps;
var Map = ReactGoogleMaps.Map;
var Marker = ReactGoogleMaps.Marker;
var LatLng = GoogleMapsAPI.LatLng;

var GoogleMapWithMarkers = React.createClass({
  getInitialState: function() {
    return {
      center: new LatLng(-34.397, 150.644),
      zoom: 16,
      markers: [
        {position: new LatLng(-34.397, 150.644)}
      ]
    };
  },

  render: function() {
    return (
      <Map
        zoom={this.state.zoom}
        initialCenter={this.state.center}
        width={700}
        height={700}
        onZoomChange={this.handleZoomChange}
        onClick={this.handleMapClick}>
        {this.state.markers.map(this.renderMarkers)}
      </Map>
      );
  },

  renderMarkers: function(state, i) {
    return (
      <Marker position={state.position} key={i} />
      );
  },

  handleMapClick: function(mapEvent) {
    var marker = {
      position: mapEvent.latLng
    };

    var markers = React.addons
      .update(this.state.markers, {$push: [marker]});

    this.setState({markers: markers});
  },

  handleZoomChange: function(map) {
    var zoom = map.getZoom();
    if (this.state.zoom > zoom) {
      this.setState({zoom: zoom});
    }
  }
});

React.renderComponent(<GoogleMapWithMarkers />, document.getElementById('example'));
<|endoftext|>


<commit_before>//
//Dependencies
var log4js = require('log4js');
var path = require('path');
var util = require('util');
var redis_client;
var redis = require('redis');
var log4js = require('log4js');

var logger = log4js.getLogger('cacheManager');

var redis_client;

//Function to connect to redis server which runs on 6379 port.
function connectClient(port, host){
//redis_client is an instance of redis module.
redis_client = redis.createClient(port, host);

//When redis-server will connected this event will be invoked.
redis_client.on("connect", function (err) {
  if (err) {
        logger.fatal(err);
        process.exit();
      }
  logger.info("Redis connected");
});

redis_client.on("error", function (err) {
  logger.info('Redis error');
  logger.fatal(err);
});
}

// Method to save in redis cache
function setToCache(key,value,timeout, callback){
    redis_client.set(key, value, function(err){
      if(!err){
        setExpiry(key, timout);
        callback(true);
      }
      else{
        callback(false);
      }
    });
};

//Method to get from cache.
function getFromCache(key, callback){
    redis_client.get(key, function(err, result){
      if(err && result == null){
        callback(true, null);
      }
      else{
        callback(false, result);
      }
    });
};

//Method to set expiry time to key.
function setExpiry(key , timeout){
  redis_client.expire(key, timeout);
}

//Interface
module.exports = {
  "connectClient" : connectClient,
  "setToCache" : setToCache,
  "getFromCache" : getFromCache
}<commit_msg>Removed cache from application<commit_after><|endoftext|>


<commit_before>module.bootstrap.configure = def(
  [
    ephox.bolt.kernel.api.config,
    ephox.bolt.kernel.modulator.compound,
    ephox.bolt.loader.api.scripttag,
    module.bootstrap.main
  ],

  function (config, compound, scripttag, main) {
    var configfile = '../build/module.js';

    var configure = function (bootstrapBasePath, configBasePath) {
      return function (configurator) {
        var pather = function(path) {
          return bootstrapBasePath + '/' + configBasePath + '/' + path;
        };

        var modulators = configurator(pather);
        var boltApi = config.configure(compound.create(modulators), onerror);

        window.define = boltApi.define;
        window.require = boltApi.require;
      };
    };

    var onsuccess = function() {
      main.configured(window.require);
    };

    // FIX: we need to change this
    var onerror = function(message) {
      throw message;
    };

    var install = function () {
      var scripts = document.getElementsByTagName("script");

      var bootstrapUrl = scripts[scripts.length - 1].src;
      var bootstrapBasePath = bootstrapUrl.substring(0, bootstrapUrl.lastIndexOf('/bootstrap.js'));

      var configFileRelativeToPage = bootstrapBasePath + '/' + configfile;
      var configBasePath = configfile.substring(0, configfile.lastIndexOf('/'));

      window.main = main.main;
      window.configure = configure(bootstrapBasePath, configBasePath);
      scripttag.load(configFileRelativeToPage, onsuccess, onerror);
    };

    return {
      install: install
    };
  }
);
<commit_msg>tweaks<commit_after>module.bootstrap.configure = def(
  [
    ephox.bolt.kernel.api.config,
    ephox.bolt.kernel.modulator.compound,
    ephox.bolt.loader.api.scripttag,
    module.bootstrap.main
  ],

  function (config, compound, scripttag, main) {
    var configfile = '../../../build/module.js';

    var configure = function (bootstrapBasePath, configBasePath) {
      return function (configurator) {
        var pather = function(path) {
          return bootstrapBasePath + '/' + configBasePath + '/' + path;
        };

        var modulators = configurator(pather);
        var boltApi = config.configure(compound.create(modulators), onerror);

        window.define = boltApi.define;
        window.require = boltApi.require;
      };
    };

    var onsuccess = function() {
      main.configured(window.require);
    };

    // FIX: we need to change this
    var onerror = function(message) {
      throw message;
    };

    var install = function () {
      var scripts = document.getElementsByTagName("script");

      var bootstrapUrl = scripts[scripts.length - 1].src;
      var bootstrapBasePath = bootstrapUrl.substring(0, bootstrapUrl.lastIndexOf('/bootstrap.js'));

      var configFileRelativeToPage = bootstrapBasePath + '/' + configfile;
      var configBasePath = configfile.substring(0, configfile.lastIndexOf('/'));

      window.main = main.main;
      window.configure = configure(bootstrapBasePath, configBasePath);
      scripttag.load(configFileRelativeToPage, onsuccess, onerror);
    };

    return {
      install: install
    };
  }
);
<|endoftext|>


<commit_before>const getImageSize = require('image-size');
const { svg, xlink } = require('../namespaces');

/**
 * @param {Buffer} buffer
 * @return {string}
 */
function rasterToSVG(buffer) {
  const info = getImageSize(buffer);
  const { width, height, type } = info;
  const defaultNS = `${svg.name}="${svg.value}"`;
  const xlinkNS = `${xlink.name}="${xlink.value}"`;
  const data = `data:image/${type};base64,${buffer.toString('base64')}`;

  return [
    `<svg ${defaultNS} ${xlinkNS} width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`,
    `<image xlink:href="${data}" width="${width}" height="${height}" />`,
    '</svg>'
  ].join('');
}

module.exports = rasterToSVG;
<commit_msg>svg-baker: cosmetics<commit_after>const getImageSize = require('image-size');
const { svg, xlink } = require('../namespaces');

/**
 * TODO rasterToSVG#getPixelRatioFromFilename
 * @param {Buffer} buffer
 * @return {string}
 */
function rasterToSVG(buffer) {
  const info = getImageSize(buffer);
  const { width, height, type } = info;
  const defaultNS = `${svg.name}="${svg.value}"`;
  const xlinkNS = `${xlink.name}="${xlink.value}"`;
  const data = `data:image/${type};base64,${buffer.toString('base64')}`;

  return [
    `<svg ${defaultNS} ${xlinkNS} width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`,
    `<image xlink:href="${data}" width="${width}" height="${height}" />`,
    '</svg>'
  ].join('');
}

module.exports = rasterToSVG;
<|endoftext|>


<commit_before>var RSS = require('rss');
var fs = require('fs');
var fsextra = require('fs-extra');

var RSSFeedGenerator = function(options) {
    this.options = options;
    this.items = [];
}

RSSFeedGenerator.prototype.addItem = function(item) {
    this.items.push(item);
}

RSSFeedGenerator.prototype.addAllItems = function(items) {
    this.items = this.items.concat(items);
}

RSSFeedGenerator.prototype.publishFeed = function(targetDateMoment, feedPath) {

    var feedJSONPath = this.generateFeedJSONPath(targetDateMoment, feedPath);

    if (!fs.existsSync(feedJSONPath)) {
        // We are in a new day, so remove outdated json (day before yesterday)
        var outdatedJSONPath = this.generateFeedJSONPath(moment(targetDateMoment).subtract(2, 'days'), feedPath);
        if (fs.existsSync(outdatedJSONPath)) {
            fsextra.removeSync(outdatedJSONPath);
        }
    }

    var yesterdayFeedJSONPath = this.generateFeedJSONPath(moment(targetDateMoment).subtract(1, 'days'), feedPath);
    // In any case we create the base json is what we have generated yesterday
    if (fs.existsSync(yesterdayFeedJSONPath)) {
        fsextra.copy(yesterdayFeedJSONPath, feedJSONPath, {force: true});
    }

    // Read the old feed JSON, append to it and write it back
    var currentItems = [];
    if (fs.existsSync(feedJSONPath)) {
        currentItems = JSON.parse(fs.readFileSync(feedJSONPath, "utf-8"));
    }

    var newItems = currentItems.concat(this.items);
    fs.writeFileSync(feedJSONPath, JSON.stringify(newItems, null, 2));

    var feed = new RSS(this.options)

    if (newItems) {
        for (var i = 0; i < newItems.length; i++) {
            feed.item(newItems[i]);
        }
    }

    var xml = feed.xml({indent: true});
    fs.writeFileSync(feedPath, xml);
}

RSSFeedGenerator.prototype.generateFeedJSONPath = function(targetDateMoment, feedPath) {
    return feedPath + ".json." + targetDateMoment.format("YYYY-MM-DD");
}

module.exports = RSSFeedGenerator;<commit_msg>rss feed gen upgrade<commit_after>var RSS = require('rss');
var fs = require('fs-extra');

var RSSFeedGenerator = function(options) {
    this.options = options;
    this.items = [];
}

RSSFeedGenerator.prototype.addItem = function(item) {
    this.items.push(item);
}

RSSFeedGenerator.prototype.addAllItems = function(items) {
    this.items = this.items.concat(items);
}

RSSFeedGenerator.prototype.publishFeed = function(targetDateMoment, feedPath) {

    var feedJSONPath = this.generateFeedJSONPath(targetDateMoment, feedPath);

    if (!fs.existsSync(feedJSONPath)) {
        // We are in a new day, so remove outdated json (day before yesterday)
        var outdatedJSONPath = this.generateFeedJSONPath(moment(targetDateMoment).subtract(2, 'days'), feedPath);
        if (fs.existsSync(outdatedJSONPath)) {
            fs.removeSync(outdatedJSONPath);
        }
    }

    var yesterdayFeedJSONPath = this.generateFeedJSONPath(moment(targetDateMoment).subtract(1, 'days'), feedPath);
    // In any case we create the base json is what we have generated yesterday
    if (fs.existsSync(yesterdayFeedJSONPath)) {
        fs.copySync(yesterdayFeedJSONPath, feedJSONPath, {force: true});
    }

    // Read the old feed JSON, append to it and write it back
    var currentItems = [];
    if (fs.existsSync(feedJSONPath)) {
        currentItems = JSON.parse(fs.readFileSync(feedJSONPath, "utf-8"));
    }

    var newItems = currentItems.concat(this.items);
    fs.writeFileSync(feedJSONPath, JSON.stringify(newItems, null, 2));

    var feed = new RSS(this.options)

    if (newItems) {
        for (var i = 0; i < newItems.length; i++) {
            feed.item(newItems[i]);
        }
    }

    var xml = feed.xml({indent: true});
    fs.writeFileSync(feedPath, xml);
}

RSSFeedGenerator.prototype.generateFeedJSONPath = function(targetDateMoment, feedPath) {
    return feedPath + ".json." + targetDateMoment.format("YYYY-MM-DD");
}

module.exports = RSSFeedGenerator;<|endoftext|>


<commit_before>/* global moment */
import Ember from 'ember';

import PaginationControllerMixin from 'kowa/mixins/pagination-controller';
import UploadJob from 'kowa/services/upload-job';

var SettingsImagesController = Ember.ArrayController.extend(PaginationControllerMixin, {
  sortProperties: ['createdAt'],
  sortAscending: false,
  itemController: 'settings/image',

  needs: ['settings'],
  site: Ember.computed.alias('controllers.settings.model'),

  uploadUrl: function() {
    return "/api/images/upload?site=" + this.get('site').get('id');
  }.property('site'),

  // compute a dummy date to preserve images order when upload is finished and correct date is sent by the server
  // index is the file index when uploading multiple files at once
  computeTmpImageDate: function(index) {
    var lastDate = this.get('firstObject').get('createdAt');
    if (lastDate) {
      return moment(lastDate).add(index + 1, 'hours').toDate();
    }
    else {
      return new Date();
    }
  },

  actions: {
    uploadImage: function(file, index) {
      var job = new UploadJob({
        url: this.get('uploadUrl'),
        file: file
      });

      var at = this.computeTmpImageDate(index);

      // create temporary image
      var tmpImage = this.store.createRecord('image', {
        createdAt: at,
        updatedAt: at,
        name: file.name,
        size: file.size,
        type: file.type,
        isUploading: true,
        uploadProgress: 0
      });

      var controller = this;

      job.on('willUpload', function() {
        job.set('tmpImage', tmpImage);
      });

      job.on('uploadProgress', function(val) {
        job.get('tmpImage').set('uploadProgress', val);
      });

      job.on('didUpload', function(response) {
        //
        // This is crazy but I don't find any correct way to just modify the localy created record and set its 'isDirty' and 'isNew' properties to false.
        // So we destroy it, and recreate a new one with the payload sent back by the server.
        //
        // cf. http://stackoverflow.com/questions/13342250/how-to-manually-set-an-object-state-to-clean-saved-using-ember-data/27482276
        //
        job.get('tmpImage').destroyRecord();

        // push uploaded image
        var recordData = controller.store.normalize('image', response.image);
        controller.store.update('image', recordData);
      });

      this.uploader.schedule(job);
    }
  }
});

export default SettingsImagesController;
<commit_msg>Removes deprecated store#update method<commit_after>/* global moment */
import Ember from 'ember';

import PaginationControllerMixin from 'kowa/mixins/pagination-controller';
import UploadJob from 'kowa/services/upload-job';

var SettingsImagesController = Ember.ArrayController.extend(PaginationControllerMixin, {
  sortProperties: ['createdAt'],
  sortAscending: false,
  itemController: 'settings/image',

  needs: ['settings'],
  site: Ember.computed.alias('controllers.settings.model'),

  uploadUrl: function() {
    return "/api/images/upload?site=" + this.get('site').get('id');
  }.property('site'),

  // compute a dummy date to preserve images order when upload is finished and correct date is sent by the server
  // index is the file index when uploading multiple files at once
  computeTmpImageDate: function(index) {
    var lastDate = this.get('firstObject').get('createdAt');
    if (lastDate) {
      return moment(lastDate).add(index + 1, 'hours').toDate();
    }
    else {
      return new Date();
    }
  },

  actions: {
    uploadImage: function(file, index) {
      var job = new UploadJob({
        url: this.get('uploadUrl'),
        file: file
      });

      var at = this.computeTmpImageDate(index);

      // create temporary image
      var tmpImage = this.store.createRecord('image', {
        createdAt: at,
        updatedAt: at,
        name: file.name,
        size: file.size,
        type: file.type,
        isUploading: true,
        uploadProgress: 0
      });

      var controller = this;

      job.on('willUpload', function() {
        job.set('tmpImage', tmpImage);
      });

      job.on('uploadProgress', function(val) {
        job.get('tmpImage').set('uploadProgress', val);
      });

      job.on('didUpload', function(response) {
        //
        // This is crazy but I don't find any correct way to just modify the localy created record and set its 'isDirty' and 'isNew' properties to false.
        // So we destroy it, and recreate a new one with the payload sent back by the server.
        //
        // cf. http://stackoverflow.com/questions/13342250/how-to-manually-set-an-object-state-to-clean-saved-using-ember-data/27482276
        //
        job.get('tmpImage').destroyRecord();

        // push uploaded image
        var recordData = controller.store.normalize('image', response.image);
        controller.store.push('image', recordData);
      });

      this.uploader.schedule(job);
    }
  }
});

export default SettingsImagesController;
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular.module('arkclient.services')
    .service('configService', ['$mdToast', 'gettextCatalog', ConfigService]);

  /**
   * ConfigService
   * @constructor
   */
  function ConfigService() {
    self.config = require('./config/config.js');

    function getByGroup(group) {
      if (self.config[group]) {
        return self.config[group];
      }

      return null
;    }

    function getByGroupAndKey(group, key) {
      if (self.config[group] && self.config[group][key]) {
        return self.config[group][key];
      }

      return null;
    }

    return {
      getByGroup: getByGroup,
      getByGroupAndKey: getByGroupAndKey
    };
  }
})();
<commit_msg>Remove unused parameters<commit_after>(function() {
  'use strict';

  angular.module('arkclient.services')
    .service('configService', [ConfigService]);

  /**
   * ConfigService
   * @constructor
   */
  function ConfigService() {
    self.config = require('./config/config.js');

    function getByGroup(group) {
      if (self.config[group]) {
        return self.config[group];
      }

      return null
;    }

    function getByGroupAndKey(group, key) {
      if (self.config[group] && self.config[group][key]) {
        return self.config[group][key];
      }

      return null;
    }

    return {
      getByGroup: getByGroup,
      getByGroupAndKey: getByGroupAndKey
    };
  }
})();
<|endoftext|>


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

/**
 * @fileoverview Directive for the learner "practice question" view.
 */

tie.directive('learnerView', [function() {
  return {
    restrict: 'E',
    scope: {},
    template: `

            Stepper:

                {{$index + 1}}

                  {{paragraph}}

                  <ui-codemirror ui-codemirror="codeMirrorOptions" ng-model="code" class="tie-codemirror-container"></ui-codemirror>

                <select class="tie-lang-select-menu"
                    name="lang-select-menu">
                  <option value="Python" selected>Python</option>
                </select>
                <button class="tie-run-button"
                    ng-class="{'active': !nextButtonIsShown}"
                    ng-click="submitCode(code)"
                    ng-disabled="nextButtonIsShown">
                  Run
                </button>

Exercise {{currentQuestionIndex + 1}}: {{title}}

                    {{paragraph}}

                  {{paragraph}}

            <button ng-click="showNextPrompt()" ng-if="nextButtonIsShown"
                class="tie-next-button">Next</button>
            </button>

    `,
    controller: [
      '$scope', '$timeout', 'SolutionHandlerService', 'QuestionDataService',
      'LANGUAGE_PYTHON',
      function(
          $scope, $timeout, SolutionHandlerService, QuestionDataService,
          LANGUAGE_PYTHON) {
        var language = LANGUAGE_PYTHON;
        // TODO(sll): Generalize this to dynamically select a question set
        // based on user input.
        var questionSetId = 'strings';
        var NEXT_QUESTION_INTRO_PARAGRAPHS = ["Now, let's try a new question."];
        var CONGRATULATORY_FEEDBACK_PARAGRAPHS = [
          "Fantastic! You're done with this exercise. Shall we try the next one?",
          "Click the \"Next\" button below to move on to the next exercise."
        ];

        QuestionDataService.initCurrentQuestionSet(questionSetId);
        var questionSet = QuestionDataService.getCurrentQuestionSet(
          questionSetId);
        $scope.currentQuestionIndex = 0;

        var question = null;
        var prompts = null;
        var currentPromptIndex = null;
        var feedbackDiv = document.getElementById('tie-feedback');
        var instructionsDiv = document.getElementById('tie-instructions');

        var loadQuestion = function(questionId, introParagraphs) {
          question = QuestionDataService.getQuestion(questionId);
          prompts = question.getPrompts();
          currentPromptIndex = 0;
          $scope.title = question.getTitle();
          $scope.code = question.getStarterCode(language);
          $scope.instructions = prompts[currentPromptIndex].getInstructions();
          $scope.previousInstructions = [];
          $scope.nextButtonIsShown = false;
          $scope.feedbackParagraphs = introParagraphs;
        };

        var clearFeedback = function() {
          $scope.feedbackParagraphs = [];
        };

        var setFeedback = function(feedback) {
          if (feedback.isAnswerCorrect()) {
            $scope.nextButtonIsShown = true;
            $scope.feedbackParagraphs = CONGRATULATORY_FEEDBACK_PARAGRAPHS;
          } else {
            $scope.feedbackParagraphs = [feedback.getMessage()];
          }
          // Skulpt processing happens outside an Angular context, so
          // $scope.$apply() is needed to force a DOM update.
          $scope.$apply();
          feedbackDiv.lastElementChild.scrollIntoView();
        };

        $scope.codeMirrorOptions = {
          autofocus: true,
          lineNumbers: true,
          mode: LANGUAGE_PYTHON,
          smartIndent: false,
          tabSize: 4
        };

        $scope.showNextPrompt = function() {
          if (question.isLastPrompt(currentPromptIndex)) {
            $scope.currentQuestionIndex++;
            if ($scope.currentQuestionIndex >= $scope.questionIds.length) {
              // TODO(sll): This needs to be fleshed out.
              alert('Congratulations, you have finished!');
              return;
            }
            var questionId = $scope.questionIds[$scope.currentQuestionIndex];
            loadQuestion(questionId);
          } else {
            currentPromptIndex++;
            $scope.previousInstructions.push($scope.instructions);
            $scope.instructions = prompts[currentPromptIndex].getInstructions();
            $scope.nextButtonIsShown = false;
            // TODO (johnmunoz): DOM not yet updated; is there a better way
            // than using a timeout?
            $timeout(function() {
              instructionsDiv.lastElementChild.scrollIntoView();
            }, 0);
            clearFeedback();
          }
        };

        $scope.submitCode = function(code) {
          SolutionHandlerService.processSolutionAsync(
            prompts[currentPromptIndex], code,
            question.getAuxiliaryCode(language), language
          ).then(setFeedback);
        };

        $scope.questionIds = questionSet.getQuestionIds();
        loadQuestion(
          questionSet.getFirstQuestionId(),
          questionSet.getIntroductionParagraphs());
      }
    ]
  };
}]);
<commit_msg>Remove autoscroll from feedback window, since the student needs to read from the top. (#26)<commit_after>// Copyright 2017 The TIE Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Directive for the learner "practice question" view.
 */

tie.directive('learnerView', [function() {
  return {
    restrict: 'E',
    scope: {},
    template: `

            Stepper:

                {{$index + 1}}

                  {{paragraph}}

                  <ui-codemirror ui-codemirror="codeMirrorOptions" ng-model="code" class="tie-codemirror-container"></ui-codemirror>

                <select class="tie-lang-select-menu"
                    name="lang-select-menu">
                  <option value="Python" selected>Python</option>
                </select>
                <button class="tie-run-button"
                    ng-class="{'active': !nextButtonIsShown}"
                    ng-click="submitCode(code)"
                    ng-disabled="nextButtonIsShown">
                  Run
                </button>

Exercise {{currentQuestionIndex + 1}}: {{title}}

                    {{paragraph}}

                  {{paragraph}}

            <button ng-click="showNextPrompt()" ng-if="nextButtonIsShown"
                class="tie-next-button">Next</button>
            </button>

    `,
    controller: [
      '$scope', '$timeout', 'SolutionHandlerService', 'QuestionDataService',
      'LANGUAGE_PYTHON',
      function(
          $scope, $timeout, SolutionHandlerService, QuestionDataService,
          LANGUAGE_PYTHON) {
        var language = LANGUAGE_PYTHON;
        // TODO(sll): Generalize this to dynamically select a question set
        // based on user input.
        var questionSetId = 'strings';
        var NEXT_QUESTION_INTRO_PARAGRAPHS = ["Now, let's try a new question."];
        var CONGRATULATORY_FEEDBACK_PARAGRAPHS = [
          "Fantastic! You're done with this exercise. Shall we try the next one?",
          "Click the \"Next\" button below to move on to the next exercise."
        ];

        QuestionDataService.initCurrentQuestionSet(questionSetId);
        var questionSet = QuestionDataService.getCurrentQuestionSet(
          questionSetId);
        $scope.currentQuestionIndex = 0;

        var question = null;
        var prompts = null;
        var currentPromptIndex = null;

        var loadQuestion = function(questionId, introParagraphs) {
          question = QuestionDataService.getQuestion(questionId);
          prompts = question.getPrompts();
          currentPromptIndex = 0;
          $scope.title = question.getTitle();
          $scope.code = question.getStarterCode(language);
          $scope.instructions = prompts[currentPromptIndex].getInstructions();
          $scope.previousInstructions = [];
          $scope.nextButtonIsShown = false;
          $scope.feedbackParagraphs = introParagraphs;
        };

        var clearFeedback = function() {
          $scope.feedbackParagraphs = [];
        };

        var setFeedback = function(feedback) {
          if (feedback.isAnswerCorrect()) {
            $scope.nextButtonIsShown = true;
            $scope.feedbackParagraphs = CONGRATULATORY_FEEDBACK_PARAGRAPHS;
          } else {
            $scope.feedbackParagraphs = [feedback.getMessage()];
          }
          // Skulpt processing happens outside an Angular context, so
          // $scope.$apply() is needed to force a DOM update.
          $scope.$apply();
        };

        $scope.codeMirrorOptions = {
          autofocus: true,
          lineNumbers: true,
          mode: LANGUAGE_PYTHON,
          smartIndent: false,
          tabSize: 4
        };

        $scope.showNextPrompt = function() {
          if (question.isLastPrompt(currentPromptIndex)) {
            $scope.currentQuestionIndex++;
            if ($scope.currentQuestionIndex >= $scope.questionIds.length) {
              // TODO(sll): This needs to be fleshed out.
              alert('Congratulations, you have finished!');
              return;
            }
            var questionId = $scope.questionIds[$scope.currentQuestionIndex];
            loadQuestion(questionId);
          } else {
            currentPromptIndex++;
            $scope.previousInstructions.push($scope.instructions);
            $scope.instructions = prompts[currentPromptIndex].getInstructions();
            $scope.nextButtonIsShown = false;
            clearFeedback();
          }
        };

        $scope.submitCode = function(code) {
          SolutionHandlerService.processSolutionAsync(
            prompts[currentPromptIndex], code,
            question.getAuxiliaryCode(language), language
          ).then(setFeedback);
        };

        $scope.questionIds = questionSet.getQuestionIds();
        loadQuestion(
          questionSet.getFirstQuestionId(),
          questionSet.getIntroductionParagraphs());
      }
    ]
  };
}]);
<|endoftext|>


<commit_before>
import { remove } from 'lodash'

/**
 * @class Expressions
 */
export default class {

  /**
   *
   * @constructor
   */
  constructor() {
    this.items = []
  }

  get length() {
    return this.items.length
  }

  /**
   *
   * @param {Expression} value
   * @return this
   */
  add(value) {
    this.items.push(value)
    return this
  }

  /**
   *
   * @param {Any} value
   * @return this
   */
  remove(value) {
    remove(this.items, col => col.isEqual(value))
    return this
  }

  /**
   *
   * @return this
   */
  clear() {
    this.items = []
    return this
  }

}<commit_msg>Delete expressions.js<commit_after><|endoftext|>


<commit_before>import isBrowser from './isBrowser';

const isIE = isBrowser ? !!document.documentElement.currentStyle : false;

const HIDDEN_TEXTAREA_STYLE = {
  'min-height': '0',
  'max-height': 'none',
  height: '0',
  visibility: 'hidden',
  overflow: 'hidden',
  position: 'absolute',
  'z-index': '-1000',
  top: '0',
  right: '0',
};

const SIZING_STYLE = [
  'letter-spacing',
  'line-height',
  'font-family',
  'font-weight',
  'font-size',
  'font-style',
  'tab-size',
  'text-rendering',
  'text-transform',
  'width',
  'text-indent',
  'padding-top',
  'padding-right',
  'padding-bottom',
  'padding-left',
  'border-top-width',
  'border-right-width',
  'border-bottom-width',
  'border-left-width',
  'box-sizing',
];

let computedStyleCache = {};
const hiddenTextarea = isBrowser && document.createElement('textarea');

const forceHiddenStyles = node => {
  Object.keys(HIDDEN_TEXTAREA_STYLE).forEach(key => {
    node.style.setProperty(key, HIDDEN_TEXTAREA_STYLE[key], 'important');
  });
};

forceHiddenStyles(hiddenTextarea);

export default function calculateNodeHeight(
  uiTextNode,
  uid,
  useCache = false,
  minRows = null,
  maxRows = null,
) {
  if (hiddenTextarea.parentNode === null) {
    document.body.appendChild(hiddenTextarea);
  }

  // Copy all CSS properties that have an impact on the height of the content in
  // the textbox
  const nodeStyling = calculateNodeStyling(uiTextNode, uid, useCache);

  if (nodeStyling === null) {
    return null;
  }

  const { paddingSize, borderSize, boxSizing, sizingStyle } = nodeStyling;

  // Need to have the overflow attribute to hide the scrollbar otherwise
  // text-lines will not calculated properly as the shadow will technically be
  // narrower for content
  Object.keys(sizingStyle).forEach(key => {
    hiddenTextarea.style[key] = sizingStyle[key];
  });
  forceHiddenStyles(hiddenTextarea);
  hiddenTextarea.value = uiTextNode.value || uiTextNode.placeholder || 'x';

  let minHeight = -Infinity;
  let maxHeight = Infinity;
  let height = hiddenTextarea.scrollHeight;

  if (boxSizing === 'border-box') {
    // border-box: add border, since height = content + padding + border
    height = height + borderSize;
  } else if (boxSizing === 'content-box') {
    // remove padding, since height = content
    height = height - paddingSize;
  }

  // measure height of a textarea with a single row
  hiddenTextarea.value = 'x';
  const singleRowHeight = hiddenTextarea.scrollHeight - paddingSize;

  if (minRows !== null || maxRows !== null) {
    if (minRows !== null) {
      minHeight = singleRowHeight * minRows;
      if (boxSizing === 'border-box') {
        minHeight = minHeight + paddingSize + borderSize;
      }
      height = Math.max(minHeight, height);
    }
    if (maxRows !== null) {
      maxHeight = singleRowHeight * maxRows;
      if (boxSizing === 'border-box') {
        maxHeight = maxHeight + paddingSize + borderSize;
      }
      height = Math.min(maxHeight, height);
    }
  }

  const rowCount = Math.floor(height / singleRowHeight);

  return { height, minHeight, maxHeight, rowCount };
}

function calculateNodeStyling(node, uid, useCache = false) {
  if (useCache && computedStyleCache[uid]) {
    return computedStyleCache[uid];
  }

  const style = window.getComputedStyle(node);

  if (style === null) {
    return null;
  }

  let sizingStyle = SIZING_STYLE.reduce((obj, name) => {
    obj[name] = style.getPropertyValue(name);
    return obj;
  }, {});

  const boxSizing = sizingStyle['box-sizing'];

  // probably node is detached from DOM, can't read computed dimensions
  if (boxSizing === '') {
    return null;
  }

  // IE (Edge has already correct behaviour) returns content width as computed width
  // so we need to add manually padding and border widths
  if (isIE && boxSizing === 'border-box') {
    sizingStyle.width =
      parseFloat(sizingStyle.width) +
      parseFloat(style['border-right-width']) +
      parseFloat(style['border-left-width']) +
      parseFloat(style['padding-right']) +
      parseFloat(style['padding-left']) +
      'px';
  }

  const paddingSize =
    parseFloat(sizingStyle['padding-bottom']) +
    parseFloat(sizingStyle['padding-top']);

  const borderSize =
    parseFloat(sizingStyle['border-bottom-width']) +
    parseFloat(sizingStyle['border-top-width']);

  const nodeInfo = {
    sizingStyle,
    paddingSize,
    borderSize,
    boxSizing,
  };

  if (useCache) {
    computedStyleCache[uid] = nodeInfo;
  }

  return nodeInfo;
}

export const purgeCache = uid => delete computedStyleCache[uid];
<commit_msg>Fix SSR regression introduced by latest commit (fixes #196)<commit_after>import isBrowser from './isBrowser';

const isIE = isBrowser ? !!document.documentElement.currentStyle : false;

const HIDDEN_TEXTAREA_STYLE = {
  'min-height': '0',
  'max-height': 'none',
  height: '0',
  visibility: 'hidden',
  overflow: 'hidden',
  position: 'absolute',
  'z-index': '-1000',
  top: '0',
  right: '0',
};

const SIZING_STYLE = [
  'letter-spacing',
  'line-height',
  'font-family',
  'font-weight',
  'font-size',
  'font-style',
  'tab-size',
  'text-rendering',
  'text-transform',
  'width',
  'text-indent',
  'padding-top',
  'padding-right',
  'padding-bottom',
  'padding-left',
  'border-top-width',
  'border-right-width',
  'border-bottom-width',
  'border-left-width',
  'box-sizing',
];

let computedStyleCache = {};
const hiddenTextarea = isBrowser && document.createElement('textarea');

const forceHiddenStyles = node => {
  Object.keys(HIDDEN_TEXTAREA_STYLE).forEach(key => {
    node.style.setProperty(key, HIDDEN_TEXTAREA_STYLE[key], 'important');
  });
};

if (isBrowser) {
  forceHiddenStyles(hiddenTextarea);
}

export default function calculateNodeHeight(
  uiTextNode,
  uid,
  useCache = false,
  minRows = null,
  maxRows = null,
) {
  if (hiddenTextarea.parentNode === null) {
    document.body.appendChild(hiddenTextarea);
  }

  // Copy all CSS properties that have an impact on the height of the content in
  // the textbox
  const nodeStyling = calculateNodeStyling(uiTextNode, uid, useCache);

  if (nodeStyling === null) {
    return null;
  }

  const { paddingSize, borderSize, boxSizing, sizingStyle } = nodeStyling;

  // Need to have the overflow attribute to hide the scrollbar otherwise
  // text-lines will not calculated properly as the shadow will technically be
  // narrower for content
  Object.keys(sizingStyle).forEach(key => {
    hiddenTextarea.style[key] = sizingStyle[key];
  });
  forceHiddenStyles(hiddenTextarea);
  hiddenTextarea.value = uiTextNode.value || uiTextNode.placeholder || 'x';

  let minHeight = -Infinity;
  let maxHeight = Infinity;
  let height = hiddenTextarea.scrollHeight;

  if (boxSizing === 'border-box') {
    // border-box: add border, since height = content + padding + border
    height = height + borderSize;
  } else if (boxSizing === 'content-box') {
    // remove padding, since height = content
    height = height - paddingSize;
  }

  // measure height of a textarea with a single row
  hiddenTextarea.value = 'x';
  const singleRowHeight = hiddenTextarea.scrollHeight - paddingSize;

  if (minRows !== null || maxRows !== null) {
    if (minRows !== null) {
      minHeight = singleRowHeight * minRows;
      if (boxSizing === 'border-box') {
        minHeight = minHeight + paddingSize + borderSize;
      }
      height = Math.max(minHeight, height);
    }
    if (maxRows !== null) {
      maxHeight = singleRowHeight * maxRows;
      if (boxSizing === 'border-box') {
        maxHeight = maxHeight + paddingSize + borderSize;
      }
      height = Math.min(maxHeight, height);
    }
  }

  const rowCount = Math.floor(height / singleRowHeight);

  return { height, minHeight, maxHeight, rowCount };
}

function calculateNodeStyling(node, uid, useCache = false) {
  if (useCache && computedStyleCache[uid]) {
    return computedStyleCache[uid];
  }

  const style = window.getComputedStyle(node);

  if (style === null) {
    return null;
  }

  let sizingStyle = SIZING_STYLE.reduce((obj, name) => {
    obj[name] = style.getPropertyValue(name);
    return obj;
  }, {});

  const boxSizing = sizingStyle['box-sizing'];

  // probably node is detached from DOM, can't read computed dimensions
  if (boxSizing === '') {
    return null;
  }

  // IE (Edge has already correct behaviour) returns content width as computed width
  // so we need to add manually padding and border widths
  if (isIE && boxSizing === 'border-box') {
    sizingStyle.width =
      parseFloat(sizingStyle.width) +
      parseFloat(style['border-right-width']) +
      parseFloat(style['border-left-width']) +
      parseFloat(style['padding-right']) +
      parseFloat(style['padding-left']) +
      'px';
  }

  const paddingSize =
    parseFloat(sizingStyle['padding-bottom']) +
    parseFloat(sizingStyle['padding-top']);

  const borderSize =
    parseFloat(sizingStyle['border-bottom-width']) +
    parseFloat(sizingStyle['border-top-width']);

  const nodeInfo = {
    sizingStyle,
    paddingSize,
    borderSize,
    boxSizing,
  };

  if (useCache) {
    computedStyleCache[uid] = nodeInfo;
  }

  return nodeInfo;
}

export const purgeCache = uid => delete computedStyleCache[uid];
<|endoftext|>


<commit_before>var common     = require('../common');
var connection = common.createConnection();
var assert     = require('assert');

connection.connect(function(err) {
  if (err) throw err;

  getMaxAllowedPacket();
});

var oldMaxAllowedPacket;
function getMaxAllowedPacket() {
  connection.query('SHOW VARIABLES WHERE Variable_name = ?', ['max_allowed_packet'], function(err, rows) {
    if (err) throw err;

    oldMaxAllowedPacket = Number(rows[0].Value);

    increaseMaxAllowedPacketIfNeeded();
  });
}

function increaseMaxAllowedPacketIfNeeded() {
  // Our test generates a SQL query a few bytes larger than 16 MB, but lets
  // leave a little margin:
  var minMaxAllowedPacket = 20 * 1024 * 1024;

  var newMaxAllowedPacket = (oldMaxAllowedPacket < minMaxAllowedPacket)
    ? minMaxAllowedPacket
    : oldMaxAllowedPacket;

  connection.query('SET GLOBAL max_allowed_packet = ?', [newMaxAllowedPacket], function(err, rows) {
    if (err) throw err;

    triggerLargeQueryAndResponsePackets();
  });
}

var rows = [];
var length = Math.pow(256, 3) / 2; // Half, because of hex encoding
var buffer = new Buffer(length);
var sql    = 'SELECT ? as bigField';

function triggerLargeQueryAndResponsePackets() {
  connection.query(sql, [buffer], function(err, _rows) {
    if (err) throw err;

    rows = _rows;

    resetMaxAllowedPacket();
  });
}

function resetMaxAllowedPacket() {
  connection.query('SET GLOBAL max_allowed_packet = ?', [oldMaxAllowedPacket], function(err, rows) {
    if (err) {
      err.message = 'Could not reset max_allowed_packet size, please check your server settings: ' + err.message;
      throw err;
    }
  });

  connection.end();
}

process.on('exit', function() {
  assert.equal(rows.length, 1);
  assert.equal(rows[0].bigField.length, length);
});
<commit_msg>Travis debugging<commit_after>var common     = require('../common');
var connection = common.createConnection();
var assert     = require('assert');

connection.connect(function(err) {
  if (err) throw err;

  getMaxAllowedPacket();
});

var oldMaxAllowedPacket;
function getMaxAllowedPacket() {
  connection.query('SHOW VARIABLES WHERE Variable_name = ?', ['max_allowed_packet'], function(err, rows) {
    if (err) throw err;

    oldMaxAllowedPacket = Number(rows[0].Value);

    increaseMaxAllowedPacketIfNeeded();
  });
}

function increaseMaxAllowedPacketIfNeeded() {
  // Our test generates a SQL query a few bytes larger than 16 MB, but lets
  // leave a little margin:
  var minMaxAllowedPacket = 20 * 1024 * 1024;

  var newMaxAllowedPacket = (oldMaxAllowedPacket < minMaxAllowedPacket)
    ? minMaxAllowedPacket
    : oldMaxAllowedPacket;

  console.log('increasing max_allowed_packet to %s', newMaxAllowedPacket);

  connection.query('SET GLOBAL max_allowed_packet = ?', [newMaxAllowedPacket], function(err, rows) {
    if (err) throw err;

    console.log('increased max_allowed_packet', arguments);
    triggerLargeQueryAndResponsePackets();
  });
}

var rows = [];
var length = Math.pow(256, 3) / 2; // Half, because of hex encoding
var buffer = new Buffer(length);
var sql    = 'SELECT ? as bigField';

function triggerLargeQueryAndResponsePackets() {
  connection.query(sql, [buffer], function(err, _rows) {
    if (err) throw err;

    rows = _rows;

    resetMaxAllowedPacket();
  });
}

function resetMaxAllowedPacket() {
  connection.query('SET GLOBAL max_allowed_packet = ?', [oldMaxAllowedPacket], function(err, rows) {
    if (err) {
      err.message = 'Could not reset max_allowed_packet size, please check your server settings: ' + err.message;
      throw err;
    }
  });

  connection.end();
}

process.on('exit', function() {
  assert.equal(rows.length, 1);
  assert.equal(rows[0].bigField.length, length);
});
<|endoftext|>


<commit_before>/**
 * @file
 * Client for calling the API.
 */

import request from 'superagent';

/**
 * Get hierarchy for index.
 *
 * @param index
 * @returns {Promise}
 */
export function hierarchy(index) {
  return call('hierarchy', {q: index});
}

/**
 * Call endpoint on API.
 *
 * @param url
 * @param query
 * @returns {Promise}
 */
function call(url, query) {
  return new Promise((resolve, reject) => {
    request(`/api/${url}`)
      .query(query)
      .end((err, res) => {
        if (err) {
          reject(err);
        }
        else {
          const result = JSON.parse(res.text).result;
          resolve(result);
        }
      });
  });
}
<commit_msg>Implemented the /list endpoint client side<commit_after>/**
 * @file
 * Client for calling the API.
 */

import request from 'superagent';

/**
 * Get hierarchy for index.
 *
 * @param index
 * @returns {Promise}
 */
export function hierarchy(index) {
  return call('hierarchy', {q: index});
}

/**
 * Get list items for index.
 *
 * @param {Array} indexes
 * @return {Promise}
 */
export function list(indexes) {
  if (!Array.isArray(indexes)) {
    indexes = [indexes];
  }

  return call('list', {q: indexes.join(',')});
}

/**
 * Call endpoint on API.
 *
 * @param url
 * @param query
 * @returns {Promise}
 */
function call(url, query) {
  return new Promise((resolve, reject) => {
    request(`/api/${url}`)
      .query(query)
      .end((err, res) => {
        if (err) {
          reject(err);
        }
        else {
          const result = JSON.parse(res.text).result;
          resolve(result);
        }
      });
  });
}
<|endoftext|>


<commit_before>const { BagItFile } = require('./bagit_file');
const crypto = require('crypto');
const EventEmitter = require('events');
const fs = require('fs');
const { ManifestParser } = require('./manifest_parser');
const os = require('os');
const path = require('path');
const stream = require('stream');
const { TagFileParser } = require('./tag_file_parser');
const { Util } = require('../core/util');

/**
 * Validator validates BagIt packages (tarred or in directory format)
 * according to a BagIt profile.
 *
 * See the validate() method for a list of events.
 *
 */
class Validator extends EventEmitter {

    /**
     * Constructs a new BagIt validator.
     *
     * @param {string} pathToBag is the absolute path the the bag,
     * whether it's a directory or a tar file.
     *
     * @param {BagItProfile} profile is the BagItProfile that describes
     * what consititutes a valid bag.
     *
     */
    constructor(pathToBag, profile) {
        super();
        /**
         * pathToBag is the path to the directory or tar file that
         * contains the bag you want to validate.
         *
         * @type {string}
         */
        this.pathToBag = pathToBag;
        /**
         * profile is the BagItProfile against which we will validate
         * the bag.
         *
         * @type {BagItProfile}
         */
        this.profile = profile;
        /**
         * bagName is the calculated name of the bag, which will be either
         * the name of the directory that contains the bag files, or the name
         * of the tar file, minus the .tar extension. You can override this
         * by setting it explicitly.
         *
         * @type {BagItProfile}
         */
        this.bagName = path.basename(pathToBag, '.tar');
        /**
         * files is a hash of BagItFiles, where the file's path
         * within the bag (relPath) is the key, and the BagItFile
         * object is the value. The hash makes it easy to get files
         * by relative path within the archive (e.g. data/photos/img.jpg).
         *
         * @type {object.<string, BagItFile>}
        */
        this.files = {};
        /**
         * payloadFiles is an array of BagItFile objects representing
         * all of the payload files in the bag. This is a subset of the
         * same BagItFile objects in the Validator.files property.
         *
         * @type {Array<BagItFile>}
         */
        this.payloadFiles = [];
        /**
         * payloadManifests is an array of BagItFile objects representing
         * all of the payload manifests in the bag. This is a subset of the
         * same BagItFile objects in the Validator.files property.
         *
         * @type {Array<BagItFile>}
         */
        this.payloadManifests = [];
        /**
         * tagManifests is an array of BagItFile objects representing
         * all of the tag manifests in the bag. This is a subset of the
         * same BagItFile objects in the Validator.files property.
         *
         * @type {Array<BagItFile>}
         */
        this.tagManifests = [];
        /**
         * tagFiles is an array of BagItFile objects representing
         * all of the tag files in the bag. This is a subset of the
         * same BagItFile objects in the Validator.files property.
         *
         * @type {Array<BagItFile>}
         */
        this.tagFiles = [];
        /**
         * topLevelDirs is a list of strings representing the relative
         * paths of all of the directories found at the top level of the
         * bag. The "data" directory should always be in this list, if a
         * bag is valid. The validator tracks these because some BagItProfiles
         * allow top-level directories other than "data" and some do not.
         *
         * @type {Array<string>}
         */
        this.topLevelDirs = [];
        /**
         * topLevelFiles is a list of strings representing the relative
         * paths of all of the files found at the top level of the
         * bag. The "bagit.txt" and "bag-info.txt" files along with at least
         * one paylowd manifest should always be in this list if a bag is valid.
         * The validator tracks these because  some BagItProfiles allow additional
         * top-level files (other than required tag files and manifests) and some
         * do not.
         *
         * @type {Array<string>}
         */
        this.topLevelFiles = [];
        /**
         * reader will be an object capable of reading the either the tarred
         * bag (a {@link TarIterator}) or an untarred bag
         * {@link FileSystemIterator}. Classes for reading various formats
         * must implement the same read() interface and emit the same events
         * as either {@link TarIterator} or {@link FileSystemIterator}, both
         * of which are in the packaging directory of the DART project.
         *
         * @type {object}
         */
        this.reader = null;
        /**
         * errors is a list of error messages describing problems encountered
         * while trying to validate the bag or specific violations of the
         * BagItProfile that render this bag invalid.
         *
         * @type {Array<string>}
         */
        this.errors = [];
    }

    /**
     * validate runs all validation operations on the bag specified in the
     * validator's pathToBag property. This includes:
     *
     * * making sure the untarred bag name matches the tarred bag name
     * * validation checksums for all payload files, and for tag files that have checksums
     * * ensuring there are no extra or missing payload files
     * * ensuring that required tag files and manifests are present and valid
     * * ensuring that required tags are present and, where applicable, have legal values
     *
     * This method emits events "start", "task", "end", and "error".
     */
    validate() {
        this.emitter.emit('validateStart', `Validating ${this.pathToBag}`);
        if (this.pathToBag.endsWith('.tar')) {
            this.reader = new TarIterator(this.pathToBag);
        } else {
            this.reader = new FileSystemIterator(this.pathToBag);
        }
        // TODO: Attach events for entry, finish, and error.
    }

    _readEntry(entry) {
        // 1. Construct a BagItFile for the entry.
        // 2. Pass the contents of the entry through the hash digests
        // 3. Parse the contents as a manifest, if it is one
        // 4. Parse the contents as a tag file, if it is one
        // 5. Add the BagItFile to Validator.files, and to payloadFiles,
        //    payloadManifests, tagFiles, or tagManifests, as appropriate.
        // Remember that the iterator won't advance unless we read the
        // file contents (or at least pass them through the hash functions).
    }
}

module.exports.Validator = Validator;
<commit_msg>More notes, stubs, and TODO's.<commit_after>const { BagItFile } = require('./bagit_file');
const crypto = require('crypto');
const EventEmitter = require('events');
const fs = require('fs');
const { ManifestParser } = require('./manifest_parser');
const os = require('os');
const path = require('path');
const stream = require('stream');
const { TagFileParser } = require('./tag_file_parser');
const { Util } = require('../core/util');

/**
 * Validator validates BagIt packages (tarred or in directory format)
 * according to a BagIt profile.
 *
 * See the validate() method for a list of events.
 *
 */
class Validator extends EventEmitter {

    /**
     * Constructs a new BagIt validator.
     *
     * @param {string} pathToBag is the absolute path the the bag,
     * whether it's a directory or a tar file.
     *
     * @param {BagItProfile} profile is the BagItProfile that describes
     * what consititutes a valid bag.
     *
     */
    constructor(pathToBag, profile) {
        super();
        /**
         * pathToBag is the path to the directory or tar file that
         * contains the bag you want to validate.
         *
         * @type {string}
         */
        this.pathToBag = pathToBag;
        /**
         * profile is the BagItProfile against which we will validate
         * the bag.
         *
         * @type {BagItProfile}
         */
        this.profile = profile;
        /**
         * bagName is the calculated name of the bag, which will be either
         * the name of the directory that contains the bag files, or the name
         * of the tar file, minus the .tar extension. You can override this
         * by setting it explicitly.
         *
         * @type {BagItProfile}
         */
        this.bagName = path.basename(pathToBag, '.tar');
        /**
         * files is a hash of BagItFiles, where the file's path
         * within the bag (relPath) is the key, and the BagItFile
         * object is the value. The hash makes it easy to get files
         * by relative path within the archive (e.g. data/photos/img.jpg).
         *
         * @type {object.<string, BagItFile>}
        */
        this.files = {};
        /**
         * payloadFiles is an array of BagItFile objects representing
         * all of the payload files in the bag. This is a subset of the
         * same BagItFile objects in the Validator.files property.
         *
         * @type {Array<BagItFile>}
         */
        this.payloadFiles = [];
        /**
         * payloadManifests is an array of BagItFile objects representing
         * all of the payload manifests in the bag. This is a subset of the
         * same BagItFile objects in the Validator.files property.
         *
         * @type {Array<BagItFile>}
         */
        this.payloadManifests = [];
        /**
         * tagManifests is an array of BagItFile objects representing
         * all of the tag manifests in the bag. This is a subset of the
         * same BagItFile objects in the Validator.files property.
         *
         * @type {Array<BagItFile>}
         */
        this.tagManifests = [];
        /**
         * tagFiles is an array of BagItFile objects representing
         * all of the tag files in the bag. This is a subset of the
         * same BagItFile objects in the Validator.files property.
         *
         * @type {Array<BagItFile>}
         */
        this.tagFiles = [];
        /**
         * topLevelDirs is a list of strings representing the relative
         * paths of all of the directories found at the top level of the
         * bag. The "data" directory should always be in this list, if a
         * bag is valid. The validator tracks these because some BagItProfiles
         * allow top-level directories other than "data" and some do not.
         *
         * @type {Array<string>}
         */
        this.topLevelDirs = [];
        /**
         * topLevelFiles is a list of strings representing the relative
         * paths of all of the files found at the top level of the
         * bag. The "bagit.txt" and "bag-info.txt" files along with at least
         * one paylowd manifest should always be in this list if a bag is valid.
         * The validator tracks these because  some BagItProfiles allow additional
         * top-level files (other than required tag files and manifests) and some
         * do not.
         *
         * @type {Array<string>}
         */
        this.topLevelFiles = [];
        /**
         * reader will be an object capable of reading the either the tarred
         * bag (a {@link TarIterator}) or an untarred bag
         * {@link FileSystemIterator}. Classes for reading various formats
         * must implement the same read() interface and emit the same events
         * as either {@link TarIterator} or {@link FileSystemIterator}, both
         * of which are in the packaging directory of the DART project.
         *
         * @type {object}
         */
        this.reader = null;
        /**
         * errors is a list of error messages describing problems encountered
         * while trying to validate the bag or specific violations of the
         * BagItProfile that render this bag invalid.
         *
         * @type {Array<string>}
         */
        this.errors = [];

        // -----------------------------------------------------------------
        // TODO: Attach log listeners for this object's events,
        // so debug logger can print info about what's happening.
        // -----------------------------------------------------------------
    }

    /**
     * validate runs all validation operations on the bag specified in the
     * validator's pathToBag property. This includes:
     *
     * * making sure the untarred bag name matches the tarred bag name
     * * validation checksums for all payload files, and for tag files that have checksums
     * * ensuring there are no extra or missing payload files
     * * ensuring that required tag files and manifests are present and valid
     * * ensuring that required tags are present and, where applicable, have legal values
     *
     * This method emits events "start", "task", "end", and "error".
     */
    validate() {
        this.emitter.emit('validateStart', `Validating ${this.pathToBag}`);
        if (this.pathToBag.endsWith('.tar')) {
            this.reader = new TarIterator(this.pathToBag);
        } else {
            this.reader = new FileSystemIterator(this.pathToBag);
        }
        // -----------------------------------------------------------------
        // TODO: Attach listeners for entry, finish, and error.
        // -----------------------------------------------------------------
    }

    _readEntry(entry) {
        //
        // emit task for the specified file
        //
        // task.relPath
        // task.operation
        //
        // call _addBagItFile
        // call _readFile
        //
        // debug logger can listen and log events
        //
        // Remember that the iterator won't advance unless we read the
        // file contents (or at least pass them through the hash functions).
    }

    _addBagItFile(entry) {
        // Construct BagItFile from entry and add to Validator.files
        // and to payloadFiles, payloadManifests, tagFiles, or tagManifests,
        // based on the value of BagItFile.getFileType().
    }

    _readFile(bagItFile) {
        // 1. Pass the contents of the entry through the hash digests
        // 2. Parse the contents as a manifest, if it is one
        // 3. Parse the contents as a tag file, if it is one
        //
        // Can do that all in one pass using pipes.
    }
}

module.exports.Validator = Validator;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 highstreet technologies GmbH and others. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

define(['app/mwtnCommons/mwtnCommons.module',
        'app/mwtnCommons/mwtnCommons.services'], function(mwtnCommonsApp) {

  mwtnCommonsApp.register.controller('mwtnCommonsCtrl', ['$scope', '$rootScope', '$mwtnCommons', '$mwtnLog', 'FileReader',
                                                         function($scope, $rootScope, $mwtnCommons, $mwtnLog, FileReader) {

    $rootScope['section_logo'] = ''; // Add your topbar logo location here such as 'assets/images/logo_topology.gif'

    $scope.mwtnCommonsInfo = {};

    $mwtnCommons.getData(function(data){
      $scope.data = data;
    });

  }]);

});
<commit_msg>housekeeping<commit_after>/*
 * Copyright (c) 2016 highstreet technologies GmbH and others. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

define(['app/mwtnCommons/mwtnCommons.module',
        'app/mwtnCommons/mwtnCommons.services'], function(mwtnCommonsApp) {

  mwtnCommonsApp.register.controller('mwtnCommonsCtrl', ['$scope', '$rootScope', '$mwtnCommons', '$mwtnLog', 'FileReader',
                                                         function($scope, $rootScope, $mwtnCommons, $mwtnLog, FileReader) {

    $rootScope.section_logo = ''; // Add your topbar logo location here such as 'assets/images/logo_topology.gif'

    $scope.mwtnCommonsInfo = {};

    $mwtnCommons.getData(function(data){
      $scope.data = data;
    });

  }]);

});
<|endoftext|>