<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 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';

// MODULES //

var resolve = require( 'path' ).resolve;
var join = require( 'path' ).join;
var exec = require( 'child_process' ).exec;
var tape = require( 'tape' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var IS_WINDOWS = require( '@stdlib/assert/is-windows' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;
var evil = require( '@stdlib/utils/eval' );

// VARIABLES //

var fpath = resolve( __dirname, '..', 'bin', 'cli' );
var opts = {
	'skip': IS_BROWSER || IS_WINDOWS
};

// FIXTURES //

var PKG_VERSION = require( './../package.json' ).version;

// TESTS //

tape( 'command-line interface', function test( t ) {
	t.ok( true, __filename );
	t.end();
});

tape( 'when invoked with a `--help` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'--help'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-h` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'-h'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `--version` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'--version'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-V` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'-V'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'the command-line interface generates a bundle', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		join( __dirname, 'fixtures', 'main' )
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
			try {
				evil( stdout.toString() );
				t.fail( 'should throw an error' );
			} catch ( err ) {
				t.equal( err.message, 'BEEP', 'has expected error message' );
			}
		}
		t.end();
	}
});

tape( 'the command-line interface supports providing a custom glob pattern', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		join( __dirname, 'fixtures', 'main' ),
		'--pattern',
		'*.js'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
			try {
				evil( stdout.toString() );
				t.fail( 'should throw an error' );
			} catch ( err ) {
				t.equal( err.message, 'BEEP', 'has expected error message' );
			}
		}
		t.end();
	}
});
<commit_msg>Set maxBuffer<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 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';

// MODULES //

var resolve = require( 'path' ).resolve;
var join = require( 'path' ).join;
var exec = require( 'child_process' ).exec;
var tape = require( 'tape' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var IS_WINDOWS = require( '@stdlib/assert/is-windows' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;
var evil = require( '@stdlib/utils/eval' );

// VARIABLES //

var fpath = resolve( __dirname, '..', 'bin', 'cli' );
var opts = {
	'skip': IS_BROWSER || IS_WINDOWS
};

// FIXTURES //

var PKG_VERSION = require( './../package.json' ).version;

// TESTS //

tape( 'command-line interface', function test( t ) {
	t.ok( true, __filename );
	t.end();
});

tape( 'when invoked with a `--help` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'--help'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-h` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'-h'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `--version` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'--version'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-V` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'-V'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'the command-line interface generates a bundle', opts, function test( t ) {
	var opts;
	var cmd;

	cmd = [
		process.execPath,
		fpath,
		join( __dirname, 'fixtures', 'main' )
	];
	opts = {
		'maxBuffer': 400*1024
	};

	exec( cmd.join( ' ' ), opts, done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
			try {
				evil( stdout.toString() );
				t.fail( 'should throw an error' );
			} catch ( err ) {
				t.equal( err.message, 'BEEP', 'has expected error message' );
			}
		}
		t.end();
	}
});

tape( 'the command-line interface supports providing a custom glob pattern', opts, function test( t ) {
	var opts;
	var cmd;

	cmd = [
		process.execPath,
		fpath,
		join( __dirname, 'fixtures', 'main' ),
		'--pattern',
		'*.js'
	];
	opts = {
		'maxBuffer': 400*1024
	};

	exec( cmd.join( ' ' ), opts, done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
			try {
				evil( stdout.toString() );
				t.fail( 'should throw an error' );
			} catch ( err ) {
				t.equal( err.message, 'BEEP', 'has expected error message' );
			}
		}
		t.end();
	}
});
<|endoftext|>


<commit_before>import React, { Component } from "react";
import { DateField } from "react-date-picker";
import "react-date-picker/index.css";
import "./CreateView.css";
import ErrorList from "./ErrorList";
import Client from "../Client";
import Redirect from "react-router/Redirect";
import PropTypes from "prop-types";
import Moment from "moment";
import EventsMap from "./EventsMap";

class CreateView extends Component {
  state = {
    fields: {
      name: "",
      date: "",
      recurring: false,
      recursuntil: "",
      recurs: 0,
      location: "",
      desc: "",
      img:  "",
      file: null,
      startTime: "",
      endTime: "",
      path: "",
      imgName: "",
      createdBy: ""
    },
    fieldErrors: [],
    progress: "create",
    event: {},
    comeFrom: "",
  }

  componentWillMount() {
    const uri = "/api/user/current";

    let fields = {};

    if (this.props.progress) {
      const progress =  this.props.progress;

      let eventUri = `/api/event/get?id=${this.props.id}&token=dashboard`;
      Client.get(eventUri)
        .then(event => {
          console.log(event);
          event = event[0];
          this.setState({event});

          let date = Moment(event.date);

          const fields = {
            name: event.name,
            date: date.format("M/D/YYYY H:mm"),
            recurring: event.recursive,
            recursuntil: event.recursUntil,
            recurs: event.recursEvery,
            location: event.address,
            desc: event.description,
            img:  event.images,
            file: null,
            startTime: "",
            endTime: "",
            path: "",
            imgName: "",
            createdBy: event.createdBy
          }

          this.setState({ progress, fields, comeFrom: "event"});
        })
    } else {
      fields = this.state.fields;
    }

    Client.get(uri)
      .then(user => {
        fields.createdBy = user.id;
        this.setState({fields});
    });
  }

  validate(fields) {
    const errors = [];
    if (!fields.name) errors.push(this.context.language.Errors.nameNeeded);
    if (!fields.date) errors.push(this.context.language.Errors.dateNeeded);
    if (!fields.location) errors.push(this.context.language.Errors.locationNeeded);
    if (!fields.desc) errors.push(this.context.language.Errors.descriptionNeeded);
    if (!fields.startTime) errors.push(this.context.language.Errors.startNeeded);
    if (!fields.endTime) errors.push(this.context.language.Errors.endNeeded);
    if (fields.startTime.length !== 5 || fields.endTime.length !== 5) errors.push(this.context.language.Errors.incorrectTime);

    return errors;
  }

  onInputChange(event) {
    const fields = this.state.fields;
    fields[event.target.name] = event.target.value;

    if (event.target.name === "recurring") {
      fields[event.target.name] = event.target.checked;
      if (event.target.checked === true) {
        document.querySelector(".recurring").classList.add("hidden");
        document.querySelector(".is-recurring").classList.remove("hidden");
      }
    }

    if (event.target.name === "img") {
      fields[event.target.name] = URL.createObjectURL(event.target.files[0]);
      const fileName = event.target.value.split("\\");
      fields.imgName = fileName[fileName.length - 1];
      fields.file = event.target.files[0];
      console.log(fields);
    }
    this.setState({ fields });
  }

  onFormSubmit(event) {
    event.preventDefault();
    const fieldErrors = this.validate(this.state.fields);
    this.setState({ fieldErrors});

    // Return on error.
    if (fieldErrors.length) return;

    let file = this.state.fields.file;
    if (file) {
      Client.uploadImage(file).then(res => {
        if(res.hasOwnProperty("message")) {
          let err = "";
          if(res.message == "415") {
            err = "Unsupported file type!";
          } else if(res.message == "413") {
            err = "File size too large!";
          } else {
            err = "Internal Server Error";
          }
          fieldErrors.push(err);
          this.setState({fieldErrors});
          return;
        }

        const fields = this.state.fields;
        fields.path = res.path;
        this.setState({ fields });
        this.setState({ progress: "preview" });
      });
    } else {
      this.setState({ progress: "preview" });
    }
  }

  onEditClick(event) {
    event.preventDefault();
    this.setState({progress: "edit"});
  }

  onSaveClick(event) {
    event.preventDefault();

    const fields = this.state.fields;
    const uri = "/api/event/create";
    const editUri = "/api/event/update";
    const date = Moment(fields.date).valueOf();
    const duration = Moment(fields.date + " " + fields.endTime).valueOf() - Moment(fields.date + " " + fields.startTime).valueOf();
    const eventObj = {
      name: fields.name,
      date: date,
      recurring: fields.recurring,
      location: fields.location,
      description: fields.desc,
      images: fields.imgName,
      duration: duration,
      path: fields.path,
      createdBy: fields.createdBy
    };

    if(fields.recurring) {
      eventObj.recursUntil = Moment(fields.recursuntil).valueOf();
      eventObj.recursEvery = parseInt(fields.recurs, 10);
    }

    console.log(eventObj);

    if (this.state.comeFrom === "event") {
      Client.post(eventObj, editUri).then(res => console.log(res));
    } else {
      Client.post(eventObj, uri).then(res => console.log(res));
    }

    const fieldErrors = [];
    fieldErrors.push(this.context.language.Errors.eventSaved);
    this.setState({fieldErrors});
    this.setState({ progress: "saved"});
    this.setState({ fields: {
      name: "",
      date: "",
      recurring: false,
      recursuntil: "",
      recurs: "",
      location: "",
      desc: "",
      img:  "",
    }});
  }

