<commit_before>export { Base };
export { BasePool };

import * as Pool from "../util/Pool.js";
import * as ActivationEscaping from "./ActivationEscaping.js";

/**
 * A placeholder for tensor.
 *
 *   - In Operation.TwinArray.operation_append_Xxx(), it is used for tracking a tensor's final operation which should be responsible
 *       for destroying the tensor.
 *
 *   - In operation's .apply(), it is used for transferring tensor to the next sub operation.
 *
 *
 *
 * @member {Operation.Base} finalOperation
 *   The operation uses this tensor at final. It should be responsible for destroying this tensor. If null, this tensor is
 * not used by any operation.
 *
 * @member {tf.tensor} realTensor
 *   The real tensor represented by this placeholder. It is filled dynamically in an operation's apply() method.
 *
 * @member {ActivationEscaping.ScaleBoundsArray} scaleBoundsArray
 *   The element value bounds (per channel) of the tensor. Usually, it is from the output of the previous operation's value bounds
 * set. It will be kept (not cloned) directly. So caller should use them carefully.
 *
 */
class Base {

  /**
   *
   */
  constructor() {
    this.setAsConstructor();
  }

  /**
   * Initialize to empty.
   *
   * @return {Base}
   *   Return the this object.
   */
  setAsConstructor() {
    this.finalOperation = null;
    this.realTensor = null;
    this.set_height_width_channelCount_scaleBoundsArray_byTensorPlaceholder( null );
    return this;
  }

  /**
   * Release the .scaleBoundsArray
   *
   * Usually, this method is not responsible for releasing .finalOperation and .realTensor. They should be handled
   * by the caller of apply().
   */
  disposeResources() {
    if ( this.scaleBoundsArray ) {
      ActivationEscaping.ScaleBoundsArrayPool.Singleton.recycle( this.scaleBoundsArray );
      this.scaleBoundsArray = null;
    }

    this.finalOperation = null;
    this.realTensor = null;
    this.set_height_width_channelCount_scaleBoundsArray_byTensorPlaceholder( null );
  }

  /**
   * After calling this method, this object should be viewed as disposed and should not be operated again.
   */
  disposeResources_and_recycleToPool() {
    this.disposeResources();
    BasePool.Singleton.recycle( this );
  }

  /**
   *
   * @param {ActivationEscaping.ScaleBoundsArray} scaleBoundsArray  The tensor placeholder's ScaleBoundsArray.
   */
  set_height_width_channelCount_scaleBoundsArray(
    height, width, channelCount, channelCount_lowerHalf, channelCount_higherHalf, scaleBoundsArray ) {
    this.height = height;
    this.width = width;
    this.channelCount = channelCount;
    this.channelCount_lowerHalf = channelCount_lowerHalf;
    this.channelCount_higherHalf = channelCount_higherHalf;
    this.scaleBoundsArray = scaleBoundsArray;
  }

  /**
   * Note: The .finalOperation and .realTensor are not modified by this method.
   *
   * @param {TensorPlaceholder} aTensorPlaceholder
   *   The tensor placeholder's height, width, channelCount, scaleBoundsArray will be used directly (i.e. not cloned) by this
   * tensor placeholder. If null, these properties will be set to undefined.
   */
  set_height_width_channelCount_scaleBoundsArray_byTensorPlaceholder( aTensorPlaceholder ) {
    if ( aTensorPlaceholder ) {
      this.set_height_width_channelCount_scaleBoundsArray(
        aTensorPlaceholder.height, aTensorPlaceholder.width,
        aTensorPlaceholder.channelCount, aTensorPlaceholder.channelCount_lowerHalf, aTensorPlaceholder.channelCount_higherHalf,
        aTensorPlaceholder.scaleBoundsArray );
    } else {
      this.set_height_width_channelCount_scaleBoundsArray(
        undefined, undefined,
        undefined, undefined, undefined,
        undefined );
    }
  }

  /**
   *
   * @param {TensorPlaceholder} aTensorPlaceholder  The tensor placeholder to be comapred.
   *
   * @return {boolean}
   *   Return true, if this tensor placeholder's height, width, channelCount are the same as aTensorPlaceholder. Note: the
   * .channelCount_lowerHalf and .channelCount_higherHalf are not compared.
   */
  is_height_width_channelCount_same_byTensorPlaceholder( aTensorPlaceholder ) {
    if (   ( this.height != aTensorPlaceholder.height )
        || ( this.width != aTensorPlaceholder.width )
        || ( this.channelCount != aTensorPlaceholder.channelCount )

        //|| ( this.channelCount_lowerHalf != aTensorPlaceholder.channelCount_lowerHalf )
        //|| ( this.channelCount_higherHalf != aTensorPlaceholder.channelCount_higherHalf )
       )
      return false;

    return true;
  }

}

/**
 * Providing TensorPlaceholder.Base
 *
 */
class BasePool extends Pool.Root {

  constructor() {
    super( Base, Base.setAsConstructor );
  }

//!!! (2022/06/22 Remarked) Base.setAsConstructor() should be enough.
//   /**
//    * @param {Base} this
//    *   The TensorPlaceholder.Base object to be initialized.
//    *
//    * @return {Base}
//    *   Return the this object.
//    */
//   static setAsConstructor() {
//     this.setAsConstructor();
//     return this;
//   }

}

/**
 * Used as default TensorPlaceholder.Base provider.
 */
BasePool.Singleton = new BasePool();
<commit_msg>Update TensorPlaceholder.js<commit_after>export { Base };
export { BasePool };

import * as Pool from "../util/Pool.js";
import * as Recyclable from "../util/Recyclable.js";
import * as ActivationEscaping from "./ActivationEscaping.js";

/**
 * A placeholder for tensor.
 *
 *   - In Operation.TwinArray.operation_append_Xxx(), it is used for tracking a tensor's final operation which should be responsible
 *       for destroying the tensor.
 *
 *   - In operation's .apply(), it is used for transferring tensor to the next sub operation.
 *
 *
 *
 * @member {Operation.Base} finalOperation
 *   The operation uses this tensor at final. It should be responsible for destroying this tensor. If null, this tensor is
 * not used by any operation.
 *
 * @member {tf.tensor} realTensor
 *   The real tensor represented by this placeholder. It is filled dynamically in an operation's apply() method.
 *
 * @member {ActivationEscaping.ScaleBoundsArray} scaleBoundsArray
 *   The element value bounds (per channel) of the tensor. Usually, it is from the output of the previous operation's value bounds
 * set. It will be kept (not cloned) directly. So caller should use them carefully.
 *
 */
class Base extends Recyclable.Root {

  /**
   *
   */
  constructor() {
    this.setAsConstructor();
  }

  /**
   * Initialize to empty.
   *
   * @return {Base}
   *   Return the this object.
   */
  setAsConstructor() {
    this.finalOperation = null;
    this.realTensor = null;
    this.set_height_width_channelCount_scaleBoundsArray_byTensorPlaceholder( null );
    return this;
  }

  /**
   * Release the .scaleBoundsArray
   *
   * Usually, this method is not responsible for releasing .finalOperation and .realTensor. They should be handled
   * by the caller of apply().
   */
  disposeResources() {
    if ( this.scaleBoundsArray ) {
      this.scaleBoundsArray.disposeResources_and_recycleToPool();
      this.scaleBoundsArray = null;
    }

    this.finalOperation = null;
    this.realTensor = null;
    this.set_height_width_channelCount_scaleBoundsArray_byTensorPlaceholder( null );

    super.disposeResources();
  }

  /**
   *
   * @param {ActivationEscaping.ScaleBoundsArray} scaleBoundsArray  The tensor placeholder's ScaleBoundsArray.
   */
  set_height_width_channelCount_scaleBoundsArray(
    height, width, channelCount, channelCount_lowerHalf, channelCount_higherHalf, scaleBoundsArray ) {
    this.height = height;
    this.width = width;
    this.channelCount = channelCount;
    this.channelCount_lowerHalf = channelCount_lowerHalf;
    this.channelCount_higherHalf = channelCount_higherHalf;
    this.scaleBoundsArray = scaleBoundsArray;
  }

