<commit_before>import React, { Component, PropTypes } from 'react';
import { FormattedMessage, defineMessages, injectIntl, intlShape } from 'react-intl';
import Relay from 'react-relay';
import { Link } from 'react-router';
import { Card, CardText, CardActions } from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import ResetPasswordMutation from '../relay/ResetPasswordMutation';
import CheckContext from '../CheckContext';

const messages = defineMessages({
  emailNotFound: {
    id: 'passwordReset.emailNotFound',
    defaultMessage: 'Email not found. Please contact check@meedan.com for support.',
  },
  emailNotValid: {
    id: 'passwordReset.emailNotValid',
    defaultMessage: 'Please enter a valid email address.',
  }
});

class UserPasswordReset extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showConfirmDialog: false,
      submitDisabled: true
    }
  }

  getHistory() {
    const history = new CheckContext(this).getContextStore().history;
    return history;
  }

  handleGoBack() {
    const history = this.getHistory();
    history.goBack();
  }

  handleSignIn() {
    const history = this.getHistory();
    history.push('/', { signInWithEmail: true });
  }

  handleChange(e) {
    const value = e.target.value.trim();
    const canSubmit = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value);
    const errorMsg = canSubmit ? '' : this.props.intl.formatMessage(messages.emailNotValid);

    this.setState({ errorMsg, email: value, submitDisabled: !canSubmit });
  }

  handleSubmit(e) {
    const that = this;

    const onFailure = (transaction) => {
      that.setState({ errorMsg: that.props.intl.formatMessage(messages.emailNotFound), submitDisabled: true });
    };

    const onSuccess = (response) => {
      that.setState({ showConfirmDialog: true });
    };

    if (!that.state.submitDisabled){
      Relay.Store.commitUpdate(
        new ResetPasswordMutation({
          email: this.state.email
        }),
        { onSuccess, onFailure },
      );
    }
    e.preventDefault();
  }

  render() {
    return (

        <Card className="user-password-reset__card">
          { this.state.showConfirmDialog ? [
            <CardText>

<FormattedMessage id="passwordReset.confirmedTitle" defaultMessage="Password reset sent" />

              <FormattedMessage id="passwordReset.confirmedText" defaultMessage="We've sent you an email from admin@checkmedia.org with instructions to reset your password. Make sure it didn't wind up in your spam mailbox. If you aren't receiving our password reset emails, contact check@meedan.com." />
            </CardText>,
            <CardActions className="user-password-reset__actions">
              <FlatButton label={<FormattedMessage id="passwordReset.goBack" defaultMessage="Go Back" />} onClick={this.handleGoBack.bind(this)} />
              <FlatButton label={<FormattedMessage id="passwordReset.signIn" defaultMessage="Sign In"/>} primary disabled={this.state.submitDisabled} onClick={this.handleSignIn.bind(this)} />
            </CardActions>
          ] : [
            <CardText>

<FormattedMessage id="passwordReset.title" defaultMessage="Forgot password" />

              <FormattedMessage id="passwordReset.text" defaultMessage="Happens to everybody! Add your address and an email will be sent with further instructions." />

                <TextField id="password-reset-email-input"
                    type="email"
                    floatingLabelText={<FormattedMessage id="passwordReset.email" defaultMessage="Email" />}
                    onChange={this.handleChange.bind(this)}
                    errorText={this.state.errorMsg}
                    fullWidth />

            </CardText>,
            <CardActions className="user-password-reset__actions">
              <FlatButton label={<FormattedMessage id="passwordReset.cancel" defaultMessage="Cancel" />} onClick={this.handleGoBack.bind(this)} />
              <FlatButton label={<FormattedMessage id="passwordReset.submit" defaultMessage="Reset Password"/>} primary disabled={this.state.submitDisabled} onClick={this.handleSubmit.bind(this)} />
            </CardActions>
          ]}
        </Card>

    );
  }
}

UserPasswordReset.contextTypes = {
  store: React.PropTypes.object,
};

export default injectIntl(UserPasswordReset);
<commit_msg>Remove the Go Back button. #5582<commit_after>import React, { Component, PropTypes } from 'react';
import { FormattedMessage, defineMessages, injectIntl, intlShape } from 'react-intl';
import Relay from 'react-relay';
import { Link } from 'react-router';
import { Card, CardText, CardActions } from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import ResetPasswordMutation from '../relay/ResetPasswordMutation';
import CheckContext from '../CheckContext';

const messages = defineMessages({
  emailNotFound: {
    id: 'passwordReset.emailNotFound',
    defaultMessage: 'Email not found. Please contact check@meedan.com for support.',
  },
  emailNotValid: {
    id: 'passwordReset.emailNotValid',
    defaultMessage: 'Please enter a valid email address.',
  }
});

class UserPasswordReset extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showConfirmDialog: false,
      submitDisabled: true
    }
  }

  getHistory() {
    const history = new CheckContext(this).getContextStore().history;
    return history;
  }

  handleGoBack() {
    const history = this.getHistory();
    history.goBack();
  }

  handleSignIn() {
    const history = this.getHistory();
    history.push('/', { signInWithEmail: true });
  }

  handleChange(e) {
    const value = e.target.value.trim();
    const canSubmit = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value);
    const errorMsg = canSubmit ? '' : this.props.intl.formatMessage(messages.emailNotValid);

    this.setState({ errorMsg, email: value, submitDisabled: !canSubmit });
  }

  handleSubmit(e) {
    const that = this;

    const onFailure = (transaction) => {
      that.setState({ errorMsg: that.props.intl.formatMessage(messages.emailNotFound), submitDisabled: true });
    };

    const onSuccess = (response) => {
      that.setState({ showConfirmDialog: true });
    };

    if (!that.state.submitDisabled){
      Relay.Store.commitUpdate(
        new ResetPasswordMutation({
          email: this.state.email
        }),
        { onSuccess, onFailure },
      );
    }
    e.preventDefault();
  }

  render() {
    return (

        <Card className="user-password-reset__card">
          { this.state.showConfirmDialog ? [
            <CardText>

<FormattedMessage id="passwordReset.confirmedTitle" defaultMessage="Password reset sent" />

              <FormattedMessage id="passwordReset.confirmedText" defaultMessage="We've sent you an email from admin@checkmedia.org with instructions to reset your password. Make sure it didn't wind up in your spam mailbox. If you aren't receiving our password reset emails, contact check@meedan.com." />
            </CardText>,
            <CardActions className="user-password-reset__actions">
              <FlatButton label={<FormattedMessage id="passwordReset.signIn" defaultMessage="Sign In"/>} primary disabled={this.state.submitDisabled} onClick={this.handleSignIn.bind(this)} />
            </CardActions>
          ] : [
            <CardText>

<FormattedMessage id="passwordReset.title" defaultMessage="Forgot password" />

              <FormattedMessage id="passwordReset.text" defaultMessage="Happens to everybody! Add your address and an email will be sent with further instructions." />

                <TextField id="password-reset-email-input"
                    type="email"
                    floatingLabelText={<FormattedMessage id="passwordReset.email" defaultMessage="Email" />}
                    onChange={this.handleChange.bind(this)}
                    errorText={this.state.errorMsg}
                    fullWidth />

            </CardText>,
            <CardActions className="user-password-reset__actions">
              <FlatButton label={<FormattedMessage id="passwordReset.cancel" defaultMessage="Cancel" />} onClick={this.handleGoBack.bind(this)} />
              <FlatButton label={<FormattedMessage id="passwordReset.submit" defaultMessage="Reset Password"/>} primary disabled={this.state.submitDisabled} onClick={this.handleSubmit.bind(this)} />
            </CardActions>
          ]}
        </Card>

    );
  }
}

UserPasswordReset.contextTypes = {
  store: React.PropTypes.object,
};

export default injectIntl(UserPasswordReset);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
import TimeAgo from 'react-timeago';
import { Link } from 'react-router';
import config from 'config';
import MediaStatus from './MediaStatus';
import MediaTags from './MediaTags';
import QuoteMediaCard from './QuoteMediaCard';
import SocialMediaCard from './SocialMediaCard';
import MediaActions from './MediaActions';
import MediaUtil from './MediaUtil';
import Tags from '../source/Tags';
import DefaultButton from '../inputs/DefaultButton';
import PenderCard from '../PenderCard';
import ImageMediaCard from './ImageMediaCard';
import UpdateMediaMutation from '../../relay/UpdateMediaMutation';
import CheckContext from '../../CheckContext';

class MediaDetail extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isEditing: false,
    };
  }

  handleEdit() {
    this.setState({ isEditing: true });
  }

  handleSave(media, event) {
    if (event) {
      event.preventDefault();
    }

    const titleInput = document.querySelector(`#media-detail-title-input-${media.dbid}`);
    const newTitle = (titleInput.value || '').trim();

    const onFailure = (transaction) => {
      const transactionError = transaction.getError();
      transactionError.json ? transactionError.json().then(handleError) : handleError(JSON.stringify(transactionError));
    };

    const onSuccess = (response) => {
      this.setState({ isEditing: false });
    };

    Relay.Store.commitUpdate(
      new UpdateMediaMutation({
        embed: JSON.stringify({ title: newTitle }),
        id: media.id,
      }),
      { onSuccess, onFailure },
    );

    this.setState({ isEditing: false });
  }

  handleCancel() {
    this.setState({ isEditing: false });
  }

  statusToClass(baseClass, status) {
    return status.length ?
      [baseClass, `${baseClass}--${status.toLowerCase().replace(/[ _]/g, '-')}`].join(' ') :
      baseClass;
  }

  render() {
    const { media, annotated, annotatedType, condensed } = this.props;
    const data = JSON.parse(media.embed);
    const createdAt = MediaUtil.createdAt(media);
    const annotationsCount = MediaUtil.notesCount(media, data);

    let projectId = media.project_id;
    if (!projectId && annotated && annotatedType === 'Project') {
      projectId = annotated.dbid;
    }
    const mediaUrl = (projectId && media.team) ? `/${media.team.slug}/project/${projectId}/media/${media.dbid}` : null;

    const byUser = (media.user && media.user.source && media.user.source.dbid && media.user.name !== 'Pender') ?
      (by {media.user.name}) : '';

    let embedCard = null;
    media.url = media.media.url;
    media.quote = media.media.quote;

    if (media.media.embed_path) {
      const path = condensed ? media.media.thumbnail_path : media.media.embed_path;
      embedCard = <ImageMediaCard imagePath={path} />;
    } else if (media.quote && media.quote.length) {
      embedCard = <QuoteMediaCard quoteText={media.quote} attributionName={null} attributionUrl={null} />;
    } else if (media.url) {
       embedCard = condensed ?
                   <SocialMediaCard media={media} data={data} condensed={condensed} /> :
                   <PenderCard url={media.url} penderUrl={config.penderUrl} fallback={<SocialMediaCard media={media} data={data} condensed={condensed} />} />;
    }

    return (

<MediaStatus media={media} readonly={this.props.readonly} />

          {this.state.isEditing ? (

              <DefaultButton onClick={this.handleCancel.bind(this)} className="media-detail__cancel-edits" size="xsmall">Cancel</DefaultButton>
              <DefaultButton onClick={this.handleSave.bind(this, media)} className="media-detail__save-edits" size="xsmall" style="primary">Done</DefaultButton>

              ) : null
            }
          {this.props.readonly || this.state.isEditing ? null :
          <MediaActions media={media} handleEdit={this.handleEdit.bind(this)} />
            }

        {this.state.isEditing ?
          <form onSubmit={this.handleSave.bind(this, media)}><input type="text" id={`media-detail-title-input-${media.dbid}`} className="media-detail__title-input" placeholder="Title" defaultValue={MediaUtil.truncatedTitle(media, data)} /></form> :

<Link to={mediaUrl}>{this.props.condensed ? MediaUtil.truncatedTitle(media, data) : MediaUtil.title(media, data)}</Link>

        }

          {embedCard}

          {byUser ? Added {byUser}  : null}
          {createdAt ?
            <Link className="media-detail__check-timestamp" to={mediaUrl}><TimeAgo date={createdAt} live={false} /></Link>
           : null}
          <Link to={mediaUrl} className="media-detail__check-notes-count">{annotationsCount}</Link>

        {media.tags ? <MediaTags media={media} tags={media.tags.edges} isEditing={this.state.isEditing} /> : null}

    );
  }
}