  render() {

    const language = this.context.language.CreateView;

    if (this.state.progress === "preview" || this.state.progress === "view") {
      return (

{language.createEvent}

            {
              this.state.progress === "preview" ?
{language.previewEvent}
 :
{language.viewEvent}

            }

{this.state.fields.name}

{this.state.fields.location} - {this.state.fields.date} - {this.state.fields.startTime} - {this.state.fields.endTime}

            <div className="img-container" style={{backgroundImage: `url(${this.state.fields.img})`}}>

{language.description}:

{this.state.fields.desc}

            {
              this.state.event.hasOwnProperty("location") ? (

                <EventsMap events={[this.state.event]} center={{lat: this.state.event.location.coordinates.coordinates[1], lng: this.state.event.location.coordinates.coordinates[0]}}/>

) : ""
            }

              {
                this.state.progress === "preview" ? <button className="btn-primary" onClick={this.onSaveClick.bind(this)}>{language.save}</button> : ""
              }
              <button className="btn-primary" onClick={this.onEditClick.bind(this)}>{language.edit}</button>

      )
    } else {
      return (

{language.createEvent}

{language.newEvent}

            <form onSubmit={this.onFormSubmit.bind(this)}>
              {language.name}:
              <input
                name="name"
                type="text"
                value={this.state.fields.name}
                onChange={this.onInputChange.bind(this)}>
              </input>

              {language.date}:
              <input
                type="date"
                name="date"
                value={this.state.fields.date}
                onChange={this.onInputChange.bind(this)}>
              </input>
              {language.time}:
              <input
                name="startTime"
                type="time"
                value={this.state.fields.startTime}
                onChange={this.onInputChange.bind(this)}
                className="time-form">
              </input>
              <input
                name="endTime"
                type="time"
                value={this.state.fields.endTime}
                onChange={this.onInputChange.bind(this)}
                placeholder="16.30..."
                className="time-form end-time">
              </input>

                {language.recurring}:
                <input
                  name="recurring"
                  type="checkbox"
                  className="approve"
                  checked={this.state.fields.recurring}
                  onChange={this.onInputChange.bind(this)}></input>

                {language.recursUntil}:
                <input
                  type="date"
                  name="recursuntil"
                  value={this.state.fields.recursuntil}
                  onChange={this.onInputChange.bind(this)}>
                </input>
                {language.recurs}:
                <select
                  className="capitalize"
                  name="recurs"
                  value={this.state.fields.recurs}
                  onChange={this.onInputChange.bind(this)}>
                  <option selected className="capitalize" value="0">{language.weekly}</option>
                  <option className="capitalize" value="1">{language.monthly}</option>
                  <option className="capitalize" value="2">{language.yearly}</option>
                </select>

              {language.location}:
              <input
                name="location"
                type="text"
                value={this.state.fields.location}
                onChange={this.onInputChange.bind(this)}>
              </input>

              {language.description}:
              <textarea
                name="desc"
                value={this.state.fields.desc}
                onChange={this.onInputChange.bind(this)}>
              </textarea>
              {language.image}:
              <input
                type="file"
                name="img"
                accept="image/*"
                onChange={this.onInputChange.bind(this)}>
              </input>
              <ErrorList className={this.state.progress === "saved" ? "success" : ""} errors={this.state.fieldErrors}/>
              <input type="submit" value={language.preview} className="btn-primary"></input>
                {
                  this.state.comeFrom === "event" ? this.state.progress === "saved" ? <Redirect to="/user/event"/> : "" : ""
                }
            </form>

      );
    }
  }
}

CreateView.contextTypes = {
  language: PropTypes.object,
}

export default CreateView;
<commit_msg>removed invalid time error<commit_after>import React, { Component } from "react";
import { DateField } from "react-date-picker";
import "react-date-picker/index.css";
import "./CreateView.css";
import ErrorList from "./ErrorList";
import Client from "../Client";
import Redirect from "react-router/Redirect";
import PropTypes from "prop-types";
import Moment from "moment";
import EventsMap from "./EventsMap";

class CreateView extends Component {
  state = {
    fields: {
      name: "",
      date: "",
      recurring: false,
      recursuntil: "",
      recurs: 0,
      location: "",
      desc: "",
      img:  "",
      file: null,
      startTime: "",
      endTime: "",
      path: "",
      imgName: "",
      createdBy: ""
    },
    fieldErrors: [],
    progress: "create",
    event: {},
    comeFrom: "",
  }

  componentWillMount() {
    const uri = "/api/user/current";

    let fields = {};

    if (this.props.progress) {
      const progress =  this.props.progress;

      let eventUri = `/api/event/get?id=${this.props.id}&token=dashboard`;
      Client.get(eventUri)
        .then(event => {
          console.log(event);
          event = event[0];
          this.setState({event});

          let date = Moment(event.date);

          const fields = {
            name: event.name,
            date: date.format("M/D/YYYY H:mm"),
            recurring: event.recursive,
            recursuntil: event.recursUntil,
            recurs: event.recursEvery,
            location: event.address,
            desc: event.description,
            img:  event.images,
            file: null,
            startTime: "",
            endTime: "",
            path: "",
            imgName: "",
            createdBy: event.createdBy
          }

          this.setState({ progress, fields, comeFrom: "event"});
        })
    } else {
      fields = this.state.fields;
    }

    Client.get(uri)
      .then(user => {
        fields.createdBy = user.id;
        this.setState({fields});
    });
  }

  validate(fields) {
    const errors = [];
    if (!fields.name) errors.push(this.context.language.Errors.nameNeeded);
    if (!fields.date) errors.push(this.context.language.Errors.dateNeeded);
    if (!fields.location) errors.push(this.context.language.Errors.locationNeeded);
    if (!fields.desc) errors.push(this.context.language.Errors.descriptionNeeded);
    if (!fields.startTime) errors.push(this.context.language.Errors.startNeeded);
    if (!fields.endTime) errors.push(this.context.language.Errors.endNeeded);

    return errors;
  }

  onInputChange(event) {
    const fields = this.state.fields;
    fields[event.target.name] = event.target.value;

    if (event.target.name === "recurring") {
      fields[event.target.name] = event.target.checked;
      if (event.target.checked === true) {
        document.querySelector(".recurring").classList.add("hidden");
        document.querySelector(".is-recurring").classList.remove("hidden");
      }
    }

    if (event.target.name === "img") {
      fields[event.target.name] = URL.createObjectURL(event.target.files[0]);
      const fileName = event.target.value.split("\\");
      fields.imgName = fileName[fileName.length - 1];
      fields.file = event.target.files[0];
      console.log(fields);
    }
    this.setState({ fields });
  }

  onFormSubmit(event) {
    event.preventDefault();
    const fieldErrors = this.validate(this.state.fields);
    this.setState({ fieldErrors});

    // Return on error.
    if (fieldErrors.length) return;

    let file = this.state.fields.file;
    if (file) {
      Client.uploadImage(file).then(res => {
        if(res.hasOwnProperty("message")) {
          let err = "";
          if(res.message == "415") {
            err = "Unsupported file type!";
          } else if(res.message == "413") {
            err = "File size too large!";
          } else {
            err = "Internal Server Error";
          }
          fieldErrors.push(err);
          this.setState({fieldErrors});
          return;
        }

        const fields = this.state.fields;
        fields.path = res.path;
        this.setState({ fields });
        this.setState({ progress: "preview" });
      });
    } else {
      this.setState({ progress: "preview" });
    }
  }

  onEditClick(event) {
    event.preventDefault();
    this.setState({progress: "edit"});
  }

  onSaveClick(event) {
    event.preventDefault();

    const fields = this.state.fields;
    const uri = "/api/event/create";
    const editUri = "/api/event/update";
    const date = Moment(fields.date).valueOf();
    const duration = Moment(fields.date + " " + fields.endTime).valueOf() - Moment(fields.date + " " + fields.startTime).valueOf();
    const eventObj = {
      name: fields.name,
      date: date,
      recurring: fields.recurring,
      location: fields.location,
      description: fields.desc,
      images: fields.imgName,
      duration: duration,
      path: fields.path,
      createdBy: fields.createdBy
    };

    if(fields.recurring) {
      eventObj.recursUntil = Moment(fields.recursuntil).valueOf();
      eventObj.recursEvery = parseInt(fields.recurs, 10);
    }

    console.log(eventObj);

    if (this.state.comeFrom === "event") {
      Client.post(eventObj, editUri).then(res => console.log(res));
    } else {
      Client.post(eventObj, uri).then(res => console.log(res));
    }

    const fieldErrors = [];
    fieldErrors.push(this.context.language.Errors.eventSaved);
    this.setState({fieldErrors});
    this.setState({ progress: "saved"});
    this.setState({ fields: {
      name: "",
      date: "",
      recurring: false,
      recursuntil: "",
      recurs: "",
      location: "",
      desc: "",
      img:  "",
    }});
  }

  render() {

    const language = this.context.language.CreateView;

    if (this.state.progress === "preview" || this.state.progress === "view") {
      return (

{language.createEvent}

            {
              this.state.progress === "preview" ?
{language.previewEvent}
 :
{language.viewEvent}

            }

{this.state.fields.name}

{this.state.fields.location} - {this.state.fields.date} - {this.state.fields.startTime} - {this.state.fields.endTime}

            <div className="img-container" style={{backgroundImage: `url(${this.state.fields.img})`}}>

{language.description}:

{this.state.fields.desc}

            {
              this.state.event.hasOwnProperty("location") ? (

                <EventsMap events={[this.state.event]} center={{lat: this.state.event.location.coordinates.coordinates[1], lng: this.state.event.location.coordinates.coordinates[0]}}/>

) : ""
            }

              {
                this.state.progress === "preview" ? <button className="btn-primary" onClick={this.onSaveClick.bind(this)}>{language.save}</button> : ""
              }
              <button className="btn-primary" onClick={this.onEditClick.bind(this)}>{language.edit}</button>

      )
    } else {
      return (

{language.createEvent}

{language.newEvent}

            <form onSubmit={this.onFormSubmit.bind(this)}>
              {language.name}:
              <input
                name="name"
                type="text"
                value={this.state.fields.name}
                onChange={this.onInputChange.bind(this)}>
              </input>

              {language.date}:
              <input
                type="date"
                name="date"
                value={this.state.fields.date}
                onChange={this.onInputChange.bind(this)}>
              </input>
              {language.time}:
              <input
                name="startTime"
                type="time"
                value={this.state.fields.startTime}
                onChange={this.onInputChange.bind(this)}
                className="time-form">
              </input>
              <input
                name="endTime"
                type="time"
                value={this.state.fields.endTime}
                onChange={this.onInputChange.bind(this)}
                placeholder="16.30..."
                className="time-form end-time">
              </input>

                {language.recurring}:
                <input
                  name="recurring"
                  type="checkbox"
                  className="approve"
                  checked={this.state.fields.recurring}
                  onChange={this.onInputChange.bind(this)}></input>

                {language.recursUntil}:
                <input
                  type="date"
                  name="recursuntil"
                  value={this.state.fields.recursuntil}
                  onChange={this.onInputChange.bind(this)}>
                </input>
                {language.recurs}:
                <select
                  className="capitalize"
                  name="recurs"
                  value={this.state.fields.recurs}
                  onChange={this.onInputChange.bind(this)}>
                  <option selected className="capitalize" value="0">{language.weekly}</option>
                  <option className="capitalize" value="1">{language.monthly}</option>
                  <option className="capitalize" value="2">{language.yearly}</option>
                </select>

              {language.location}:
              <input
                name="location"
                type="text"
                value={this.state.fields.location}
                onChange={this.onInputChange.bind(this)}>
              </input>

              {language.description}:
              <textarea
                name="desc"
                value={this.state.fields.desc}
                onChange={this.onInputChange.bind(this)}>
              </textarea>
              {language.image}:
              <input
                type="file"
                name="img"
                accept="image/*"
                onChange={this.onInputChange.bind(this)}>
              </input>
              <ErrorList className={this.state.progress === "saved" ? "success" : ""} errors={this.state.fieldErrors}/>
              <input type="submit" value={language.preview} className="btn-primary"></input>
                {
                  this.state.comeFrom === "event" ? this.state.progress === "saved" ? <Redirect to="/user/event"/> : "" : ""
                }
            </form>

      );
    }
  }
}