  /**
   * Note: The .finalOperation and .realTensor are not modified by this method.
   *
   * @param {TensorPlaceholder} aTensorPlaceholder
   *   The tensor placeholder's height, width, channelCount, scaleBoundsArray will be used directly (i.e. not cloned) by this
   * tensor placeholder. If null, these properties will be set to undefined.
   */
  set_height_width_channelCount_scaleBoundsArray_byTensorPlaceholder( aTensorPlaceholder ) {
    if ( aTensorPlaceholder ) {
      this.set_height_width_channelCount_scaleBoundsArray(
        aTensorPlaceholder.height, aTensorPlaceholder.width,
        aTensorPlaceholder.channelCount, aTensorPlaceholder.channelCount_lowerHalf, aTensorPlaceholder.channelCount_higherHalf,
        aTensorPlaceholder.scaleBoundsArray );
    } else {
      this.set_height_width_channelCount_scaleBoundsArray(
        undefined, undefined,
        undefined, undefined, undefined,
        undefined );
    }
  }

  /**
   *
   * @param {TensorPlaceholder} aTensorPlaceholder  The tensor placeholder to be comapred.
   *
   * @return {boolean}
   *   Return true, if this tensor placeholder's height, width, channelCount are the same as aTensorPlaceholder. Note: the
   * .channelCount_lowerHalf and .channelCount_higherHalf are not compared.
   */
  is_height_width_channelCount_same_byTensorPlaceholder( aTensorPlaceholder ) {
    if (   ( this.height != aTensorPlaceholder.height )
        || ( this.width != aTensorPlaceholder.width )
        || ( this.channelCount != aTensorPlaceholder.channelCount )

        //|| ( this.channelCount_lowerHalf != aTensorPlaceholder.channelCount_lowerHalf )
        //|| ( this.channelCount_higherHalf != aTensorPlaceholder.channelCount_higherHalf )
       )
      return false;

    return true;
  }

}

/**
 * Providing TensorPlaceholder.Base
 *
 */
class BasePool extends Pool.Root {

  constructor() {
    super( Base, Base.setAsConstructor );
  }

}

/**
 * Used as default TensorPlaceholder.Base provider for conforming to Recyclable interface.
 */
Base.Pool = new BasePool();
<|endoftext|>


<commit_before>// (c) 2012 Richard Carter
// This code is licensed under the MIT license; see LICENSE.txt for details.

// This script handles the following functions:
//     some url - look up the url's title and announce it

var request = require('request'),
    entities = require('./lib/entities');

listen(/\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?]))/i, function(match, data, replyTo) {
    var url = match[0];

    if(url.indexOf('http') != 0) {
        url = 'https://' + url;
    }

    var requestObject = {
        uri: url,
        strictSSL: false,
        timeout: 10000,
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31 Nodebot'
        }
    };

    request(requestObject, function(error, response, body) {
        if(error) {
            if((""+error).indexOf('SSL routines') < 0) {
                irc.privmsg(replyTo, "Error looking up URL: " + error);
            }
        } else if(response.statusCode != 200) {
            // Ignore 403 Access Forbidden; some websites block bots with this
            // code (e.g. Wikipedia).
            if(response.statusCode != 403) {
                irc.privmsg(replyTo, "" + response.statusCode);
            }
        } else if(response.headers['content-type'] && response.headers['content-type'].toLowerCase().indexOf('text/html') == -1) {
            // Not an HTML page
        } else {
            var titleMatch = /<title>([^<]+)<\/title>/i.exec(body),
                hostname = response.request.host;

            if(titleMatch && titleMatch[1]) {
                var title = titleMatch[1];

                // replace multi-spaces/newlines with spaces
                title = title.replace(/\s{2,}/g," ");

                // trim front and back
                title = title.replace(/^\s+/,"");
                title = title.replace(/\s+$/,"");

                // decode HTML entities
                title = entities.decode(title);

                irc.privmsg(replyTo, hostname + " : " + title);
            } else {
                irc.privmsg(replyTo, hostname + " : title not found");
            }
        }
    });
});
<commit_msg>title: blank line at end of file<commit_after>// (c) 2012 Richard Carter
// This code is licensed under the MIT license; see LICENSE.txt for details.

// This script handles the following functions:
//     some url - look up the url's title and announce it

var request = require('request'),
    entities = require('./lib/entities');

listen(/\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?]))/i, function(match, data, replyTo) {
    var url = match[0];

    if(url.indexOf('http') != 0) {
        url = 'https://' + url;
    }

    var requestObject = {
        uri: url,
        strictSSL: false,
        timeout: 10000,
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31 Nodebot'
        }
    };

    request(requestObject, function(error, response, body) {
        if(error) {
            if((""+error).indexOf('SSL routines') < 0) {
                irc.privmsg(replyTo, "Error looking up URL: " + error);
            }
        } else if(response.statusCode != 200) {
            // Ignore 403 Access Forbidden; some websites block bots with this
            // code (e.g. Wikipedia).
            if(response.statusCode != 403) {
                irc.privmsg(replyTo, "" + response.statusCode);
            }
        } else if(response.headers['content-type'] && response.headers['content-type'].toLowerCase().indexOf('text/html') == -1) {
            // Not an HTML page
        } else {
            var titleMatch = /<title>([^<]+)<\/title>/i.exec(body),
                hostname = response.request.host;

            if(titleMatch && titleMatch[1]) {
                var title = titleMatch[1];

                // replace multi-spaces/newlines with spaces
                title = title.replace(/\s{2,}/g," ");

                // trim front and back
                title = title.replace(/^\s+/,"");
                title = title.replace(/\s+$/,"");

                // decode HTML entities
                title = entities.decode(title);

                irc.privmsg(replyTo, hostname + " : " + title);
            } else {
                irc.privmsg(replyTo, hostname + " : title not found");
            }
        }
    });
});

<|endoftext|>


<commit_before>// @flow

import React, { Component } from 'react';
import cx from 'classnames';
import styles from './bdb.css';
import { Content } from 'app/components/Content';
import {
  sortByYearThenSemester,
  getContactedStatuses,
  DetailNavigation
} from '../utils.js';
import InfoBubble from 'app/components/InfoBubble';
import CommentView from 'app/components/Comments/CommentView';
import Time from 'app/components/Time';
import { Link } from 'react-router';
import LoadingIndicator from 'app/components/LoadingIndicator';
import { Image } from 'app/components/Image';
import SemesterStatusDetail from './SemesterStatusDetail';
import { EVENT_CONSTANTS } from 'app/routes/events/utils';
import truncateString from 'app/utils/truncateString';
import type {
  CompanyEntity,
  BaseSemesterStatusEntity,
  SemesterStatusEntity
} from 'app/reducers/companies';
import type { CompanySemesterEntity } from 'app/reducers/companySemesters';
import type { UserEntity } from 'app/reducers/users';
import Button from 'app/components/Button';
import Tooltip from 'app/components/Tooltip';
import type { CompanySemesterContactedStatus, ID } from 'app/models';
import { ConfirmModalWithParent } from 'app/components/Modal/ConfirmModal';

type Props = {
  company: CompanyEntity,
  comments: Array<Object>,
  companyEvents: Array<Object>,
  currentUser: any,
  deleteSemesterStatus: (number, number) => Promise<*>,
  deleteCompanyContact: (number, number) => Promise<*>,
  loggedIn: boolean,
  companySemesters: Array<CompanySemesterEntity>,
  editSemesterStatus: (BaseSemesterStatusEntity, ?Object) => Promise<*>,
  companyEvents: Array<Object>,
  fetching: boolean,
  editCompany: Object => void,
  deleteCompany: number => Promise<*>,
  deleteComment: (id: ID, contentTarget: string) => Promise<*>,
  showFetchMoreEvents: boolean,
  fetchMoreEvents: () => Promise<*>
};

type State = {
  addingFiles: boolean,
  eventsToDisplay: number
};

export default class BdbDetail extends Component<Props, State> {
  state = {
    addingFiles: false,
    eventsToDisplay: 3
  };

  componentDidMount() {
    window.scrollTo(0, 0);
  }

  semesterStatusOnChange = (
    semesterStatus: SemesterStatusEntity,
    statusString: CompanySemesterContactedStatus
  ) => {
    const { companySemesters, editSemesterStatus, company } = this.props;

    const newStatus = {
      ...semesterStatus,
      contactedStatus: getContactedStatuses(
        semesterStatus.contactedStatus,
        statusString
      )
    };

    const companySemester = companySemesters.find(
      companySemester =>
        companySemester.year === newStatus.year &&
        companySemester.semester === newStatus.semester
    );

    if (!companySemester) {
      throw new Error('Could not find company semester');
    }

    const sendableSemester = {
      contactedStatus: newStatus.contactedStatus,
      semesterStatusId: newStatus.id,
      semester: companySemester.id,
      companyId: company.id
    };

    return editSemesterStatus(sendableSemester, { detail: true });
  };

  deleteSemesterStatus = (semesterStatusId: number) => {
    const { deleteSemesterStatus, company } = this.props;
    return deleteSemesterStatus(company.id, semesterStatusId);
  };