MediaDetail.contextTypes = {
  store: React.PropTypes.object,
};

export default MediaDetail;
<commit_msg>Ticket #5447: Do not use a fallback on <PenderCard /><commit_after>import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
import TimeAgo from 'react-timeago';
import { Link } from 'react-router';
import config from 'config';
import MediaStatus from './MediaStatus';
import MediaTags from './MediaTags';
import QuoteMediaCard from './QuoteMediaCard';
import SocialMediaCard from './SocialMediaCard';
import MediaActions from './MediaActions';
import MediaUtil from './MediaUtil';
import Tags from '../source/Tags';
import DefaultButton from '../inputs/DefaultButton';
import PenderCard from '../PenderCard';
import ImageMediaCard from './ImageMediaCard';
import UpdateMediaMutation from '../../relay/UpdateMediaMutation';
import CheckContext from '../../CheckContext';

class MediaDetail extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isEditing: false,
    };
  }

  handleEdit() {
    this.setState({ isEditing: true });
  }

  handleSave(media, event) {
    if (event) {
      event.preventDefault();
    }

    const titleInput = document.querySelector(`#media-detail-title-input-${media.dbid}`);
    const newTitle = (titleInput.value || '').trim();

    const onFailure = (transaction) => {
      const transactionError = transaction.getError();
      transactionError.json ? transactionError.json().then(handleError) : handleError(JSON.stringify(transactionError));
    };

    const onSuccess = (response) => {
      this.setState({ isEditing: false });
    };

    Relay.Store.commitUpdate(
      new UpdateMediaMutation({
        embed: JSON.stringify({ title: newTitle }),
        id: media.id,
      }),
      { onSuccess, onFailure },
    );

    this.setState({ isEditing: false });
  }

  handleCancel() {
    this.setState({ isEditing: false });
  }

  statusToClass(baseClass, status) {
    return status.length ?
      [baseClass, `${baseClass}--${status.toLowerCase().replace(/[ _]/g, '-')}`].join(' ') :
      baseClass;
  }

  render() {
    const { media, annotated, annotatedType, condensed } = this.props;
    const data = JSON.parse(media.embed);
    const createdAt = MediaUtil.createdAt(media);
    const annotationsCount = MediaUtil.notesCount(media, data);

    let projectId = media.project_id;
    if (!projectId && annotated && annotatedType === 'Project') {
      projectId = annotated.dbid;
    }
    const mediaUrl = (projectId && media.team) ? `/${media.team.slug}/project/${projectId}/media/${media.dbid}` : null;

    const byUser = (media.user && media.user.source && media.user.source.dbid && media.user.name !== 'Pender') ?
      (by {media.user.name}) : '';

    let embedCard = null;
    media.url = media.media.url;
    media.quote = media.media.quote;

    if (media.media.embed_path) {
      const path = condensed ? media.media.thumbnail_path : media.media.embed_path;
      embedCard = <ImageMediaCard imagePath={path} />;
    } else if (media.quote && media.quote.length) {
      embedCard = <QuoteMediaCard quoteText={media.quote} attributionName={null} attributionUrl={null} />;
    } else if (media.url) {
       embedCard = condensed ?
                   <SocialMediaCard media={media} data={data} condensed={condensed} /> :
                   <PenderCard url={media.url} penderUrl={config.penderUrl} fallback={null} />;
    }

    return (

<MediaStatus media={media} readonly={this.props.readonly} />

          {this.state.isEditing ? (

              <DefaultButton onClick={this.handleCancel.bind(this)} className="media-detail__cancel-edits" size="xsmall">Cancel</DefaultButton>
              <DefaultButton onClick={this.handleSave.bind(this, media)} className="media-detail__save-edits" size="xsmall" style="primary">Done</DefaultButton>

              ) : null
            }
          {this.props.readonly || this.state.isEditing ? null :
          <MediaActions media={media} handleEdit={this.handleEdit.bind(this)} />
            }

        {this.state.isEditing ?
          <form onSubmit={this.handleSave.bind(this, media)}><input type="text" id={`media-detail-title-input-${media.dbid}`} className="media-detail__title-input" placeholder="Title" defaultValue={MediaUtil.truncatedTitle(media, data)} /></form> :

<Link to={mediaUrl}>{this.props.condensed ? MediaUtil.truncatedTitle(media, data) : MediaUtil.title(media, data)}</Link>

        }

          {embedCard}

          {byUser ? Added {byUser}  : null}
          {createdAt ?
            <Link className="media-detail__check-timestamp" to={mediaUrl}><TimeAgo date={createdAt} live={false} /></Link>
           : null}
          <Link to={mediaUrl} className="media-detail__check-notes-count">{annotationsCount}</Link>

        {media.tags ? <MediaTags media={media} tags={media.tags.edges} isEditing={this.state.isEditing} /> : null}

    );
  }
}

MediaDetail.contextTypes = {
  store: React.PropTypes.object,
};

export default MediaDetail;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import FontAwesome from 'react-fontawesome';
import TimeAgo from 'react-timeago';
import { Link } from 'react-router';
import PenderCard from '../PenderCard';
import config from 'config';
import MediaStatus from './MediaStatus';

class MediaDetail extends Component {
  statusToClass(status) {
    if (status === '') {
      return '';
    }
    return 'media-detail__media--' + status.toLowerCase().replace(/[ _]/g, '-');
  }

  render() {
    const media = this.props.media;
    media.created_at = new Date(parseInt(media.published) * 1000);
    const data = JSON.parse(media.jsondata);
    const prefix = '/source/';

    const hide = {
      title: { twitter: true, instagram: true },
      description: { twitter: true, oembed: true, instagram: true }
    };

    return (

<MediaStatus media={media} />

          <PenderCard url={media.url} penderUrl={config.penderUrl} />

          <Link to={data.url} target="_blank">Posted</Link> by {media.account.source.name} (<Link to={data.author_url} target="_blank">@{data.username}</Link>) to <Link to={'https://' + media.domain}>{media.domain}</Link> {data.published_at ? <Link to={data.url} target="_blank"><TimeAgo date={data.published_at} live={false} /></Link> : null}

{hide.title[data.provider] ? null : data.title}

{hide.description[data.provider] ? null : data.description}

    );
  }
}

export default MediaDetail;
<commit_msg>Ticket #5269: Do not crash media view when some media information is not available<commit_after>import React, { Component, PropTypes } from 'react';
import FontAwesome from 'react-fontawesome';
import TimeAgo from 'react-timeago';
import { Link } from 'react-router';
import PenderCard from '../PenderCard';
import config from 'config';
import MediaStatus from './MediaStatus';

class MediaDetail extends Component {
  statusToClass(status) {
    if (status === '') {
      return '';
    }
    return 'media-detail__media--' + status.toLowerCase().replace(/[ _]/g, '-');
  }

  render() {
    const media = this.props.media;
    media.created_at = new Date(parseInt(media.published) * 1000);
    const data = JSON.parse(media.jsondata);
    const prefix = '/source/';

    const hide = {
      title: { twitter: true, instagram: true },
      description: { twitter: true, oembed: true, instagram: true }
    };

    const username = data.username ? ('@' + data.username) : data.author_url;

    return (

<MediaStatus media={media} />

          <PenderCard url={media.url} penderUrl={config.penderUrl} />

          <Link to={data.url} target="_blank">Posted</Link>

          {(() => {
            if (media.account && media.account.source && media.account.source.name) {
              return (
                by {media.account.source.name} (<Link to={data.author_url} target="_blank">{username}</Link>)
              );
            }
          })()}

          to <Link to={'https://' + media.domain}>{media.domain}</Link> {data.published_at ? <Link to={data.url} target="_blank"><TimeAgo date={data.published_at} live={false} /></Link> : null}

{hide.title[data.provider] ? null : data.title}

{hide.description[data.provider] ? null : data.description}

    );
  }
}

export default MediaDetail;
<|endoftext|>