CreateView.contextTypes = {
  language: PropTypes.object,
}

export default CreateView;
<|endoftext|>


<commit_before><commit_msg>Explicitly disable nodeIntegration in service workers<commit_after><|endoftext|>


<commit_before><commit_msg>Added main.js<commit_after><|endoftext|>


<commit_before><commit_msg>Add title text to buttons<commit_after><|endoftext|>


<commit_before><commit_msg>Update main.js<commit_after><|endoftext|>


<commit_before><commit_msg>changed setConfig() to restartWithConfig() that cooperates with new stop() method<commit_after><|endoftext|>


<commit_before><commit_msg>removed unnecessary util module<commit_after><|endoftext|>


<commit_before><commit_msg>Add an ugly confirm box to protect people from accidentally retiring their champions.<commit_after><|endoftext|>


<commit_before>/*

Meme.js
=======

Use one function to generate a meme.

You can call it all with strings:

     Meme('dog.jpg', 'canvasID', 'Buy pizza, 'Pay in snakes');

Or with a selected canvas element:

     var canvas = document.getElementById('canvasID');
     Meme('wolf.jpg', canvas, 'The time is now', 'to take what\'s yours');

Or with a jQuery/Zepto selection:

     Meme('spidey.jpg', $('#canvasID'), 'Did someone say', 'Spiderman JS?');

You can also pass in an image:

     var img = new Image();
     img.src = 'insanity.jpg';
     var can = document.getElementById('canvasID');
     Meme(img, can, 'you ignore my calls', 'I ignore your screams of mercy');

********************************************************************************

Copyright (c) 2012 BuddyMeme

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

window.Meme = function(image, canvas, top, bottom) {

	/*
	Default top and bottom
	*/

	top = top || '';
	bottom = bottom || '';

	/*
	Deal with the canvas
	*/

	// If it's nothing, set it to a dummy value to trigger error
	if (!canvas)
		canvas = 0;

	// If it's a string, conver it
	if (canvas.toUpperCase)
		canvas = document.getElementById(canvas);

	// If it's jQuery or Zepto, convert it
	if (($) && (canvas instanceof $))
		canvas = canvas[0];

	// Throw error
	if (!(canvas instanceof HTMLCanvasElement))
		throw new Error('No canvas selected');

	// Get context
	var context = canvas.getContext('2d');

	/*
	Deal with the image
	*/

	// If there's no image, set it to a dummy value to trigger an error
	if (!image)
		image = 0;

	// Convert it from a string
	if (image.toUpperCase) {
		var src = image;
		image = new Image();
		image.src = src;
	}

	// Set the proper width and height of the canvas
	var setCanvasDimensions = function(w, h) {
		canvas.width = w;
		canvas.height = h;
	};
	setCanvasDimensions(image.width, image.height);

	/*
	Draw a centered meme string
	*/

	var drawText = function(text, topOrBottom, y) {

		// Variable setup
		topOrBottom = topOrBottom || 'top';
		var fontSize = (canvas.height / 8);
		var x = canvas.width / 2;
		if (typeof y === 'undefined') {
			y = fontSize;
			if (topOrBottom === 'bottom')
				y = canvas.height - 10;
		}

		// Should we split it into multiple lines?
		if (context.measureText(text).width > (canvas.width * 1.1)) {

			// Split word by word
			var words = text.split(' ');
			var wordsLength = words.length;

			// Start with the entire string, removing one word at a time. If
			// that removal lets us make a line, place the line and recurse with
			// the rest. Removes words from the back if placing at the top;
			// removes words at the front if placing at the bottom.
			if (topOrBottom === 'top') {
				var i = wordsLength;
				while (i --) {
					var justThis = words.slice(0, i).join(' ');
					if (context.measureText(justThis).width < (canvas.width * 1.0)) {
						drawText(justThis, topOrBottom, y);
						drawText(words.slice(i, wordsLength).join(' '), topOrBottom, y + fontSize);
						return;
					}
				}
			}
			else if (topOrBottom === 'bottom') {
				for (var i = 0; i < wordsLength; i ++) {
					var justThis = words.slice(i, wordsLength).join(' ');
					if (context.measureText(justThis).width < (canvas.width * 1.0)) {
						drawText(justThis, topOrBottom, y);
						drawText(words.slice(0, i).join(' '), topOrBottom, y - fontSize);
						return;
					}
				}
			}

		}

		// Draw!
		context.fillText(text, x, y, canvas.width * .9);
		context.strokeText(text, x, y, canvas.width * .9);

	};

	/*
	Do everything else after image loads
	*/

	image.onload = function() {

		// Set dimensions
		setCanvasDimensions(this.width, this.height);

		// Draw the image
		context.drawImage(image, 0, 0);

		// Set up text variables
		context.fillStyle = 'white';
		context.strokeStyle = 'black';
		context.lineWidth = 2;
		var fontSize = (canvas.height / 8);
		context.font = fontSize + 'px Impact';
		context.textAlign = 'center';

		// Draw them!
		drawText(top, 'top');
		drawText(bottom, 'bottom');

	};

};

/*

//once clicking submit
$('#post').click(function(){
	//save canvas element to a data uri
  mixpanel.track("Submitted Meme");
	dataURI = can.toDataURL();
	//pass the data uri to a server to generate an image
	//saveImage(dataURI);
  var body = 'Reading JS SDK documentation';
  $('#formimage').val(dataURI);
  $('#form').submit();
/*  var formData = new FormData();

/*  for (var i = 0, dataURI; dataURI = dataURI[i]; ++i) {
    formData.append(dataURI.name, dataURI);
  }
/*  formData.append('source', dataURI.replace(/^data:image\/\w+;base64,/, ""));
  formData.append('message', 'test');

  $.ajax({
    type:'POST',
    url: 'http://talktomindy.com/saveImage.php',
    data: {image:dataURI, hash:'test'},
    success: function(){
      alert('test');
    }
  })
  FB.api('/me/photos', 'post', formData, function(response) {
    if (!response || response.error) {
      alert('Error occured: ' + JSON.stringify(response.error));
    } else {
      alert('Post ID: ' + response.id);
    }
  });
/*  data = {data:dataURI};
  $.ajax({
    type: 'POST',
    url: 'writer',
    data: data,
    success: function(){ alert('woohoo')},
  });
});

});

*/
<commit_msg>Remove unused comments<commit_after>/*

Meme.js
=======

Use one function to generate a meme.

You can call it all with strings:

     Meme('dog.jpg', 'canvasID', 'Buy pizza, 'Pay in snakes');

Or with a selected canvas element:

     var canvas = document.getElementById('canvasID');
     Meme('wolf.jpg', canvas, 'The time is now', 'to take what\'s yours');

Or with a jQuery/Zepto selection:

     Meme('spidey.jpg', $('#canvasID'), 'Did someone say', 'Spiderman JS?');

You can also pass in an image:

     var img = new Image();
     img.src = 'insanity.jpg';
     var can = document.getElementById('canvasID');
     Meme(img, can, 'you ignore my calls', 'I ignore your screams of mercy');

********************************************************************************

Copyright (c) 2012 BuddyMeme

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

window.Meme = function(image, canvas, top, bottom) {

	/*
	Default top and bottom
	*/

	top = top || '';
	bottom = bottom || '';

	/*
	Deal with the canvas
	*/

	// If it's nothing, set it to a dummy value to trigger error
	if (!canvas)
		canvas = 0;

	// If it's a string, conver it
	if (canvas.toUpperCase)
		canvas = document.getElementById(canvas);

	// If it's jQuery or Zepto, convert it
	if (($) && (canvas instanceof $))
		canvas = canvas[0];

	// Throw error
	if (!(canvas instanceof HTMLCanvasElement))
		throw new Error('No canvas selected');

	// Get context
	var context = canvas.getContext('2d');

	/*
	Deal with the image
	*/

	// If there's no image, set it to a dummy value to trigger an error
	if (!image)
		image = 0;

	// Convert it from a string
	if (image.toUpperCase) {
		var src = image;
		image = new Image();
		image.src = src;
	}

	// Set the proper width and height of the canvas
	var setCanvasDimensions = function(w, h) {
		canvas.width = w;
		canvas.height = h;
	};
	setCanvasDimensions(image.width, image.height);

	/*
	Draw a centered meme string
	*/

	var drawText = function(text, topOrBottom, y) {

		// Variable setup
		topOrBottom = topOrBottom || 'top';
		var fontSize = (canvas.height / 8);
		var x = canvas.width / 2;
		if (typeof y === 'undefined') {
			y = fontSize;
			if (topOrBottom === 'bottom')
				y = canvas.height - 10;
		}

		// Should we split it into multiple lines?
		if (context.measureText(text).width > (canvas.width * 1.1)) {

			// Split word by word
			var words = text.split(' ');
			var wordsLength = words.length;

			// Start with the entire string, removing one word at a time. If
			// that removal lets us make a line, place the line and recurse with
			// the rest. Removes words from the back if placing at the top;
			// removes words at the front if placing at the bottom.
			if (topOrBottom === 'top') {
				var i = wordsLength;
				while (i --) {
					var justThis = words.slice(0, i).join(' ');
					if (context.measureText(justThis).width < (canvas.width * 1.0)) {
						drawText(justThis, topOrBottom, y);
						drawText(words.slice(i, wordsLength).join(' '), topOrBottom, y + fontSize);
						return;
					}
				}
			}
			else if (topOrBottom === 'bottom') {
				for (var i = 0; i < wordsLength; i ++) {
					var justThis = words.slice(i, wordsLength).join(' ');
					if (context.measureText(justThis).width < (canvas.width * 1.0)) {
						drawText(justThis, topOrBottom, y);
						drawText(words.slice(0, i).join(' '), topOrBottom, y - fontSize);
						return;
					}
				}
			}

		}

		// Draw!
		context.fillText(text, x, y, canvas.width * .9);
		context.strokeText(text, x, y, canvas.width * .9);

	};

	/*
	Do everything else after image loads
	*/

	image.onload = function() {

		// Set dimensions
		setCanvasDimensions(this.width, this.height);

		// Draw the image
		context.drawImage(image, 0, 0);

		// Set up text variables
		context.fillStyle = 'white';
		context.strokeStyle = 'black';
		context.lineWidth = 2;
		var fontSize = (canvas.height / 8);
		context.font = fontSize + 'px Impact';
		context.textAlign = 'center';

		// Draw them!
		drawText(top, 'top');
		drawText(bottom, 'bottom');

	};

};
<|endoftext|>