  deleteCompanyContact = (companyContactId: number) => {
    const { deleteCompanyContact, company } = this.props;
    return deleteCompanyContact(company.id, companyContactId);
  };

  addFileToSemester = (
    fileName: string,
    fileToken: string,
    type: string,
    semesterStatus: Object
  ) => {
    const { editSemesterStatus, company } = this.props;

    const sendableSemester = {
      semesterStatusId: semesterStatus.id,
      companyId: company.id,
      contactedStatus: semesterStatus.contactedStatus,
      [type]: fileToken
    };

    return editSemesterStatus(sendableSemester, { detail: true });
  };

  removeFileFromSemester = (
    semesterStatus: SemesterStatusEntity,
    type: string
  ) => {
    const { editSemesterStatus, company } = this.props;

    const sendableSemester = {
      semesterStatusId: semesterStatus.id,
      contactedStatus: semesterStatus.contactedStatus,
      companyId: company.id,
      [type]: null
    };

    return editSemesterStatus(sendableSemester, { detail: true });
  };

  studentContactLink = (studentContact?: UserEntity): string => {
    return studentContact
      ? 'abakus.no/users/' + String(studentContact.username)
      : '';
  };

  render() {
    const {
      company,
      comments,
      currentUser,
      loggedIn,
      companyEvents,
      fetching,
      deleteCompany,
      deleteComment,
      showFetchMoreEvents,
      fetchMoreEvents
    } = this.props;

    if (fetching || !company.semesterStatuses) {
      return <LoadingIndicator loading />;
    }

    const semesters = company.semesterStatuses
      // $FlowFixMe
      .sort(sortByYearThenSemester)
      .map(semesterStatus => (
        <SemesterStatusDetail
          semesterStatus={semesterStatus}
          key={semesterStatus.id}
          companyId={company.id}
          deleteSemesterStatus={this.deleteSemesterStatus}
          editFunction={this.semesterStatusOnChange}
          addFileToSemester={this.addFileToSemester}
          removeFileFromSemester={this.removeFileFromSemester}
        />
      ));

    const companyContacts =
      company.companyContacts &&
      company.companyContacts.map(contact => (

          {contact.name || '-'}
          {contact.role || '-'}
          {contact.mail || '-'}

              {contact.phone || '-'}

                <Link
                  to={`/bdb/${String(company.id)}/company-contacts/${String(
                    contact.id
                  )}`}
                >

                </Link>
                <ConfirmModalWithParent
                  title="Slett bedriftskontakt"
                  message="Er du sikker på at du vil slette denne bedriftskontakten?"
                  onConfirm={() => this.deleteCompanyContact(contact.id)}
                  closeOnConfirm
                >

                </ConfirmModalWithParent>

      ));

    const events =
      companyEvents &&
      companyEvents
        .sort((a, b) => Date.parse(b.startTime) - Date.parse(a.startTime))
        .slice(0, this.state.eventsToDisplay)
        .map(event => (

              <Link to={`events/${event.id}`}>{event.title}</Link>

            {EVENT_CONSTANTS[event.eventType]}

              <Time time={event.startTime} format="DD.MM.YYYY" />

            {truncateString(event.location, 50)}
            {truncateString(event.description, 70)}

              {event.survey && (
                <Tooltip content="Spørreundersøkelse">
                  <Link to={`surveys/${event.survey}`}>

                  </Link>
                </Tooltip>
              )}

        ));

    const title = (

        {company.name}
        {!company.active &&  (Inaktiv)}
        <Link to={`/bdb/${company.id}/edit`}>

        </Link>

    );

    return (
      <Content>

          {company.logo && (
            <Image
              src={company.logo}
              style={{
                height: 'inherit',
                border: '1px solid #ccc',
                marginBottom: '15px'
              }}
            />
          )}
          <DetailNavigation
            title={title}
            companyId={company.id}
            deleteFunction={deleteCompany}
          />

            {company.description || 'Ingen beskrivelse tilgjengelig.'}

            <InfoBubble
              icon="briefcase"
              data={company.companyType}
              meta="Type bedrift"
              style={{ order: 0 }}
            />
            <InfoBubble
              icon="mail"
              data={company.paymentMail}
              meta="Fakturamail"
              style={{ order: 1 }}
            />
            <InfoBubble
              icon="call"
              data={company.phone}
              meta="Telefon"
              style={{ order: 2 }}
            />
            <InfoBubble
              icon="at"
              data={company.website}
              meta="Nettside"
              style={{ order: 3 }}
              link={company.website}
            />
            <InfoBubble
              icon="home"
              data={company.address}
              meta="Adresse"
              style={{ order: 4 }}
            />
            <InfoBubble
              icon="person"
              data={`${(company.studentContact &&
                company.studentContact.fullName) ||
                '-'}`}
              meta="Studentkontakt"
              link={this.studentContactLink(company.studentContact)}
              style={{ order: 5 }}
            />

Bedriftskontakter

          {companyContacts && companyContacts.length > 0 ? (

                    Navn
                    Rolle
                    E-post
                    Tlf

{companyContacts}

          ) : (

              Ingen bedriftskontakter registrert.

          )}
          <Link
            to={`/bdb/${company.id}/company-contacts/add`}
            style={{ marginTop: '10px' }}
          >
             Legg til bedriftskontakt
          </Link>

Semesterstatuser

          {semesters.length > 0 ? (

Tips: Du kan endre semestere ved å trykke på dem i listen!

                    Semester
                    Status
                    Kontrakt
                    Statistikk
                    Evaluering

{semesters}

          ) : (
            Ingen sememsterstatuser.
          )}

            <Link to={`/bdb/${company.id}/semesters/add`}>
               Legg til nytt semester
            </Link>

Filer

              {!company.files || company.files.length === 0 ? (
                Ingen filer.
              ) : (
                company.files.map(file => (

                    {truncateString(file.file, 100)}

                ))
              )}

Notat i listen

            {company.adminComment || Ingen notater}

Bedriftens arrangementer

          {events.length > 0 ? (

                    Tittel
                    Arrangementstype
                    Når
                    Hvor
                    Hva

{events}

              {this.state.eventsToDisplay === 3 ? (
                <Button
                  style={{ width: '100%', marginTop: '20px' }}
                  onClick={() => this.setState({ eventsToDisplay: 100 })}
                >
                  Vis alle arrangementer
                </Button>
              ) : (
                showFetchMoreEvents && (
                  <Button onClick={fetchMoreEvents}>Hent flere</Button>
                )
              )}

          ) : (
            Ingen arrangementer.
          )}

          {company.contentTarget && (
            <CommentView
              user={currentUser}
              contentTarget={company.contentTarget}
              loggedIn={loggedIn}
              comments={comments}
              newOnTop
              deleteComment={deleteComment}
            />
          )}

      </Content>
    );
  }
}
<commit_msg>Add additional slash to survey-link<commit_after>// @flow

import React, { Component } from 'react';
import cx from 'classnames';
import styles from './bdb.css';
import { Content } from 'app/components/Content';
import {
  sortByYearThenSemester,
  getContactedStatuses,
  DetailNavigation
} from '../utils.js';
import InfoBubble from 'app/components/InfoBubble';
import CommentView from 'app/components/Comments/CommentView';
import Time from 'app/components/Time';
import { Link } from 'react-router';
import LoadingIndicator from 'app/components/LoadingIndicator';
import { Image } from 'app/components/Image';
import SemesterStatusDetail from './SemesterStatusDetail';
import { EVENT_CONSTANTS } from 'app/routes/events/utils';
import truncateString from 'app/utils/truncateString';
import type {
  CompanyEntity,
  BaseSemesterStatusEntity,
  SemesterStatusEntity
} from 'app/reducers/companies';
import type { CompanySemesterEntity } from 'app/reducers/companySemesters';
import type { UserEntity } from 'app/reducers/users';
import Button from 'app/components/Button';
import Tooltip from 'app/components/Tooltip';
import type { CompanySemesterContactedStatus, ID } from 'app/models';
import { ConfirmModalWithParent } from 'app/components/Modal/ConfirmModal';

type Props = {
  company: CompanyEntity,
  comments: Array<Object>,
  companyEvents: Array<Object>,
  currentUser: any,
  deleteSemesterStatus: (number, number) => Promise<*>,
  deleteCompanyContact: (number, number) => Promise<*>,
  loggedIn: boolean,
  companySemesters: Array<CompanySemesterEntity>,
  editSemesterStatus: (BaseSemesterStatusEntity, ?Object) => Promise<*>,
  companyEvents: Array<Object>,
  fetching: boolean,
  editCompany: Object => void,
  deleteCompany: number => Promise<*>,
  deleteComment: (id: ID, contentTarget: string) => Promise<*>,
  showFetchMoreEvents: boolean,
  fetchMoreEvents: () => Promise<*>
};

