<commit_before>// @flow

import timm from 'timm';
import React from 'react';
import Relay, { graphql } from 'react-relay';
import pick from 'lodash/pick';
import {
  flexContainer,
  Icon,
  Select,
  Checkbox,
  TextInput,
  Modal,
  notify,
} from 'giu';
import type { ViewerT } from '../../common/types';
import _t from '../../translate';
import updateConfig from '../mutations/updateConfig';
import { LANG_OPTIONS } from '../gral/constants';
import { mutate } from './helpers';

// ==========================================
// Component declarations
// ==========================================
type PublicProps = {
  lang: string,
  viewer: ViewerT,
  onChangeLang: (str: string) => void,
  onClose: () => void,
};
type Props = PublicProps;

type FlexDirT = 'row' | 'column';

const gqlFragments = graphql`
  fragment aeSettings_viewer on Viewer {
    id
    config {
      langs
      srcPaths
      srcExtensions
      msgFunctionNames
      msgRegexps
      fMinify
      fJsOutput
      fJsonOutput
      fReactIntlOutput
    }
  }
`;

// ==========================================
// Component
// ==========================================
class Settings extends React.Component {
  props: Props;
  state: {
    langs: Array<string>,
    srcPaths: Array<string>,
    srcExtensions: Array<string>,
    msgFunctionNames: Array<string>,
    msgRegexps: Array<string>,
    fJsOutput: boolean,
  };
  refLang: ?Object;
  refMinify: ?Object;
  refReactIntlOutput: ?Object;
  refJsonOutput: ?Object;

  constructor(props: Props) {
    super(props);
    // For arrays without IDs, it's better if we keep the current state at this level,
    // rather than relying on `giu`. For other attributes (`lang`, `fMinify`...), we can
    // leave state handling entirely to `giu`, and fetch the value when the user clicks on
    // Save.
    this.state = pick(props.viewer.config, [
      'langs',
      'srcPaths',
      'srcExtensions',
      'msgFunctionNames',
      'msgRegexps',
      'fJsOutput',
    ]);
  }

  // ------------------------------------------
  render() {
    const buttons = [
      { label: _t('button_Cancel'), onClick: this.onCancel, left: true },
      { label: _t('button_Save'), onClick: this.onSave, defaultButton: true },
    ];
    return (
      <Modal
        buttons={buttons}
        onEsc={this.onCancel}
        onClickBackdrop={this.onCancel}
      >
        {this.renderConfig()}
      </Modal>
    );
  }

  renderConfig() {
    const { lang } = this.props;
    const { fMinify, fJsonOutput, fReactIntlOutput } = this.props.viewer.config;
    const { fJsOutput } = this.state;
    return (

          {_t('settingsForm_Mady language:')}{' '}
          <Select
            ref={c => {
              this.refLang = c;
            }}
            value={lang}
            items={LANG_OPTIONS}
            required
          />

          {_t('settingsForm_Languages (BCP47 codes):')}

        {this.renderList({
          id: 'langs',
          dir: 'row',
          Component: TextInput,
          placeholder: 'e.g. es-ES, ca…',
          width: 80,
        })}

          {_t('settingsForm_Source paths:')}

        {this.renderList({
          id: 'srcPaths',
          dir: 'column',
          Component: TextInput,
          placeholder: 'e.g. src/client',
          width: 300,
        })}

          {_t('settingsForm_Source extensions:')}

        {this.renderList({
          id: 'srcExtensions',
          dir: 'row',
          Component: TextInput,
          placeholder: 'e.g. .js',
          width: 60,
        })}

          {_t('settingsForm_Message translation functions to look for:')}

        {this.renderList({
          id: 'msgFunctionNames',
          dir: 'row',
          Component: TextInput,
          placeholder: 'e.g. _t',
          width: 60,
        })}

          {_t(
            'settingsForm_ADVANCED: Additional regular expressions for message parsing:'
          )}{' '}
          <Icon
            icon="info-circle"
            title={_t(
              'settingsForm_Make sure your regular expression has exactly one capture group, for example: (.*?)'
            )}
            style={style.info}
          />

        {this.renderList({
          id: 'msgRegexps',
          dir: 'column',
          Component: TextInput,
          placeholder: 'e.g. {{\\s*(.*?)\\s*}}',
          width: 300,
        })}

            {_t('settingsForm_Output:')}

            <Checkbox
              id="fJsOutput"
              value={fJsOutput}
              onChange={(ev, val) => this.setState({ fJsOutput: val })}
            />

              {_t(
                "settingsForm_JavaScript module (required if you use Mady's translation function)"
              )}
            {' '}
            <Checkbox
              ref={c => {
                this.refMinify = c;
              }}
              id="fMinify"
              disabled={!fJsOutput}
              value={fMinify}
            />
            {_t('settingsForm_Minified')}

            <Checkbox
              ref={c => {
                this.refReactIntlOutput = c;
              }}
              id="fReactIntlOutput"
              value={fReactIntlOutput}
            />

              {_t('settingsForm_React Intl JSON file')}

            <Checkbox
              ref={c => {
                this.refJsonOutput = c;
              }}
              id="fJsonOutput"
              value={fJsonOutput}
            />

              {_t('settingsForm_Generic JSON file')}

    );
  }

  /* eslint-disable react/no-unused-prop-types */
  renderList({
    id,
    dir,
    Component,
    placeholder,
    width,
  }: {
    id: string,
    dir: FlexDirT,
    Component: any,
    placeholder: string,
    width: number,
  }) {
    /* eslint-enable react/no-unused-prop-types */
    const values = this.state[id];
    return (

        {values.map((value, idx) =>

            <Component
              id={`${id}.${idx}`}
              value={value}
              placeholder={placeholder}
              onChange={this.onUpdateListItem}
              required
              errorZ={52}
              style={style.input(width)}
            />
            <Icon
              id={`${id}.${idx}`}
              icon="remove"
              onClick={this.onRemoveListItem}
              style={style.remove}
            />

        )}
        <Icon
          id={id}
          icon="plus"
          onClick={this.onCreateListItem}
          style={style.add}
        />

    );
  }

  // ------------------------------------------
  onCreateListItem = (ev: SyntheticEvent) => {
    if (!(ev.currentTarget instanceof HTMLElement)) return;
    const { id } = ev.currentTarget;
    const newList = timm.addLast(this.state[id], '');
    this.setState({ [id]: newList });
  };

  onRemoveListItem = (ev: SyntheticEvent) => {
    if (!(ev.currentTarget instanceof HTMLElement)) return;
    const [id, idx] = ev.currentTarget.id.split('.');
    const newList = timm.removeAt(this.state[id], Number(idx));
    this.setState({ [id]: newList });
  };

  onUpdateListItem = (ev: SyntheticEvent) => {
    if (!(ev.currentTarget instanceof HTMLInputElement)) return;
    const value = ev.currentTarget.value;
    const [id, idx] = ev.currentTarget.id.split('.');
    const newList = timm.replaceAt(this.state[id], Number(idx), value);
    this.setState({ [id]: newList });
  };

  onCancel = () => {
    this.props.onClose();
  };
  onSave = () => {
    // Save lang
    if (this.refLang == null) return;
    const lang = this.refLang.getValue();
    if (lang !== this.props.lang) this.props.onChangeLang(lang);

    // Save other settings
    const attrs = pick(this.state, [
      'langs',
      'srcPaths',
      'srcExtensions',
      'msgFunctionNames',
      'msgRegexps',
    ]);
    if (this.refMinify == null) return;
    attrs.fMinify = this.refMinify.getValue();
    if (this.refReactIntlOutput == null) return;
    attrs.fReactIntlOutput = this.refReactIntlOutput.getValue();
    if (this.refJsonOutput == null) return;
    attrs.fJsonOutput = this.refJsonOutput.getValue();
    mutate({
      description: 'Click on Save settings',
      mutationOptions: updateConfig({ attrs }),
      onSuccess: () => this.props.onClose(),
      onFailure: () => {
        notify({
          msg: _t('error_Configuration could not be saved'),
          type: 'error',
          icon: 'save',
        });
      },
    });
  };
}

// ------------------------------------------
const style = {
  listLabel: {
    marginTop: 7,
    marginBottom: 3,
  },
  list: (dir: FlexDirT) =>
    flexContainer(dir, {
      marginLeft: 15,
    }),
  listItem: (dir: FlexDirT) => ({
    padding: '0px 2px',
    marginTop: dir === 'column' ? 1 : undefined,
    marginRight: 10,
    whiteSpace: 'nowrap',
  }),
  input: width => ({ width }),
  add: {
    display: 'inline-block',
    marginTop: 5,
    color: '#444',
  },
  remove: { color: '#444' },
  configLine: {
    marginTop: 7,
  },
  indented: {
    marginLeft: 15,
  },
  info: {
    cursor: 'pointer',
  },
};

// ==========================================
// Public API
// ==========================================
const Container = Relay.createFragmentContainer(Settings, gqlFragments);
export default Container;
export { Settings as _Settings };
<commit_msg>Fix incorrect config update (fJsOutput)<commit_after>// @flow

import timm from 'timm';
import React from 'react';
import Relay, { graphql } from 'react-relay';
import pick from 'lodash/pick';
import {
  flexContainer,
  Icon,
  Select,
  Checkbox,
  TextInput,
  Modal,
  notify,
} from 'giu';
import type { ViewerT } from '../../common/types';
import _t from '../../translate';
import updateConfig from '../mutations/updateConfig';
import { LANG_OPTIONS } from '../gral/constants';
import { mutate } from './helpers';

// ==========================================
// Component declarations
// ==========================================
type PublicProps = {
  lang: string,
  viewer: ViewerT,
  onChangeLang: (str: string) => void,
  onClose: () => void,
};
type Props = PublicProps;

type FlexDirT = 'row' | 'column';

const gqlFragments = graphql`
  fragment aeSettings_viewer on Viewer {
    id
    config {
      langs
      srcPaths
      srcExtensions
      msgFunctionNames
      msgRegexps
      fMinify
      fJsOutput
      fJsonOutput
      fReactIntlOutput
    }
  }
`;

const STATE_ATTRS = [
  'langs',
  'srcPaths',
  'srcExtensions',
  'msgFunctionNames',
  'msgRegexps',
  'fJsOutput',
];