<commit_before>var onDocumentLoad = function ( event ) {

	var path;
	var pathname = window.location.pathname;
	var section = /\/(manual|api|examples)\//.exec( pathname )[ 1 ].toString().split( '.html' )[ 0 ];
	var name = /[\-A-z0-9]+\.html/.exec( pathname ).toString().split( '.html' )[ 0 ];

	switch ( section ) {

		case 'api':
			path = /\/api\/[A-z0-9\/]+/.exec( pathname ).toString().substr( 5 );
			break;

		case 'examples':
			path = /\/examples\/[A-z0-9\/]+/.exec( pathname ).toString().substr( 10 );
			break;

		case 'manual':
			name = name.replace( /\-/g, ' ' );

			path = pathname.replace( /\ /g, '-' );
			path = /\/manual\/[-A-z0-9\/]+/.exec( path ).toString().substr( 8 );
			break;

	}

	var text = document.body.innerHTML;

	text = text.replace( /\[name\]/gi, name );
	text = text.replace( /\[path\]/gi, path );
	text = text.replace( /\[page:([\w\.]+)\]/gi, "[page:$1 $1]" ); // [page:name] to [page:name title]
	text = text.replace( /\[page:\.([\w\.]+) ([\w\.\s]+)\]/gi, "[page:" + name + ".$1 $2]" ); // [page:.member title] to [page:name.member title]
	text = text.replace( /\[page:([\w\.]+) ([\w\.\s]+)\]/gi, "$2" ); // [page:name title]
	// text = text.replace( /\[member:.([\w]+) ([\w\.\s]+)\]/gi, "$2" );

	text = text.replace( /\[(?:member|property|method):([\w]+)\]/gi, "[member:$1 $1]" ); // [member:name] to [member:name title]
	text = text.replace( /\[(?:member|property|method):([\w]+) ([\w\.\s]+)\]/gi, "# .$2 " );

	text = text.replace( /\[link:([\w|\:|\/|\.|\-|\_]+)\]/gi, "[link:$1 $1]" ); // [link:url] to [link:url title]
	text = text.replace( /\[link:([\w|\:|\/|\.|\-|\_|\(|\)|\#]+) ([\w|\:|\/|\.|\-|\_|\s]+)\]/gi, "$2" ); // [link:url title]
	text = text.replace( /\*([\w|\d|\"|\-|\(][\w|\d|\ |\-|\/|\+|\-|\(|\)|\=|\,|\.\"]*[\w|\d|\"|\)]|\w)\*/gi, "$1" ); // *

	text = text.replace( /\[example:([\w\_]+)\]/gi, "[example:$1 $1]" ); // [example:name] to [example:name title]
	text = text.replace( /\[example:([\w\_]+) ([\w\:\/\.\-\_ \s]+)\]/gi, "$2" ); // [example:name title]

	document.body.innerHTML = text;

	// handle code snippets formatting

	var elements = document.getElementsByTagName( 'code' );

	for ( var i = 0; i < elements.length; i ++ ) {

		var element = elements[ i ];

		text = element.textContent.trim();
		text = text.replace( /^\t\t/gm, '' );

		element.textContent = text;

	}

	// Edit button

	var button = document.createElement( 'div' );
	button.id = 'button';
	button.textContent = 'Edit';

	button.addEventListener( 'click', function ( event ) {

		window.open( 'https://github.com/mrdoob/three.js/blob/dev/docs/' + section + '/' + path + '.html' );

	}, false );

	document.body.appendChild( button );

	// Syntax highlighting

	var styleBase = document.createElement( 'link' );
	styleBase.href = pathname.substring( 0, pathname.indexOf( 'docs' ) + 4 ) + '/prettify/prettify.css';
	styleBase.rel = 'stylesheet';

	var styleCustom = document.createElement( 'link' );
	styleCustom.href = pathname.substring( 0, pathname.indexOf( 'docs' ) + 4 ) + '/prettify/threejs.css';
	styleCustom.rel = 'stylesheet';

	document.head.appendChild( styleBase );
	document.head.appendChild( styleCustom );

	var prettify = document.createElement( 'script' );
	prettify.src = pathname.substring( 0, pathname.indexOf( 'docs' ) + 4 ) + '/prettify/prettify.js';

	prettify.onload = function () {

		var elements = document.getElementsByTagName( 'code' );

		for ( var i = 0; i < elements.length; i ++ ) {

			var e = elements[ i ];
			e.className += ' prettyprint';

		}

		prettyPrint();

	}

	document.head.appendChild( prettify );

};

document.addEventListener( 'DOMContentLoaded', onDocumentLoad, false );
<commit_msg>Terminate statement in page.js<commit_after>var onDocumentLoad = function ( event ) {

	var path;
	var pathname = window.location.pathname;
	var section = /\/(manual|api|examples)\//.exec( pathname )[ 1 ].toString().split( '.html' )[ 0 ];
	var name = /[\-A-z0-9]+\.html/.exec( pathname ).toString().split( '.html' )[ 0 ];

	switch ( section ) {

		case 'api':
			path = /\/api\/[A-z0-9\/]+/.exec( pathname ).toString().substr( 5 );
			break;

		case 'examples':
			path = /\/examples\/[A-z0-9\/]+/.exec( pathname ).toString().substr( 10 );
			break;

		case 'manual':
			name = name.replace( /\-/g, ' ' );

			path = pathname.replace( /\ /g, '-' );
			path = /\/manual\/[-A-z0-9\/]+/.exec( path ).toString().substr( 8 );
			break;

	}

	var text = document.body.innerHTML;

	text = text.replace( /\[name\]/gi, name );
	text = text.replace( /\[path\]/gi, path );
	text = text.replace( /\[page:([\w\.]+)\]/gi, "[page:$1 $1]" ); // [page:name] to [page:name title]
	text = text.replace( /\[page:\.([\w\.]+) ([\w\.\s]+)\]/gi, "[page:" + name + ".$1 $2]" ); // [page:.member title] to [page:name.member title]
	text = text.replace( /\[page:([\w\.]+) ([\w\.\s]+)\]/gi, "$2" ); // [page:name title]
	// text = text.replace( /\[member:.([\w]+) ([\w\.\s]+)\]/gi, "$2" );

	text = text.replace( /\[(?:member|property|method):([\w]+)\]/gi, "[member:$1 $1]" ); // [member:name] to [member:name title]
	text = text.replace( /\[(?:member|property|method):([\w]+) ([\w\.\s]+)\]/gi, "# .$2 " );

	text = text.replace( /\[link:([\w|\:|\/|\.|\-|\_]+)\]/gi, "[link:$1 $1]" ); // [link:url] to [link:url title]
	text = text.replace( /\[link:([\w|\:|\/|\.|\-|\_|\(|\)|\#]+) ([\w|\:|\/|\.|\-|\_|\s]+)\]/gi, "$2" ); // [link:url title]
	text = text.replace( /\*([\w|\d|\"|\-|\(][\w|\d|\ |\-|\/|\+|\-|\(|\)|\=|\,|\.\"]*[\w|\d|\"|\)]|\w)\*/gi, "$1" ); // *

	text = text.replace( /\[example:([\w\_]+)\]/gi, "[example:$1 $1]" ); // [example:name] to [example:name title]
	text = text.replace( /\[example:([\w\_]+) ([\w\:\/\.\-\_ \s]+)\]/gi, "$2" ); // [example:name title]

	document.body.innerHTML = text;

	// handle code snippets formatting

	var elements = document.getElementsByTagName( 'code' );

	for ( var i = 0; i < elements.length; i ++ ) {

		var element = elements[ i ];

		text = element.textContent.trim();
		text = text.replace( /^\t\t/gm, '' );

		element.textContent = text;

	}

	// Edit button

	var button = document.createElement( 'div' );
	button.id = 'button';
	button.textContent = 'Edit';

	button.addEventListener( 'click', function ( event ) {

		window.open( 'https://github.com/mrdoob/three.js/blob/dev/docs/' + section + '/' + path + '.html' );

	}, false );

	document.body.appendChild( button );

	// Syntax highlighting

	var styleBase = document.createElement( 'link' );
	styleBase.href = pathname.substring( 0, pathname.indexOf( 'docs' ) + 4 ) + '/prettify/prettify.css';
	styleBase.rel = 'stylesheet';

	var styleCustom = document.createElement( 'link' );
	styleCustom.href = pathname.substring( 0, pathname.indexOf( 'docs' ) + 4 ) + '/prettify/threejs.css';
	styleCustom.rel = 'stylesheet';

	document.head.appendChild( styleBase );
	document.head.appendChild( styleCustom );

	var prettify = document.createElement( 'script' );
	prettify.src = pathname.substring( 0, pathname.indexOf( 'docs' ) + 4 ) + '/prettify/prettify.js';

	prettify.onload = function () {

		var elements = document.getElementsByTagName( 'code' );

		for ( var i = 0; i < elements.length; i ++ ) {

			var e = elements[ i ];
			e.className += ' prettyprint';

		}

		prettyPrint();

	};

	document.head.appendChild( prettify );

};

document.addEventListener( 'DOMContentLoaded', onDocumentLoad, false );
<|endoftext|>


<commit_before>Ext.define('NetProfile.form.FileUpload', {
	extend: 'Ext.form.Panel',
	alias: 'widget.fileuploadform',
	requires: [
		'Ext.form.*',
		'Ext.button.Button'
	],

	cls: 'np-file-upload',
	border: false,
	layout: 'anchor',
	resizable: {
		handles: 'e',
		pinned: true
	},
	defaults: {
		anchor: '100%'
	},
	minWidth: 280,

	titleText: 'Upload Files',
	closeText: 'Close',
	addText: 'Add',
	uploadText: 'Upload',
	removeText: 'Remove',
	errorText: 'Error',

	waitMsg: 'Uploading Files...',
	clientInvalidMsg: 'Form fields may not be submitted with invalid values.',
	connectFailureMsg: 'Can\'t connect to server.',

	initComponent: function()
	{
		var me = this;

		me.title = me.titleText;
		me.items = [me.getUploadField()];
		me.buttons = [{
			text: this.closeText,
			iconCls: 'ico-cancel',
			handler: 'onButtonClose',
			scope: me
		}, '->', {
			text: this.addText,
			iconCls: 'ico-add',
			handler: 'onButtonAdd',
			scope: me
		}, {
			text: this.uploadText,
			formBind: true,
			disabled: true,
			iconCls: 'ico-upload',
			handler: 'onButtonSubmit',
			scope: me
		}];

		me.callParent(arguments);
	},
	onButtonClose: function()
	{
		var me = this,
			fb = me.ownerCt,
			tbar = fb.down('toolbar[dock=top]'),
			btn = tbar.getComponent('btn_upload');

		btn.toggle(false);
		me.removeAll(true);
		me.add(me.getUploadField());
	},
	onButtonAdd: function()
	{
		this.add(this.getUploadField());
	},
	onButtonSubmit: function()
	{
		var me = this,
			form = me.getForm(),
			fb = me.ownerCt;

		if(!form || !form.isValid())
			return;
		form.submit({
			params: fb.getUploadParams(),
			success: function(rform, act)
			{
				fb.updateStore();
				me.onButtonClose();
			},
			failure: function(rform, act)
			{
				// TODO: externalize this code
				switch(act.failureType)
				{
					case Ext.form.action.Action.CLIENT_INVALID:
						NetProfile.msg.err(me.errorText, me.clientInvalidMsg);
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						NetProfile.msg.err(me.errorText, me.connectFailureMsg);
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						NetProfile.msg.err(me.errorText, act.result && act.result.msg);
						break;
					case Ext.form.action.Action.LOAD_FAILURE:
						// TODO: write this
						break;
					default:
						break;
				}
				fb.updateStore();
				me.onButtonClose();
			},
			waitMsg: me.waitMsg
		});
	},
	getUploadField: function()
	{
		var me = this,
			cfg = {
				xtype: 'container',
				cls: 'np-file-upload-cont',
				layout: {
					type: 'hbox',
					align: 'stretch',
					pack: 'end'
				},
				defaults: {
					margin: 0
				},
				items: [{
					xtype: 'filefield',
					name: 'file',
					flex: 1,
					allowBlank: true
				}, {
					xtype: 'tool',
					cls: 'np-file-upload-close',
					tooltip: this.uploadRemoveText,
					type: 'close',
					handler: function()
					{
						var cont, pcont;

						cont = this.up('container[cls~=np-file-upload-cont]');
						if(!cont || !cont.ownerCt)
							return;
						pcont = cont.ownerCt;
						pcont.remove(cont, true);
					},
					width: 20
				}]
			};
		return cfg;
	}
});

<commit_msg>Temporary fix for file upload form weirdness<commit_after>Ext.define('NetProfile.form.FileUpload', {
	extend: 'Ext.form.Panel',
	alias: 'widget.fileuploadform',
	requires: [
		'Ext.form.*',
		'Ext.button.Button'
	],

	cls: 'np-file-upload',
	border: false,
	layout: 'anchor',
	resizable: {
		handles: 'e',
		pinned: true
	},
	defaults: {
		anchor: '100%'
	},
	minWidth: 280,

	titleText: 'Upload Files',
	closeText: 'Close',
	addText: 'Add',
	uploadText: 'Upload',
	removeText: 'Remove',
	errorText: 'Error',

	waitMsg: 'Uploading Files...',
	clientInvalidMsg: 'Form fields may not be submitted with invalid values.',
	connectFailureMsg: 'Can\'t connect to server.',

	initComponent: function()
	{
		var me = this;

		me.title = me.titleText;
		me.items = [me.getUploadField()];
		me.buttons = [{
			text: this.closeText,
			iconCls: 'ico-cancel',
			handler: 'onButtonClose',
			scope: me
		}, '->', {
			text: this.addText,
			iconCls: 'ico-add',
			handler: 'onButtonAdd',
			scope: me
		}, {
			text: this.uploadText,
			formBind: true,
			disabled: true,
			iconCls: 'ico-upload',
			handler: 'onButtonSubmit',
			scope: me
		}];

		me.callParent(arguments);
	},
	onButtonClose: function()
	{
		var me = this,
			fb = me.ownerCt,
			tbar = fb.down('toolbar[dock=top]'),
			btn = tbar.getComponent('btn_upload');

		btn.toggle(false);
		me.removeAll(true);
		me.add(me.getUploadField());
	},
	onButtonAdd: function()
	{
		this.add(this.getUploadField());
	},
	onButtonSubmit: function()
	{
		var me = this,
			form = me.getForm(),
			fb = me.ownerCt;

		if(!form || !form.isValid())
			return;
		form.submit({
			params: fb.getUploadParams(),
			success: function(rform, act)
			{
				fb.updateStore();
				me.onButtonClose();
			},
			failure: function(rform, act)
			{
				// TODO: externalize this code
				switch(act.failureType)
				{
					case Ext.form.action.Action.CLIENT_INVALID:
						NetProfile.msg.err(me.errorText, me.clientInvalidMsg);
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						NetProfile.msg.err(me.errorText, me.connectFailureMsg);
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						NetProfile.msg.err(me.errorText, act.result && act.result.msg);
						break;
					case Ext.form.action.Action.LOAD_FAILURE:
						// TODO: write this
						break;
					default:
						break;
				}
				fb.updateStore();
				me.onButtonClose();
			},
			waitMsg: me.waitMsg
		});
	},
	getUploadField: function()
	{
		var me = this,
			cfg = {
				xtype: 'container',
				cls: 'np-file-upload-cont',
				layout: {
					type: 'hbox',
					align: 'stretch',
					pack: 'end'
				},
				defaults: {
					margin: 0
				},
				items: [{
					xtype: 'filefield',
					name: 'file',
					flex: 1,
					allowBlank: false
				}, {
					xtype: 'tool',
					cls: 'np-file-upload-close',
					tooltip: this.uploadRemoveText,
					type: 'close',
					handler: function()
					{
						var cont, pcont;

						cont = this.up('container[cls~=np-file-upload-cont]');
						if(!cont || !cont.ownerCt)
							return;
						pcont = cont.ownerCt;
						pcont.remove(cont, true);
					},
					width: 20
				}]
			};
		return cfg;
	}
});

<|endoftext|>


<commit_before>var hexDump = require('hexy').hexy

exports.hexDump = function(data) {
  console.log(hexDump(data))
}

exports.ext = function(name) {
  return name.substring(name.lastIndexOf('.')+1, name.length).toLowerCase()
}

exports.hex = function(n, len) {
  n = (n*1).toString(16)
  while (n.length < len) n = '0' + n
  return n
}

exports.IPv4toInt32LE = function(IPv4) {
  var ip = IPv4.split('.')
  ip = (ip[0]*1) + (ip[1]*0x100) + (ip[2]*0x10000) + (ip[3]*0x1000000)
  if (ip<0) log.error(ip)
  return ip
}

/**
 * Get file type based on file extension. The file type can be one on these:
 * 'video', 'audio', 'image', 'pro'.
 *
 * @param {String} name Filename
 * @returns {String} File type
 */
exports.getFileType = function(name) {
  var extensions = {
    video:
      '3gp,aaf,asf,avchd,avi,fla,flv,m1v,m2v,m4v,mp4,mpg,mpe,mpeg,mov,mkv,mp4,'+
      'ogg,rm,svi'
      .split(','),
    audio:
      'aiff,au,wav,flac,la,pac,m4a,ape,rka,shn,tta,wv,wma,brstm,amr,mp2,mp3,'+
      'ogg,aac,m4a,mpc,ra,ots,vox,voc,mid,mod,s3m,xm,it,asf'
      .split(','),
    image:
      'cr2,pdn,pgm,pict,bmp,png,dib,djvu,gif,psd,pdd,icns,ico,rle,tga,jpeg,'+
      'jpg,tiff,tif,jp2,jps,mng,xbm,xcf,pcx'
      .split(','),
    pro:
      '7z,ace,arc,arj,bzip2,cab,gzip,rar,tar,zip,iso,nrg,img,adf,dmg,cue,bin,'+
      'cif,ccd,sub,raw'.split(','),
  }
  if (!typeof name == 'string') { return '' }
  var ext = exports.ext(name)
  if (extensions.video.indexOf(ext)>=0) return 'Video'
  if (extensions.audio.indexOf(ext)>=0) return 'Audio'
  if (extensions.image.indexOf(ext)>=0) return 'Image'
  if (extensions.pro  .indexOf(ext)>=0) return 'Pro'
  return ''
}

exports.isProtocol = function(protocol) {
  return
    (protocol == PR_ED2K) ||
    (protocol == PR_EMULE) ||
    (protocol == PR_ZLIB)
}

/**
 * Draws an ASCII box around some text
 */
exports.box = function(text) {
  var l = text.length + 2
  var s = ''
  while (l--) s+= '-'
  s = '+'+s+'+'
  return s+'\n'+'| '+text+' |'+'\n'+s
}

/**
 * Returns a UNIX timestamp
 */
exports.unixTimestamp = function() {
  return Math.round((new Date()).getTime()/1000)
}
<commit_msg>check for valid string in get extension<commit_after>var hexDump = require('hexy').hexy

/**
 * Prints an hexadecimal dump in console
 */
exports.hexDump = function(data) {
  console.log(hexDump(data))
}

/**
 * Get file extension
 *
 * @param {String} name Filename
 * @returns {String} Extension (without the dot)
 */
exports.ext = function(name) {
  if (!name) return ''
  return name.substring(name.lastIndexOf('.')+1, name.length).toLowerCase()
}

exports.hex = function(n, len) {
  n = (n*1).toString(16)
  while (n.length < len) n = '0' + n
  return n
}

exports.IPv4toInt32LE = function(IPv4) {
  var ip = IPv4.split('.')
  ip = (ip[0]*1) + (ip[1]*0x100) + (ip[2]*0x10000) + (ip[3]*0x1000000)
  if (ip<0) log.error(ip)
  return ip
}

/**
 * Get file type based on file extension. The file type can be one on these:
 * 'video', 'audio', 'image', 'pro'.
 *
 * @param {String} name Filename
 * @returns {String} File type
 */
exports.getFileType = function(name) {
  var extensions = {
    video:
      '3gp,aaf,asf,avchd,avi,fla,flv,m1v,m2v,m4v,mp4,mpg,mpe,mpeg,mov,mkv,mp4,'+
      'ogg,rm,svi'
      .split(','),
    audio:
      'aiff,au,wav,flac,la,pac,m4a,ape,rka,shn,tta,wv,wma,brstm,amr,mp2,mp3,'+
      'ogg,aac,m4a,mpc,ra,ots,vox,voc,mid,mod,s3m,xm,it,asf'
      .split(','),
    image:
      'cr2,pdn,pgm,pict,bmp,png,dib,djvu,gif,psd,pdd,icns,ico,rle,tga,jpeg,'+
      'jpg,tiff,tif,jp2,jps,mng,xbm,xcf,pcx'
      .split(','),
    pro:
      '7z,ace,arc,arj,bzip2,cab,gzip,rar,tar,zip,iso,nrg,img,adf,dmg,cue,bin,'+
      'cif,ccd,sub,raw'.split(','),
  }
  if (!typeof name == 'string') { return '' }
  var ext = exports.ext(name)
  if (extensions.video.indexOf(ext)>=0) return 'Video'
  if (extensions.audio.indexOf(ext)>=0) return 'Audio'
  if (extensions.image.indexOf(ext)>=0) return 'Image'
  if (extensions.pro  .indexOf(ext)>=0) return 'Pro'
  return ''
}

/**
 * Returns true if the given parameter is valid eD2K/eMule protocol number
 *
 * @param {Integer} protocol
 * @returns {Boolean}
 */
exports.isProtocol = function(protocol) {
  return
    (protocol == PR_ED2K) ||
    (protocol == PR_EMULE) ||
    (protocol == PR_ZLIB)
}

exports.isFunction = function(something) {
  return typeof(something) == 'function'
}

/**
 * Draws an ASCII box around some text
 */
exports.box = function(text) {
  var l = text.length + 2
  var s = ''
  while (l--) s+= '-'
  s = '+'+s+'+'
  return s+'\n'+'| '+text+' |'+'\n'+s
}

/**
 * Returns a UNIX timestamp
 */
exports.unixTimestamp = function() {
  return Math.round((new Date()).getTime()/1000)
}
<|endoftext|>


<commit_before><commit_msg>fixed error regarding adding minutes<commit_after><|endoftext|>


<commit_before><commit_msg>FPI updates<commit_after><|endoftext|>


<commit_before>//
// Copyright (C) 2014 - present Instructure, Inc.
//
// This file is part of Canvas.
//
// Canvas is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License as published by the Free
// Software Foundation, version 3 of the License.
//
// Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
// A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
// details.
//
// You should have received a copy of the GNU Affero General Public License along
// with this program. If not, see <http://www.gnu.org/licenses/>.

import $ from 'jquery'

import {useScope as useI18nScope} from '@canvas/i18n'
import '@canvas/jquery/jquery.ajaxJSON'
import '@canvas/jquery/jquery.instructure_misc_helpers'
import '@canvas/rails-flash-notifications'

const I18n = useI18nScope('external_content.success')

const ExternalContentSuccess = {}

const {lti_response_messages} = ENV
const {service_id} = ENV
const data = ENV.retrieved_data
const callback = ENV.service
let parentWindow = window.parent || window.opener

ExternalContentSuccess.getIFrameSrc = function () {
  let src = parentWindow.$('[data-cid="Modal"]').find('iframe').attr('src')

  if (src === undefined) {
    src = parentWindow.$('[data-cid="Tray"]').find('iframe').attr('src')
  }

  return src
}

ExternalContentSuccess.getLaunchType = function () {
  const src = ExternalContentSuccess.getIFrameSrc()

  if (src === undefined) {
    return undefined
  }

  const params = new URLSearchParams(src.split('?')[1])
  return params.get('launch_type')
}

ExternalContentSuccess.dataReady = function (data, service_id) {
  const e = $.Event('externalContentReady')
  e.contentItems = data
  e.service_id = service_id

  parentWindow.$(parentWindow).trigger('externalContentReady', e)

  if (parentWindow[callback] && parentWindow[callback].ready) {
    parentWindow[callback].ready(data)
    setTimeout(() => {
      if (callback === 'external_tool_dialog') {
        $('#dialog_message').text(
          I18n.t('popup_success', 'Success! This popup should close on its own...')
        )
      } else {
        $('#dialog_message').text('')
      }
    }, 1000)
  } else {
    $('#dialog_message').text(
      I18n.t(
        'content_failure',
        'Content retrieval failed, please try again or notify your system administrator of the error.'
      )
    )
  }
}

// Handles lti 1.0 responses for Assignments 2 which expects a
// vanilla JS event from LTI tools in the following form.
ExternalContentSuccess.a2DataReady = function (data) {
  parentWindow.postMessage(
    {
      subject: 'A2ExternalContentReady',
      content_items: data,
      msg: ENV.message,
      log: ENV.log,
      errormsg: ENV.error_message,
      errorlog: ENV.error_log,
      ltiEndpoint: ENV.lti_endpoint
    },
    ENV.DEEP_LINKING_POST_MESSAGE_ORIGIN
  )
}

ExternalContentSuccess.start = function () {
  while (parentWindow && parentWindow.parent !== parentWindow && !parentWindow[callback]) {
    parentWindow = parentWindow.parent
  }

  if (parentWindow.$ === undefined) {
    parentWindow.$ = $
  }

  if (lti_response_messages && lti_response_messages.lti_errormsg) {
    parentWindow.$.flashError(lti_response_messages.lti_errormsg)
  }
  if (lti_response_messages && lti_response_messages.lti_msg) {
    parentWindow.$.flashMessage(lti_response_messages.lti_msg)
  }

  if (ENV.oembed) {
    const url = $.replaceTags(
      $.replaceTags(
        $('#oembed_retrieve_url').attr('href'),
        'endpoint',
        encodeURIComponent(ENV.oembed.endpoint)
      ),
      'url',
      encodeURIComponent(ENV.oembed.url)
    )
    $.ajaxJSON(
      url,
      'GET',
      {},
      data => ExternalContentSuccess.dataReady(data),
      () =>
        $('#dialog_message').text(
          I18n.t(
            'oembed_failure',
            'Content retrieval failed, please try again or notify your system administrator of the error.'
          )
        )
    )
  } else if (ExternalContentSuccess.getLaunchType() === 'assignment_index_menu') {
    parentWindow.location.reload()
  } else {
    ExternalContentSuccess.dataReady(data, service_id)
    ExternalContentSuccess.a2DataReady(data)
  }
}

$(document).ready(() => {
  ExternalContentSuccess.start()
})

export default ExternalContentSuccess
<commit_msg>Fix Assignment Enhancements duplicated LTI entry<commit_after>//
// Copyright (C) 2014 - present Instructure, Inc.
//
// This file is part of Canvas.
//
// Canvas is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License as published by the Free
// Software Foundation, version 3 of the License.
//
// Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
// A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
// details.
//
// You should have received a copy of the GNU Affero General Public License along
// with this program. If not, see <http://www.gnu.org/licenses/>.

import $ from 'jquery'

import {useScope as useI18nScope} from '@canvas/i18n'
import '@canvas/jquery/jquery.ajaxJSON'
import '@canvas/jquery/jquery.instructure_misc_helpers'
import '@canvas/rails-flash-notifications'

const I18n = useI18nScope('external_content.success')

const ExternalContentSuccess = {}

const {lti_response_messages} = ENV
const {service_id} = ENV
const data = ENV.retrieved_data
const callback = ENV.service
let parentWindow = window.parent || window.opener

ExternalContentSuccess.getIFrameSrc = function () {
  let src = parentWindow.$('[data-cid="Modal"]').find('iframe').attr('src')

  if (src === undefined) {
    src = parentWindow.$('[data-cid="Tray"]').find('iframe').attr('src')
  }

  return src
}

ExternalContentSuccess.getLaunchType = function () {
  const src = ExternalContentSuccess.getIFrameSrc()

  if (src === undefined) {
    return undefined
  }

  const params = new URLSearchParams(src.split('?')[1])
  return params.get('launch_type')
}

ExternalContentSuccess.dataReady = function (data, service_id) {
  const e = $.Event('externalContentReady')
  e.contentItems = data
  e.service_id = service_id

  parentWindow.$(parentWindow).trigger('externalContentReady', e)

  if (parentWindow[callback] && parentWindow[callback].ready) {
    parentWindow[callback].ready(data)
    setTimeout(() => {
      if (callback === 'external_tool_dialog') {
        $('#dialog_message').text(
          I18n.t('popup_success', 'Success! This popup should close on its own...')
        )
      } else {
        $('#dialog_message').text('')
      }
    }, 1000)
  } else {
    $('#dialog_message').text(
      I18n.t(
        'content_failure',
        'Content retrieval failed, please try again or notify your system administrator of the error.'
      )
    )
  }
}

// Handles lti 1.0 responses for Assignments 2 which expects a
// vanilla JS event from LTI tools in the following form.
ExternalContentSuccess.a2DataReady = function (data) {
  parentWindow.postMessage(
    {
      subject: 'A2ExternalContentReady',
      content_items: data,
      msg: ENV.message,
      log: ENV.log,
      errormsg: ENV.error_message,
      errorlog: ENV.error_log,
      ltiEndpoint: ENV.lti_endpoint
    },
    ENV.DEEP_LINKING_POST_MESSAGE_ORIGIN
  )
}

ExternalContentSuccess.start = function () {
  while (parentWindow && parentWindow.parent !== parentWindow && !parentWindow[callback]) {
    parentWindow = parentWindow.parent
  }

  if (parentWindow.$ === undefined) {
    parentWindow.$ = $
  }

  if (lti_response_messages && lti_response_messages.lti_errormsg) {
    parentWindow.$.flashError(lti_response_messages.lti_errormsg)
  }
  if (lti_response_messages && lti_response_messages.lti_msg) {
    parentWindow.$.flashMessage(lti_response_messages.lti_msg)
  }

  if (ENV.oembed) {
    const url = $.replaceTags(
      $.replaceTags(
        $('#oembed_retrieve_url').attr('href'),
        'endpoint',
        encodeURIComponent(ENV.oembed.endpoint)
      ),
      'url',
      encodeURIComponent(ENV.oembed.url)
    )
    $.ajaxJSON(
      url,
      'GET',
      {},
      data => ExternalContentSuccess.dataReady(data),
      () =>
        $('#dialog_message').text(
          I18n.t(
            'oembed_failure',
            'Content retrieval failed, please try again or notify your system administrator of the error.'
          )
        )
    )
  } else if (ExternalContentSuccess.getLaunchType() === 'assignment_index_menu') {
    parentWindow.location.reload()
  } else if (parentWindow.$(parentWindow).data('events')?.externalContentReady) {
    ExternalContentSuccess.dataReady(data, service_id)
  } else {
    ExternalContentSuccess.a2DataReady(data)
  }
}

$(document).ready(() => {
  ExternalContentSuccess.start()
})

export default ExternalContentSuccess
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'

import QueryBuilder from './QueryBuilder'
import QueryMakerTab from './QueryMakerTab'
import QueryTabList from 'src/shared/components/QueryTabList'
import buildInfluxQLQuery from 'utils/influxql'
import classnames from 'classnames'

const {arrayOf, bool, func, node, number, shape, string} = PropTypes

const QueryMaker = React.createClass({
  propTypes: {
    source: shape({
      links: shape({
        queries: string.isRequired,
      }).isRequired,
    }).isRequired,
    queries: arrayOf(shape({})).isRequired,
    timeRange: shape({
      upper: string,
      lower: string,
    }).isRequired,
    isInDataExplorer: bool,
    actions: shape({
      chooseNamespace: func.isRequired,
      chooseMeasurement: func.isRequired,
      chooseTag: func.isRequired,
      groupByTag: func.isRequired,
      addQuery: func.isRequired,
      toggleField: func.isRequired,
      groupByTime: func.isRequired,
      toggleTagAcceptance: func.isRequired,
      applyFuncsToField: func.isRequired,
      editRawTextAsync: func.isRequired,
    }).isRequired,
    height: string,
    top: string,
    setActiveQueryIndex: func.isRequired,
    onDeleteQuery: func.isRequired,
    activeQueryIndex: number,
    children: node,
    layout: string,
  },

  render() {
    const {
      height,
      top,
      layout,
      queries,
      timeRange,
      onAddQuery,
      onDeleteQuery,
      activeQueryIndex,
      setActiveQueryIndex,
    } = this.props

    return (

        <QueryTabList
          queries={queries}
          timeRange={timeRange}
          onAddQuery={onAddQuery}
          onDeleteQuery={onDeleteQuery}
          activeQueryIndex={activeQueryIndex}
          setActiveQueryIndex={setActiveQueryIndex}
        />
        {this.renderQueryBuilder()}

    )
  },

  renderQueryBuilder() {
    const {
      timeRange,
      actions,
      source,
      layout,
      isInDataExplorer,
      activeQuery,
      onAddQuery,
    } = this.props

    if (!activeQuery) {
      return (

This Graph has no Queries

            Add a Query

      )
    }

    // NOTE
    // the layout prop is intended to toggle between a horizontal and vertical layout
    // the layout will be horizontal by default
    // vertical layout is known as "panel" layout as it will be used to build
    // a "cell editor panel" though that term might change
    // Currently, if set to "panel" the only noticeable difference is that the
    // DatabaseList becomes DatabaseDropdown (more space efficient in vertical layout)
    // and is outside the container with measurements/tags/fields
    //
    // TODO:
    // - perhaps switch to something like "isVertical" and accept boolean instead of string
    // - more css/markup work to make the alternate appearance look good

    return (
      <QueryBuilder
        source={source}
        timeRange={timeRange}
        query={activeQuery}
        actions={actions}
        onAddQuery={onAddQuery}
        layout={layout}
        isInDataExplorer={isInDataExplorer}
      />
    )
  },
})

QueryMaker.defaultProps = {
  layout: 'default',
}
export default QueryMaker
<commit_msg>Make DataExplorer's QueryMaker an SFC<commit_after>import React, {PropTypes} from 'react'

import QueryBuilder from './QueryBuilder'
import EmptyQuery from 'src/shared/components/EmptyQuery'
import QueryTabList from 'src/shared/components/QueryTabList'

const QueryMaker = ({
  source,
  actions,
  queries,
  timeRange,
  onAddQuery,
  activeQuery,
  onDeleteQuery,
  activeQueryIndex,
  setActiveQueryIndex,
}) =>

    <QueryTabList
      queries={queries}
      timeRange={timeRange}
      onAddQuery={onAddQuery}
      onDeleteQuery={onDeleteQuery}
      activeQueryIndex={activeQueryIndex}
      setActiveQueryIndex={setActiveQueryIndex}
    />
    {activeQuery
      ? <QueryBuilder
          layout={'default'}
          source={source}
          actions={actions}
          query={activeQuery}
          timeRange={timeRange}
          onAddQuery={onAddQuery}
          isInDataExplorer={true}
        />
      : <EmptyQuery onAddQuery={onAddQuery} />}

const {arrayOf, func, number, shape, string} = PropTypes

QueryMaker.propTypes = {
  source: shape({
    links: shape({
      queries: string.isRequired,
    }).isRequired,
  }).isRequired,
  queries: arrayOf(shape({})).isRequired,
  timeRange: shape({
    upper: string,
    lower: string,
  }).isRequired,
  actions: shape({
    chooseNamespace: func.isRequired,
    chooseMeasurement: func.isRequired,
    chooseTag: func.isRequired,
    groupByTag: func.isRequired,
    addQuery: func.isRequired,
    toggleField: func.isRequired,
    groupByTime: func.isRequired,
    toggleTagAcceptance: func.isRequired,
    applyFuncsToField: func.isRequired,
    editRawTextAsync: func.isRequired,
  }).isRequired,
  setActiveQueryIndex: func.isRequired,
  onDeleteQuery: func.isRequired,
  onAddQuery: func.isRequired,
  activeQuery: shape({}),
  activeQueryIndex: number,
}

export default QueryMaker
<|endoftext|>


<commit_before>(function () {

    // Main module
    var app = angular.module('odalic-app');

    // graphvis directive
    var currentFolder = $.getPathForRelativePath('');
    app.directive('graphvis', function (sharedata) {
        return {
            restrict: 'E',
            templateUrl: currentFolder + 'graphvis.html',
            link: function (scope, iElement, iAtttrs) {

                // Retrieve the necessary data
                var tScope = sharedata.get(iAtttrs['scope']);
                var vertices = tScope['inputFile']['columns'];
                var result = tScope['result'];
                var openModal = tScope['gvmodal']['open'];

                // Load the necessary modules
                var toLoad = ['graphcore.js', 'node.js', 'link.js', 'label.js', 'edgecreator.js'];
                toLoad.forEach(function (item) {
                    $.getScriptSync(currentFolder + item, function () {
                        /* Purposefully empty. */
                    });
                });

                // Create a root <svg> element
                var svg = d3.select(iElement.get(0).childNodes[2])
                    .append('svg')
                    .attr('width', 900)
                    .attr('height', 450);

                // Create a marker (arrow)
                (function () {
                    var defs = svg.append('defs');
                    defs
                        .append('marker')
                        .attrs({
                            'id': 'line-arrow-end',
                            'viewBox': '0 0 10 10',
                            'refX': 49,
                            'refY': 5,
                            'markerUnits': 'strokeWidth',
                            'orient': 'auto',
                            'markerWidth': 4,
                            'markerHeight': 4,
                            'xoverflow': 'visible'
                        })
                        .append('path')
                        .attr('d', 'M 0 0 L 10 5 L 0 10 z');
                    defs
                        .append('marker')
                        .attrs({
                            'id': 'line-arrow-start',
                            'viewBox': '0 0 10 10',
                            'refX': -41,
                            'refY': 5,
                            'markerUnits': 'strokeWidth',
                            'orient': 'auto',
                            'markerWidth': 4,
                            'markerHeight': 4,
                            'xoverflow': 'visible'
                        })
                        .append('path')
                        .attr('d', 'M -2 5 L 8 0 L 8 10 z');
                })();

                // Create a graph
                var g = new graph(svg, {
                    decay: {
                        velocity: 0.05,
                        alpha: 0.02,
                    },
                    collision: {
                        radius: 75,
                        strength: 0.1
                    },
                    centering: {
                        strength: 0.1
                    },
                    linksDistance: 250,
                    manyBody: {
                        strength: 0
                    }
                });

                // General graph state, properties and functions
                var gprops = (function () {
                    var _state = 0;
                    return {
                        states: {
                            NodeDragging: 0,
                            LinkCreation: 1,
                            ResetLayout: 2
                        },
                        get state() {
                            return _state;
                        },
                        set state(value) {
                            if (_state != value) {
                                _state = value;

                                // Call each vertex and edge and inform it about the state update
                                var arrs = [g.vertices.arr, g.edges.arr];
                                arrs.forEach(function (arr) {
                                    arr.forEach(function (item) {
                                        var fn = 'stateEnter';
                                        if (fn in item) {
                                            item[fn]();
                                        }
                                    });
                                });
                            }
                        },
                        link: {
                            create: function (node1, node2) {
                                var column1 = g.vertices.indexOf(node1.id);
                                var column2 = g.vertices.indexOf(node2.id);
                                if (column1 !== column2) {
                                    openModal(column1, column2);
                                }
                            },
                            settings: function (node1, node2) {
                                var column1 = g.vertices.indexOf(node1.id);
                                var column2 = g.vertices.indexOf(node2.id);
                                if (column1 !== column2) {
                                    openModal(column1, column2);
                                }
                            },
                            hoveredNode: null
                        },
                        graph: {
                            canvas: {
                                get width() {
                                    return svg.attr('width');
                                },
                                get height() {
                                    return svg.attr('height');
                                }
                            }
                        }
                    };
                })();

                // Set state; reset layout button
                (function () {
                    // Set state
                    scope.setDraggingDis = function () {
                        return (gprops.state === gprops.states.NodeDragging)
                    };
                    scope.setDragging = function () {
                        gprops.state = gprops.states.NodeDragging;
                    };
                    scope.setLinkCreationDis = function () {
                        return (gprops.state === gprops.states.LinkCreation)
                    };
                    scope.setLinkCreation = function () {
                        gprops.state = gprops.states.LinkCreation;
                    };

                    // Reset layout button
                    scope.resetLayoutDis = function () {
                        return (gprops.state !== gprops.states.NodeDragging);
                    };
                    scope.resetLayout = function () {
                        if (!scope.resetLayoutDis()) {
                            gprops.state = gprops.states.ResetLayout;
                            gprops.state = gprops.states.NodeDragging;
                        }
                    };
                })();

                // Prepare
                var node = nodeWrapper(gprops);
                var link = linkWrapper(gprops);

                // Generate vertices
                vertices.forEach(function (item) {
                    g.vertices.addItem(new node(item));
                });

                // Edges model reflection; generate edges
                (function () {
                    var modelChanged = function (column1, column2) {
                        var vertex1 = g.vertices.arr[column1].id;
                        var vertex2 = g.vertices.arr[column2].id;

                        var selection = tScope['currentRelations'][column1][column2];
                        var e = g.edges.find(vertex1, vertex2);
                        var labels = [];

                        // Construct predicate label for a given KB and a candidate
                        var handleCandidate = function (kb, candidate) {
                            var concept = candidate['label'];
                            if (!concept) {
                                var resource = candidate['resource'];
                                try {
                                    concept = text.uri(resource).page;
                                } catch (e) {
                                    concept = text.dotted(resource, 10);
                                }
                            }
                            labels.push(kb + ':' + concept);
                        };

                        // Retrieve selected predicate labels
                        objForEach(selection, function (kb, scArr) {
                            if (kb === 'other') {
                                if (scArr && scArr[0]['resource']) {
                                    handleCandidate(kb, scArr[0]);
                                }
                                return;
                            }

                            scArr.forEach(function (candidate) {
                                handleCandidate(kb, candidate);
                            });
                        });

                        // Set the label
                        if (labels.length > 0) {
                            if (e === null) {
                                e = new link(column1, column2);
                                var _e = g.edges.addItem(e);
                                e = _e ? _e : e;
                                g.forceUpdate();
                            }
                            e.setLabel(labels.join(', '), vertex1, vertex2);
                        }
                        // Remove the whole edge as there are no selected relations
                        else {
                            if (e !== null) {
                                g.edges.removeItem(vertex1, vertex2);
                            }
                        }
                    };

                    // Set the event handler for model changes
                    tScope['gvmodal']['modelChanged'] = modelChanged;

                    // Generate first edges the similar way
                    objForEach(tScope['currentRelations'], function (column1, cl1) {
                        objForEach(cl1, function (column2, cl2) {
                            modelChanged(parseInt(column1), parseInt(column2));
                        });
                    });
                })();
            }
        }
    });

})();<commit_msg>Label shortening correction (issue #75), p1<commit_after>(function () {

    // Main module
    var app = angular.module('odalic-app');

    // graphvis directive
    var currentFolder = $.getPathForRelativePath('');
    app.directive('graphvis', function (sharedata) {
        return {
            restrict: 'E',
            templateUrl: currentFolder + 'graphvis.html',
            link: function (scope, iElement, iAtttrs) {

                // Retrieve the necessary data
                var tScope = sharedata.get(iAtttrs['scope']);
                var vertices = tScope['inputFile']['columns'];
                var result = tScope['result'];
                var openModal = tScope['gvmodal']['open'];

                // Load the necessary modules
                var toLoad = ['graphcore.js', 'node.js', 'link.js', 'label.js', 'edgecreator.js'];
                toLoad.forEach(function (item) {
                    $.getScriptSync(currentFolder + item, function () {
                        /* Purposefully empty. */
                    });
                });

                // Create a root <svg> element
                var svg = d3.select(iElement.get(0).childNodes[2])
                    .append('svg')
                    .attr('width', 900)
                    .attr('height', 450);

                // Create a marker (arrow)
                (function () {
                    var defs = svg.append('defs');
                    defs
                        .append('marker')
                        .attrs({
                            'id': 'line-arrow-end',
                            'viewBox': '0 0 10 10',
                            'refX': 49,
                            'refY': 5,
                            'markerUnits': 'strokeWidth',
                            'orient': 'auto',
                            'markerWidth': 4,
                            'markerHeight': 4,
                            'xoverflow': 'visible'
                        })
                        .append('path')
                        .attr('d', 'M 0 0 L 10 5 L 0 10 z');
                    defs
                        .append('marker')
                        .attrs({
                            'id': 'line-arrow-start',
                            'viewBox': '0 0 10 10',
                            'refX': -41,
                            'refY': 5,
                            'markerUnits': 'strokeWidth',
                            'orient': 'auto',
                            'markerWidth': 4,
                            'markerHeight': 4,
                            'xoverflow': 'visible'
                        })
                        .append('path')
                        .attr('d', 'M -2 5 L 8 0 L 8 10 z');
                })();

                // Create a graph
                var g = new graph(svg, {
                    decay: {
                        velocity: 0.05,
                        alpha: 0.02,
                    },
                    collision: {
                        radius: 75,
                        strength: 0.1
                    },
                    centering: {
                        strength: 0.1
                    },
                    linksDistance: 250,
                    manyBody: {
                        strength: 0
                    }
                });

                // General graph state, properties and functions
                var gprops = (function () {
                    var _state = 0;
                    return {
                        states: {
                            NodeDragging: 0,
                            LinkCreation: 1,
                            ResetLayout: 2
                        },
                        get state() {
                            return _state;
                        },
                        set state(value) {
                            if (_state != value) {
                                _state = value;

                                // Call each vertex and edge and inform it about the state update
                                var arrs = [g.vertices.arr, g.edges.arr];
                                arrs.forEach(function (arr) {
                                    arr.forEach(function (item) {
                                        var fn = 'stateEnter';
                                        if (fn in item) {
                                            item[fn]();
                                        }
                                    });
                                });
                            }
                        },
                        link: {
                            create: function (node1, node2) {
                                var column1 = g.vertices.indexOf(node1.id);
                                var column2 = g.vertices.indexOf(node2.id);
                                if (column1 !== column2) {
                                    openModal(column1, column2);
                                }
                            },
                            settings: function (node1, node2) {
                                var column1 = g.vertices.indexOf(node1.id);
                                var column2 = g.vertices.indexOf(node2.id);
                                if (column1 !== column2) {
                                    openModal(column1, column2);
                                }
                            },
                            hoveredNode: null
                        },
                        graph: {
                            canvas: {
                                get width() {
                                    return svg.attr('width');
                                },
                                get height() {
                                    return svg.attr('height');
                                }
                            }
                        }
                    };
                })();

                // Set state; reset layout button
                (function () {
                    // Set state
                    scope.setDraggingDis = function () {
                        return (gprops.state === gprops.states.NodeDragging)
                    };
                    scope.setDragging = function () {
                        gprops.state = gprops.states.NodeDragging;
                    };
                    scope.setLinkCreationDis = function () {
                        return (gprops.state === gprops.states.LinkCreation)
                    };
                    scope.setLinkCreation = function () {
                        gprops.state = gprops.states.LinkCreation;
                    };

                    // Reset layout button
                    scope.resetLayoutDis = function () {
                        return (gprops.state !== gprops.states.NodeDragging);
                    };
                    scope.resetLayout = function () {
                        if (!scope.resetLayoutDis()) {
                            gprops.state = gprops.states.ResetLayout;
                            gprops.state = gprops.states.NodeDragging;
                        }
                    };
                })();

                // Prepare
                var node = nodeWrapper(gprops);
                var link = linkWrapper(gprops);

                // Generate vertices
                vertices.forEach(function (item) {
                    g.vertices.addItem(new node(item));
                });

                // Edges model reflection; generate edges
                (function () {
                    var modelChanged = function (column1, column2) {
                        var vertex1 = g.vertices.arr[column1].id;
                        var vertex2 = g.vertices.arr[column2].id;

                        var selection = tScope['currentRelations'][column1][column2];
                        var e = g.edges.find(vertex1, vertex2);
                        var labels = [];

                        // Construct predicate label for a given KB and a candidate
                        var handleCandidate = function (kb, candidate) {
                            var concept = candidate['label'];
                            if (!concept) {
                                var resource = candidate['resource'];
                                try {
                                    concept = text.uri(resource).page;
                                } catch (e) {
                                    concept = text.dotted(resource, 25);
                                }
                            }
                            labels.push(kb + ':' + concept);
                        };

                        // Retrieve selected predicate labels
                        objForEach(selection, function (kb, scArr) {
                            if (kb === 'other') {
                                if (scArr && scArr[0]['resource']) {
                                    handleCandidate(kb, scArr[0]);
                                }
                                return;
                            }

                            scArr.forEach(function (candidate) {
                                handleCandidate(kb, candidate);
                            });
                        });

                        // Set the label
                        if (labels.length > 0) {
                            if (e === null) {
                                e = new link(column1, column2);
                                var _e = g.edges.addItem(e);
                                e = _e ? _e : e;
                                g.forceUpdate();
                            }
                            e.setLabel(labels.join(', '), vertex1, vertex2);
                        }
                        // Remove the whole edge as there are no selected relations
                        else {
                            if (e !== null) {
                                g.edges.removeItem(vertex1, vertex2);
                            }
                        }
                    };

                    // Set the event handler for model changes
                    tScope['gvmodal']['modelChanged'] = modelChanged;

                    // Generate first edges the similar way
                    objForEach(tScope['currentRelations'], function (column1, cl1) {
                        objForEach(cl1, function (column2, cl2) {
                            modelChanged(parseInt(column1), parseInt(column2));
                        });
                    });
                })();
            }
        }
    });

})();
<|endoftext|>