type State = {
  addingFiles: boolean,
  eventsToDisplay: number
};

export default class BdbDetail extends Component<Props, State> {
  state = {
    addingFiles: false,
    eventsToDisplay: 3
  };

  componentDidMount() {
    window.scrollTo(0, 0);
  }

  semesterStatusOnChange = (
    semesterStatus: SemesterStatusEntity,
    statusString: CompanySemesterContactedStatus
  ) => {
    const { companySemesters, editSemesterStatus, company } = this.props;

    const newStatus = {
      ...semesterStatus,
      contactedStatus: getContactedStatuses(
        semesterStatus.contactedStatus,
        statusString
      )
    };

    const companySemester = companySemesters.find(
      companySemester =>
        companySemester.year === newStatus.year &&
        companySemester.semester === newStatus.semester
    );

    if (!companySemester) {
      throw new Error('Could not find company semester');
    }

    const sendableSemester = {
      contactedStatus: newStatus.contactedStatus,
      semesterStatusId: newStatus.id,
      semester: companySemester.id,
      companyId: company.id
    };

    return editSemesterStatus(sendableSemester, { detail: true });
  };

  deleteSemesterStatus = (semesterStatusId: number) => {
    const { deleteSemesterStatus, company } = this.props;
    return deleteSemesterStatus(company.id, semesterStatusId);
  };

  deleteCompanyContact = (companyContactId: number) => {
    const { deleteCompanyContact, company } = this.props;
    return deleteCompanyContact(company.id, companyContactId);
  };

  addFileToSemester = (
    fileName: string,
    fileToken: string,
    type: string,
    semesterStatus: Object
  ) => {
    const { editSemesterStatus, company } = this.props;

    const sendableSemester = {
      semesterStatusId: semesterStatus.id,
      companyId: company.id,
      contactedStatus: semesterStatus.contactedStatus,
      [type]: fileToken
    };

    return editSemesterStatus(sendableSemester, { detail: true });
  };

  removeFileFromSemester = (
    semesterStatus: SemesterStatusEntity,
    type: string
  ) => {
    const { editSemesterStatus, company } = this.props;

    const sendableSemester = {
      semesterStatusId: semesterStatus.id,
      contactedStatus: semesterStatus.contactedStatus,
      companyId: company.id,
      [type]: null
    };

    return editSemesterStatus(sendableSemester, { detail: true });
  };

  studentContactLink = (studentContact?: UserEntity): string => {
    return studentContact
      ? 'abakus.no/users/' + String(studentContact.username)
      : '';
  };

  render() {
    const {
      company,
      comments,
      currentUser,
      loggedIn,
      companyEvents,
      fetching,
      deleteCompany,
      deleteComment,
      showFetchMoreEvents,
      fetchMoreEvents
    } = this.props;

    if (fetching || !company.semesterStatuses) {
      return <LoadingIndicator loading />;
    }

    const semesters = company.semesterStatuses
      // $FlowFixMe
      .sort(sortByYearThenSemester)
      .map(semesterStatus => (
        <SemesterStatusDetail
          semesterStatus={semesterStatus}
          key={semesterStatus.id}
          companyId={company.id}
          deleteSemesterStatus={this.deleteSemesterStatus}
          editFunction={this.semesterStatusOnChange}
          addFileToSemester={this.addFileToSemester}
          removeFileFromSemester={this.removeFileFromSemester}
        />
      ));

    const companyContacts =
      company.companyContacts &&
      company.companyContacts.map(contact => (

          {contact.name || '-'}
          {contact.role || '-'}
          {contact.mail || '-'}

              {contact.phone || '-'}

                <Link
                  to={`/bdb/${String(company.id)}/company-contacts/${String(
                    contact.id
                  )}`}
                >

                </Link>
                <ConfirmModalWithParent
                  title="Slett bedriftskontakt"
                  message="Er du sikker på at du vil slette denne bedriftskontakten?"
                  onConfirm={() => this.deleteCompanyContact(contact.id)}
                  closeOnConfirm
                >

                </ConfirmModalWithParent>

      ));

    const events =
      companyEvents &&
      companyEvents
        .sort((a, b) => Date.parse(b.startTime) - Date.parse(a.startTime))
        .slice(0, this.state.eventsToDisplay)
        .map(event => (

              <Link to={`events/${event.id}`}>{event.title}</Link>

            {EVENT_CONSTANTS[event.eventType]}

              <Time time={event.startTime} format="DD.MM.YYYY" />

            {truncateString(event.location, 50)}
            {truncateString(event.description, 70)}

              {event.survey && (
                <Tooltip content="Spørreundersøkelse">
                  <Link to={`/surveys/${event.survey}`}>

                  </Link>
                </Tooltip>
              )}

        ));

    const title = (

        {company.name}
        {!company.active &&  (Inaktiv)}
        <Link to={`/bdb/${company.id}/edit`}>

        </Link>

    );

    return (
      <Content>

          {company.logo && (
            <Image
              src={company.logo}
              style={{
                height: 'inherit',
                border: '1px solid #ccc',
                marginBottom: '15px'
              }}
            />
          )}
          <DetailNavigation
            title={title}
            companyId={company.id}
            deleteFunction={deleteCompany}
          />

            {company.description || 'Ingen beskrivelse tilgjengelig.'}

            <InfoBubble
              icon="briefcase"
              data={company.companyType}
              meta="Type bedrift"
              style={{ order: 0 }}
            />
            <InfoBubble
              icon="mail"
              data={company.paymentMail}
              meta="Fakturamail"
              style={{ order: 1 }}
            />
            <InfoBubble
              icon="call"
              data={company.phone}
              meta="Telefon"
              style={{ order: 2 }}
            />
            <InfoBubble
              icon="at"
              data={company.website}
              meta="Nettside"
              style={{ order: 3 }}
              link={company.website}
            />
            <InfoBubble
              icon="home"
              data={company.address}
              meta="Adresse"
              style={{ order: 4 }}
            />
            <InfoBubble
              icon="person"
              data={`${(company.studentContact &&
                company.studentContact.fullName) ||
                '-'}`}
              meta="Studentkontakt"
              link={this.studentContactLink(company.studentContact)}
              style={{ order: 5 }}
            />

Bedriftskontakter

          {companyContacts && companyContacts.length > 0 ? (

                    Navn
                    Rolle
                    E-post
                    Tlf

{companyContacts}

          ) : (

              Ingen bedriftskontakter registrert.

          )}
          <Link
            to={`/bdb/${company.id}/company-contacts/add`}
            style={{ marginTop: '10px' }}
          >
             Legg til bedriftskontakt
          </Link>

Semesterstatuser

          {semesters.length > 0 ? (

Tips: Du kan endre semestere ved å trykke på dem i listen!

                    Semester
                    Status
                    Kontrakt
                    Statistikk
                    Evaluering

{semesters}

          ) : (
            Ingen sememsterstatuser.
          )}

            <Link to={`/bdb/${company.id}/semesters/add`}>
               Legg til nytt semester
            </Link>

Filer

              {!company.files || company.files.length === 0 ? (
                Ingen filer.
              ) : (
                company.files.map(file => (

                    {truncateString(file.file, 100)}

                ))
              )}

Notat i listen

            {company.adminComment || Ingen notater}

Bedriftens arrangementer

          {events.length > 0 ? (

                    Tittel
                    Arrangementstype
                    Når
                    Hvor
                    Hva

{events}

              {this.state.eventsToDisplay === 3 ? (
                <Button
                  style={{ width: '100%', marginTop: '20px' }}
                  onClick={() => this.setState({ eventsToDisplay: 100 })}
                >
                  Vis alle arrangementer
                </Button>
              ) : (
                showFetchMoreEvents && (
                  <Button onClick={fetchMoreEvents}>Hent flere</Button>
                )
              )}

          ) : (
            Ingen arrangementer.
          )}

          {company.contentTarget && (
            <CommentView
              user={currentUser}
              contentTarget={company.contentTarget}
              loggedIn={loggedIn}
              comments={comments}
              newOnTop
              deleteComment={deleteComment}
            />
          )}

      </Content>
    );
  }
}
<|endoftext|>