// ==========================================
// Component
// ==========================================
class Settings extends React.Component {
  props: Props;
  state: {
    langs: Array<string>,
    srcPaths: Array<string>,
    srcExtensions: Array<string>,
    msgFunctionNames: Array<string>,
    msgRegexps: Array<string>,
    fJsOutput: boolean,
  };
  refLang: ?Object;
  refMinify: ?Object;
  refReactIntlOutput: ?Object;
  refJsonOutput: ?Object;

  constructor(props: Props) {
    super(props);
    // - For arrays without IDs, it's better if we keep the current state at this level,
    // rather than relying on `giu`.
    // - For `fJsOutput`, we need to track it since more than one input depend on it.
    // - For other attributes (`lang`, `fMinify`...), we can
    // leave state handling entirely to `giu`, and fetch the value when the user clicks on
    // Save.
    this.state = pick(props.viewer.config, STATE_ATTRS);
  }

  // ------------------------------------------
  render() {
    const buttons = [
      { label: _t('button_Cancel'), onClick: this.onCancel, left: true },
      { label: _t('button_Save'), onClick: this.onSave, defaultButton: true },
    ];
    return (
      <Modal
        buttons={buttons}
        onEsc={this.onCancel}
        onClickBackdrop={this.onCancel}
      >
        {this.renderConfig()}
      </Modal>
    );
  }

  renderConfig() {
    const { lang } = this.props;
    const { fMinify, fJsonOutput, fReactIntlOutput } = this.props.viewer.config;
    const { fJsOutput } = this.state;
    return (

          {_t('settingsForm_Mady language:')}{' '}
          <Select
            ref={c => {
              this.refLang = c;
            }}
            value={lang}
            items={LANG_OPTIONS}
            required
          />

          {_t('settingsForm_Languages (BCP47 codes):')}

        {this.renderList({
          id: 'langs',
          dir: 'row',
          Component: TextInput,
          placeholder: 'e.g. es-ES, ca…',
          width: 80,
        })}

          {_t('settingsForm_Source paths:')}

        {this.renderList({
          id: 'srcPaths',
          dir: 'column',
          Component: TextInput,
          placeholder: 'e.g. src/client',
          width: 300,
        })}

          {_t('settingsForm_Source extensions:')}

        {this.renderList({
          id: 'srcExtensions',
          dir: 'row',
          Component: TextInput,
          placeholder: 'e.g. .js',
          width: 60,
        })}

          {_t('settingsForm_Message translation functions to look for:')}

        {this.renderList({
          id: 'msgFunctionNames',
          dir: 'row',
          Component: TextInput,
          placeholder: 'e.g. _t',
          width: 60,
        })}

          {_t(
            'settingsForm_ADVANCED: Additional regular expressions for message parsing:'
          )}{' '}
          <Icon
            icon="info-circle"
            title={_t(
              'settingsForm_Make sure your regular expression has exactly one capture group, for example: (.*?)'
            )}
            style={style.info}
          />

        {this.renderList({
          id: 'msgRegexps',
          dir: 'column',
          Component: TextInput,
          placeholder: 'e.g. {{\\s*(.*?)\\s*}}',
          width: 300,
        })}

            {_t('settingsForm_Output:')}

            <Checkbox
              id="fJsOutput"
              value={fJsOutput}
              onChange={(ev, val) => this.setState({ fJsOutput: val })}
            />

              {_t(
                "settingsForm_JavaScript module (required if you use Mady's translation function)"
              )}
            {' '}
            <Checkbox
              ref={c => {
                this.refMinify = c;
              }}
              id="fMinify"
              disabled={!fJsOutput}
              value={fMinify}
            />
            {_t('settingsForm_Minified')}

            <Checkbox
              ref={c => {
                this.refReactIntlOutput = c;
              }}
              id="fReactIntlOutput"
              value={fReactIntlOutput}
            />

              {_t('settingsForm_React Intl JSON file')}

            <Checkbox
              ref={c => {
                this.refJsonOutput = c;
              }}
              id="fJsonOutput"
              value={fJsonOutput}
            />

              {_t('settingsForm_Generic JSON file')}

    );
  }

  /* eslint-disable react/no-unused-prop-types */
  renderList({
    id,
    dir,
    Component,
    placeholder,
    width,
  }: {
    id: string,
    dir: FlexDirT,
    Component: any,
    placeholder: string,
    width: number,
  }) {
    /* eslint-enable react/no-unused-prop-types */
    const values = this.state[id];
    return (

        {values.map((value, idx) =>

            <Component
              id={`${id}.${idx}`}
              value={value}
              placeholder={placeholder}
              onChange={this.onUpdateListItem}
              required
              errorZ={52}
              style={style.input(width)}
            />
            <Icon
              id={`${id}.${idx}`}
              icon="remove"
              onClick={this.onRemoveListItem}
              style={style.remove}
            />

        )}
        <Icon
          id={id}
          icon="plus"
          onClick={this.onCreateListItem}
          style={style.add}
        />

    );
  }

  // ------------------------------------------
  onCreateListItem = (ev: SyntheticEvent) => {
    if (!(ev.currentTarget instanceof HTMLElement)) return;
    const { id } = ev.currentTarget;
    const newList = timm.addLast(this.state[id], '');
    this.setState({ [id]: newList });
  };

  onRemoveListItem = (ev: SyntheticEvent) => {
    if (!(ev.currentTarget instanceof HTMLElement)) return;
    const [id, idx] = ev.currentTarget.id.split('.');
    const newList = timm.removeAt(this.state[id], Number(idx));
    this.setState({ [id]: newList });
  };

  onUpdateListItem = (ev: SyntheticEvent) => {
    if (!(ev.currentTarget instanceof HTMLInputElement)) return;
    const value = ev.currentTarget.value;
    const [id, idx] = ev.currentTarget.id.split('.');
    const newList = timm.replaceAt(this.state[id], Number(idx), value);
    this.setState({ [id]: newList });
  };

  onCancel = () => {
    this.props.onClose();
  };
  onSave = () => {
    // Save lang
    if (this.refLang == null) return;
    const lang = this.refLang.getValue();
    if (lang !== this.props.lang) this.props.onChangeLang(lang);

    // Save other settings
    const attrs = pick(this.state, STATE_ATTRS);
    if (this.refMinify == null) return;
    attrs.fMinify = this.refMinify.getValue();
    if (this.refReactIntlOutput == null) return;
    attrs.fReactIntlOutput = this.refReactIntlOutput.getValue();
    if (this.refJsonOutput == null) return;
    attrs.fJsonOutput = this.refJsonOutput.getValue();
    mutate({
      description: 'Click on Save settings',
      mutationOptions: updateConfig({ attrs }),
      onSuccess: () => this.props.onClose(),
      onFailure: () => {
        notify({
          msg: _t('error_Configuration could not be saved'),
          type: 'error',
          icon: 'save',
        });
      },
    });
  };
}

// ------------------------------------------
const style = {
  listLabel: {
    marginTop: 7,
    marginBottom: 3,
  },
  list: (dir: FlexDirT) =>
    flexContainer(dir, {
      marginLeft: 15,
    }),
  listItem: (dir: FlexDirT) => ({
    padding: '0px 2px',
    marginTop: dir === 'column' ? 1 : undefined,
    marginRight: 10,
    whiteSpace: 'nowrap',
  }),
  input: width => ({ width }),
  add: {
    display: 'inline-block',
    marginTop: 5,
    color: '#444',
  },
  remove: { color: '#444' },
  configLine: {
    marginTop: 7,
  },
  indented: {
    marginLeft: 15,
  },
  info: {
    cursor: 'pointer',
  },
};

// ==========================================
// Public API
// ==========================================
const Container = Relay.createFragmentContainer(Settings, gqlFragments);
export default Container;
export { Settings as _Settings };
<|endoftext|>


<commit_before>var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');

var logger = require(__libs+'/eris/eris-logger');
var taskManager = require(__js+'/taskManager');
var taskDb = require(__js+'/taskDb');

var init = function () {

    var log = logger.getLogger('eris.chain.server');

    var portHTTP = process.env.IDI_PORT || __settings.eris.server.port_http || 8082;
    var app = express();

    // Configure PORTAL
    // app.use('/'+(__settings.eris.server.contextPath || 'hello-eris'), express.static(__dirname + '/ui'));

    // Configure JSON parsing as default
    app.use(bodyParser.json());

    /**
     * ROUTING
     */

    // GET multiple
    app.get('/tasks', function (req, res) {
        res.send("/tasks endpoint");
    });

    // GET single
    app.get('/task/:id', function (req, res) {
        res.send("/tasks endpoint with ID: " + req.params.id);
    });

    // POST new task
    app.post('/tasks', function (req, res) {
        var task = req.body;

        console.log("POST task: ", task);
        taskManager.addTask(task, function (err) {
            if (err) {
                console.error(err);
                res.sendStatus(500);
            } else {
                res.sendStatus(200);
            }
        });

        /* chain.addDeal(deal, function (error) {
            // needs timeout!
            db.listen.once( db.events.NEW_DEAL+'_'+deal.id, function(deal) {
                res.sendStatus(200);
            });
        }); */
    });

    http.createServer(app).listen(portHTTP, function () {
        console.log('Listening for HTTP requests on port ' + portHTTP + '.');
    });
};

module.exports = {"init": init};
<commit_msg>Fill placeholder responses<commit_after>var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');

var logger = require(__libs+'/eris/eris-logger');
var taskManager = require(__js+'/taskManager');
var taskDb = require(__js+'/taskDb');

var init = function () {

    var log = logger.getLogger('eris.chain.server');

    var portHTTP = process.env.IDI_PORT || __settings.eris.server.port_http || 8082;
    var app = express();

    // Configure PORTAL
    // app.use('/'+(__settings.eris.server.contextPath || 'hello-eris'), express.static(__dirname + '/ui'));

    // Configure JSON parsing as default
    app.use(bodyParser.json());

    /**
     * ROUTING
     */

    // GET multiple
    app.get('/tasks', function (req, res) {
        taskManager.getTaskListSize(function (size) {
            res.send("TaskListSize:" + size);
        });
    });

    // GET single
    app.get('/task/:id', function (req, res) {
        taskManager.getTaskAtIndex(req.params.id, function (data) {
            res.send(data);
        });
    });

    app.get('/keyatidx/:idx', function (req, res) {
        taskManager.getTaskKeyAtIndex(req.params.idx, function (data) {
            res.send(data);
        });
    });

    // POST new task
    app.post('/tasks', function (req, res) {
        var task = req.body;

        log.debug("POST task: ", task);
        taskManager.addTask(task, function (err) {
            if (err) {
                console.error(err);
                res.sendStatus(500);
            } else {
                res.sendStatus(200);
            }
        });

        /* chain.addDeal(deal, function (error) {
            // needs timeout!
            db.listen.once( db.events.NEW_DEAL+'_'+deal.id, function(deal) {
                res.sendStatus(200);
            });
        }); */
    });

    http.createServer(app).listen(portHTTP, function () {
        console.log('Listening for HTTP requests on port ' + portHTTP + '.');
    });
};