<commit_before>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('angular2/core');
var http_1 = require('angular2/http');
var UrlInput = (function () {
    function UrlInput(http) {
        this.CLIENT_ID = '02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea';
        this.get_track_id_url = 'http://api.soundcloud.com/resolve.json?url=';
        this.get_track_from_id_url = 'http://api.soundcloud.com/i1/tracks/';
        this.addNewTrack = new core_1.EventEmitter();
        this.http = http;
    }
    UrlInput.prototype.enterUrl = function (url) {
        this.get_track_id_obj(url);
    };
    UrlInput.prototype.get_track_id_obj = function (url) {
        var _this = this;
        this.http.get("" + this.get_track_id_url + url + "&client_id=" + this.CLIENT_ID)
            .map(function (res) {
            return _this.prune_id_response(res.json());
        })
            .subscribe(function (data) { return _this.get_track_url(data); }, function (err) { return _this.logError(err); });
    };
    UrlInput.prototype.get_track_url = function (obj) {
        var _this = this;
        this.http.get("" + this.get_track_from_id_url + obj.id + "/streams?client_id=" + this.CLIENT_ID)
            .map(function (res) {
            obj.url = res.json().http_mp3_128_url;
            delete obj.id;
            return obj;
        })
            .subscribe(function (data) { _this.addNewTrack.emit(data); }, function (err) { return _this.logError(err); });
    };
    UrlInput.prototype.logError = function (err) {
        console.warn("error: " + err);
    };
    UrlInput.prototype.prune_id_response = function (res) {
        return {
            title: res.title,
            artwork_url: res.artwork_url,
            description: res.description,
            id: res.id,
            genre: res.genre
        };
    };
    UrlInput = __decorate([
        core_1.Component({
            outputs: ['addNewTrack'],
            selector: 'url-input',
            styles: [require('./urlInput.scss')],
            template: require('./urlInput.jade')
        }),
        __metadata('design:paramtypes', [http_1.Http])
    ], UrlInput);
    return UrlInput;
})();
exports.UrlInput = UrlInput;
//# sourceMappingURL=urlInput.js.map
<commit_msg>Update urlInput.js<commit_after>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('angular2/core');
var http_1 = require('angular2/http');
var UrlInput = (function () {
    function UrlInput(http) {
        this.CLIENT_ID = 'JlZIsxg2hY5WnBgtn3jfS0UYCl0K8DOg';
        this.get_track_id_url = 'http://api.soundcloud.com/resolve.json?url=';
        this.get_track_from_id_url = 'http://api.soundcloud.com/i1/tracks/';
        this.addNewTrack = new core_1.EventEmitter();
        this.http = http;
    }
    UrlInput.prototype.enterUrl = function (url) {
        this.get_track_id_obj(url);
    };
    UrlInput.prototype.get_track_id_obj = function (url) {
        var _this = this;
        this.http.get("" + this.get_track_id_url + url + "&client_id=" + this.CLIENT_ID)
            .map(function (res) {
            return _this.prune_id_response(res.json());
        })
            .subscribe(function (data) { return _this.get_track_url(data); }, function (err) { return _this.logError(err); });
    };
    UrlInput.prototype.get_track_url = function (obj) {
        var _this = this;
        this.http.get("" + this.get_track_from_id_url + obj.id + "/streams?client_id=" + this.CLIENT_ID)
            .map(function (res) {
            obj.url = res.json().http_mp3_128_url;
            delete obj.id;
            return obj;
        })
            .subscribe(function (data) { _this.addNewTrack.emit(data); }, function (err) { return _this.logError(err); });
    };
    UrlInput.prototype.logError = function (err) {
        console.warn("error: " + err);
    };
    UrlInput.prototype.prune_id_response = function (res) {
        return {
            title: res.title,
            artwork_url: res.artwork_url,
            description: res.description,
            id: res.id,
            genre: res.genre
        };
    };
    UrlInput = __decorate([
        core_1.Component({
            outputs: ['addNewTrack'],
            selector: 'url-input',
            styles: [require('./urlInput.scss')],
            template: require('./urlInput.jade')
        }),
        __metadata('design:paramtypes', [http_1.Http])
    ], UrlInput);
    return UrlInput;
})();
exports.UrlInput = UrlInput;
//# sourceMappingURL=urlInput.js.map
<|endoftext|>


<commit_before>// Connecting to ROS
// -----------------
var ros = new ROSLIB.Ros();

// If there is an error on the backend, an 'error' emit will be emitted.
ros.on('error', function(error) {
  document.getElementById('connecting').style.display = 'none';
  document.getElementById('connected').style.display = 'none';
  document.getElementById('closed').style.display = 'none';
  document.getElementById('error').style.display = 'block';
  document.getElementById('troubleshooting').style.display = 'inline-block';
  console.log(error);
});

// Find out exactly when we made a connection.
ros.on('connection', function() {
  console.log('Connection made!');
  document.getElementById('connecting').style.display = 'none';
  document.getElementById('error').style.display = 'none';
  document.getElementById('closed').style.display = 'none';
  document.getElementById('connected').style.display = 'block';
});

ros.on('close', function() {
  console.log('Connection closed.');
  document.getElementById('connecting').style.display = 'none';
  document.getElementById('connected').style.display = 'none';
  document.getElementById('closed').style.display = 'inline-block';
  document.getElementById('error').style.display = 'inline-block';
});

// Guess connection of the rosbridge websocket
function getRosBridgeHost() {
  if (window.location.protocol == 'file:') {
    return 'localhost';
  } else {
    return window.location.hostname;
  }
}

var rosBridgePort = 9090;
// Create a connection to the rosbridge WebSocket server.
ros.connect('ws://' + getRosBridgeHost() + ':' + rosBridgePort);

// First, we create a Topic object with details of the topic's name and message type.
var elemPressed = new ROSLIB.Topic({
  ros : ros,
  name : '/web_interface',
  messageType : 'std_msgs/String'
});

// Topic for error passing to the left arm
var errorPressedL = new ROSLIB.Topic({
  ros : ros,
  name : '/robot/digital_io/left_lower_button/state',
  messageType : 'baxter_core_msgs/DigitalIOState'
});

// Topic for error passing to the right arm
var errorPressedR = new ROSLIB.Topic({
  ros : ros,
  name : '/robot/digital_io/right_lower_button/state',
  messageType : 'baxter_core_msgs/DigitalIOState'
});

// Service Client to interface with the left arm
var leftArmService  = new ROSLIB.Service({
  ros : ros,
  name: '/action_provider/service_left',
  messageType : 'baxter_collaboration/DoAction'
});

// Service Client to interface with the right arm
var rightArmService = new ROSLIB.Service({
  ros : ros,
  name: '/action_provider/service_right',
  messageType : 'baxter_collaboration/DoAction'
});

// Add a callback for any element on the page
function callback(e) {
    var e = window.e || e;

    // console.log(e.target.tagName);
    if (e.target.tagName == 'BUTTON')
    {
        var obj = e.target.firstChild.nodeValue;
        console.log('Pressed '+ e.target.tagName +
                    ' item: ' + obj);

        if (obj == 'error')
        {
          var message = new ROSLIB.Message({
            state: 1,
            isInputOnly: true
          });

          errorPressedL.publish(message);
          errorPressedR.publish(message);
        }
        else if (obj == 'hold')
        {
          var req = new ROSLIB.ServiceRequest(
          {
            action: 'hold',
            object: -1
          });
          var res = new ROSLIB.ServiceResponse();

          rightArmService.callService(req,function(rsp) {
              console.log('Got Response: ' + rsp.success);
          });
        }
        else if (obj == 'get CF' || obj == 'get LL' ||
                 obj == 'get RL' || obj == 'get TOP' )
        {
          var req = new ROSLIB.ServiceRequest();
          req.action = 'get';

          if      (obj.replace('get ','') == 'CF')  { req.object = 24; }
          else if (obj.replace('get ','') == 'LL')  { req.object = 17; }
          else if (obj.replace('get ','') == 'RL')  { req.object = 26; }
          else if (obj.replace('get ','') == 'TOP') { req.object = 21; }
          else { console.error('Requested an object that was not allowed!'); };

          var res = new ROSLIB.ServiceResponse();

          leftArmService.callService(req,function(rsp) {
              console.log('Got Response: ' + rsp.success);
          });
        }
        else
        {
          var message = new ROSLIB.Message({
            data: obj
          });

          elemPressed.publish(message);
        }
    }

    return;
}

if (document.addEventListener)
    document.addEventListener('click', callback, false);
else
    document.attachEvent('onclick', callback);

<commit_msg>Added get and pass in place of only get<commit_after>// Connecting to ROS
// -----------------
var ros = new ROSLIB.Ros();

// If there is an error on the backend, an 'error' emit will be emitted.
ros.on('error', function(error) {
  document.getElementById('connecting').style.display = 'none';
  document.getElementById('connected').style.display = 'none';
  document.getElementById('closed').style.display = 'none';
  document.getElementById('error').style.display = 'block';
  document.getElementById('troubleshooting').style.display = 'inline-block';
  console.log(error);
});

// Find out exactly when we made a connection.
ros.on('connection', function() {
  console.log('Connection made!');
  document.getElementById('connecting').style.display = 'none';
  document.getElementById('error').style.display = 'none';
  document.getElementById('closed').style.display = 'none';
  document.getElementById('connected').style.display = 'block';
});

ros.on('close', function() {
  console.log('Connection closed.');
  document.getElementById('connecting').style.display = 'none';
  document.getElementById('connected').style.display = 'none';
  document.getElementById('closed').style.display = 'inline-block';
  document.getElementById('error').style.display = 'inline-block';
});

// Guess connection of the rosbridge websocket
function getRosBridgeHost() {
  if (window.location.protocol == 'file:') {
    return 'localhost';
  } else {
    return window.location.hostname;
  }
}

var rosBridgePort = 9090;
// Create a connection to the rosbridge WebSocket server.
ros.connect('ws://' + getRosBridgeHost() + ':' + rosBridgePort);

// First, we create a Topic object with details of the topic's name and message type.
var elemPressed = new ROSLIB.Topic({
  ros : ros,
  name : '/web_interface',
  messageType : 'std_msgs/String'
});

// Topic for error passing to the left arm
var errorPressedL = new ROSLIB.Topic({
  ros : ros,
  name : '/robot/digital_io/left_lower_button/state',
  messageType : 'baxter_core_msgs/DigitalIOState'
});

// Topic for error passing to the right arm
var errorPressedR = new ROSLIB.Topic({
  ros : ros,
  name : '/robot/digital_io/right_lower_button/state',
  messageType : 'baxter_core_msgs/DigitalIOState'
});

// Service Client to interface with the left arm
var leftArmService  = new ROSLIB.Service({
  ros : ros,
  name: '/action_provider/service_left',
  messageType : 'baxter_collaboration/DoAction'
});

// Service Client to interface with the right arm
var rightArmService = new ROSLIB.Service({
  ros : ros,
  name: '/action_provider/service_right',
  messageType : 'baxter_collaboration/DoAction'
});

// Add a callback for any element on the page
function callback(e) {
    var e = window.e || e;

    // console.log(e.target.tagName);
    if (e.target.tagName == 'BUTTON')
    {
        var obj = e.target.firstChild.nodeValue;
        console.log('Pressed '+ e.target.tagName +
                    ' item: ' + obj);

        if (obj == 'error')
        {
          var message = new ROSLIB.Message({
            state: 1,
            isInputOnly: true
          });

          errorPressedL.publish(message);
          errorPressedR.publish(message);
        }
        else if (obj == 'hold')
        {
          var req = new ROSLIB.ServiceRequest(
          {
            action: 'hold',
            object: -1
          });
          var res = new ROSLIB.ServiceResponse();

          console.log('Requested: ', req.action, req.object);
          rightArmService.callService(req,function(res) {
              console.log('Got Response: ' + res.success);
          });
        }
        else if (obj == 'get CF' || obj == 'get LL' ||
                 obj == 'get RL' || obj == 'get TOP' )
        {
          var req = new ROSLIB.ServiceRequest();
          req.action = 'get';

          if      (obj.replace('get ','') == 'CF')  { req.object = 24; }
          else if (obj.replace('get ','') == 'LL')  { req.object = 17; }
          else if (obj.replace('get ','') == 'RL')  { req.object = 26; }
          else if (obj.replace('get ','') == 'TOP') { req.object = 21; }
          else { console.error('Requested an object that was not allowed!'); };

          var res = new ROSLIB.ServiceResponse();

          console.log('Requested: ', req.action, req.object);
          leftArmService.callService(req,function(res)
          {
            console.log('Got Response: ' + res.success);

            if (res.success == true)
            {
              req.action = 'pass';

              console.log('Requested: ', req.action, req.object)
              leftArmService.callService(req,function(res)
              {
                console.log('Got Response: ' + res.success);
              });
            };
          });
        }
        else
        {
          var message = new ROSLIB.Message({
            data: obj
          });

          elemPressed.publish(message);
        }
    }

    return;
}