<commit_before>var AdminFilters = function(element, labels, form, filters, active_filters) {
    // Admin filters will deal with the adding and removing of search filters
    // :param labels:
    //      {'col','label'}
    // :param active_filters:
    //      [['col','filter name','value'],[...],...]

    var $root = $(element);
    var $container = $('.filters', $root);
    var lastCount = 0;

    function removeFilter() {
        $(this).closest('tr').remove();
        $('button', $root).show();

        return false;
    }

    function addActiveFilters()
    {
        $(active_filters).each(function() {
            addActiveFilter(this[0], this[1], this[2]);
        });
    }

    function addActiveFilter(name, filter_name, value)
    {
        var $el = $('
').appendTo($container);

	    addRemoveFilter($el, name, labels[name]);
        var i_option = addFilterOptionsValue($el, name, filter_name);

        var $field = $(form[name])
        // if form item complex like
<input bla>
, datetime
        if ( $("input", $($field)).html() != undefined ) {
            $field_inner = $("input", $field)
            $field_inner.attr('name', '_flt_' + i_option + '_' + name);
            $field_inner.val(value);
            $field_inner.attr('class', ' filter_val ' + $field_inner.attr('class'));
	    }
        else {
            if (($field.attr( 'type')) == 'checkbox') {
                $field.attr( 'checked', true );
            }
            $field.attr('name', '_flt_' + i_option + '_' + name);
            $field.val(value);
            $field.attr('class', ' filter_val ' + $field.attr('class'));
        }
        $el.append(
            $('').append($field)
            );;
    }

	function addRemoveFilter($el, name, label)
	{
		$el.append(
                $('').append(
                    $('')
                        .append($('×'))
                        .append(' ')
                        .append(label)
                        .on('click', removeFilter)
                    )
            );
	}

    function addFilterOptionsValue($el, name, value)
	{
		var $select = $('<select class="filter-op my_select2" />')

		cx = 0;
        var i_option = -1;
        $(filters[name]).each(function() {
            if (value == this) {
                $select.append($('<option selected="selected"/>').attr('value', cx).text(this));
                i_option = cx;
            }
            else {
                $select.append($('<option/>').attr('value', cx).text(this));
            }
	    cx += 1;
        });

        $el.append(
               $('').append($select)
        );
        // avoids error
        if (i_option == -1) { $select.select2(); }
        $select.on('change', function(e) {
        	changeOperation(e, $el, name)
    	});

        return i_option;
	}

    function addFilter(name, filter) {
        var $el = $('
').appendTo($container);

	    addRemoveFilter($el, name, labels[name]);

        addFilterOptionsValue($el, name);
	    var $field = $(form[name])

	    // if form item complex like
<input bla>
, datetime
	    if ( $("input", $($field)).html() != undefined ) {
		    $field_inner = $("input", $($field))
		    $field_inner.attr('name', '_flt_0_' + name);
		    $field_inner.attr('class', ' filter_val ' + $field_inner.attr('class'));

	    }
	    else {
		    $field.attr('name', '_flt_0_' + name);
		    $field.attr('class', ' filter_val ' + $field.attr('class'));
	    }
	    $el.append(
        	$('').append($field)
        );;
        if ($field.hasClass( "my_select2" )) {
        	$field.select2({placeholder: "Select a State", allowClear: true});
        }
        if ($field.hasClass( "appbuilder_datetime" )) {
        	$field.datetimepicker();
        }
        if ($field.hasClass( "appbuilder_date" )) {
        	$field.datetimepicker({pickTime: false });
        }
        lastCount += 1;
    };

	// ----------------------------------------------------------
	// Trigger for option change will change input element name
	// ----------------------------------------------------------
    function changeOperation(e, $el, name) {
        $in = $el.find('.filter_val');
        $in.attr('name','_flt_' + e.val + '_' + name);
    }

    $('a.filter').on('click', function() {
        var name = $(this).attr('name')
        addFilter(name);
    });

    addActiveFilters();

};
<commit_msg>small fixes<commit_after>var AdminFilters = function(element, labels, form, filters, active_filters) {
    // Admin filters will deal with the adding and removing of search filters
    // :param labels:
    //      {'col','label'}
    // :param active_filters:
    //      [['col','filter name','value'],[...],...]

    var $root = $(element);
    var $container = $('.filters', $root);
    var lastCount = 0;

    function removeFilter() {
        $(this).closest('tr').remove();
        $('button', $root).show();

        return false;
    }

    function addActiveFilters()
    {
        $(active_filters).each(function() {
            addActiveFilter(this[0], this[1], this[2]);
        });
    }

    function addActiveFilter(name, filter_name, value)
    {
        var $el = $('
').appendTo($container);

	    addRemoveFilter($el, name, labels[name]);
        var i_option = addFilterOptionsValue($el, name, filter_name);

        var $field = $(form[name])
        // if form item complex like
<input bla>
, datetime
        if ( $("input", $($field)).html() != undefined ) {
            $field_inner = $("input", $field)
            $field_inner.attr('name', '_flt_' + i_option + '_' + name);
            $field_inner.val(value);
            $field_inner.attr('class', ' filter_val ' + $field_inner.attr('class'));
	    }
        else {
            if (($field.attr( 'type')) == 'checkbox') {
                $field.attr( 'checked', true );
            }
            $field.attr('name', '_flt_' + i_option + '_' + name);
            $field.val(value);
            $field.attr('class', ' filter_val ' + $field.attr('class'));
        }
        $el.append(
            $('').append($field)
            );
    }

	function addRemoveFilter($el, name, label)
	{
		$el.append(
            $('').append(
                $('')
                    .append($('×'))
                    .append(' ')
                    .append(label)
                    .on('click', removeFilter)
                )
            );
	}

    function addFilterOptionsValue($el, name, value)
	{
		var $select = $('<select class="filter-op my_select2" />')

		cx = 0;
        var i_option = -1;
        $(filters[name]).each(function() {
            if (value == this) {
                $select.append($('<option selected="selected"/>').attr('value', cx).text(this));
                i_option = cx;
            }
            else {
                $select.append($('<option/>').attr('value', cx).text(this));
            }
	    cx += 1;
        });

        $el.append(
               $('').append($select)
        );
        // avoids error
        if (i_option == -1) { $select.select2(); }
        $select.on('change', function(e) {
        	changeOperation(e, $el, name)
    	});

        return i_option;
	}

    function addFilter(name, filter) {
        var $el = $('
').appendTo($container);

	    addRemoveFilter($el, name, labels[name]);

        addFilterOptionsValue($el, name);
	    var $field = $(form[name])

	    // if form item complex like
<input bla>
, datetime
	    if ( $("input", $($field)).html() != undefined ) {
		    $field_inner = $("input", $($field))
		    $field_inner.attr('name', '_flt_0_' + name);
		    $field_inner.attr('class', ' filter_val ' + $field_inner.attr('class'));

	    }
	    else {
		    $field.attr('name', '_flt_0_' + name);
		    $field.attr('class', ' filter_val ' + $field.attr('class'));
	    }
	    $el.append(
        	$('').append($field)
        );;
        if ($field.hasClass( "my_select2" )) {
        	$field.select2({placeholder: "Select a State", allowClear: true});
        }
        if ($field.hasClass( "appbuilder_datetime" )) {
        	$field.datetimepicker();
        }
        if ($field.hasClass( "appbuilder_date" )) {
        	$field.datetimepicker({pickTime: false });
        }
        lastCount += 1;
    }

	// ----------------------------------------------------------
	// Trigger for option change will change input element name
	// ----------------------------------------------------------
    function changeOperation(e, $el, name) {
        $in = $el.find('.filter_val');
        $in.attr('name','_flt_' + e.val + '_' + name);
    }

    $('a.filter').on('click', function() {
        var name = $(this).attr('name');
        addFilter(name);
    });

    addActiveFilters();

};
<|endoftext|>


<commit_before>/*
 * MelonJS Game Engine
 * Copyright (C) 2012, Olivier BIOT
 * http://www.melonjs.org
 *
 */

(function($, undefined) {

	/**
	 * There is no constructor function for me.input.
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */
	me.input = (function() {

		// hold public stuff in our singletong
		var obj = {};

		/*---------------------------------------------

			PRIVATE STUFF

		  ---------------------------------------------*/

		// list of binded keys
		var KeyBinding = [];

		// corresponding actions
		var keyStatus = [];

		// lock enable flag for keys
		var keyLock = [];
		// actual lock status of each key
		var keyLocked = [];

		// callback function for mouse & gyro
		var mouseEventCB = null;
		var gyroEventCB = null;

		// some usefull flags
		var keyboardInitialized = false;

		/*---

			enable keyboard event

			---*/
		function enableKeyboardEvent(enable) {
			if (enable) {
				// Event Management
				if (!keyboardInitialized) {
					$.addEventListener('keydown', keydown, false);
					$.addEventListener('keyup', keyup, false);
				}
			} else {
				// remove the even listeners
				$.removeEventListener('keydown', keydown, false);
				$.removeEventListener('keyup', keyup, false);
			}
			keyboardInitialized = enable;
		};

		/* ---

			prevent event propagation

			---*/
		function preventDefault(e) {
			e.stopPropagation();
			if (e.preventDefault)
				e.preventDefault();
			e.returnValue = false;
			// this is apprently needed on some platforms
			e.cancelBubble = true;
		};

		/* ---

			key down event

			---	*/
		/*
		function dispatchEvent (e)
		{
			var action = KeyBinding[e.keyCode || e.which];

			if(action)
			{
				console.log(e);
				if ((e.type === "keydown")&&(!keyLocked[action]))
				{
						keyStatus[action] = true;
						// lock the key if requested
						keyLocked[action] = keyLock[action];
				}
				else if(e.type === "keyup")
				{
					keyStatus[action] = false;
					keyLocked[action] = false;
				}
			}
			// prevent event propagation
			preventDefault(event);
			return false;
		};
		 */

		function keydown(e) {

			var action = KeyBinding[e.keyCode || e.which];

			if (action) {
				//console.log(e, action);

				//console.log(action);
				if (!keyLocked[action]) {
					keyStatus[action] = true;
					// lock the key if requested
					keyLocked[action] = keyLock[action];
				}
				// prevent event propagation
				preventDefault(e);
				return false;
			}
			return true;
		}
		;

		/* ---

			key up event

			---	*/
		function keyup(e) {

			var action = KeyBinding[e.keyCode || e.which];

			//console.log(e, action);

			if (action) {

				keyStatus[action] = false;
				keyLocked[action] = false;
				// prevent the event propagation
				preventDefault(e);
				return false;
			}
			return true;

		}

		/* ---

			 translate Mouse Coordinates

			---								*/
		function updateMouseCoords(x, y) {
			obj.mouse.pos.set(x,y);
			obj.mouse.pos.sub(obj.mouse.offset);
			return obj.mouse.pos;
		};

		/* ---

			 mouse event management (click)

			---										*/
		function onMouseMove(e) {
			// update mouse position
			updateMouseCoords(e.pageX, e.pageY);
		};

		/* ---

			 mouse event management (click)

			---										*/
		function onMouseEvent(e) {
			// propagate the event to the callback with x,y coords
			mouseEventCB(obj.mouse.pos);
		};

		/* ---

				 event management (Gyroscopic)

				---										*/
		function onGyroEvent(event) {
			// http://www.mobilexweb.com/samples/ball.html
			// http://www.mobilexweb.com/blog/safari-ios-accelerometer-websockets-html5
			//
			// ax = event.accelerationIncludingGravity.x;
			// ay = event.accelerationIncludingGravity.y;

			// use acceleration instead on iphone4
			// event.accelerationIncludingGravity.x
			// event.accelerationIncludingGravity.y
			// event.accelerationIncludingGravity.z

			// Gyroscope
			// window.ondeviceorientation = function(event) {
			// event.alpha
			// event.beta
			// event.gamma
			//}
		}
		;

		/*---------------------------------------------

			PUBLIC STUFF

		  ---------------------------------------------*/

		obj.mouse = {
			pos : null,
			offset : null
		}

		/**
		 * list of mappable keys :
		 * LEFT, UP, RIGHT, DOWN, ENTER, SHIFT, CTRL, ALT, PAUSE, ESC, ESCAPE, [0..9], [A..Z]
		 * @public
		 * @enum {number}
		 * @name me.input#KEY
		 */
		obj.KEY = {
			'LEFT' : 37,
			'UP' : 38,
			'RIGHT' : 39,
			'DOWN' : 40,
			'ENTER' : 13,
			'SHIFT' : 16,
			'CTRL' : 17,
			'ALT' : 18,
			'PAUSE' : 19,
			'ESC' : 27,
			'SPACE' : 32,
			'NUM0' : 48,
			'NUM1' : 49,
			'NUM2' : 50,
			'NUM3' : 51,
			'NUM4' : 52,
			'NUM5' : 53,
			'NUM6' : 54,
			'NUM7' : 55,
			'NUM8' : 56,
			'NUM9' : 57,
			'A' : 65,
			'B' : 66,
			'C' : 67,
			'D' : 68,
			'E' : 69,
			'F' : 70,
			'G' : 71,
			'H' : 72,
			'I' : 73,
			'J' : 74,
			'K' : 75,
			'L' : 76,
			'M' : 77,
			'N' : 78,
			'O' : 79,
			'P' : 80,
			'Q' : 81,
			'R' : 82,
			'S' : 83,
			'T' : 84,
			'U' : 85,
			'V' : 86,
			'W' : 87,
			'X' : 88,
			'Y' : 89,
			'Z' : 90,
		};

		/**
		 * return the key press status of the specified action
		 * @name me.input#isKeyPressed
		 * @public
		 * @function
		 * @example
		 * if (me.input.isKeyPressed('left'))
		 * {
		 *    //do something
		 * }
		 * else if (me.input.isKeyPressed('right'))
		 * {
		 *    //do something else...
		 * }
		 *
		 */

		obj.isKeyPressed = function(action) {
			if (keyStatus[action]) {
				if (keyLock[action]) {
					keyLocked[action] = true;
					// "eat" the event
					keyStatus[action] = false;
				}
				return true;
			}
			return false;
		};

		/**
		 * return the key status of the specified action
		 * @name me.input#keyStatus
		 * @public
		 * @function
		 * @return {boolean} down (true) or up(false)
		 */

		obj.keyStatus = function(action) {
			return (keyLocked[action] === true) ? true : keyStatus[action];
		};

		/**
		 * associate a user defined action to a keycode
		 * @name me.input#bindKey
		 * @public
		 * @function
		 * @param {me.input#KEY} keycode
		 * @param {String} action user defined corresponding action
		 * @param {boolean} lock cancel the keypress event once read
		 * @example
		 * // enable the keyboard
		 * me.input.bindKey(me.input.KEY.LEFT,  "left");
		 * me.input.bindKey(me.input.KEY.RIGHT, "right");
		 * me.input.bindKey(me.input.KEY.X,     "jump", true);
		 */
		obj.bindKey = function(keycode, action, lock) {
			if (!keyboardInitialized)
				enableKeyboardEvent(true);

			KeyBinding[keycode] = action;

			keyLock[action] = lock ? lock : false;
			keyLocked[action] = false;
			//console.log(this);
		};

		/**
		 * unbind the defined keycode
		 * @name me.input#unbindKey
		 * @public
		 * @function
		 * @example
		 * me.input.unbindKey(me.input.KEY.LEFT);
		 */
		obj.unbindKey = function(keycode) {
			// clear the event status
			keyStatus[KeyBinding[keycode]] = false;
			keyLock[KeyBinding[keycode]] = false;
			// remove the key binding
			KeyBinding[keycode] = null;
		};

		/**
		 * enable mouse event
		 * @name me.input#enableMouseEvent
		 * @public
		 * @function
		 * @deprecated to be rewritten
		 */
		obj.enableMouseEvent = function(enable, callback) {
			if (enable) {
				// initialize mouse pos (0,0)
				obj.mouse.pos = new me.Vector2d(0,0);
				// get relative canvas position in the page
				obj.mouse.offset = me.video.getPos();
				// add a listener for the mouse
				me.video.getScreenCanvas().addEventListener('mousemove', onMouseMove, false);
				me.video.getScreenCanvas().addEventListener('click', onMouseEvent, false);

				// set the callback
				mouseEventCB = callback || me.game.mouseEvent.bind(me.game);
			} else {
				me.video.getScreenCanvas().removeEventListener('mousemove', onMouseMove, false);
				me.video.getScreenCanvas().removeEventListener('click', onMouseEvent, false);
			}
		};

		/**
		 * enable gyroscopic event (not implemented)
		 * @name me.input#enableGyroscopicEvent
		 * @public
		 * @function
		 */
		obj.enableGyroscopicEvent = function(enable, callback) {
			if ($.sys.gyro) {
				// add a listener for the mouse
				$.ondevicemotion = enable ? onGyroEvent : null;
				// set the callback
				gyroEventCB = enable ? callback : null;
			}

		};

		// return our object
		return obj;

	})();

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
<commit_msg>Revert "Fixed wrong mouse position detection (#Issue 43)"<commit_after>/*
 * MelonJS Game Engine
 * Copyright (C) 2012, Olivier BIOT
 * http://www.melonjs.org
 *
 */

(function($, undefined) {

	/**
	 * There is no constructor function for me.input.
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */
	me.input = (function() {

		// hold public stuff in our singletong
		var obj = {};

		/*---------------------------------------------

			PRIVATE STUFF

		  ---------------------------------------------*/

		// list of binded keys
		var KeyBinding = [];

		// corresponding actions
		var keyStatus = [];

		// lock enable flag for keys
		var keyLock = [];
		// actual lock status of each key
		var keyLocked = [];

		// callback function for mouse & gyro
		var mouseEventCB = null;
		var gyroEventCB = null;

		// some usefull flags
		var keyboardInitialized = false;

		/*---

			enable keyboard event

			---*/
		function enableKeyboardEvent(enable) {
			if (enable) {
				// Event Management
				if (!keyboardInitialized) {
					$.addEventListener('keydown', keydown, false);
					$.addEventListener('keyup', keyup, false);
				}
			} else {
				// remove the even listeners
				$.removeEventListener('keydown', keydown, false);
				$.removeEventListener('keyup', keyup, false);
			}
			keyboardInitialized = enable;
		};

		/* ---

			prevent event propagation

			---*/
		function preventDefault(e) {
			e.stopPropagation();
			if (e.preventDefault)
				e.preventDefault();
			e.returnValue = false;
			// this is apprently needed on some platforms
			e.cancelBubble = true;
		};

		/* ---

			key down event

			---	*/
		/*
		function dispatchEvent (e)
		{
			var action = KeyBinding[e.keyCode || e.which];

			if(action)
			{
				console.log(e);
				if ((e.type === "keydown")&&(!keyLocked[action]))
				{
						keyStatus[action] = true;
						// lock the key if requested
						keyLocked[action] = keyLock[action];
				}
				else if(e.type === "keyup")
				{
					keyStatus[action] = false;
					keyLocked[action] = false;
				}
			}
			// prevent event propagation
			preventDefault(event);
			return false;
		};
		 */

		function keydown(e) {

			var action = KeyBinding[e.keyCode || e.which];

			if (action) {
				//console.log(e, action);

				//console.log(action);
				if (!keyLocked[action]) {
					keyStatus[action] = true;
					// lock the key if requested
					keyLocked[action] = keyLock[action];
				}
				// prevent event propagation
				preventDefault(e);
				return false;
			}
			return true;
		}
		;

		/* ---

			key up event

			---	*/
		function keyup(e) {

			var action = KeyBinding[e.keyCode || e.which];

			//console.log(e, action);

			if (action) {

				keyStatus[action] = false;
				keyLocked[action] = false;
				// prevent the event propagation
				preventDefault(e);
				return false;
			}
			return true;

		}

		/* ---

			 translate Mouse Coordinates

			---								*/
		function translateMouseCoords(x, y) {
			var canvas = me.video.getScreenCanvas();
			return new me.Vector2d(x + document.body.scrollLeft + document.documentElement.scrollLeft - ~~canvas.offsetLeft,
								   y + document.body.scrollTop + document.documentElement.scrollTop - ~~canvas.offsetTop + 1);
		};

		/* ---

			 mouse event management (click)

			---										*/
		function onMouseEvent(e) {
			// propagate the event to the callback with x,y coords
			mouseEventCB(translateMouseCoords(e.clientX, e.clientY));
		};

		/* ---

				 event management (Gyroscopic)

				---										*/
		function onGyroEvent(event) {
			// http://www.mobilexweb.com/samples/ball.html
			// http://www.mobilexweb.com/blog/safari-ios-accelerometer-websockets-html5
			//
			// ax = event.accelerationIncludingGravity.x;
			// ay = event.accelerationIncludingGravity.y;

			// use acceleration instead on iphone4
			// event.accelerationIncludingGravity.x
			// event.accelerationIncludingGravity.y
			// event.accelerationIncludingGravity.z

			// Gyroscope
			// window.ondeviceorientation = function(event) {
			// event.alpha
			// event.beta
			// event.gamma
			//}
		}
		;

		/*---------------------------------------------

			PUBLIC STUFF

		  ---------------------------------------------*/

		/**
		 * list of mappable keys :
		 * LEFT, UP, RIGHT, DOWN, ENTER, SHIFT, CTRL, ALT, PAUSE, ESC, ESCAPE, [0..9], [A..Z]
		 * @public
		 * @enum {number}
		 * @name me.input#KEY
		 */
		obj.KEY = {
			'LEFT' : 37,
			'UP' : 38,
			'RIGHT' : 39,
			'DOWN' : 40,
			'ENTER' : 13,
			'SHIFT' : 16,
			'CTRL' : 17,
			'ALT' : 18,
			'PAUSE' : 19,
			'ESC' : 27,
			'SPACE' : 32,
			'NUM0' : 48,
			'NUM1' : 49,
			'NUM2' : 50,
			'NUM3' : 51,
			'NUM4' : 52,
			'NUM5' : 53,
			'NUM6' : 54,
			'NUM7' : 55,
			'NUM8' : 56,
			'NUM9' : 57,
			'A' : 65,
			'B' : 66,
			'C' : 67,
			'D' : 68,
			'E' : 69,
			'F' : 70,
			'G' : 71,
			'H' : 72,
			'I' : 73,
			'J' : 74,
			'K' : 75,
			'L' : 76,
			'M' : 77,
			'N' : 78,
			'O' : 79,
			'P' : 80,
			'Q' : 81,
			'R' : 82,
			'S' : 83,
			'T' : 84,
			'U' : 85,
			'V' : 86,
			'W' : 87,
			'X' : 88,
			'Y' : 89,
			'Z' : 90,
		};

		/**
		 * return the key press status of the specified action
		 * @name me.input#isKeyPressed
		 * @public
		 * @function
		 * @example
		 * if (me.input.isKeyPressed('left'))
		 * {
		 *    //do something
		 * }
		 * else if (me.input.isKeyPressed('right'))
		 * {
		 *    //do something else...
		 * }
		 *
		 */

		obj.isKeyPressed = function(action) {
			if (keyStatus[action]) {
				if (keyLock[action]) {
					keyLocked[action] = true;
					// "eat" the event
					keyStatus[action] = false;
				}
				return true;
			}
			return false;
		};

		/**
		 * return the key status of the specified action
		 * @name me.input#keyStatus
		 * @public
		 * @function
		 * @return {boolean} down (true) or up(false)
		 */

		obj.keyStatus = function(action) {
			return (keyLocked[action] === true) ? true : keyStatus[action];
		};

		/**
		 * associate a user defined action to a keycode
		 * @name me.input#bindKey
		 * @public
		 * @function
		 * @param {me.input#KEY} keycode
		 * @param {String} action user defined corresponding action
		 * @param {boolean} lock cancel the keypress event once read
		 * @example
		 * // enable the keyboard
		 * me.input.bindKey(me.input.KEY.LEFT,  "left");
		 * me.input.bindKey(me.input.KEY.RIGHT, "right");
		 * me.input.bindKey(me.input.KEY.X,     "jump", true);
		 */
		obj.bindKey = function(keycode, action, lock) {
			if (!keyboardInitialized)
				enableKeyboardEvent(true);

			KeyBinding[keycode] = action;

			keyLock[action] = lock ? lock : false;
			keyLocked[action] = false;
			//console.log(this);
		};

		/**
		 * unbind the defined keycode
		 * @name me.input#unbindKey
		 * @public
		 * @function
		 * @example
		 * me.input.unbindKey(me.input.KEY.LEFT);
		 */
		obj.unbindKey = function(keycode) {
			// clear the event status
			keyStatus[KeyBinding[keycode]] = false;
			keyLock[KeyBinding[keycode]] = false;
			// remove the key binding
			KeyBinding[keycode] = null;
		};

		/**
		 * enable mouse event
		 * @name me.input#enableMouseEvent
		 * @public
		 * @function
		 * @deprecated to be rewritten
		 */
		obj.enableMouseEvent = function(enable, callback) {
			if (enable) {
				// add a listener for the mouse
				me.video.getScreenCanvas().addEventListener('click', onMouseEvent, false);
				// set the callback
				mouseEventCB = callback || me.game.mouseEvent.bind(me.game);
			} else {
				me.video.getScreenCanvas().removeEventListener('click', onMouseEvent, false);
			}
		};

		/**
		 * enable gyroscopic event (not implemented)
		 * @name me.input#enableGyroscopicEvent
		 * @public
		 * @function
		 */
		obj.enableGyroscopicEvent = function(enable, callback) {
			if ($.sys.gyro) {
				// add a listener for the mouse
				$.ondevicemotion = enable ? onGyroEvent : null;
				// set the callback
				gyroEventCB = enable ? callback : null;
			}

		};

		// return our object
		return obj;

	})();

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
<|endoftext|>


<commit_before>var fs = require("fs");

function main() {
    try {
        fs.readFile(process.argv[2], function (err, data) {
            if (err) {
                throw err
            } else {
                fs.writeFile(process.argv[2] + ".base64", new Buffer(data, 'binary').toString('base64'), function (err) {
                    if (err) {
                        throw err;
                    } else {
                        return;
                    }
                });
            }
        });
    } catch (e) {
        console.log(e);
    }
};

main();<commit_msg>Encoding and decoding<commit_after>var fs = require("fs");

function main() {
    try {
        switch (process.argv[2]) {
            case "encode":
                console.log("Encoding " + process.argv[3] + " to base64.");
                fs.readFile(process.argv[3], function (err, data) {
                    if (err) {
                        throw err
                    } else {
                        fs.writeFile(process.argv[3] + ".base64", new Buffer(data, 'binary').toString('base64'), function (err) {
                            if (err) {
                                throw err;
                            } else {
                                return;
                            }
                        });
                    }
                });
                console.log("Done! Encoded file: " + process.argv[3] + ".base64");
                break;
            case "decode":
                console.log("Decoding " + process.argv[3] + " to binary.");
                fs.readFile(process.argv[3], function (err, data) {
                    if (err) {
                        throw err
                    } else {
                        fs.writeFile(process.argv[3] + ".bin", new Buffer(data, 'base64').toString('binary'), function (err) {
                            if (err) {
                                throw err;
                            } else {
                                return;
                            }
                        });
                    }
                });
                console.log("Done! Decoded file: " + process.argv[3] + ".bin");
                break;
            default:
                console.log("Sup Laaawl!");
                console.log("Usage");
                console.log("node b64.js encode/decode some/path/to.file");
                break;
        }
    } catch (e) {
        console.log(e);
    }
};

main();<|endoftext|>


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

(function ($) {
	$.fn.teddybar = function (options) {
		var config = {
			document : function () { return document.getElementById('iframe').contentWindow.document },
			menu : {
				'Gras': 'bold',
				'Italique': 'italic',
				'Souligner': 'underline',
				'Barrer': 'strikethrough',
				'-1': null,
				'Police': ['fontname', {'- Police -': '0','Serif': 'serif', 'Sans-serif': 'sans-serif','Courier': 'courier new'}],
				'Taille': ['fontsize', {'- Taille -': '0','1 (8pt)': '1', '2 (10pt)': '2','3 (12pt)': '3','4 (14pt)': '4','5 (18pt)': '5','6 (24pt)': '6','7 (36pt)': '7'}],
				'Format': ['formatblock', {'- Format -': '0','Titre 1': 'h1','Titre 2': 'h2','Titre 3': 'h3','Titre 4': 'h4','Titre 5': 'h5','Titre 6': 'h6','Paragraphe': 'p','Preformaté': 'pre'}],
				'-2': null,
				'Liste numerotée': 'insertorderedlist',
				'Liste': 'insertunorderedlist',
				'-3': null,
				'Aligner à gauche': 'justifyleft',
				'Aligner à droite': 'justifyright',
				'Centrer': 'justifycenter',
				'Justifier': 'justifyfull',
				'-4': null,
				'Annuler': 'undo',
				'Refaire': 'redo',
                '-5': null,
                'Enregistrer le document': 'save',
                'Enregistrer le document avec un message': 'save_as',
                'Générer le PDF': 'pdf',
                '-6': null,
                'Options': 'settings'
			}
		};
        if (options) {
		        $.extend(true, config, options);
        }
		return this.each(function () {
			var $this=$(this);
			var block = $('<ul>').appendTo($this);
			$.each(config.menu, function (name, command) {
				if (command == null) {
					// make a separator
					block = $('<ul>').appendTo($this);
				} else if (typeof command == 'string') {
					// make a button
					$('<input>', {"title": name, "type": "button", "value": name, "class": command, "data-command": command}).appendTo(block).wrap('<li>');
				} else {
					// make a select
					$('<select>', {"title": name, "data-command": command[0]}).appendTo(block).wrap('<li>');
					$.each(command[1], function(label, value) {
						$('select[data-command='+command[0]+']').append($('<option>', {"value":value}).html(label));
					});
				}
			});

			// execCommand on select elements
			$('select').change(function() {
				var command = $(this).attr('data-command');
				var value = $(this).val();
				if (command in config.commands) {
					config.commands[command](value);
				} else {
					config.document().execCommand(command,false,value);
				}
			});

			// execCommand on input elements
			$('input[type=button]').on('click', function () {
				var command = $(this).attr('data-command');
				if (command in config.commands) {
					config.commands[command]();
				} else {
					config.document().execCommand(command,false,'');
				}
			});
		});
	};
})(jQuery);
<commit_msg>Try firefox hack for Teddybar<commit_after>// Copyright (C) 2012 Kozea
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

(function ($) {
	$.fn.teddybar = function (options) {
		var config = {
			document : function () { return document.getElementById('iframe').contentWindow.document },
			menu : {
				'Gras': 'bold',
				'Italique': 'italic',
				'Souligner': 'underline',
				'Barrer': 'strikethrough',
				'-1': null,
				'Police': ['fontname', {'- Police -': '0','Serif': 'serif', 'Sans-serif': 'sans-serif','Courier': 'courier new'}],
				'Taille': ['fontsize', {'- Taille -': '0','1 (8pt)': '1', '2 (10pt)': '2','3 (12pt)': '3','4 (14pt)': '4','5 (18pt)': '5','6 (24pt)': '6','7 (36pt)': '7'}],
				'Format': ['formatblock', {'- Format -': '0','Titre 1': 'h1','Titre 2': 'h2','Titre 3': 'h3','Titre 4': 'h4','Titre 5': 'h5','Titre 6': 'h6','Paragraphe': 'p','Preformaté': 'pre'}],
				'-2': null,
				'Liste numerotée': 'insertorderedlist',
				'Liste': 'insertunorderedlist',
				'-3': null,
				'Aligner à gauche': 'justifyleft',
				'Aligner à droite': 'justifyright',
				'Centrer': 'justifycenter',
				'Justifier': 'justifyfull',
				'-4': null,
				'Annuler': 'undo',
				'Refaire': 'redo',
                '-5': null,
                'Enregistrer le document': 'save',
                'Enregistrer le document avec un message': 'save_as',
                'Générer le PDF': 'pdf',
                '-6': null,
                'Options': 'settings'
			}
		};
        if (options) {
		        $.extend(true, config, options);
        }
		return this.each(function () {
			var $this=$(this);
			var block = $('<ul>').appendTo($this);
			$.each(config.menu, function (name, command) {
				if (command == null) {
					// make a separator
					block = $('<ul>').appendTo($this);
				} else if (typeof command == 'string') {
					// make a button
					$('<input>', {"title": name, "type": "button", "value": name, "class": command, "data-command": command}).appendTo(block).wrap('<li>');
				} else {
					// make a select
					$('<select>', {"title": name, "data-command": command[0]}).appendTo(block).wrap('<li>');
					$.each(command[1], function(label, value) {
						$('select[data-command='+command[0]+']').append($('<option>', {"value":value}).html(label));
					});
				}
			});

			// execCommand on select elements
			$('select').change(function() {
				var command = $(this).attr('data-command');
				var value = $(this).val();
				if (command in config.commands) {
					config.commands[command](value);
				} else {
                    try { config.document().designMode = "on"; }
                    catch(e) { }
                    try {
                        config.document().execCommand("styleWithCSS", 0, false);
                    } catch (e) {
                        try {
                            config.document().execCommand("useCSS", 0, true);
                        } catch (e) {
                            try {
                                config.document().execCommand('styleWithCSS', false, false);
                            }
                            catch (e) {
                            }
                        }
                    }
					config.document().execCommand(command,false,value);
				}
			});

			// execCommand on input elements
			$('input[type=button]').on('click', function () {
				var command = $(this).attr('data-command');
				if (command in config.commands) {
					config.commands[command]();
				} else {
                    try { config.document().designMode = "on"; }
                    catch(e) { }
                    try {
                        config.document().execCommand("styleWithCSS", 0, false);
                    } catch (e) {
                        try {
                            config.document().execCommand("useCSS", 0, true);
                        } catch (e) {
                            try {
                                config.document().execCommand('styleWithCSS', false, false);
                            }
                            catch (e) {
                            }
                        }
                    }
					config.document().execCommand(command,false,'');
				}
			});
		});
	};
})(jQuery);
<|endoftext|>