module.exports = {init: init};
<|endoftext|>


<commit_before>'use strict';

// https://www.hackerrank.com/challenges/aorb
// tip: be aware of HUGE numbers
// FIXME: this solution fails (timeout) for test cases #11 and above

const BigNumber = require('bignumber.js');

function main() {
    input = input.split('\n');
    for (let i = 1; --input[0] >= 0; i += 4) {
        // parse input
        let k = new BigNumber(input[i + 0], 10);
        let a = new BigNumber(input[i + 1], 16);
        let b = new BigNumber(input[i + 2], 16);
        let c = new BigNumber(input[i + 3], 16);
        process.stderr.write(`${k} ${a.toString(16)} ${b.toString(16)} ${c.toString(16)}\n`);

        a = a.toString(2);
        b = b.toString(2);
        c = c.toString(2);

        // add leading zeros, so all numbers have the same length
        const length = Math.max(a.length, b.length, c.length);
        a = padLeft(a, length).split('');
        b = padLeft(b, length).split('');
        c = padLeft(c, length).split('');
        process.stderr.write(`a ${a.join('')}\nb ${b.join('')}\nc ${c.join('')}\n`);

        // mandatory swaps
        let swaps = 0;
        for (let i = 0; i < length; i++) {
            if (c[i] === '0') {
                swaps += +a[i] + +b[i];
                a[i] = b[i] = '0';
            } else if (a[i] === '0' && b[i] === '0') {
                b[i] = '1';
                swaps++;
            }
        }

        process.stderr.write(`a ${a.join('')}\nb ${b.join('')}\nc ${c.join('')}\n= ${swaps}\n`);

        if (swaps <= k) {
            // reduce 'a' as much as possible
            for (let i = 0; i < length && swaps < k; i++) {
                if (c[i] === '1') {
                    if (a[i] === '1' && b[i] === '1') {
                        if (swaps < k) {
                            a[i] = '0';
                            swaps++;
                        }
                    } else if(b[i] === '0' && swaps < k - 1) {
                        a[i] = '0', b[i] = '1';
                        swaps += 2;
                    }
                }
            }

            process.stderr.write(`a ${a.join('')}\nb ${b.join('')}\nc ${c.join('')}\n= ${swaps}\n`);
            process.stdout.write(`${new BigNumber(a.join(''), 2).toString(16).toUpperCase()}\n`);
            process.stdout.write(`${new BigNumber(b.join(''), 2).toString(16).toUpperCase()}\n`);
        } else {
            process.stdout.write('-1\n');
        }
    }

}

function padLeft(n, zeros) {
    while (n.length < zeros) n = '0' + n;
    return n;
}

process.stdin.resume();
process.stdin.setEncoding('ascii');

let input = "";

process.stdin.on('data', function (data) {
    input += data;
});

process.stdin.on('end', main);

if (process.argv[2] === 'test') {
    process.stdin.pause();
    input = `
    4
    8
    2B
    9F
    58
    5
    B9
    40
    5A
    5
    B9
    72
    5A
    2
    91
    BE
    A8
    `.replace(/^\s+/mg, "").trim();
    process.stdout.write(`Input:\n${input}\n\nOutput:\n`);
    main();
}
<commit_msg>fixes #2<commit_after>'use strict';

// https://www.hackerrank.com/challenges/aorb
// tip: be aware of HUGE numbers

function main() {
    input = input.split('\n');
    let output = '';

    for (let i = 1; --input[0] >= 0; i += 4) {
        // parse input
        let k = input[i + 0];
        let a = input[i + 1];
        let b = input[i + 2];
        let c = input[i + 3];
        // process.stderr.write(`${k} ${a} ${b} ${c}\n`);

        // add leading zeros, so all numbers have the same length
        const length = Math.max(a.length, b.length, c.length);
        a = padLeft(a, length).split('');
        b = padLeft(b, length).split('');
        c = padLeft(c, length).split('');
        // process.stderr.write(`a ${a.join('')}\nb ${b.join('')}\nc ${c.join('')}\n`);

        // mandatory swaps
        let swaps = 0;
        for (let i = 0; i < length; i++) {
            let abin = padLeft(parseInt(a[i], 16).toString(2), 4).split('');
            let bbin = padLeft(parseInt(b[i], 16).toString(2), 4).split('');
            let cbin = padLeft(parseInt(c[i], 16).toString(2), 4).split('');

            for (let j = 0; j < 4; j++) {
                if (cbin[j] === '0') {
                    swaps += +abin[j] + +bbin[j];
                    abin[j] = bbin[j] = '0';
                } else if (abin[j] === '0' && bbin[j] === '0') {
                    bbin[j] = '1';
                    swaps++;
                }
            }

            a[i] = parseInt(abin.join(''), 2).toString(16);
            b[i] = parseInt(bbin.join(''), 2).toString(16);
        }

        // process.stderr.write(`a ${a.join('')}\nb ${b.join('')}\nc ${c.join('')}\n= ${swaps}\n`);

        if (swaps > k) {
            output += '-1\n';
        } else {

            // try to reduce 'a' as much as possible
            for (let i = 0; i < length && swaps < k; i++) {
                let abin = padLeft(parseInt(a[i], 16).toString(2), 4).split('');
                let bbin = padLeft(parseInt(b[i], 16).toString(2), 4).split('');
                let cbin = padLeft(parseInt(c[i], 16).toString(2), 4).split('');

                for (let j = 0; j < 4 && swaps < k; j++) {
                    if (cbin[j] === '1') {
                        if (abin[j] === '1' && bbin[j] === '1') {
                            if (swaps < k) {
                                abin[j] = '0';
                                swaps++;
                            }
                        } else if (bbin[j] === '0' && swaps < k - 1) {
                            abin[j] = '0', bbin[j] = '1';
                            swaps += 2;
                        }
                    }
                }

                a[i] = parseInt(abin.join(''), 2).toString(16);
                b[i] = parseInt(bbin.join(''), 2).toString(16);
            }

            // process.stderr.write(`a ${a.join('')}\nb ${b.join('')}\nc ${c.join('')}\n= ${swaps}\n`);
            output += `${leftTrim(a.join('').toUpperCase())}\n`;
            output += `${leftTrim(b.join('').toUpperCase())}\n`;
        }
    }
    process.stdout.write(output);
}

function padLeft(n, zeros) {
    while (n.length < zeros) n = '0' + n;
    return n;
}

function leftTrim(n) {
    for (var i = 0; n[i] === '0'; i++);
    return n.slice(i) || '0';
}

process.stdin.resume();
process.stdin.setEncoding('ascii');

let input = "";

process.stdin.on('data', function (data) {
    input += data;
});

process.stdin.on('end', main);

if (process.argv[2] === 'test') {
    process.stdin.pause();
    input = `
    5
    251
    5A302CEBBF618BEF55645BBC1AFD79C03F05BE16E7862
    457BCC077D82C59529919ED8F366BC8210DDCE43BD572
    8D4766143946FA2B34C31AFFE2AB82E6F2E58F9B8D278
    172
    1B8EE98D97F32750E43C9BB37309A8DC35A1E3E7AEBC5
    DD350FEBA12D2B7A83EDEFC1E3BCE71F4544420F42C6E
    8067E45E06C3182991DE523722B4E12229A0DFED6A072
    76
    4C3EA80D02FB6ED90F2AFFAEC08C7BF87261B6FB8E6EC
    C7D297281041819301A27CDDB859F362B354A7DC71DF2
    2327D5E92B4B0EA44CF713180DF2BF41279FC79E3D93B
    53
    9F0661A8AA59C0812A8BA423250C9CF0BF7211ABBF480
    49271D15F47553E13EC25E368E283A803A747996D0B24
    F37809DED47B6FE07E31678F0EC0AF432BB25912D8D37
    4
    7E607DCF2DE21420A8DD898FC7D2E7EE59061D839F447
    BAFDF5DB3D07497EE094A49ADAAE60787268F9C4A613B
    FEFDFDDF3DE75D7EE8DDAD9FDFFEE7FE7B6EFDC7BF57F
    `.replace(/^\s+/mg, "").trim();
    process.stdout.write(`Input:\n${input}\n\nOutput:\n`);
    main();
}
<|endoftext|>


<commit_before>declareUpdate();

var util = require('util.sjs');

console.log(xdmp.getRequestFieldNames());

var files = xdmp.getRequestField('files'); // Array<Node>
var fileNames = xdmp.getRequestFieldFilename('files').toArray(); // Array<string>

var uris = xdmp.getRequestField('uris', 'filename');

var collectionBatch = xdmp.getRequestField('collection-batch');
var collectionsDefault = xdmp.getRequestField('collection-defaults');
var collections = (xdmp.getRequestField('collections') || []);
if(collectionBatch) {
  collections.push('batch-' + util.uuid());
}
if(collectionsDefault) {
  collections = collections.concat(xdmp.defaultCollections().toArray())
}

// console.log(
//   xdmp.getRequestFieldNames()
//     .toArray()
//     .filter(function(f){
//       console.log(f);
//       return f.match(/^permission\*/);
//     })
//     .map(function(f){
//       var perm = {};
//       perm[f.split('\*')[1]] = xdmp.getRequestField(f);
//       return perm;
//     })
//   );