if (document.addEventListener)
    document.addEventListener('click', callback, false);
else
    document.attachEvent('onclick', callback);

<|endoftext|>


<commit_before>/**
 * This file is part of QBWebSQL
 *
 * (c) Muhamad Surya Iksanudin<surya.kejawen@gmail.com>
 *
 * @author : Muhamad Surya Iksanudin
 *
 * @todos:
 * - improve performance
 * - improve codes
 **/
(function (WebSQL) {
    //Root class
    WebSQL.db = {};

    //Define default properties
    WebSQL.db.name = "websql";
    WebSQL.db.version = "1.0";
    WebSQL.db.size = 5 * 1024 * 1024;//5 MB
    WebSQL.db.description = "WebSQL Database";
    WebSQL.db.connection = null;

    //Open database
    /**
     * @param string @default 'websql'
     * @param string @default '1.0'
     * @param integer @default 5MB @example : 5 * 1024 * 1024 = 5MB
     * @param string @default 'WebSQL Database'
     *
     * @return WebSQL.db object
     **/
    WebSQL.db.open = function (name, version, size, description) {
        //Override any values
        if (name) {
            WebSQL.db.name = name;
        }

        if (version) {
            WebSQL.db.version = version;
        }

        if (size) {
            WebSQL.db.size = size;
        }

        if (description) {
            WebSQL.db.description = description;
        }

        //Now we ready to make connection
        try {
            WebSQL.db.connection = openDatabase(WebSQL.db.name, WebSQL.db.version, WebSQL.db.description, WebSQL.size);

            return WebSQL.db;
        } catch (e) {
            console.log(e.message);
        }
    }

    //Create bootstrap function
    WebSQL.db.init = function(callback) {
        WebSQL.db.open();
        if(callback && "function" === typeof(callback)){
            callback();
        }
    }

    //Transaction handle
    /**
     * @param string
     * @param array
     * @param callable function
     **/
    WebSQL.db.execute = function (sqlStatement, parameters, callback) {
        try {
            WebSQL.db.transaction.executeSql(sqlStatement, parameters,
                function (sqlTransaction, sqlResultSet) {
                    if(callback && "function" === typeof callback){
                        callback(sqlTransaction, sqlResultSet);
                    }
                },
                function(sqlTransaction, sqlError) {
                    console.log(sqlError.message);
                }
            );
        } catch (e) {
            WebSQL.db.connection.transaction(function (trx) {
                WebSQL.db.transaction = trx;
                trx.executeSql(sqlStatement, parameters,
                    function (sqlTransaction, sqlResultSet) {
                        if(callback && "function" === typeof callback){
                            callback(sqlTransaction, sqlResultSet);
                        }
                    },
                    function(sqlTransaction, sqlError) {
                        console.log(sqlError.message);
                    }
                );
            });
        }

        return WebSQL.db;
    }

    //Insert utility
    /**
     * @param array
     * @param array
     * @param callable function
     **/
    WebSQL.db.insert = function (table, columns, values, callback) {
        try {
            var parameters = "";
            for (var i = 0; i < columns.length; i++) {
                parameters += "? ,";
            }
            //trim space and comma from start and end of string
            parameters = parameters.replace(/([\s,]+|[,\s])+$/,'');

            var sqlStatement = "INSERT INTO " + table+ "(" + columns.join(', ') + ") VALUES (" + parameters +") ";

            WebSQL.db.execute(sqlStatement, values, callback);
        } catch (e) {
            console.log(e.message);
        }

        return WebSQL.db;
    }

    //Update utility
    /**
     * @param string
     * @param array
     * @param array
     * @param array
     * @param callable function
     **/
    WebSQL.db.update = function (table, columns, values, where, callback) {
        try {
            var parameters = "";
            for (var i = 0; i < columns.length; i++) {
                parameters += columns[i] + " = ?, ";
            }
            //trim space and comma from start and end of string
            parameters = parameters.replace(/([\s,]+|[,\s])+$/,'');

            var where = "";
            for (var i = 0; i < wheres.length; i++) {
                if (i !== 0) {
                    where += " " + wheres[i].conjunction + " ";
                }
                where += wheres[i].id + " ";
                where += wheres[i].operator + "?";
                values.push(wheres[i].value);
            }
            //trim space from start and end of string
            where = where.trim();
            var sqlStatement = "UPDATE " + table + " SET " + parameters + " WHERE " + where;

            WebSQL.db.execute(sqlStatement, values, callback);
        } catch (e) {
            console.log(e.message);
        }

        return WebSQL.db;
    }

    //Delete utility
    /**
     * @param string
     * @param array
     * @param callable function
     **/
    WebSQL.db.destroy = function(table, where, callback) {
        try {
            var values = [];
            var where = "";
            for (var i = 0; i < wheres.length; i++) {
                if (i !== 0) {
                    where += " " + wheres[i].conjunction + " ";
                }
                where += wheres[i].id + " ";
                where += wheres[i].operator + "?";
                values.push(wheres[i].value);
            }
            //trim space from start and end of string
            where = where.trim();

            var sqlStatement = "DELETE FROM " + table + " WHERE " + where;

            WebSQL.db.execute(sqlStatement, values, callback);
        } catch (e) {
            console.log(e.message);
        }

        return WebSQL.db;
    }

    //Select utilities
    WebSQL.db.queryBuilder = {};
    WebSQL.db.queryBuilder.fields = [];
    WebSQL.db.queryBuilder.froms = [];
    WebSQL.db.queryBuilder.joins = [];
    WebSQL.db.queryBuilder.wheres = [];
    WebSQL.db.queryBuilder.groups = [];
    WebSQL.db.queryBuilder.havings = [];
    WebSQL.db.queryBuilder.orders = [];
    WebSQL.db.queryBuilder.per = null;
    WebSQL.db.queryBuilder.offset = null;

    //Create hook
    /**
     * @param string sql clausal
     * @param string parameter
     **/
    WebSQL.db.queryBuilder.add = function(method, params, callback) {
        method = "WebSQL.db.queryBuilder." + method + "('" + params + "')";
        eval(method);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add selection
    /**
     * @param string
     **/
    WebSQL.db.queryBuilder.select = function (column, callback) {
        WebSQL.db.queryBuilder.fields.push(column);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }
    /**
     * @param array
     **/
    WebSQL.db.queryBuilder.selects = function (columns, callback) {
        WebSQL.db.queryBuilder.fields = WebSQL.db.queryBuilder.fields.concat(columns);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add from
    /**
     * @param string
     */
    WebSQL.db.queryBuilder.from = function (table, callback) {
        WebSQL.db.queryBuilder.froms.push(table);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add join
    /**
     * @param string
     */
    WebSQL.db.queryBuilder.join = function (table, joinStatement, type, callback) {
        if ("undefined" === typeof type) {
            type = "LEFT";
        }
        WebSQL.db.queryBuilder.joins[table] = [type, joinStatement];

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add where
    /**
     * @param array
     **/
    WebSQL.db.queryBuilder.where = function (where, callback) {
        for (var i = 0; i < where.length; i++) {
            if (0 === i) {
                WebSQL.db.queryBuilder.wheres[i] = [where[i].id, "", where[i].operator, where[i].value];
            } else {
                WebSQL.db.queryBuilder.wheres[i] = [where[i].id, where[i].conjunction, where[i].operator, where[i].value];
            }
        }

        if(callback && "function" === typeof callback){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add Group By
    /**
     * @param string
     **/
    WebSQL.db.queryBuilder.groupBy = function(column, callback) {
        WebSQL.db.queryBuilder.groups.push(column);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add Order By
    /**
     * @param string
     **/
    WebSQL.db.queryBuilder.orderBy = function(column, callback) {
        WebSQL.db.queryBuilder.orders.push(column);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }
    //Add Limit
    /**
     * @param integer
     * @param integer
     **/
    WebSQL.db.queryBuilder.limit = function(limit, offset, callback) {
        WebSQL.db.queryBuilder.per = limit;

        if (offset) {
            WebSQL.db.queryBuilder.offset = offset;
        }

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Compile query
    /**
     * @return string
     *
     * SELECT
     * FROM
     * JOIN
     * WHERE
     * GROUP BY
     * HAVING
     * ORDER BY
     * LIMIT
     * OFFSET
     **/
    WebSQL.db.queryBuilder.query = function(callback) {
        var query = "";
        var parameters = [];
        //Compile Select
        if (WebSQL.db.queryBuilder.fields.length > 0) {
            query += "SELECT ";
            for (var i = 0; i < WebSQL.db.queryBuilder.fields.length; i++) {
                query += WebSQL.db.queryBuilder.fields[i] + ", ";
            }
            //trim space and comma from start and end of string
            query = query.replace(/([\s,]+|[,\s])+$/,'');
        } else {
            query += "SELECT *";
        }
        //trim space and comma from start and end of string
        query = query.replace(/([\s,]+|[,\s])+$/,'');
        //Compile From
        query += " FROM ";
        for (var i = 0; i < WebSQL.db.queryBuilder.froms.length; i++) {
            query += WebSQL.db.queryBuilder.froms[i] + ", ";
        }
        //trim space and comma from start and end of string
        query = query.replace(/([\s,]+|[,\s])+$/,'');
        query += " ";//make sure we have extra space in the end of string
        //Compile Join
        for (var key in WebSQL.db.queryBuilder.joins) {
            if (WebSQL.db.queryBuilder.joins.hasOwnProperty(key)) {
                query += WebSQL.db.queryBuilder.joins[key][0] + " JOIN ";
                query += key + " ON ";
                query += WebSQL.db.queryBuilder.joins[key][1] + " ";
            }
        }
        //trim space from start and end of string
        query = query.trim();
        //Compile Where
        if (Object.keys(WebSQL.db.queryBuilder.wheres).length > 0) {
            query += " WHERE ";
            var where = "";
            for (var key in WebSQL.db.queryBuilder.wheres) {
                if (WebSQL.db.queryBuilder.wheres.hasOwnProperty(key)) {
                    where += " " + WebSQL.db.queryBuilder.wheres[key][1] + " ";
                    where += WebSQL.db.queryBuilder.wheres[key][0] + " ";
                    where += WebSQL.db.queryBuilder.wheres[key][2] + "?";
                    parameters.push(WebSQL.db.queryBuilder.wheres[key][3]);
                }
            }
                //trim space from start and end of string
            where = where.trim();
            //Now we have real sql statement
            query += where;
        }
        //Compile Group By
        if (WebSQL.db.queryBuilder.groups > 0) {
            query += " GROUP BY ";
            for (var i = 0; i < WebSQL.db.queryBuilder.groups.length; i++) {
                query += WebSQL.db.queryBuilder.groups[i] + ", ";
            }
            //trim space and comma from start and end of string
            query = query.replace(/([\s,]+|[,\s])+$/,'');
        }
        //Compile Order By
        if (WebSQL.db.queryBuilder.orders > 0) {
            query += " ORDER BY ";
            for (var i = 0; i < WebSQL.db.queryBuilder.orders.length; i++) {
                query += WebSQL.db.queryBuilder.orders[i] + ", ";
            }
            //trim space and comma from start and end of string
            query = query.replace(/([\s,]+|[,\s])+$/,'');
        }
        //Compile LIMIT
        if (WebSQL.db.queryBuilder.per) {
            query += " LIMIT " + WebSQL.db.queryBuilder.per + " ";
            if (WebSQL.db.queryBuilder.offset) {
                query += "OFFSET " + WebSQL.db.queryBuilder.offset;
            } else {
                query += "OFFSET 0";
            }
        }
        //make sure to remove all query builder value
        WebSQL.db.queryBuilder.fields = [];
        WebSQL.db.queryBuilder.froms = [];
        WebSQL.db.queryBuilder.joins = [];
        WebSQL.db.queryBuilder.wheres = [];
        WebSQL.db.queryBuilder.groups = [];
        WebSQL.db.queryBuilder.havings = [];
        WebSQL.db.queryBuilder.orders = [];
        WebSQL.db.queryBuilder.per = null;
        WebSQL.db.queryBuilder.offset = null;

        if(callback && "function" === typeof(callback)){
            callback(query, parameters);
        }
    }
}(window.WebSQL = window.WebSQL || {}));
<commit_msg>add having cluase<commit_after>/**
 * This file is part of QBWebSQL
 *
 * (c) Muhamad Surya Iksanudin<surya.kejawen@gmail.com>
 *
 * @author : Muhamad Surya Iksanudin
 *
 * @todos:
 * - improve performance
 * - improve codes
 **/
(function (WebSQL) {
    //Root class
    WebSQL.db = {};

    //Define default properties
    WebSQL.db.name = "websql";
    WebSQL.db.version = "1.0";
    WebSQL.db.size = 5 * 1024 * 1024;//5 MB
    WebSQL.db.description = "WebSQL Database";
    WebSQL.db.connection = null;

    //Open database
    /**
     * @param string @default 'websql'
     * @param string @default '1.0'
     * @param integer @default 5MB @example : 5 * 1024 * 1024 = 5MB
     * @param string @default 'WebSQL Database'
     *
     * @return WebSQL.db object
     **/
    WebSQL.db.open = function (name, version, size, description) {
        //Override any values
        if (name) {
            WebSQL.db.name = name;
        }

        if (version) {
            WebSQL.db.version = version;
        }

        if (size) {
            WebSQL.db.size = size;
        }

        if (description) {
            WebSQL.db.description = description;
        }

        //Now we ready to make connection
        try {
            WebSQL.db.connection = openDatabase(WebSQL.db.name, WebSQL.db.version, WebSQL.db.description, WebSQL.size);

            return WebSQL.db;
        } catch (e) {
            console.log(e.message);
        }
    }

    //Create bootstrap function
    WebSQL.db.init = function(callback) {
        WebSQL.db.open();
        if(callback && "function" === typeof(callback)){
            callback();
        }
    }

    //Transaction handle
    /**
     * @param string
     * @param array
     * @param callable function
     **/
    WebSQL.db.execute = function (sqlStatement, parameters, callback) {
        try {
            WebSQL.db.transaction.executeSql(sqlStatement, parameters,
                function (sqlTransaction, sqlResultSet) {
                    if(callback && "function" === typeof callback){
                        callback(sqlTransaction, sqlResultSet);
                    }
                },
                function(sqlTransaction, sqlError) {
                    console.log(sqlError.message);
                }
            );
        } catch (e) {
            WebSQL.db.connection.transaction(function (trx) {
                WebSQL.db.transaction = trx;
                trx.executeSql(sqlStatement, parameters,
                    function (sqlTransaction, sqlResultSet) {
                        if(callback && "function" === typeof callback){
                            callback(sqlTransaction, sqlResultSet);
                        }
                    },
                    function(sqlTransaction, sqlError) {
                        console.log(sqlError.message);
                    }
                );
            });
        }

        return WebSQL.db;
    }

    //Insert utility
    /**
     * @param array
     * @param array
     * @param callable function
     **/
    WebSQL.db.insert = function (table, columns, values, callback) {
        try {
            var parameters = "";
            for (var i = 0; i < columns.length; i++) {
                parameters += "? ,";
            }
            //trim space and comma from start and end of string
            parameters = parameters.replace(/([\s,]+|[,\s])+$/,'');

            var sqlStatement = "INSERT INTO " + table+ "(" + columns.join(', ') + ") VALUES (" + parameters +") ";

            WebSQL.db.execute(sqlStatement, values, callback);
        } catch (e) {
            console.log(e.message);
        }

        return WebSQL.db;
    }

    //Update utility
    /**
     * @param string
     * @param array
     * @param array
     * @param array
     * @param callable function
     **/
    WebSQL.db.update = function (table, columns, values, where, callback) {
        try {
            var parameters = "";
            for (var i = 0; i < columns.length; i++) {
                parameters += columns[i] + " = ?, ";
            }
            //trim space and comma from start and end of string
            parameters = parameters.replace(/([\s,]+|[,\s])+$/,'');

            var where = "";
            for (var i = 0; i < wheres.length; i++) {
                if (i !== 0) {
                    where += " " + wheres[i].conjunction + " ";
                }
                where += wheres[i].id + " ";
                where += wheres[i].operator + "?";
                values.push(wheres[i].value);
            }
            //trim space from start and end of string
            where = where.trim();
            var sqlStatement = "UPDATE " + table + " SET " + parameters + " WHERE " + where;

            WebSQL.db.execute(sqlStatement, values, callback);
        } catch (e) {
            console.log(e.message);
        }

        return WebSQL.db;
    }

    //Delete utility
    /**
     * @param string
     * @param array
     * @param callable function
     **/
    WebSQL.db.destroy = function(table, where, callback) {
        try {
            var values = [];
            var where = "";
            for (var i = 0; i < wheres.length; i++) {
                if (i !== 0) {
                    where += " " + wheres[i].conjunction + " ";
                }
                where += wheres[i].id + " ";
                where += wheres[i].operator + "?";
                values.push(wheres[i].value);
            }
            //trim space from start and end of string
            where = where.trim();

            var sqlStatement = "DELETE FROM " + table + " WHERE " + where;

            WebSQL.db.execute(sqlStatement, values, callback);
        } catch (e) {
            console.log(e.message);
        }

        return WebSQL.db;
    }

    //Select utilities
    WebSQL.db.queryBuilder = {};
    WebSQL.db.queryBuilder.fields = [];
    WebSQL.db.queryBuilder.froms = [];
    WebSQL.db.queryBuilder.joins = [];
    WebSQL.db.queryBuilder.wheres = [];
    WebSQL.db.queryBuilder.groups = [];
    WebSQL.db.queryBuilder.havings = [];
    WebSQL.db.queryBuilder.orders = [];
    WebSQL.db.queryBuilder.per = null;
    WebSQL.db.queryBuilder.offset = null;

    //Create hook
    /**
     * @param string sql clausal
     * @param string parameter
     **/
    WebSQL.db.queryBuilder.add = function(method, params, callback) {
        method = "WebSQL.db.queryBuilder." + method + "('" + params + "')";
        eval(method);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add selection
    /**
     * @param string
     **/
    WebSQL.db.queryBuilder.select = function (column, callback) {
        WebSQL.db.queryBuilder.fields.push(column);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }
    /**
     * @param array
     **/
    WebSQL.db.queryBuilder.selects = function (columns, callback) {
        WebSQL.db.queryBuilder.fields = WebSQL.db.queryBuilder.fields.concat(columns);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add from
    /**
     * @param string
     */
    WebSQL.db.queryBuilder.from = function (table, callback) {
        WebSQL.db.queryBuilder.froms.push(table);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add join
    /**
     * @param string
     */
    WebSQL.db.queryBuilder.join = function (table, joinStatement, type, callback) {
        if ("undefined" === typeof type) {
            type = "LEFT";
        }
        WebSQL.db.queryBuilder.joins[table] = [type, joinStatement];

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add where
    /**
     * @param array
     **/
    WebSQL.db.queryBuilder.where = function (where, callback) {
        for (var i = 0; i < where.length; i++) {
            if (0 === i) {
                WebSQL.db.queryBuilder.wheres[i] = [where[i].id, "", where[i].operator, where[i].value];
            } else {
                WebSQL.db.queryBuilder.wheres[i] = [where[i].id, where[i].conjunction, where[i].operator, where[i].value];
            }
        }

        if(callback && "function" === typeof callback){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add Group By
    /**
     * @param string
     **/
    WebSQL.db.queryBuilder.groupBy = function(column, callback) {
        WebSQL.db.queryBuilder.groups.push(column);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add Order By
    /**
     * @param string
     **/
    WebSQL.db.queryBuilder.orderBy = function(column, callback) {
        WebSQL.db.queryBuilder.orders.push(column);

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add Having
    /**
     * @param array
     **/
    WebSQL.db.queryBuilder.having = function (having, callback) {
        for (var i = 0; i < having.length; i++) {
            if (0 === i) {
                WebSQL.db.queryBuilder.havings[i] = [having[i].id, "", having[i].operator, having[i].value];
            } else {
                WebSQL.db.queryBuilder.havings[i] = [having[i].id, having[i].conjunction, having[i].operator, having[i].value];
            }
        }

        if(callback && "function" === typeof callback){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Add Limit
    /**
     * @param integer
     * @param integer
     **/
    WebSQL.db.queryBuilder.limit = function(limit, offset, callback) {
        WebSQL.db.queryBuilder.per = limit;

        if (offset) {
            WebSQL.db.queryBuilder.offset = offset;
        }

        if(callback && "function" === typeof(callback)){
            callback();
        }

        return WebSQL.db.queryBuilder;
    }

    //Compile query
    /**
     * @return string
     *
     * SELECT
     * FROM
     * JOIN
     * WHERE
     * GROUP BY
     * HAVING
     * ORDER BY
     * LIMIT
     **/
    WebSQL.db.queryBuilder.query = function(callback) {
        var query = "";
        var parameters = [];
        //Compile Select
        if (WebSQL.db.queryBuilder.fields.length > 0) {
            query += "SELECT ";
            for (var i = 0; i < WebSQL.db.queryBuilder.fields.length; i++) {
                query += WebSQL.db.queryBuilder.fields[i] + ", ";
            }
            //trim space and comma from start and end of string
            query = query.replace(/([\s,]+|[,\s])+$/,'');
        } else {
            query += "SELECT *";
        }
        //trim space and comma from start and end of string
        query = query.replace(/([\s,]+|[,\s])+$/,'');
        //Compile From
        query += " FROM ";
        for (var i = 0; i < WebSQL.db.queryBuilder.froms.length; i++) {
            query += WebSQL.db.queryBuilder.froms[i] + ", ";
        }
        //trim space and comma from start and end of string
        query = query.replace(/([\s,]+|[,\s])+$/,'');
        query += " ";//make sure we have extra space in the end of string
        //Compile Join
        for (var key in WebSQL.db.queryBuilder.joins) {
            if (WebSQL.db.queryBuilder.joins.hasOwnProperty(key)) {
                query += WebSQL.db.queryBuilder.joins[key][0] + " JOIN ";
                query += key + " ON ";
                query += WebSQL.db.queryBuilder.joins[key][1] + " ";
            }
        }
        //trim space from start and end of string
        query = query.trim();
        //Compile Where
        if (Object.keys(WebSQL.db.queryBuilder.wheres).length > 0) {
            query += " WHERE ";
            var where = "";
            for (var key in WebSQL.db.queryBuilder.wheres) {
                if (WebSQL.db.queryBuilder.wheres.hasOwnProperty(key)) {
                    where += " " + WebSQL.db.queryBuilder.wheres[key][1] + " ";
                    where += WebSQL.db.queryBuilder.wheres[key][0] + " ";
                    where += WebSQL.db.queryBuilder.wheres[key][2] + "?";
                    parameters.push(WebSQL.db.queryBuilder.wheres[key][3]);
                }
            }
                //trim space from start and end of string
            where = where.trim();
            //Now we have real sql statement
            query += where;
        }
        //Compile Group By
        if (WebSQL.db.queryBuilder.groups > 0) {
            query += " GROUP BY ";
            for (var i = 0; i < WebSQL.db.queryBuilder.groups.length; i++) {
                query += WebSQL.db.queryBuilder.groups[i] + ", ";
            }
            //trim space and comma from start and end of string
            query = query.replace(/([\s,]+|[,\s])+$/,'');
        }
        //Compile Having
        if (Object.keys(WebSQL.db.queryBuilder.havings).length > 0) {
            query += " HAVING ";
            var having = "";
            for (var key in WebSQL.db.queryBuilder.havings) {
                if (WebSQL.db.queryBuilder.havings.hasOwnProperty(key)) {
                    having += " " + WebSQL.db.queryBuilder.havings[key][1] + " ";
                    having += WebSQL.db.queryBuilder.havings[key][0] + " ";
                    having += WebSQL.db.queryBuilder.havings[key][2] + "?";
                    parameters.push(WebSQL.db.queryBuilder.havings[key][3]);
                }
            }
            //trim space from start and end of string
            having = having.trim();
            //Now we have real sql statement
            query += having;
        }
        //Compile Order By
        if (WebSQL.db.queryBuilder.orders > 0) {
            query += " ORDER BY ";
            for (var i = 0; i < WebSQL.db.queryBuilder.orders.length; i++) {
                query += WebSQL.db.queryBuilder.orders[i] + ", ";
            }
            //trim space and comma from start and end of string
            query = query.replace(/([\s,]+|[,\s])+$/,'');
        }
        //Compile LIMIT
        if (WebSQL.db.queryBuilder.per) {
            query += " LIMIT " + WebSQL.db.queryBuilder.per + " ";
            if (WebSQL.db.queryBuilder.offset) {
                query += "OFFSET " + WebSQL.db.queryBuilder.offset;
            } else {
                query += "OFFSET 0";
            }
        }
        //make sure to remove all query builder value
        WebSQL.db.queryBuilder.fields = [];
        WebSQL.db.queryBuilder.froms = [];
        WebSQL.db.queryBuilder.joins = [];
        WebSQL.db.queryBuilder.wheres = [];
        WebSQL.db.queryBuilder.groups = [];
        WebSQL.db.queryBuilder.havings = [];
        WebSQL.db.queryBuilder.orders = [];
        WebSQL.db.queryBuilder.per = null;
        WebSQL.db.queryBuilder.offset = null;

        if(callback && "function" === typeof(callback)){
            callback(query, parameters);
        }
    }
}(window.WebSQL = window.WebSQL || {}));
<|endoftext|>


<commit_before>// CLIENT

Object._ = function(){}

var shoe = require('shoe')
, MuxDemux = require('mux-demux')
, bricoleur = require('./_brico')
, tmp_id = null
, id = null

var brico = new bricoleur({scope:'client'})

var bus = shoe('/bus')

bus.on('connect', function () {
  tmp_id = new Date().getTime()
  bus.write(JSON.stringify({tmp_id:tmp_id}))
})

bus.on('data', function (json) {
  var data = JSON.parse(json)

  if (typeof data === 'object') console.dir(data)

  if (data[tmp_id]) id = data[tmp_id]

  if (data.id === id) { // handle data -- pass to brico
    console.log('sending data to brico from '+id)
  }
})

setTimeout(function () {
  console.log('sending to ... '+id)
  bus.write(JSON.stringify({id:id, params:['test',2,'r']}))
}, 300)
<commit_msg>use document.URL to check host?<commit_after>// CLIENT

Object._ = function(){}

var shoe = require('shoe')
, MuxDemux = require('mux-demux')
, bricoleur = require('./_brico')
, tmp_id = null
, id = null

var brico = new bricoleur({scope:'client'})

var bus = shoe('/bus')

bus.on('connect', function () {
  tmp_id = new Date().getTime()
  bus.write(JSON.stringify({tmp_id:tmp_id}))
})

bus.on('data', function (json) {
  var data = JSON.parse(json)

  if (typeof data === 'object') console.dir(data)

  if (data[tmp_id]) id = data[tmp_id]

  if (data.id === id) { // handle data -- pass to brico
    console.log('sending data to brico from '+document.URL)
  }
})

setTimeout(function () {
  console.log('sending to ... '+id)
  bus.write(JSON.stringify({id:id, params:['test',2,'r']}))
}, 300)
<|endoftext|>


<commit_before>var telepath = require('tele')
, stream = require('stream')
, async = require ('async')

module.exports = function (usr) { // BRICOLEUR
  var self = this
  , map = null
  , _ = {} // module scope
  telepath(this)

  // detect if running in node or browser
  if (global.process && global.process.title==='node') self.scope = 'server'
  if (!global.process) self.scope = 'client'

  if (usr) self.usr = usr

  this.recv = function (buffer) {
    var data = JSON.parse(buffer.toString())

    if (data.meta==='module_map') { // add map
      map = data[self.scope]
      self.build()
    }
  }

  this.build = function () { // load modules
    if (!map) throw new Error('no map')

    async.forEach(map, match, function () {
      console.log(usr.host+' modules loaded')
    })

    function match (mod, cb) {
      var modules = self.usr.modules
      for (var i=0;i<modules.length;i++) {
        if (modules[i]===mod.id) {
          self.loadModule(mod)
          cb()
          break
        } else cb()
      }
    }
  }

  this.loadModule = function (mod) {
    _[mod.id.toUpperCase()] = require(mod.filePath)
    _[mod.id] = new _[mod.id.toUpperCase()]()
    if (mod.html) _[mod.id].template = mod.html
    console.log(_[mod.id])
  }

  // ----------------------------------------------------
  this.addConnection = function (key) {
    self[key] = {}
    var s = self[key]

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk)
      cb()
    }

    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }// ---------------------------------------------------
}
<commit_msg>added connModule, disconnModule and unloadModule methods to brico<commit_after>var telepath = require('tele')
, stream = require('stream')
, async = require ('async')

module.exports = function (usr) { // BRICOLEUR
  var self = this
  , map = null
  , _ = {} // module scope
  telepath(this)

  // detect if running in node or browser
  if (global.process && global.process.title === 'node') self.scope = 'server'
  if (!global.process) self.scope = 'client'

  if (usr) self.usr = usr

  this.recv = function (buffer) {
    var data = JSON.parse(buffer.toString())

    if (data.meta === 'module_map') { // add map
      map = data[self.scope]
      self.build()
    }
  }

  this.build = function () { // load modules
    if (!map) throw new Error('no map')

    async.forEach(map, match, function () {
      console.log(usr.host+' modules loaded')
    })

    function match (mod, cb) {
      var modules = self.usr.modules
      for (var i=0;i<modules.length;i++) {
        if (modules[i]===mod.id) {
          self.loadModule(mod)
          cb()
          break
        } else cb()
      }
    }
  }

  this.connModule = function (connect) { // ['modA>modB','modB>modC']

  }

  this.disconnModule = function (disconnect) {

  }

  this.loadModule = function (mod) { // load module!
    _[mod.id.toUpperCase()] = require(mod.filePath)
    _[mod.id] = new _[mod.id.toUpperCase()]()
    if (mod.html) _[mod.id].template = mod.html
  }

  this.unloadModule = function (mod) {

  }

  // ----------------------------------------------------
  this.addConnection = function (key) {
    self[key] = {}
    var s = self[key]

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk)
      cb()
    }

    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }// ---------------------------------------------------
}
<|endoftext|>


<commit_before>// BRICO

var through = require('through')
var fern = require('fern')
var conf = require('./__conf.json')
var proc = process.title // node or browser
var interface

module.exports = function bricoleur (data) {
  var WILDS = {}

  WILDS['*'] = function (i,o) { // * MODULE

  }
  WILDS['^'] = function (i,o) { // ^ LIBRARY

  }
  WILDS['#'] = function (i,o) { // # CONNECT

  }
  WILDS['_'] = function (i,o} { // _ PROCESS

  }

  var liveStream = data.liveStream({old:false})
  liveStream.on('data', handleData)

  function handleData (d) {
    if(filter[d.type]) filter[d.type](d)
  }

  var filter = {
    put: function (d) {
      var path = d.key.split(':')

    },
    del: function (d) {
      var path = d.key.split(':')

    }
  }

  // abstraction layer
  interface = through(function write (d) {
    console.log(d)
  }, function end () {
    this.emit('end')
  }, {autoDestroy:false})

  return interface
}

// UTIL

function search (args, cb) {
  var match = false
  var ks = data.createKeyStream()
  ks.on('data', function (d) {
    var path = d.split(':')
    if (args[1] === path[1]) {
      match = true
      for (var i=2; i<args.length; i++) {
        var pair = args[i].split('=')
        var key = pair[0]
        var val = pair[1]
        opts[key] = val
      }
      if (opts === {}) opts = null
    }
  })
  ks.on('end', function () {
    if (match !== true) interface.emit('error', new Error('could not find module'))
  })
}
<commit_msg>fix WILDS fn syntax err<commit_after>// BRICO

var through = require('through')
var fern = require('fern')
var conf = require('./__conf.json')
var proc = process.title // node or browser
var interface

module.exports = function bricoleur (data) {
  var WILDS = {}

  WILDS['*'] = function (i,o) { // * MODULE

  }
  WILDS['^'] = function (i,o) { // ^ LIBRARY

  }
  WILDS['#'] = function (i,o) { // # CONNECT

  }
  WILDS['_'] = function (i,o) { // _ PROCESS

  }

  var liveStream = data.liveStream({old:false})
  liveStream.on('data', handleData)

  function handleData (d) {
    if(filter[d.type]) filter[d.type](d)
  }

  var filter = {
    put: function (d) {
      var path = d.key.split(':')

    },
    del: function (d) {
      var path = d.key.split(':')

    }
  }

  // abstraction layer
  interface = through(function write (d) {
    console.log(d)
  }, function end () {
    this.emit('end')
  }, {autoDestroy:false})

  return interface
}

/////////////////////////////////////////////

function search (args, cb) {
  var match = false
  var ks = data.createKeyStream()
  ks.on('data', function (d) {
    var path = d.split(':')
    if (args[1] === path[1]) {
      match = true
      for (var i=2; i<args.length; i++) {
        var pair = args[i].split('=')
        var key = pair[0]
        var val = pair[1]
        opts[key] = val
      }
      if (opts === {}) opts = null
    }
  })
  ks.on('end', function () {
    if (match !== true) interface.emit('error', new Error('could not find module'))
  })
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name            JSON prettifier.
// @namespace       https://github.com/kilfu0701
// @description     Prettify json string.
// @match           http://*/*
// @match           https://*/*
// @run-at          document-end
// @include         *
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @version         1.0
// ==/UserScript==

//"use strict";
var debug_mode = 1;

(function(window, document) {
    //console.log("script starting");
    document.onkeypress = function(e) {
        e = e || window.event;

        // charCode = 80, shift + p
        var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
        var t = document.body.textContent;
        var pre = document.createElement('pre');

        document.body.textContent = '';
        pre.textContent = JSON.stringify(JSON.parse(t), undefined, 4);
        document.body.appendChild(pre);
    };
})(window, document);
<commit_msg>change descriptions.<commit_after>// ==UserScript==
// @name            JSON prettifier.
// @namespace       https://github.com/kilfu0701
// @description     Prettify json string, use 'shift + p' to run this script.
// @match           http://*/*
// @match           https://*/*
// @run-at          document-end
// @include         *
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @version         1.0
// ==/UserScript==

//"use strict";
var debug_mode = 1;

(function(window, document) {
    //console.log("script starting");
    document.onkeypress = function(e) {
        e = e || window.event;

        // charCode = 80, shift + p
        var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
        var t = document.body.textContent;
        var pre = document.createElement('pre');

        document.body.textContent = '';
        pre.textContent = JSON.stringify(JSON.parse(t), undefined, 4);
        document.body.appendChild(pre);
    };
})(window, document);
<|endoftext|>


<commit_before>//make requests to get the data
var request = require('request');
var async = require('async');
//mongoose for IDs
var mongoose = require('mongoose');

//raingauge model
var modelGauge = require('./models/gauge.js');

	module.exports.generateGaugeInfo = function() {
		//request the rainfall data
		console.log('Requesting present rainfall data');
		var rainUrl = 'http://www.harriscountyfws.org/Home/GetSiteRecentData';
		request.post({url: rainUrl, form: {regionId: 1, timeSpan: 1}}, function(err, res, body) {
			if(!err){
				//console.log(res);
				safejson.parse(body, function(err, rainfall) {
					if(!err) {
						//console.log(rainfall);
						//log each site location and rainfall
						console.log('Printing present rainfall data...');
						for(var i = 0; i < rainfall.Sites.length; i++) {
							console.log('Rainfall at ' + rainfall.Sites[i].Longitude + ', ' + rainfall.Sites[i].Latitude + ' was ' + rainfall.Sites[i].Rainfall);
						}

					} else {
						console.log(err);
					}
				})
			} else {
				console.log(err);
			}

		});
	}<commit_msg>Worked on adding rain gauges to geospacial db<commit_after>//make requests to get the data
var request = require('request');
var async = require('async');
//mongoose for IDs
var mongoose = require('mongoose');

//raingauge model
var modelGauge = require('./models/gauge.js');

	module.exports.generateGaugeInfo = function() {
		//request the rainfall data
		console.log('Requesting present rainfall data');
		var rainUrl = 'http://www.harriscountyfws.org/Home/GetSiteRecentData';
		request.post({url: rainUrl, form: {regionId: 1, timeSpan: 1}}, function(err, res, body) {
			if(!err){
				//console.log(res);
				safejson.parse(body, function(err, rainfall) {
					if(!err) {
						//console.log(rainfall);
						//log each site location and rainfall
						console.log('Printing present rainfall data...');
						for(var i = 0; i < rainfall.Sites.length; i++) {
							console.log('Rainfall at ' + rainfall.Sites[i].Longitude + ', ' + rainfall.Sites[i].Latitude + ' was ' + rainfall.Sites[i].Rainfall);
						}
						var gauge = {
							id: rainfall.Sites[i].id,
							Loc: {
								latitude: rainfall.Sites[i].Latitude,
								longitude: rainfall.Sites[i].Longitude
							}
						};

					} else {
						console.log(err);
					}
				})
			} else {
				console.log(err);
			}

		});
	}<|endoftext|>


<commit_before>
 google.load('visualization', '1', {'packages':['annotatedtimeline']});

function annotatedTimeLineChart(chart_element, url, dataString) {

    chart_element.text('Loading...');

    $.ajax({
	    url: url,
        //dataType: 'json',
        //timeout: 30000,
        data: dataString,
        success: function (data_perl) {

            //var data_json = eval (data_perl);
            var data = new google.visualization.DataTable(data_perl, 0.6);

            //var chart_placement =  document.getElementById('line_chart');
            var chart = new google.visualization.AnnotatedTimeLine(chart_element.get(0));

            var json = data.toJSON();

            //alert(json);
            chart.draw(data, {
                displayAnnotations: true,
		legendPosition: 'newRow'
            });

            //alert(data.toJSON() );

        },
        error: function (jqXHR, textStatus, errorThrownsuccess) {
            alert(textStatus);
        }
    });

}<commit_msg>hack to make the google term freq charts use the same default color pallete as the cluster maps<commit_after>
 google.load('visualization', '1', {'packages':['annotatedtimeline']});

function annotatedTimeLineChart(chart_element, url, dataString) {

    chart_element.text('Loading...');

    $.ajax({
	    url: url,
        //dataType: 'json',
        //timeout: 30000,
        data: dataString,
        success: function (data_perl) {

            //var data_json = eval (data_perl);
            var data = new google.visualization.DataTable(data_perl, 0.6);

            //var chart_placement =  document.getElementById('line_chart');
            var chart = new google.visualization.AnnotatedTimeLine(chart_element.get(0));

            var json = data.toJSON();

            //alert(json);
            chart.draw(data, {
                displayAnnotations: true,
		        legendPosition: 'newRow'
		        colors: [ '#2ca02c', '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5', '#84c4ce', '#ffa779', '#cc5ace', '#6f11c9', '#6f3e5d' ] } );

            //alert(data.toJSON() );

        },
        error: function (jqXHR, textStatus, errorThrownsuccess) {
            alert(textStatus);
        }
    });

}<|endoftext|>


<commit_before>/*
Script: ART.Widget.js

License:
	MIT-style license.
*/

// Base widget class. Based on » http://gist.github.com/85837
(function(){

var counting, focused;

ART.Widget = new Class({

	Implements: [Options, Events],

	ns: 'art',
	name: 'widget',

	options: {
		// onShow: $empty,
		// onHide: $empty,
		// onFocus: $empty,
		// onBlur: $empty,
		// onEnable: $empty,
		// onDisable: $empty,
		// onDestroy: $empty,
		// onAdoption: $empty(parentWidget),
		// onOrphan: $empty(previousParent),
		// id: null,
		// style: null,
		renderWhileHidden: false,
		className: '',
		keyboardOptions: {
			active: true
		},
		parentWidget: null
	},

	initialize: function(options){
		this.latchEvents('adopt');
		this.pseudos = [];
		this.childWidgets = [];
		this.keyboard = new Keyboard();
		this.keyboard.widget = this;
		var parent;
		if (options) {
			if (options.parentWidget) {
				parent = options.parentWidget;
				delete options.parentWidget;
			}
		}
		this.setOptions(options);
		this.keyboard.setOptions(this.options.keyboardOptions).setup();
		this.prefix = this.ns + '-' + this.name;
		this.element = new Element('div', {
			id: this.options.id || this.prefix+new Date().getTime(),
			'class': this.options.className
		}).store(this.prefix, this).store('widget', this);
		this.element.addClass(this.ns).addClass(this.prefix);
		this.classes = this.options.classes;
		this.classes = (this.options.className) ? this.options.className.split(' ') : [];
		if (parent) this.setParent(parent);
	},

	getSelector: function(){
		var selector = (this.parentWidget) ? this.parentWidget.getSelector() + ' ' : '';
		selector += this.name;
		if (this.classes.length) selector += '.' + this.classes.join('.');
		if (this.pseudos.length) selector += ':' + this.pseudos.join(':');
		return selector;
	},

	addPseudo: function(pseudo){
		this.pseudos.include(pseudo);
	},

	removePseudo: function(pseudo){
		this.pseudos.erase(pseudo);
	},

	setParent: function(widget, initing){
		if (!initing) this.removeParent();
		this.parentWidget = widget;
		widget.childWidgets.include(this);
		this.parentWidget.keyboard.manage(this.keyboard);
		this.enable();
		this.fireEvent('adoption', widget);
		return this;
	},

	removeParent: function(){
		this.prevParent = this.parentWidget || this.prevParent;
		if (!this.prevParent) return;
		if (this.parentWidget) {
			this.parentWidget.childWidgets.erase(this);
			Keyboard.manager.manage(this.keyboard);
			this.parentWidget = null;
		}
		this.fireEvent('orphan', this.prevParent);
	},

	// render

	requireToRender: function(){
		this.requiredToRender = this.requiredToRender || [];
		$A(arguments).each(function(requirement) {
			this.requiredToRender.push(requirement);
		}, this);
	},

	readyToRender: function() {
		if (!this.requiredToRender || !this.requiredToRender.length) return;
		$A(arguments).each(function(requirement) {
			this.requiredToRender.erase(requirement);
		}, this);
	},

	redraw: function(){
		if (counting) this._counters();
		this.childWidgets.each(function(child) {
			child.render();
		});
		return this;
	},

	isReadyToRender: function(){
		var isReady = (!this.requiredToRender || !this.requiredToRender.length) && !this.destroyed && (this.options.renderWhileHidden || !this.hidden);
		if (isReady && this.parentWidget) isReady = this.parentWidget.isReadyToRender();
		return isReady;
	},

	render: function(override){
		if (this.isReadyToRender()) this.redraw(override);
		return this;
	},

	// special states

	hide: function(){
		if (!this.hidden){
			this.hidden = true;
			this.fireEvent('hide');
			this.element.addClass(this.prefix + '-hidden');
			this.addPseudo('hidden');
			this.render();
		}
		return this;
	},

	activate: function(){
		if (!this.active){
			this.active = true;
			this.fireEvent('activate');
			this.element.addClass(this.prefix + '-active');
			this.addPseudo('active');
			this.render();
		}
		return this;
	},

	focus: function(){
		if (!this.focused){
			this.focused = true;
			this.fireEvent('focus');
			this.element.addClass(this.prefix + '-focused');
			this.addPseudo('focus');
			if (focused) focused.blur();
			this.keyboard.activate();
			focused = this;
			this.render();
		}
		return this;
	},

	disable: function(byParent){
		this.disabledByParent = false;
		if (!this.disabled){
			if (byParent) this.disabledByParent = true;
			this.blur();
			this.fireEvent('disable');
			this.keyboard.deactivate();
			this.childWidgets.each(function(child){
				child.disable(true);
			});
			this.element.addClass(this.prefix + '-disabled');
			this.addPseudo('disabled');
			this.disabled = true;
			this.render();
		}
		return this;
	},

	// normal states

	show: function(){
		if (this.hidden){
			this.hidden = false;
			this.fireEvent('show');
			this.element.removeClass(this.prefix + '-hidden');
			this.removePseudo('hidden');
			this.render();
		}
		return this;
	},

	deactivate: function(){
		if (this.active){
			this.active = false;
			this.fireEvent('deactivate');
			this.element.removeClass(this.prefix + '-active');
			this.removePseudo('active');
			this.render();
		}
		return this;
	},

	blur: function(){
		if (this.focused){
			this.focused = false;
			this.fireEvent('blur');
			this.element.removeClass(this.prefix + '-focused');
			this.removePseudo('focus');
			this.render();
		}
		return this;
	},

	enable: function(){
		if (this.parentWidget && this.parentWidget.disabled) {
			this.disabledByParent = true;
			return this;
		};
		delete this.disabledByParent;
		if (this.disabled){
			this.disabled = false;
			this.keyboard.activate();
			this.fireEvent('enable');
			this.element.removeClass(this.prefix + '-disabled');
			this.removePseudo('disabled');
			this.render();
		}
		this.childWidgets.each(function(child){
			if (child.disabledByParent) {
				child.enable();
				delete child.disabledByParent;
			}
		});
		return this;
	},

	attachKeys: function(events){
		this.keyboard.addEvents(events);
	},

	detachKeys: function(events) {
		this.keyboard.removeEvents(events);
	},

	destroy: function(){
		this.removeParent();
		for(var i = 0; i < this.childWidgets.length; i++) {
			this.childWidgets[i].destroy();
		}
		this.element.destroy();
		this.destroyed = true;
		return this.fireEvent('destroy');
	},

	// toElement

	toElement: function(){
		return this.element;
	},

	_redrawCount: 0,
	_counters: function(){
		this._redrawCount++;
		$clear(this._countTimer);
		this._countTimer = (function(){
			this._redrawCount = 0;
		}).delay(1000, this);
		console.log('redraw %s: ', this.name, this._redrawCount, this.element);
	}

});

ART._counts = function(){
	counting = !counting;
	if (counting) console.log('counting widget renders');
	else console.log('disabling widget render counts');
};

})();<commit_msg>fixing loop that destroys children; it was never cleaning them all out...<commit_after>/*
Script: ART.Widget.js

License:
	MIT-style license.
*/

// Base widget class. Based on » http://gist.github.com/85837
(function(){

var counting, focused;

ART.Widget = new Class({

	Implements: [Options, Events],

	ns: 'art',
	name: 'widget',

	options: {
		// onShow: $empty,
		// onHide: $empty,
		// onFocus: $empty,
		// onBlur: $empty,
		// onEnable: $empty,
		// onDisable: $empty,
		// onDestroy: $empty,
		// onAdoption: $empty(parentWidget),
		// onOrphan: $empty(previousParent),
		// id: null,
		// style: null,
		renderWhileHidden: false,
		className: '',
		keyboardOptions: {
			active: true
		},
		parentWidget: null
	},

	initialize: function(options){
		this.latchEvents('adopt');
		this.pseudos = [];
		this.childWidgets = [];
		this.keyboard = new Keyboard();
		this.keyboard.widget = this;
		var parent;
		if (options) {
			if (options.parentWidget) {
				parent = options.parentWidget;
				delete options.parentWidget;
			}
		}
		this.setOptions(options);
		this.keyboard.setOptions(this.options.keyboardOptions).setup();
		this.prefix = this.ns + '-' + this.name;
		this.element = new Element('div', {
			id: this.options.id || this.prefix+new Date().getTime(),
			'class': this.options.className
		}).store(this.prefix, this).store('widget', this);
		this.element.addClass(this.ns).addClass(this.prefix);
		this.classes = this.options.classes;
		this.classes = (this.options.className) ? this.options.className.split(' ') : [];
		if (parent) this.setParent(parent);
	},

	getSelector: function(){
		var selector = (this.parentWidget) ? this.parentWidget.getSelector() + ' ' : '';
		selector += this.name;
		if (this.classes.length) selector += '.' + this.classes.join('.');
		if (this.pseudos.length) selector += ':' + this.pseudos.join(':');
		return selector;
	},

	addPseudo: function(pseudo){
		this.pseudos.include(pseudo);
	},

	removePseudo: function(pseudo){
		this.pseudos.erase(pseudo);
	},

	setParent: function(widget, initing){
		if (!initing) this.removeParent();
		this.parentWidget = widget;
		widget.childWidgets.include(this);
		this.parentWidget.keyboard.manage(this.keyboard);
		this.enable();
		this.fireEvent('adoption', widget);
		return this;
	},

	removeParent: function(){
		this.prevParent = this.parentWidget || this.prevParent;
		if (!this.prevParent) return;
		if (this.parentWidget) {
			this.parentWidget.childWidgets.erase(this);
			Keyboard.manager.manage(this.keyboard);
			this.parentWidget = null;
		}
		this.fireEvent('orphan', this.prevParent);
	},

	// render

	requireToRender: function(){
		this.requiredToRender = this.requiredToRender || [];
		$A(arguments).each(function(requirement) {
			this.requiredToRender.push(requirement);
		}, this);
	},

	readyToRender: function() {
		if (!this.requiredToRender || !this.requiredToRender.length) return;
		$A(arguments).each(function(requirement) {
			this.requiredToRender.erase(requirement);
		}, this);
	},

	redraw: function(){
		if (counting) this._counters();
		this.childWidgets.each(function(child) {
			child.render();
		});
		return this;
	},

	isReadyToRender: function(){
		var isReady = (!this.requiredToRender || !this.requiredToRender.length) && !this.destroyed && (this.options.renderWhileHidden || !this.hidden);
		if (isReady && this.parentWidget) isReady = this.parentWidget.isReadyToRender();
		return isReady;
	},

	render: function(override){
		if (this.isReadyToRender()) this.redraw(override);
		return this;
	},

	// special states

	hide: function(){
		if (!this.hidden){
			this.hidden = true;
			this.fireEvent('hide');
			this.element.addClass(this.prefix + '-hidden');
			this.addPseudo('hidden');
			this.render();
		}
		return this;
	},

	activate: function(){
		if (!this.active){
			this.active = true;
			this.fireEvent('activate');
			this.element.addClass(this.prefix + '-active');
			this.addPseudo('active');
			this.render();
		}
		return this;
	},

	focus: function(){
		if (!this.focused){
			this.focused = true;
			this.fireEvent('focus');
			this.element.addClass(this.prefix + '-focused');
			this.addPseudo('focus');
			if (focused) focused.blur();
			this.keyboard.activate();
			focused = this;
			this.render();
		}
		return this;
	},

	disable: function(byParent){
		this.disabledByParent = false;
		if (!this.disabled){
			if (byParent) this.disabledByParent = true;
			this.blur();
			this.fireEvent('disable');
			this.keyboard.deactivate();
			this.childWidgets.each(function(child){
				child.disable(true);
			});
			this.element.addClass(this.prefix + '-disabled');
			this.addPseudo('disabled');
			this.disabled = true;
			this.render();
		}
		return this;
	},

	// normal states

	show: function(){
		if (this.hidden){
			this.hidden = false;
			this.fireEvent('show');
			this.element.removeClass(this.prefix + '-hidden');
			this.removePseudo('hidden');
			this.render();
		}
		return this;
	},

	deactivate: function(){
		if (this.active){
			this.active = false;
			this.fireEvent('deactivate');
			this.element.removeClass(this.prefix + '-active');
			this.removePseudo('active');
			this.render();
		}
		return this;
	},

	blur: function(){
		if (this.focused){
			this.focused = false;
			this.fireEvent('blur');
			this.element.removeClass(this.prefix + '-focused');
			this.removePseudo('focus');
			this.render();
		}
		return this;
	},

	enable: function(){
		if (this.parentWidget && this.parentWidget.disabled) {
			this.disabledByParent = true;
			return this;
		};
		delete this.disabledByParent;
		if (this.disabled){
			this.disabled = false;
			this.keyboard.activate();
			this.fireEvent('enable');
			this.element.removeClass(this.prefix + '-disabled');
			this.removePseudo('disabled');
			this.render();
		}
		this.childWidgets.each(function(child){
			if (child.disabledByParent) {
				child.enable();
				delete child.disabledByParent;
			}
		});
		return this;
	},

	attachKeys: function(events){
		this.keyboard.addEvents(events);
	},

	detachKeys: function(events) {
		this.keyboard.removeEvents(events);
	},

	destroy: function(){
		this.removeParent();
		while(this.childWidgets.length) {
			this.childWidgets[0].destroy();
		}
		this.element.destroy();
		this.destroyed = true;
		return this.fireEvent('destroy');
	},

	// toElement

	toElement: function(){
		return this.element;
	},

	_redrawCount: 0,
	_counters: function(){
		this._redrawCount++;
		$clear(this._countTimer);
		this._countTimer = (function(){
			this._redrawCount = 0;
		}).delay(1000, this);
		console.log('redraw %s: ', this.name, this._redrawCount, this.element);
	}

});

ART._counts = function(){
	counting = !counting;
	if (counting) console.log('counting widget renders');
	else console.log('disabling widget render counts');
};

})();<|endoftext|>