function calculatePermissions(permissions, defaults) {
  var perms = [];
  permissions.forEach(function(role){
    for(r in role) {
      if(!Array.isArray(role[r])) { role[r] = [role[r]]; }
      perms = perms.concat(
        role[r].map(function(cap){
          console.log(xdmp.permission(r, cap));
          return xdmp.permission(r, cap);
        })
      );
    }
  });
  if(defaults) {
    perms = perms.concat(xdmp.defaultPermissions());
  }
  return perms;
}
var permissions = xdmp.getRequestFieldNames()
  .toArray()
  .filter(function(f){
    console.log(f);
    return f.match(/^permission\*/);
  })
  .map(function(f){
    var perm = {};
    perm[f.split('\*')[1]] = xdmp.getRequestField(f);
    return perm;
  });

function deriveURI(node, policy, filename) {
  var basename = filename;
  switch (policy) {
    case 'filename':
      break;
    case 'id':
      throw new TypeError('id policy is not yet implemented');
      break;
    case 'uuid':
      basename = util.uuid() + '.json';
      break;
    default:
      throw new TypeError(policy + ' is not a valid URI policy');
  }
  return '/' + basename;
}

function findID(node) {
  // TODO: Get the id or _id property out of JSON or the corresponding elements out of XML
}

for(var i = 0; i < files.length; i++) {
  var node = xdmp.unquote(files[i]);
  xdmp.documentInsert(
    deriveURI(node, uris, fileNames[i]),
    node,
    calculatePermissions(permissions, xdmp.getRequestField('permission-defaults')),
    collections
  );
}

xdmp.setResponseCode(200, 'OK');
xdmp.addResponseHeader('Content-Type', 'application/json;charset=utf-8');
collections;
<commit_msg>Fixes assumption that collections are always arrays.<commit_after>declareUpdate();

var util = require('util.sjs');

console.log(xdmp.getRequestFieldNames());

var files = xdmp.getRequestField('files'); // Array<Node>
var fileNames = xdmp.getRequestFieldFilename('files').toArray(); // Array<string>

var uris = xdmp.getRequestField('uris', 'filename');

var collectionBatch = xdmp.getRequestField('collection-batch');
var collectionsDefault = xdmp.getRequestField('collection-defaults');
var collections = xdmp.getRequestField('collections');
if('string' === typeof collections) { collections = [collections]; }
if(collectionBatch) {
  collections.push('batch-' + util.uuid());
}
if(collectionsDefault) {
  collections = collections.concat(xdmp.defaultCollections().toArray())
}

// console.log(
//   xdmp.getRequestFieldNames()
//     .toArray()
//     .filter(function(f){
//       console.log(f);
//       return f.match(/^permission\*/);
//     })
//     .map(function(f){
//       var perm = {};
//       perm[f.split('\*')[1]] = xdmp.getRequestField(f);
//       return perm;
//     })
//   );

function calculatePermissions(permissions, defaults) {
  var perms = [];
  permissions.forEach(function(role){
    for(r in role) {
      if(!Array.isArray(role[r])) { role[r] = [role[r]]; }
      perms = perms.concat(
        role[r].map(function(cap){
          console.log(xdmp.permission(r, cap));
          return xdmp.permission(r, cap);
        })
      );
    }
  });
  if(defaults) {
    perms = perms.concat(xdmp.defaultPermissions());
  }
  return perms;
}
var permissions = xdmp.getRequestFieldNames()
  .toArray()
  .filter(function(f){
    console.log(f);
    return f.match(/^permission\*/);
  })
  .map(function(f){
    var perm = {};
    perm[f.split('\*')[1]] = xdmp.getRequestField(f);
    return perm;
  });

function deriveURI(node, policy, filename) {
  var basename = filename;
  switch (policy) {
    case 'filename':
      break;
    case 'id':
      throw new TypeError('id policy is not yet implemented');
      break;
    case 'uuid':
      basename = util.uuid() + '.json';
      break;
    default:
      throw new TypeError(policy + ' is not a valid URI policy');
  }
  return '/' + basename;
}

function findID(node) {
  // TODO: Get the id or _id property out of JSON or the corresponding elements out of XML
}

for(var i = 0; i < files.length; i++) {
  var node = xdmp.unquote(files[i]);
  xdmp.documentInsert(
    deriveURI(node, uris, fileNames[i]),
    node,
    calculatePermissions(permissions, xdmp.getRequestField('permission-defaults')),
    collections
  );
}

xdmp.setResponseCode(200, 'OK');
xdmp.addResponseHeader('Content-Type', 'application/json;charset=utf-8');
collections;
<|endoftext|>


<commit_before>///////////////////////////////////////
//          CharManager v1.0         //
// Copyright 2014 The Mastboys3 Team //
///////////////////////////////////////

var fromChars=function(){var e="";if(arguments.length==1){if(typeof arguments[0]=="string"||arguments[0]instanceof String){args=arguments[0].split(",");for(var t=0;t<args.length;++t){e+=String.fromCharCode(args[t])}return e}else if(typeof arguments[0]=="array"||arguments[0]instanceof Array){args=arguments[0];for(var t=0;t<args.length;++t){e+=String.fromCharCode(args[t])}return e}}else{for(var t=0;t<arguments.length;++t){e+=String.fromCharCode(arguments[t])}return e}};var toChars=function(e){var t=[];if(typeof e=="string"||e instanceof String){var n=e.split("");for(var r=0;r<n.length;r++){t.push(e.charCodeAt(r))}return t}else if(typeof e=="array"||e instanceof Array){var n=e;for(var r=0;r<n.length;r++){t.push(n[r].charCodeAt(0))}return t}};var charset=function(e){var t=document.getElementsByTagName("meta");for(var n=0;n<t.length;n++){if(t[n].getAttribute("http-equiv")=="Content-Type"){var r=t[n].getAttribute("content").split(",").join(";").split(";");for(var i=0;i<r.length;i++){if(r[i].indexOf("charset=")===0){var s=r[i].split("charset=");if(s[1]==e){return}else{var o=r;o[i]="charset="+e;document.getElementsByTagName("meta")[n].setAttribute("content",o.join(";"));return}}}}}t=document.createElement("meta");t.setAttribute("http-equiv","Content-Type");t.setAttribute("content","text/html;charset="+e);document.getElementsByTagName("head")[0].appendChild(t)};var include=function(e){var t=document.getElementsByTagName("script");for(var n=0;n<t.length;n++){if(t[n].getAttribute("src")!=null){if(t[n].getAttribute("src").indexOf(e)===0){return}}}t=document.createElement("script");t.setAttribute("type","text/javascript");t.setAttribute("src",e);document.getElementsByTagName("HEAD")[0].appendChild(t)};window.fromChars=fromChars;window.toChars=toChars;window.charset=charset;window.include=include
<commit_msg>Added the variable "params"<commit_after>///////////////////////////////////////
//          CharManager v1.0         //
// Copyright 2014 The Mastboys3 Team //
///////////////////////////////////////

var fromChars=function(){var e="";if(arguments.length==1){if(typeof arguments[0]=="string"||arguments[0]instanceof String){args=arguments[0].split(",");for(var t=0;t<args.length;++t){e+=String.fromCharCode(args[t])}return e}else if(typeof arguments[0]=="array"||arguments[0]instanceof Array){args=arguments[0];for(var t=0;t<args.length;++t){e+=String.fromCharCode(args[t])}return e}}else{for(var t=0;t<arguments.length;++t){e+=String.fromCharCode(arguments[t])}return e}};var toChars=function(e){var t=[];if(typeof e=="string"||e instanceof String){var n=e.split("");for(var r=0;r<n.length;r++){t.push(e.charCodeAt(r))}return t}else if(typeof e=="array"||e instanceof Array){var n=e;for(var r=0;r<n.length;r++){t.push(n[r].charCodeAt(0))}return t}};var charset=function(e){var t=document.getElementsByTagName("meta");for(var n=0;n<t.length;n++){if(t[n].getAttribute("http-equiv")=="Content-Type"){var r=t[n].getAttribute("content").split(",").join(";").split(";");for(var i=0;i<r.length;i++){if(r[i].indexOf("charset=")===0){var s=r[i].split("charset=");if(s[1]==e){return}else{var o=r;o[i]="charset="+e;document.getElementsByTagName("meta")[n].setAttribute("content",o.join(";"));return}}}}}t=document.createElement("meta");t.setAttribute("http-equiv","Content-Type");t.setAttribute("content","text/html;charset="+e);document.getElementsByTagName("head")[0].appendChild(t)};var include=function(e){var t=document.getElementsByTagName("script");for(var n=0;n<t.length;n++){if(t[n].getAttribute("src")!=null){if(t[n].getAttribute("src").indexOf(e)===0){return}}}t=document.createElement("script");t.setAttribute("type","text/javascript");t.setAttribute("src",e);document.getElementsByTagName("HEAD")[0].appendChild(t)};window.fromChars=fromChars;window.toChars=toChars;window.charset=charset;window.include=include;window.params=function(){var e,t=/\+/g,n=/([^&=]+)=?([^&]*)/g,r=function(e){return decodeURIComponent(e.replace(t," "))},i=window.location.search.substring(1),s={};while(e=n.exec(i)){s[r(e[1])]=r(e[2])}return s}()
<|endoftext|>


<commit_before>/*
XMLHttpRequest:
https://en.wikipedia.org/wiki/XMLHttpRequest

CouchDB:
http://guide.couchdb.org/draft/tour.html
https://wiki.apache.org/couchdb/HTTP_Document_API
http://docs.couchdb.org/en/1.6.1/config/intro.html
http://docs.couchdb.org/en/1.6.1/config/http.html#cross-origin-resource-sharing
http://docs.couchdb.org/en/1.6.1/intro/curl.html

HTML(5):
http://www.w3schools.com/html/default.asp
http://www.w3schools.com/jsref/default.asp

CouchDB configuration (Mac OS X):
~/Library/Application Support/CouchDB/etc/couchdb/local.ini
/Applications/Apache CouchDB.app/Contents/Resources/couchdbx-core/etc/couchdb/local.ini
CouchDB configuration (Windows):
C:\Program Files (x86)\Apache Software Foundation\CouchDB\etc\couchdb\local.ini
start/stop/restart: Control Panel --> Services --> Apache CouchDB

[httpd]
enable_cors = true
bind_address = 0.0.0.0  <-- for access from other devices, 127.0.0.1: local device only
...

[cors]
origins = *

*/

var request = new XMLHttpRequest();

request.onreadystatechange = function() {
	// console.log("onreadystatechange: " + request.readyState + ", " +  request.status);
	// console.log(request.responseText);
	if (request.readyState == 4) {
		if (request.status == 200) {
			var response = JSON.parse(request.responseText);
			handlers[response._id](response);
		}
		if (request.status == 404) {
			console.log("not found: " + request.responseText);
		}
	}
};

function get(variable) {
	// console.log("get " + variable);
	request.open("GET", dburl + variable, false);
	request.send();
}

function update() {
	for (var name in handlers) {
		// console.log("updating " + name);
		get(name);
	}
}

// request updates with a fixed interval (ms)
var intervalID = setInterval(update, 20000);

///////////////////////////////////////////////////////////////////////////////
// your code below

var dbname = "hci1";
var dburl = "http://127.0.0.1:5984/" + dbname + "/";
var handlers = {
	"animal" : updateAnimal,
	"showCounter" : showCounter,
	"counter" : updateCounter,
	"mytext" : updateText,
	// add further handlers here
};

function updateAnimal(response) {
	document.getElementById(response._id).src = response.src;
	document.getElementById(response._id).width = response.width;
}

function updateCounter(response) {
	document.getElementById(response._id).innerHTML =
		showCounter ? response.value : "";
}

var showCounter = true;

function showCounter(response) {
	showCounter = response.checked;
}

function updateText(response) {
	document.getElementsById("mytext").innerHTML = response.value;
}

function hideAll() {
	$('.screen').hide();
}
function showOnly(screen) {
	hideAll();
	show(screen);
}
function hide(screen) {
	document.getElementById(screen).style.display = 'none';
}
function show(screen) {
	document.getElementById(screen).style.display = 'block';
}

function replaceContent(identifier, content) {
	console.log(identifier);
	console.log(content);

	$(identifier).html(content);
}

function incNumber(element) {
	$(element).val(parseInt($(element).val()) + 1);
}
function decNumber(element) {
	$(element).val(parseInt($(element).val()) - 1);
}

function submitBookingStep1() {

	replaceContent('.js-from', $('#from').val());
	replaceContent('.js-to', $('#to').val());
	replaceContent('.js-date', $('#date').val());
	replaceContent('.js-time', $('#time').val());

	// AB is checked
	if ($("#ab").is(':checked')) {
		replaceContent('.js-ab', $('#time').val());

		var theTimeArr =  $('#time').val().split(":");
		var theTime = parseInt(theTimeArr[0]);
		theTime += 2;

		replaceContent('.js-an', theTime + ':' + theTimeArr[1]);

	} else {
		replaceContent('.js-an', $('#time').val());

		var theTimeArr =  $('#time').val().split(":");
		var theTime = parseInt(theTimeArr[0]);
		theTime -= 2;

		replaceContent('.js-ab', theTime + ':' + theTimeArr[1]);
	}

	replaceContent('.js-duration', Math.abs(theTime - theTimeArr[0]) + ' Stunden');

	showOnly('booking-step-3');
}

function submitBookingStep4() {
	alert('Vielen Dank für Ihre Bestellung!');

	show('indicator-long');
	hide('indicator-short');
	hide('indicator-arrived');

	// cycle through indicators
	setTimeout(function() {
		hide('indicator-long');
		show('indicator-short');
	}, 3000);
	setTimeout(function() {
		hide('indicator-short');
		show('indicator-arrived');
	}, 6000);
	setTimeout(function() {
		hide('indicator-arrived');
	}, 9000);

	showOnly('dashboard')
}<commit_msg>removed unused WOZ-Code<commit_after>/*
XMLHttpRequest:
https://en.wikipedia.org/wiki/XMLHttpRequest

CouchDB:
http://guide.couchdb.org/draft/tour.html
https://wiki.apache.org/couchdb/HTTP_Document_API
http://docs.couchdb.org/en/1.6.1/config/intro.html
http://docs.couchdb.org/en/1.6.1/config/http.html#cross-origin-resource-sharing
http://docs.couchdb.org/en/1.6.1/intro/curl.html

HTML(5):
http://www.w3schools.com/html/default.asp
http://www.w3schools.com/jsref/default.asp

CouchDB configuration (Mac OS X):
~/Library/Application Support/CouchDB/etc/couchdb/local.ini
/Applications/Apache CouchDB.app/Contents/Resources/couchdbx-core/etc/couchdb/local.ini
CouchDB configuration (Windows):
C:\Program Files (x86)\Apache Software Foundation\CouchDB\etc\couchdb\local.ini
start/stop/restart: Control Panel --> Services --> Apache CouchDB

[httpd]
enable_cors = true
bind_address = 0.0.0.0  <-- for access from other devices, 127.0.0.1: local device only
...

[cors]
origins = *

*/

var request = new XMLHttpRequest();

request.onreadystatechange = function() {
	// console.log("onreadystatechange: " + request.readyState + ", " +  request.status);
	// console.log(request.responseText);
	if (request.readyState == 4) {
		if (request.status == 200) {
			var response = JSON.parse(request.responseText);
			handlers[response._id](response);
		}
		if (request.status == 404) {
			console.log("not found: " + request.responseText);
		}
	}
};

function get(variable) {
	// console.log("get " + variable);
	request.open("GET", dburl + variable, false);
	request.send();
}

function update() {
	for (var name in handlers) {
		// console.log("updating " + name);
		get(name);
	}
}

// request updates with a fixed interval (ms)
var intervalID = setInterval(update, 200);

///////////////////////////////////////////////////////////////////////////////
// your code below

var dbname = "hci1";
var dburl = "http://127.0.0.1:5984/" + dbname + "/";
var handlers = {
	// add further handlers here
};

function hideAll() {
	$('.screen').hide();
}
function showOnly(screen) {
	hideAll();
	show(screen);
}
function hide(screen) {
	document.getElementById(screen).style.display = 'none';
}
function show(screen) {
	document.getElementById(screen).style.display = 'block';
}

function replaceContent(identifier, content) {
	console.log(identifier);
	console.log(content);

	$(identifier).html(content);
}

function incNumber(element) {
	$(element).val(parseInt($(element).val()) + 1);
}
function decNumber(element) {
	$(element).val(parseInt($(element).val()) - 1);
}

function submitBookingStep1() {

	replaceContent('.js-from', $('#from').val());
	replaceContent('.js-to', $('#to').val());
	replaceContent('.js-date', $('#date').val());
	replaceContent('.js-time', $('#time').val());

	// AB is checked
	if ($("#ab").is(':checked')) {
		replaceContent('.js-ab', $('#time').val());

		var theTimeArr =  $('#time').val().split(":");
		var theTime = parseInt(theTimeArr[0]);
		theTime += 2;

		replaceContent('.js-an', theTime + ':' + theTimeArr[1]);

	} else {
		replaceContent('.js-an', $('#time').val());

		var theTimeArr =  $('#time').val().split(":");
		var theTime = parseInt(theTimeArr[0]);
		theTime -= 2;

		replaceContent('.js-ab', theTime + ':' + theTimeArr[1]);
	}

	replaceContent('.js-duration', Math.abs(theTime - theTimeArr[0]) + ' Stunden');

	showOnly('booking-step-3');
}

function submitBookingStep4() {
	alert('Vielen Dank für Ihre Bestellung!');

	show('indicator-long');
	hide('indicator-short');
	hide('indicator-arrived');

	// cycle through indicators
	setTimeout(function() {
		hide('indicator-long');
		show('indicator-short');
	}, 3000);
	setTimeout(function() {
		hide('indicator-short');
		show('indicator-arrived');
	}, 6000);
	setTimeout(function() {
		hide('indicator-arrived');
	}, 9000);

	showOnly('dashboard')
}<|endoftext|>


<commit_before>define(function(require, module, exports) {
    main.consumes = [
        "Plugin", "build", "settings", "commands", "fs", "save",
        "menus", "tabManager", "ui", "dialog.error"
    ];
    main.provides = ["build.gui"];
    return main;

    function main(options, imports, register) {
        var Plugin      = imports.Plugin;
        var settings    = imports.settings;
        var commands    = imports.commands;
        var menus       = imports.menus;
        var save        = imports.save;
        var build       = imports.build;
        var fs          = imports.fs;
        var ui          = imports.ui;
        var tabs        = imports.tabManager;
        var showError   = imports["dialog.error"].show;
        var uCaseFirst  = require("c9/string").uCaseFirst;

        /***** Initialization *****/

        var plugin  = new Plugin("Ajax.org", main.consumes);
        // var emit    = plugin.getEmitter();

        var process, currentBuilder;

        var loaded = false;
        function load(){
            if (loaded) return false;
            loaded = true;

            // Commands
            commands.addCommand({
                name    : "build",
                group   : "Run & Debug",
                hint    : "builds the current file (focussed document)",
                bindKey : { mac: "Command-B", win: "Ctrl-B" },
                isAvailable : function(){
                    return getFocusTab() ? true : false;
                },
                exec : function(){
                    buildFocusTab();
                }
            }, plugin);

            commands.addCommand({
                name    : "stopbuild",
                group   : "Run & Debug",
                hint    : "stop a running build",
                bindKey : { mac: "Ctrl-Shift-C", win: "Ctrl-Shift-C" },
                isAvailable : function(){
                    return process && process.running;
                },
                exec    : function(){
                    process && process.stop();
                }
            }, plugin);

            // Settings
            settings.on("read", function(){
                settings.setDefaults("project/build", [
                    ["saveall", "true"],
                    ["builder", "auto"]
                ]);
                settings.setDefaults("user/build", [
                    ["autobuild", "true"]
                ]);

                var name = settings.get("project/build/@builder");
                setCurrentBuilder(name, function(){});
            });

            // Menus
            var c = 10000;
            menus.addItemByPath("Run/~", new ui.divider(), c += 100, plugin);

            var mnuBuildSystem = new ui.menu({
                "onprop.visible": function(e){
                    if (e.value) {
                        build.listBuilders(function(err, names){
                            var nodes = mnuBuildSystem.childNodes;
                            for (var i = nodes.length - 3; i >= 2; i--) {
                                mnuBuildSystem.removeChild(nodes[i]);
                            }

                            var builder = settings.get("project/build/@builder");
                            if (builder == "auto")
                                nodes[0].select();

                            var c = 300;
                            names.forEach(function(name){
                                menus.addItemToMenu(mnuBuildSystem, new ui.item({
                                    type     : "radio",
                                    caption  : uCaseFirst(name),
                                    value    : name,
                                    selected : builder == name
                                }), c++, plugin);
                            });
                        });
                    }
                },
                "onitemclick": function(e){
                    if (e.value == "new-build-system") {
                        tabs.open({
                            path   : settings.get("project/build/@path")
                              + "/New Builder.build",
                            active : true,
                            value  : '// Create a custom Cloud9 build system - similar to the Sublime build system\n'
                              + '// For more information see http://docs.c9.io:8080/#!/api/run-method-run\n'
                              + '{\n'
                              + '    "cmd" : ["ls", "$file", "$args"],\n'
                              + '    "env" : {},\n'
                              + '    "info" : "Building $project_path/$file",\n'
                              + '    "selector": "source.ext"\n'
                              + '}',
                            document : {
                                meta : {
                                    newfile: true
                                },
                                ace : {
                                    customSyntax : "javascript"
                                }
                            }
                        }, function(){});
                        return;
                    }

                    setCurrentBuilder(e.value, function(){});
                    settings.set("project/build/@builder", e.value);
                }
            });

            menus.addItemByPath("Run/Build System/", mnuBuildSystem,
                c += 100, plugin);
            menus.addItemByPath("Run/Build", new ui.item({
                command : "build"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Cancel Build", new ui.item({
                command : "stopbuild"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Show Build Result", new ui.item({
                onclick: function(){
                    commands.exec("showoutput", null, { id: "build" });
                }
            }), c += 100, plugin);
            menus.addItemByPath("Run/Automatically Build Supported Files", new ui.item({
                type    : "check",
                checked : "user/build/@autobuild"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Save All on Build", new ui.item({
                type    : "check",
                checked : "project/build/@saveall"
            }), c += 100, plugin);

            c = 0;
            menus.addItemByPath("Run/Build System/Automatic", new ui.item({
                type  : "radio",
                value : "auto"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Build System/~", new ui.divider(), c += 100, plugin);
            menus.addItemByPath("Run/Build System/~", new ui.divider(), c += 1000, plugin);
            menus.addItemByPath("Run/Build System/New Build System", new ui.item({
                value : "new-build-system"
            }), c += 100, plugin);

            // Hook into FS and build file when writeFile is triggered
            save.on("afterSave", function(e){
                if (!settings.getBool("user/build/@autobuild"))
                    return;

                var ext = fs.getExtension(e.path);
                if (!ext)
                    return;

                // @todo consider making this a hash map
                if (currentBuilder == "auto") {
                    if (Object.keys(build.builders).every(function(name){
                        return build.builders[name].selector != "source." + ext;
                    })) return;
                }
                else if (currentBuilder.selector != "source." + ext)
                    return;

                buildFocusTab(true, e.path);
            });
        };

        /***** Methods *****/

        function setCurrentBuilder(name, callback){
            currentBuilder = name;
            if (currentBuilder != "auto") {
                build.getBuilder(currentBuilder, true, function(err, builder){
                    if (err)
                        currentBuilder = "auto";
                    else
                        currentBuilder = builder;
                    callback(err, builder);
                });
            }
        }

        function getFocusTab(){
            var tab = tabs.focussedTab;
            if (!tab) return false;
            if (tab.path) return tab;
            if (tab.editor.type != "output") return false;

            var splits = tab.pane.aml
                .parentNode.parentNode.getElementsByTagName("tab");
            if (splits.length > 1) {
                var idx = splits[0].cloud9pane == tab.pane ? 1 : 0;
                tab = splits[idx].cloud9pane.getTab();
                return tab;
            }
            return false;
        }

        function buildFocusTab(onlyBuild, path){
            if (!path) {
                var tab = getFocusTab();
                if (!tab) return;
                path = tab.path;
            }

            if (!onlyBuild)
                commands.exec("showoutput", null, { id: "build" });

            if (settings.get("project/build/@saveall"))
                save.saveAll(done);
            else
                done();

            function done(){
                process = build.build(currentBuilder,
                    { path: path }, "build", function(err, pid){
                        if (err && err.code != "EBUILDERNOTFOUND")
                            return showError(err);
                    });
            }
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            loaded = false;
        });

        /***** Register and define API *****/

        /**
         * UI for the {@link build} plugin. This plugin is responsible for the Run
         * menu in the main menu bar, as well as the settings and the
         * preferences UI for the run plugin.
         * @singleton
         */
        /**
         * @command build Builds the currently focussed tab.
         */
        /**
         * @command stopbuild Stops the running build.
         */
        plugin.freezePublicAPI({

        });

        register(null, {
            "build.gui": plugin
        });
    }
});
<commit_msg>Avoid getting two menu items called "New Runner"<commit_after>define(function(require, module, exports) {
    main.consumes = [
        "Plugin", "build", "settings", "commands", "fs", "save",
        "menus", "tabManager", "ui", "dialog.error"
    ];
    main.provides = ["build.gui"];
    return main;

    function main(options, imports, register) {
        var Plugin      = imports.Plugin;
        var settings    = imports.settings;
        var commands    = imports.commands;
        var menus       = imports.menus;
        var save        = imports.save;
        var build       = imports.build;
        var fs          = imports.fs;
        var ui          = imports.ui;
        var tabs        = imports.tabManager;
        var showError   = imports["dialog.error"].show;
        var uCaseFirst  = require("c9/string").uCaseFirst;

        /***** Initialization *****/

        var plugin  = new Plugin("Ajax.org", main.consumes);
        // var emit    = plugin.getEmitter();

        var process, currentBuilder;

        var loaded = false;
        function load(){
            if (loaded) return false;
            loaded = true;

            // Commands
            commands.addCommand({
                name    : "build",
                group   : "Run & Debug",
                hint    : "builds the current file (focussed document)",
                bindKey : { mac: "Command-B", win: "Ctrl-B" },
                isAvailable : function(){
                    return getFocusTab() ? true : false;
                },
                exec : function(){
                    buildFocusTab();
                }
            }, plugin);

            commands.addCommand({
                name    : "stopbuild",
                group   : "Run & Debug",
                hint    : "stop a running build",
                bindKey : { mac: "Ctrl-Shift-C", win: "Ctrl-Shift-C" },
                isAvailable : function(){
                    return process && process.running;
                },
                exec    : function(){
                    process && process.stop();
                }
            }, plugin);

            // Settings
            settings.on("read", function(){
                settings.setDefaults("project/build", [
                    ["saveall", "true"],
                    ["builder", "auto"]
                ]);
                settings.setDefaults("user/build", [
                    ["autobuild", "true"]
                ]);

                var name = settings.get("project/build/@builder");
                setCurrentBuilder(name, function(){});
            });

            // Menus
            var c = 10000;
            menus.addItemByPath("Run/~", new ui.divider(), c += 100, plugin);

            var mnuBuildSystem = new ui.menu({
                "onprop.visible": function(e){
                    if (e.value) {
                        build.listBuilders(function(err, names){
                            var nodes = mnuBuildSystem.childNodes;
                            for (var i = nodes.length - 3; i >= 2; i--) {
                                mnuBuildSystem.removeChild(nodes[i]);
                            }

                            var builder = settings.get("project/build/@builder");
                            if (builder == "auto")
                                nodes[0].select();

                            var c = 300;
                            names.forEach(function(name){
                                menus.addItemToMenu(mnuBuildSystem, new ui.item({
                                    type     : "radio",
                                    caption  : uCaseFirst(name),
                                    value    : name,
                                    selected : builder == name
                                }), c++, plugin);
                            });
                        });
                    }
                },
                "onitemclick": function(e){
                    if (e.value == "new-build-system") {
                        tabs.open({
                            path   : settings.get("project/build/@path")
                              + "/My Builder.build",
                            active : true,
                            value  : '// Create a custom Cloud9 build system - similar to the Sublime build system\n'
                              + '// For more information see http://docs.c9.io:8080/#!/api/run-method-run\n'
                              + '{\n'
                              + '    "cmd" : ["ls", "$file", "$args"],\n'
                              + '    "env" : {},\n'
                              + '    "info" : "Building $project_path/$file",\n'
                              + '    "selector": "source.ext"\n'
                              + '}',
                            document : {
                                meta : {
                                    newfile: true
                                },
                                ace : {
                                    customSyntax : "javascript"
                                }
                            }
                        }, function(){});
                        return;
                    }

                    setCurrentBuilder(e.value, function(){});
                    settings.set("project/build/@builder", e.value);
                }
            });

            menus.addItemByPath("Run/Build System/", mnuBuildSystem,
                c += 100, plugin);
            menus.addItemByPath("Run/Build", new ui.item({
                command : "build"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Cancel Build", new ui.item({
                command : "stopbuild"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Show Build Result", new ui.item({
                onclick: function(){
                    commands.exec("showoutput", null, { id: "build" });
                }
            }), c += 100, plugin);
            menus.addItemByPath("Run/Automatically Build Supported Files", new ui.item({
                type    : "check",
                checked : "user/build/@autobuild"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Save All on Build", new ui.item({
                type    : "check",
                checked : "project/build/@saveall"
            }), c += 100, plugin);

            c = 0;
            menus.addItemByPath("Run/Build System/Automatic", new ui.item({
                type  : "radio",
                value : "auto"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Build System/~", new ui.divider(), c += 100, plugin);
            menus.addItemByPath("Run/Build System/~", new ui.divider(), c += 1000, plugin);
            menus.addItemByPath("Run/Build System/New Build System", new ui.item({
                value : "new-build-system"
            }), c += 100, plugin);

            // Hook into FS and build file when writeFile is triggered
            save.on("afterSave", function(e){
                if (!settings.getBool("user/build/@autobuild"))
                    return;

                var ext = fs.getExtension(e.path);
                if (!ext)
                    return;

                // @todo consider making this a hash map
                if (currentBuilder == "auto") {
                    if (Object.keys(build.builders).every(function(name){
                        return build.builders[name].selector != "source." + ext;
                    })) return;
                }
                else if (currentBuilder.selector != "source." + ext)
                    return;

                buildFocusTab(true, e.path);
            });
        };

        /***** Methods *****/

        function setCurrentBuilder(name, callback){
            currentBuilder = name;
            if (currentBuilder != "auto") {
                build.getBuilder(currentBuilder, true, function(err, builder){
                    if (err)
                        currentBuilder = "auto";
                    else
                        currentBuilder = builder;
                    callback(err, builder);
                });
            }
        }

        function getFocusTab(){
            var tab = tabs.focussedTab;
            if (!tab) return false;
            if (tab.path) return tab;
            if (tab.editor.type != "output") return false;

            var splits = tab.pane.aml
                .parentNode.parentNode.getElementsByTagName("tab");
            if (splits.length > 1) {
                var idx = splits[0].cloud9pane == tab.pane ? 1 : 0;
                tab = splits[idx].cloud9pane.getTab();
                return tab;
            }
            return false;
        }

        function buildFocusTab(onlyBuild, path){
            if (!path) {
                var tab = getFocusTab();
                if (!tab) return;
                path = tab.path;
            }

            if (!onlyBuild)
                commands.exec("showoutput", null, { id: "build" });

            if (settings.get("project/build/@saveall"))
                save.saveAll(done);
            else
                done();

            function done(){
                process = build.build(currentBuilder,
                    { path: path }, "build", function(err, pid){
                        if (err && err.code != "EBUILDERNOTFOUND")
                            return showError(err);
                    });
            }
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            loaded = false;
        });

        /***** Register and define API *****/

        /**
         * UI for the {@link build} plugin. This plugin is responsible for the Run
         * menu in the main menu bar, as well as the settings and the
         * preferences UI for the run plugin.
         * @singleton
         */
        /**
         * @command build Builds the currently focussed tab.
         */
        /**
         * @command stopbuild Stops the running build.
         */
        plugin.freezePublicAPI({

        });

        register(null, {
            "build.gui": plugin
        });
    }
});
<|endoftext|>


<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
*/

var path = require('path');
var util = require('../cordova/util');
var platforms = require('./platformsConfig.json');
var events = require('cordova-common').events;

// Avoid loading the same platform projects more than once (identified by path)
var cachedApis = {};

// getPlatformApi() should be the only method of instantiating the
// PlatformProject classes for now.
function getPlatformApi(platform, platformRootDir) {

    // if platformRootDir is not specified, try to detect it first
    if (!platformRootDir) {
        var projectRootDir = util.isCordova();
        platformRootDir = projectRootDir && path.join(projectRootDir, 'platforms', platform);
    }

    if (!platformRootDir) {
        // If platformRootDir is still undefined, then we're probably is not inside of cordova project
        throw new Error('Current location is not a Cordova project');
    }

    // CB-11174 Resolve symlinks first before working with root directory
    platformRootDir = util.convertToRealPathSafe(platformRootDir);

    var cached = cachedApis[platformRootDir];
    if (cached && cached.platform == platform) return cached;

    if (!platforms[platform]) throw new Error('Unknown platform ' + platform);

    var PlatformApi;
    try {
        // First we need to find whether platform exposes its' API via js module
        // If it does, then we require and instantiate it.
        var platformApiModule = path.join(platformRootDir, 'cordova', 'Api.js');
        PlatformApi = require(platformApiModule);
    } catch (err) {
        // Check if platform already compatible w/ PlatformApi and show deprecation warning
        if (err && err.code === 'MODULE_NOT_FOUND' && platforms[platform].apiCompatibleSince) {
            events.emit('warn', ' Using this version of Cordova with older version of cordova-' + platform +
                ' is being deprecated. Consider upgrading to cordova-' + platform + '@' +
                platforms[platform].apiCompatibleSince + ' or newer.');
        } else {
            events.emit('warn', 'Error loading cordova-'+platform);
        }

        PlatformApi = require('./PlatformApiPoly');
    }

    var platformApi = new PlatformApi(platform, platformRootDir, events);
    cachedApis[platformRootDir] = platformApi;
    return platformApi;
}

module.exports = platforms;

// We don't want these methods to be enumerable on the platforms object, because we expect enumerable properties of the
// platforms object to be platforms.
Object.defineProperties(module.exports, {
    'getPlatformApi': {value: getPlatformApi, configurable: true, writable: true}
});
<commit_msg>CB-12088 Fix misleading warning when adding platform without Api.js<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
*/

var path = require('path');
var util = require('../cordova/util');
var platforms = require('./platformsConfig.json');
var events = require('cordova-common').events;

// Avoid loading the same platform projects more than once (identified by path)
var cachedApis = {};

// getPlatformApi() should be the only method of instantiating the
// PlatformProject classes for now.
function getPlatformApi(platform, platformRootDir) {

    // if platformRootDir is not specified, try to detect it first
    if (!platformRootDir) {
        var projectRootDir = util.isCordova();
        platformRootDir = projectRootDir && path.join(projectRootDir, 'platforms', platform);
    }

    if (!platformRootDir) {
        // If platformRootDir is still undefined, then we're probably is not inside of cordova project
        throw new Error('Current location is not a Cordova project');
    }

    // CB-11174 Resolve symlinks first before working with root directory
    platformRootDir = util.convertToRealPathSafe(platformRootDir);

    var cached = cachedApis[platformRootDir];
    if (cached && cached.platform == platform) return cached;

    if (!platforms[platform]) throw new Error('Unknown platform ' + platform);

    var PlatformApi;
    try {
        // First we need to find whether platform exposes its' API via js module
        // If it does, then we require and instantiate it.
        var platformApiModule = path.join(platformRootDir, 'cordova', 'Api.js');
        PlatformApi = require(platformApiModule);
    } catch (err) {
        // Check if platform already compatible w/ PlatformApi and show deprecation warning
        if (err && err.code === 'MODULE_NOT_FOUND') {
            if (platforms[platform].apiCompatibleSince) {
                events.emit('warn', ' Using this version of Cordova with older version of cordova-' + platform +
                    ' is being deprecated. Consider upgrading to cordova-' + platform + '@' +
                    platforms[platform].apiCompatibleSince + ' or newer.');
            }
            // else nothing - there is no Api.js and no deprecation information hence
            // the platform just does not expose Api and we will use polyfill as usual
        } else {
            events.emit('warn', 'Error loading cordova-'+platform);
        }

        PlatformApi = require('./PlatformApiPoly');
    }

    var platformApi = new PlatformApi(platform, platformRootDir, events);
    cachedApis[platformRootDir] = platformApi;
    return platformApi;
}

module.exports = platforms;

// We don't want these methods to be enumerable on the platforms object, because we expect enumerable properties of the
// platforms object to be platforms.
Object.defineProperties(module.exports, {
    'getPlatformApi': {value: getPlatformApi, configurable: true, writable: true}
});
<|endoftext|>


<commit_before>(function() {

	// A multiple bar chart

	// The Model
	// The model abstraction is a matrix of categories: the main dimansion will define the groups,
	// and the secondary will define the single bars.
	// Optional dimension is on the bar chart color (to be defined).

	var model = raw.model();

	// Group dimension.
	// It can accept both numbers and strings
	var groups = model.dimension()
		.title('Groups')
		.types(Number, String)

	// Categories dimension. each category will define a bar
	// It can accept both numbers and strings
	var categories = model.dimension()
		.title('Categories')
		.types(Number, String)
		.required(1)

	// Values dimension. It will define the height of the bars
	var sizes = model.dimension()
		.title('Size')
		.types(Number)

	// Colors dimension. It will define the color of the bars
	var colorsDimesion = model.dimension()
		.title('Colors')
		.types(String)

	// Mapping function
	// For each record in the data returns the values
	// for the X and Y dimensions and casts them as numbers
	model.map(function(data) {

		var results = d3.nest()
						.key(groups)
						.key(categories)
						.rollup(function(g){
							//get all the variables from the first item
							var result = g.map(function(d){
														return {
															group: groups(d),
															category: categories(d),
															color: colorsDimesion(d)
														}
													})[0];
							//If the size is defined, sum the size, otherwise count items
							result.size = sizes() != null ? d3.sum(g, function(d) {return sizes(d) }) : g.length;

							return result;
						})
						.entries(data);

		//for each group, flatten the second level of nest
		results.forEach(function(group){
			temp_values = [];
			//get the values, flatten them
			group.values.forEach(function(category){
				temp_values.push(category.values);
			})
			group.values = temp_values;
		});

		console.log(results);

		return results;

		/*
		if(groups() != null) {

			var nest = d3.nest()
				.key(groups)
				.rollup(function(g) {
					return g.map(function(d) {
						return {
							group: groups(d),
							category: categories(d),
							size: +sizes(d),
							color: colorsDimesion(d)
						};
					})
				})
				.entries(data)

			return nest;
		} else {
			var catNest = d3.nest()
					.key(categories)
					.rollup(function(g) {
						if(sizes() != null) {
							return d3.sum(g, function(d) {return sizes(d) })
						} else {
							return g.length
						}
					})
					.entries(data);

			var results = {};
			results.key = "";
			results.values = [];
			for(cat in catNest){
				results.values.push({group: "",
									category: catNest[cat].key,
									size: catNest[cat].values,
									color: ""
				})
			}

			return [results];
		}*/

	})

	// The Chart

	var chart = raw.chart()
		.title("Bar chart")
		.description("A bar chart or bar graph is a chart or graph that presents grouped data with rectangular bars with heights proportional to the values that they represent.
Chart based on https://bl.ocks.org/mbostock/3310560")
		.thumbnail("imgs/barChart.png")
		.model(model)

	// visualiziation options
	// Width
	var width = chart.number()
		.title('Width')
		.defaultValue(900)

	// Height
	var height = chart.number()
		.title('Height')
		.defaultValue(600)

	// Space between barcharts
	var padding = chart.number()
		.title('Vertical padding')
		.defaultValue(10);

	// Padding between bars
	var xPadding = chart.number()
		.title('Horizontal padding')
		.defaultValue(0.1);

	// Use or not the same scale across all the bar charts
	var sameScale = chart.checkbox()
        .title("Use same scale")
        .defaultValue(false)

	// Chart colors
	var colors = chart.color()
        .title("Color scale")

	// Drawing function
	// selection represents the d3 selection (svg)
	// data is not the original set of records
	// but the result of the model map function
	chart.draw(function(selection, data) {

		// Define margins
		var margin = {top: 0, right: 0, bottom: 50, left: 50};

		// Define common variables.
    	// Find the overall maximum value
    	var maxValue

    	if(sameScale()) {
    		maxValue = d3.max(data, function(item) {
    			return d3.max(item.values, function(d) {
    				return d.size; }); })
    		console.log(maxValue);
    	}

    	// Check consistency among categories and colors, save them all
    	var allCategories = [];
    	var allColors = [];
    	data.forEach(function(item){

    		var temp_categories = item.values.map(function(val){
    			return val.category;
    		})
    		allCategories = allCategories.concat(temp_categories);

    		// Same for color
    		var temp_colors = item.values.map(function(val){
    			return val.color;
    		})
    		allColors = allColors.concat(temp_colors);
    	})
    	//keep uniques
    	allCategories = d3.set(allCategories).values();
    	allColors = d3.set(allColors).values();

		// svg size
		selection
			.attr("width", width())
			.attr("height", height())

		// define single barchart height,
		// depending on the number of bar charts
		var w = +width() - margin.left,
			h = (+height() - margin.bottom - (+padding() * (data.length - 1))) / data.length;

		// Define scales
		var xScale = d3.scale.ordinal()
			.rangeRoundBands([0, w], +xPadding(), 0);

		var yScale = d3.scale.linear()
			.range([h, 0]);

		// Define color scale domain
		colors.domain(allColors);

		// Draw each bar chart
		data.forEach(function(item, index) {

			// Define x domain
			xScale.domain(allCategories);
			// Define y domain
			if(sameScale()) {
				yScale.domain([0, maxValue]);
			} else {
				yScale.domain([0, d3.max(item.values, function(d) {
					return d.size;
				})]);
			}

			// Append a grupo containing axis and bars,
			// move it according the index
			barchart = selection.append("g")
				.attr("transform", "translate(" + margin.left + "," + index * (h + padding()) + ")");

			// Draw y axis
			barchart.append("g")
				.attr("class", "y axis")
				.call(d3.svg.axis().scale(yScale).orient("left").ticks(h/20));

			// Draw the bars
			barchart.selectAll(".bar")
				.data(item.values)
				.enter().append("rect")
				.attr("class", "bar")
				.attr("x", function(d) {
					return xScale(d.category);
				})
				.attr("width", xScale.rangeBand())
				.attr("y", function(d) {
					return yScale(d.size);
				})
				.attr("height", function(d) {
					return h - yScale(d.size);
				})
				.style("fill", function(d){
					return colors()(d.color);
				});

		})

		// After all the charts, draw x axis
		selection.append("g")
			.attr("class", "x axis")
			.attr("transform", "translate(" + margin.bottom + "," + ((h + padding()) * data.length - padding()) + ")")
			.call(d3.svg.axis().scale(xScale).orient("bottom"));

		// Set styles

		d3.selectAll(".axis line, .axis path")
			.style("shape-rendering", "crispEdges")
			.style("fill", "none")
			.style("stroke", "#ccc")

	})
})();
<commit_msg>removed useless code from barChart<commit_after>(function() {

	// A multiple bar chart

	// The Model
	// The model abstraction is a matrix of categories: the main dimansion will define the groups,
	// and the secondary will define the single bars.
	// Optional dimension is on the bar chart color (to be defined).

	var model = raw.model();

	// Group dimension.
	// It can accept both numbers and strings
	var groups = model.dimension()
		.title('Groups')
		.types(Number, String)

	// Categories dimension. each category will define a bar
	// It can accept both numbers and strings
	var categories = model.dimension()
		.title('Categories')
		.types(Number, String)
		.required(1)

	// Values dimension. It will define the height of the bars
	var sizes = model.dimension()
		.title('Size')
		.types(Number)

	// Colors dimension. It will define the color of the bars
	var colorsDimesion = model.dimension()
		.title('Colors')
		.types(String)

	// Mapping function
	// For each record in the data returns the values
	// for the X and Y dimensions and casts them as numbers
	model.map(function(data) {

		var results = d3.nest()
						.key(groups)
						.key(categories)
						.rollup(function(g){
							//get all the variables from the first item
							var result = g.map(function(d){
														return {
															group: groups(d),
															category: categories(d),
															color: colorsDimesion(d)
														}
													})[0];
							//If the size is defined, sum the size, otherwise count items
							result.size = sizes() != null ? d3.sum(g, function(d) {return sizes(d) }) : g.length;

							return result;
						})
						.entries(data);

		//for each group, flatten the second level of nest
		results.forEach(function(group){
			temp_values = [];
			//get the values, flatten them
			group.values.forEach(function(category){
				temp_values.push(category.values);
			})
			group.values = temp_values;
		});

		console.log(results);

		return results;
	})

	// The Chart

	var chart = raw.chart()
		.title("Bar chart")
		.description("A bar chart or bar graph is a chart or graph that presents grouped data with rectangular bars with heights proportional to the values that they represent.
Chart based on https://bl.ocks.org/mbostock/3310560")
		.thumbnail("imgs/barChart.png")
		.model(model)

	// visualiziation options
	// Width
	var width = chart.number()
		.title('Width')
		.defaultValue(900)

	// Height
	var height = chart.number()
		.title('Height')
		.defaultValue(600)

	// Space between barcharts
	var padding = chart.number()
		.title('Vertical padding')
		.defaultValue(10);

	// Padding between bars
	var xPadding = chart.number()
		.title('Horizontal padding')
		.defaultValue(0.1);

	// Use or not the same scale across all the bar charts
	var sameScale = chart.checkbox()
        .title("Use same scale")
        .defaultValue(false)

	// Chart colors
	var colors = chart.color()
        .title("Color scale")

	// Drawing function
	// selection represents the d3 selection (svg)
	// data is not the original set of records
	// but the result of the model map function
	chart.draw(function(selection, data) {

		// Define margins
		var margin = {top: 0, right: 0, bottom: 50, left: 50};

		// Define common variables.
    	// Find the overall maximum value
    	var maxValue

    	if(sameScale()) {
    		maxValue = d3.max(data, function(item) {
    			return d3.max(item.values, function(d) {
    				return d.size; }); })
    		console.log(maxValue);
    	}

    	// Check consistency among categories and colors, save them all
    	var allCategories = [];
    	var allColors = [];
    	data.forEach(function(item){

    		var temp_categories = item.values.map(function(val){
    			return val.category;
    		})
    		allCategories = allCategories.concat(temp_categories);

    		// Same for color
    		var temp_colors = item.values.map(function(val){
    			return val.color;
    		})
    		allColors = allColors.concat(temp_colors);
    	})
    	//keep uniques
    	allCategories = d3.set(allCategories).values();
    	allColors = d3.set(allColors).values();

		// svg size
		selection
			.attr("width", width())
			.attr("height", height())

		// define single barchart height,
		// depending on the number of bar charts
		var w = +width() - margin.left,
			h = (+height() - margin.bottom - (+padding() * (data.length - 1))) / data.length;

		// Define scales
		var xScale = d3.scale.ordinal()
			.rangeRoundBands([0, w], +xPadding(), 0);

		var yScale = d3.scale.linear()
			.range([h, 0]);

		// Define color scale domain
		colors.domain(allColors);

		// Draw each bar chart
		data.forEach(function(item, index) {

			// Define x domain
			xScale.domain(allCategories);
			// Define y domain
			if(sameScale()) {
				yScale.domain([0, maxValue]);
			} else {
				yScale.domain([0, d3.max(item.values, function(d) {
					return d.size;
				})]);
			}

			// Append a grupo containing axis and bars,
			// move it according the index
			barchart = selection.append("g")
				.attr("transform", "translate(" + margin.left + "," + index * (h + padding()) + ")");

			// Draw y axis
			barchart.append("g")
				.attr("class", "y axis")
				.call(d3.svg.axis().scale(yScale).orient("left").ticks(h/20));

			// Draw the bars
			barchart.selectAll(".bar")
				.data(item.values)
				.enter().append("rect")
				.attr("class", "bar")
				.attr("x", function(d) {
					return xScale(d.category);
				})
				.attr("width", xScale.rangeBand())
				.attr("y", function(d) {
					return yScale(d.size);
				})
				.attr("height", function(d) {
					return h - yScale(d.size);
				})
				.style("fill", function(d){
					return colors()(d.color);
				});

		})

		// After all the charts, draw x axis
		selection.append("g")
			.attr("class", "x axis")
			.attr("transform", "translate(" + margin.bottom + "," + ((h + padding()) * data.length - padding()) + ")")
			.call(d3.svg.axis().scale(xScale).orient("bottom"));

		// Set styles

		d3.selectAll(".axis line, .axis path")
			.style("shape-rendering", "crispEdges")
			.style("fill", "none")
			.style("stroke", "#ccc")

	})
})();
<|endoftext|>


<commit_before>var playlists = [];

function updateUserPage (user) {
  /* Do something with the user
   * OLD TEST CODE
  playlists = ['abc', 'def', 'xyz', 'fuck you michael'];

  var list = document.getElementById("playlists");
  var scope = angular.element(list).scope();

  console.log(list);
  console.log(scope);

  scope.$apply(function() {scope.playlists = playlists});
  */
}

function updateSporklists (sporklists) {
  var sidebarList = document.getElementById("playlists");
  var scope = angular.element(list).scope();
  scope.$apply(function() {scope.playlists = sporklists});
}

/* This is the wrapper for the entire UI */
(function () {
  angular.module('Playlist',[]).controller('PLCtrl',function($scope) {
    /* EDIT THE FOLLOWING FOR REAL DATA */

    /* playlists -> get playlists from Parse */
    $scope.playlists = playlists;
  });
}());
<commit_msg>undid the updating to sporklists<commit_after>var playlists = [];

function updateUserPage (user) {
  /* Do something with the user
   * OLD TEST CODE
  playlists = ['abc', 'def', 'xyz', 'fuck you michael'];

  var list = document.getElementById("playlists");
  var scope = angular.element(list).scope();

  console.log(list);
  console.log(scope);

  scope.$apply(function() {scope.playlists = playlists});
  */
}

function updateSporklists (sporklists) {
  var sidebarList = document.getElementById("playlists");
  var scope = angular.element(list).scope();
  /* scope.$apply(function() {scope.playlists = sporklists}); */
}

/* This is the wrapper for the entire UI */
(function () {
  angular.module('Playlist',[]).controller('PLCtrl',function($scope) {
    /* EDIT THE FOLLOWING FOR REAL DATA */

    /* playlists -> get playlists from Parse */
    $scope.playlists = playlists;
  });
}());
<|endoftext|>