<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

/*global Windows:true */

var cordova = require('cordova'),
    Media = require('cordova-plugin-media.Media');

var MediaError = require('cordova-plugin-media.MediaError');

var recordedFile;

module.exports = {
    mediaCaptureMrg:null,

    // Initiates the audio file
    create:function(win, lose, args) {
        var id = args[0];
        var src = args[1];
        var thisM = Media.get(id);
        Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STARTING);

        Media.prototype.node = null;

        var fn = src.split('.').pop(); // gets the file extension
        if (thisM.node === null) {
            if (fn === 'mp3' || fn === 'wma' || fn === 'wav' ||
                fn === 'cda' || fn === 'adx' || fn === 'wm' ||
                fn === 'm3u' || fn === 'wmx' || fn === 'm4a') {
                thisM.node = new Audio(src);
                thisM.node.load();

                var getDuration = function () {
                    var dur = thisM.node.duration;
                    if (isNaN(dur)) {
                        dur = -1;
                    }
                    Media.onStatus(id, Media.MEDIA_DURATION, dur);
                };

                thisM.node.onloadedmetadata = getDuration;
                getDuration();
            }
            else {
                lose && lose({ code: MediaError.MEDIA_ERR_ABORTED });
                return false; // unable to create
            }
        }

        return true; // successfully created
    },

    // Start playing the audio
    startPlayingAudio:function(win, lose, args) {
        var id = args[0];
        //var src = args[1];
        //var options = args[2];

        var thisM = Media.get(id);
        // if Media was released, then node will be null and we need to create it again
        if (!thisM.node) {
            if (!module.exports.create(win, lose, args)) {
                // there is no reason to continue if we can't create media
                // corresponding callback has been invoked in create so we don't need to call it here
                return;
            }
        }

        try {
            thisM.node.play();
            Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);
        } catch (err) {
            lose && lose({code:MediaError.MEDIA_ERR_ABORTED});
        }
    },

    // Stops the playing audio
    stopPlayingAudio:function(win, lose, args) {
        var id = args[0];
        try {
            var thisM = Media.get(id);
            thisM.node.pause();
            if (thisM.node.currentTime != 0) {
                // prevents failing w/ InvalidStateError if playback has not started
                thisM.node.currentTime = 0;
            }
            Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);
            win();
        } catch (err) {
            lose("Failed to stop: "+err);
        }
    },

    // Seeks to the position in the audio
    seekToAudio:function(win, lose, args) {
        var id = args[0];
        var milliseconds = args[1];
        try {
            (Media.get(id)).node.currentTime = milliseconds / 1000;
            win();
        } catch (err) {
            lose("Failed to seek: "+err);
        }
    },

    // Pauses the playing audio
    pausePlayingAudio:function(win, lose, args) {
        var id = args[0];
        var thisM = Media.get(id);
        try {
            thisM.node.pause();
            Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_PAUSED);
        } catch (err) {
            lose("Failed to pause: "+err);
        }
    },

    // Gets current position in the audio
    getCurrentPositionAudio:function(win, lose, args) {
        var id = args[0];
        try {
            var p = (Media.get(id)).node.currentTime;
            Media.onStatus(id, Media.MEDIA_POSITION, p);
            win(p);
        } catch (err) {
            lose(err);
        }
    },

    // Start recording audio
    startRecordingAudio:function(win, lose, args) {
        var id = args[0];
        var src = args[1];

        var normalizedSrc = src.replace(/\//g, '\\');
        var destPath = normalizedSrc.substr(0, normalizedSrc.lastIndexOf('\\'));
        var destFileName = normalizedSrc.replace(destPath + '\\', '');

        // Initialize device
        Media.prototype.mediaCaptureMgr = null;
        var thisM = (Media.get(id));
        var captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
        captureInitSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.audio;
        thisM.mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
        thisM.mediaCaptureMgr.addEventListener("failed", lose);

        thisM.mediaCaptureMgr.initializeAsync(captureInitSettings).done(function (result) {
            thisM.mediaCaptureMgr.addEventListener("recordlimitationexceeded", lose);
            thisM.mediaCaptureMgr.addEventListener("failed", lose);

            // Start recording
            Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync(destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(function (newFile) {
                recordedFile = newFile;
                var encodingProfile = null;
                switch (newFile.fileType) {
                    case '.m4a':
                        encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createM4a(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
                        break;
                    case '.mp3':
                        encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp3(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
                        break;
                    case '.wma':
                        encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createWma(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
                        break;
                    default:
                        lose("Invalid file type for record");
                        break;
                }
                thisM.mediaCaptureMgr.startRecordToStorageFileAsync(encodingProfile, newFile).done(win, lose);
            }, lose);
        }, lose);
    },

    // Stop recording audio
    stopRecordingAudio:function(win, lose, args) {
        var id = args[0];
        var thisM = Media.get(id);

        var normalizedSrc = thisM.src.replace(/\//g, '\\');
        var destPath = normalizedSrc.substr(0, normalizedSrc.lastIndexOf('\\'));
        var destFileName = normalizedSrc.replace(destPath + '\\', '');

        thisM.mediaCaptureMgr.stopRecordAsync().done(function () {
            if (destPath) {
                Windows.Storage.StorageFolder.getFolderFromPathAsync(destPath).done(function(destFolder) {
                    recordedFile.copyAsync(destFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(win, lose);
                }, lose);
            } else {
                // if path is not defined, we leave recorded file in temporary folder (similar to iOS)
                win();
            }
        }, lose);
    },

    // Release the media object
    release:function(win, lose, args) {
        var id = args[0];
        var thisM = Media.get(id);
        try {
            if (thisM.node) {
                thisM.node.onloadedmetadata = null;
                delete thisM.node;
            }
        } catch (err) {
            lose("Failed to release: "+err);
        }
    },
    setVolume:function(win, lose, args) {
        var id = args[0];
        var volume = args[1];
        var thisM = Media.get(id);
        thisM.volume = volume;
    }
};

require("cordova/exec/proxy").add("Media",module.exports);
<commit_msg>CB-8888 Makes media status reporting on windows more precise<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

/*global Windows:true */

var Media = require('cordova-plugin-media.Media');
var MediaError = require('cordova-plugin-media.MediaError');

var recordedFile;

module.exports = {
    mediaCaptureMrg:null,

    // Initiates the audio file
    create:function(win, lose, args) {
        var id = args[0];
        var src = args[1];
        var thisM = Media.get(id);

        Media.prototype.node = null;

        var fn = src.split('.').pop(); // gets the file extension
        if (thisM.node === null) {
            if (fn === 'mp3' || fn === 'wma' || fn === 'wav' ||
                fn === 'cda' || fn === 'adx' || fn === 'wm' ||
                fn === 'm3u' || fn === 'wmx' || fn === 'm4a') {
                thisM.node = new Audio(src);

                thisM.node.onloadstart = function () {
                    Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STARTING);
                };

                thisM.node.ontimeupdate = function (e) {
                    Media.onStatus(id, Media.MEDIA_POSITION, e.target.currentTime);
                };

                thisM.node.onplaying = function () {
                    Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);
                };

                thisM.node.ondurationchange = function (e) {
                    Media.onStatus(id, Media.MEDIA_DURATION, e.target.duration || -1);
                };

                thisM.node.onerror = function(e) {
                    // Due to media.spec.15 It should return MediaError for bad filename
                    var err = e.target.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED ?
                        { code: MediaError.MEDIA_ERR_ABORTED } :
                        e.target.error;

                    Media.onStatus(id, Media.MEDIA_ERROR, err);
                };

                thisM.node.onended = function () {
                    Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);
                };

            } else {
                lose && lose({ code: MediaError.MEDIA_ERR_ABORTED });
                return false; // unable to create
            }
        }

        return true; // successfully created
    },

    // Start playing the audio
    startPlayingAudio:function(win, lose, args) {
        var id = args[0];
        //var src = args[1];
        //var options = args[2];

        var thisM = Media.get(id);
        // if Media was released, then node will be null and we need to create it again
        if (!thisM.node) {
            if (!module.exports.create(win, lose, args)) {
                // there is no reason to continue if we can't create media
                // corresponding callback has been invoked in create so we don't need to call it here
                return;
            }
        }

        try {
            thisM.node.play();
        } catch (err) {
            lose && lose({code:MediaError.MEDIA_ERR_ABORTED});
        }
    },

    // Stops the playing audio
    stopPlayingAudio:function(win, lose, args) {
        var id = args[0];
        try {
            var thisM = Media.get(id);
            thisM.node.pause();
            thisM.node.currentTime = 0;
            Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);
        } catch (err) {
            lose("Failed to stop: "+err);
        }
    },

    // Seeks to the position in the audio
    seekToAudio:function(win, lose, args) {
        var id = args[0];
        var milliseconds = args[1];
        var thisM = Media.get(id);
        try {
            thisM.node.currentTime = milliseconds / 1000;
            win(thisM.node.currentTime);
        } catch (err) {
            lose("Failed to seek: "+err);
        }
    },

    // Pauses the playing audio
    pausePlayingAudio:function(win, lose, args) {
        var id = args[0];
        var thisM = Media.get(id);
        try {
            thisM.node.pause();
            Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_PAUSED);
        } catch (err) {
            lose("Failed to pause: "+err);
        }
    },

    // Gets current position in the audio
    getCurrentPositionAudio:function(win, lose, args) {
        var id = args[0];
        try {
            var p = (Media.get(id)).node.currentTime;
            win(p);
        } catch (err) {
            lose(err);
        }
    },

    // Start recording audio
    startRecordingAudio:function(win, lose, args) {
        var id = args[0];
        var src = args[1];

        var normalizedSrc = src.replace(/\//g, '\\');
        var destPath = normalizedSrc.substr(0, normalizedSrc.lastIndexOf('\\'));
        var destFileName = normalizedSrc.replace(destPath + '\\', '');

        // Initialize device
        Media.prototype.mediaCaptureMgr = null;
        var thisM = (Media.get(id));
        var captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
        captureInitSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.audio;
        thisM.mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
        thisM.mediaCaptureMgr.addEventListener("failed", lose);

        thisM.mediaCaptureMgr.initializeAsync(captureInitSettings).done(function (result) {
            thisM.mediaCaptureMgr.addEventListener("recordlimitationexceeded", lose);
            thisM.mediaCaptureMgr.addEventListener("failed", lose);

            // Start recording
            Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync(destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(function (newFile) {
                recordedFile = newFile;
                var encodingProfile = null;
                switch (newFile.fileType) {
                    case '.m4a':
                        encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createM4a(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
                        break;
                    case '.mp3':
                        encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp3(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
                        break;
                    case '.wma':
                        encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createWma(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
                        break;
                    default:
                        lose("Invalid file type for record");
                        break;
                }
                thisM.mediaCaptureMgr.startRecordToStorageFileAsync(encodingProfile, newFile).done(win, lose);
            }, lose);
        }, lose);
    },

    // Stop recording audio
    stopRecordingAudio:function(win, lose, args) {
        var id = args[0];
        var thisM = Media.get(id);

        var normalizedSrc = thisM.src.replace(/\//g, '\\');
        var destPath = normalizedSrc.substr(0, normalizedSrc.lastIndexOf('\\'));
        var destFileName = normalizedSrc.replace(destPath + '\\', '');

        thisM.mediaCaptureMgr.stopRecordAsync().done(function () {
            if (destPath) {
                Windows.Storage.StorageFolder.getFolderFromPathAsync(destPath).done(function(destFolder) {
                    recordedFile.copyAsync(destFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(win, lose);
                }, lose);
            } else {
                // if path is not defined, we leave recorded file in temporary folder (similar to iOS)
                win();
            }
        }, lose);
    },

    // Release the media object
    release:function(win, lose, args) {
        var id = args[0];
        var thisM = Media.get(id);
        try {
            if (thisM.node) {
                thisM.node.onloadedmetadata = null;
                delete thisM.node;
            }
        } catch (err) {
            lose("Failed to release: "+err);
        }
    },
    setVolume:function(win, lose, args) {
        var id = args[0];
        var volume = args[1];
        var thisM = Media.get(id);
        thisM.volume = volume;
    }
};

require("cordova/exec/proxy").add("Media",module.exports);
<|endoftext|>


<commit_before>import { ELEMENTS_SERVER } from './constants';

/**
 * Hides <default-content> elements by injecting a style tag into the head
 * @return {undefined}
 */
export function hideDefaultContent() {
  let style = document.createElement('style');
  style.innerHTML = 'default-content { display: none; }';
  document.head.appendChild(style);
}

/**
 * Ready web components in the browser. If webcomponents are natively supported
 * 	it will do nothing, otherwise it will load in the webcomponents polyfills
 * @return {Promise}  Promise which resolves once web components is definitely ready
 */
export function readyWebComponents() {
  // Conditionally load WCjs
  const webComponentsSupported =
      'registerElement' in document &&
      'import' in document.createElement('link') &&
      'content' in document.createElement('template');

  if (webComponentsSupported) {
    return Promise.resolve();
  }

  /**
   * Load in web components polyfill
   * @return {Promise} Promise which resolves once finished
   */
  return new Promise(resolve => {
    let script = document.createElement('script');
    script.async = true;
    script.src = `${ELEMENTS_SERVER}/webcomponentsjs/webcomponents-lite.min.js`;
    script.onload = resolve;
    document.head.appendChild(script);
  });
};

/**
 * Configure Polymer with dom = shadow, unless Polymer is already defined
 * @return {undefined}
 */
export function configurePolymer() {
  window.Polymer = window.Polymer || { dom: 'shadow' };
}
<commit_msg>move deprecation functions to utils<commit_after>import { ELEMENTS_SERVER } from './constants';

/**
 * Hides <default-content> elements by injecting a style tag into the head
 * @return {undefined}
 */
export function hideDefaultContent() {
  let style = document.createElement('style');
  style.innerHTML = 'default-content { display: none; }';
  document.head.appendChild(style);
}

/**
 * Ready web components in the browser. If webcomponents are natively supported
 * 	it will do nothing, otherwise it will load in the webcomponents polyfills
 * @return {Promise}  Promise which resolves once web components is definitely ready
 */
export function readyWebComponents() {
  // Conditionally load WCjs
  const webComponentsSupported =
      'registerElement' in document &&
      'import' in document.createElement('link') &&
      'content' in document.createElement('template');

  if (webComponentsSupported) {
    return Promise.resolve();
  }

  /**
   * Load in web components polyfill
   * @return {Promise} Promise which resolves once finished
   */
  return new Promise(resolve => {
    let script = document.createElement('script');
    script.async = true;
    script.src = `${ELEMENTS_SERVER}/webcomponentsjs/webcomponents-lite.min.js`;
    script.onload = resolve;
    document.head.appendChild(script);
  });
};

/**
 * Configure Polymer with dom = shadow, unless Polymer is already defined
 * @return {undefined}
 */
export function configurePolymer() {
  window.Polymer = window.Polymer || { dom: 'shadow' };
}

/**
 * NOTE: This is here purely for backwards compatibility, in future it should
 * 	be removed when possible
 * 	@return {undefined}
 */
export function supportDeprecatedInitializer(init) {
  let tag = document.querySelector('script[simpla-api]'),
      project = tag && tag.getAttribute('simpla-api');

  if (project) {
    console.warn(`The [simpla-api] attribute setup method is deprecated. Please use Simpla('${project}') instead, see https://www.simpla.io/docs/start`);
    init(project);
  }
}

/**
 * NOTE: Also for backwards compatibility. This below is a private API and can be
 * 	safely removed once all elements who depend on it are upgraded
 * 	@return {undefined}
 */
export function supportDeprecatedConfig(authEndpoint, project) {
  window.simpla = {
    config: {
      server: authEndpoint,
      api: project
    }
  };
}
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------- \\
// File: Stylesheet.js                                                        \\
// Module: DOM                                                                \\
// Requires: Core                                                             \\
// Author: Neil Jenkins                                                       \\
// License: © 2010–2012 Opera Software ASA. All rights reserved.              \\
// -------------------------------------------------------------------------- \\

/*global document */

"use strict";

( function ( NS ) {

NS.Stylesheet = {
    create: function ( id, data ) {
        var doc = document,
            head = doc.documentElement.firstChild,
            style = NS.Element.create( 'style', {
                type: 'text/css',
                id: id
            });

        if ( style.styleSheet ) {
            // IE8: must append to document BEFORE adding styles
            // or you get the IE7 CSS parser!
            head.appendChild( style );
            style.styleSheet.cssText = data;
        } else {
            // Everyone else
            style.appendChild( doc.createTextNode( data ) );
            head.appendChild( style );
        }
        return style;
    }
};

}( this.O ) );
<commit_msg>Add documentation for Stylesheet object.<commit_after>// -------------------------------------------------------------------------- \\
// File: Stylesheet.js                                                        \\
// Module: DOM                                                                \\
// Requires: Core, Element.js                                                 \\
// Author: Neil Jenkins                                                       \\
// License: © 2010–2012 Opera Software ASA. All rights reserved.              \\
// -------------------------------------------------------------------------- \\

/*global document */

"use strict";

( function ( NS ) {

/**
    Namespace: O.Stylesheet

    The O.Stylesheet namespace contains helper functions for dealing with CSS
    stylesheets.
*/
NS.Stylesheet = {
    /**
        Function: O.Stylesheet.create

        Injects CSS into the document by creating a new stylesheet and appending
        it to the document.

        Parameters:
            id  - {String} The id to give the node in the document.
            css - {String} The CSS to insert into the stylesheet.

        Returns:
            {Element} The <style> node that was created.
    */
    create: function ( id, css ) {
        var doc = document,
            head = doc.documentElement.firstChild,
            style = NS.Element.create( 'style', {
                type: 'text/css',
                id: id
            });

        if ( style.styleSheet ) {
            // IE8: must append to document BEFORE adding styles
            // or you get the IE7 CSS parser!
            head.appendChild( style );
            style.styleSheet.cssText = css;
        } else {
            // Everyone else
            style.appendChild( doc.createTextNode( css ) );
            head.appendChild( style );
        }
        return style;
    }
};

}( this.O ) );
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import moment from 'moment';
import Events from '../components/Events';

const mergeEventImages = (eventImage, companyEvent) => {
  const eventImages = [];
  // Event images
  if (eventImage) {
    eventImages.push(eventImage);
  }
  // Company images
  const companyImages = companyEvent.map(company => (
    company.company.image
  ));
  return [...eventImages, ...companyImages];
};

const apiEventsToEvents = event => ({
  eventUrl: `/events/${event.id}/${event.slug}`,
  ingress: event.ingress_short,
  startDate: event.event_start,
  title: event.title,
  images: mergeEventImages(event.image, event.company_event),
});

const sortEvents = (a, b) => {
  // checks if the event is starting today or ongoing
  if (moment().isAfter(a.event_start, 'day') && moment().isBefore(a.event_end)) {
    return 1;
  }
  // checks which event comes first
  if (moment(a.event_start).isBefore(b.event_start)) {
    return 1;
  }
  return -1;
};

class EventsContainer extends Component {
  constructor(props) {
    super(props);
    this.API_URL = `/api/v1/events/?event_end__gte=${moment().format('YYYY-MM-DD')}`;
    this.state = {
      events: [],
      showKurs: true,
      showBedpress: true,
      showSocial: true,
      showOther: true,
      socialEvents: [],
      bedpressEvents: [],
      kursEvents: [],
      otherEvents: [],
    };
    this.setEventVisibility = this.setEventVisibility.bind(this);
    this.getVisibleEvents = this.getVisibleEvents.bind(this);
    this.fetchEvents();
    this.eventTypes = [
      { id: 1, name: 'Sosialt', display: this.state.showSocial },
      { id: 2, name: 'Bedriftspresentasjon', display: this.state.showBedpress },
      { id: 3, name: 'Kurs', display: this.state.showKurs },
      { id: 4, name: 'Annet', display: this.state.showOther },
    ];
    this.eventTypes.forEach((eventType) => {
      this.fetchEventsByType(eventType.id);
    });
  }

  getVisibleEvents() {
    let visibleEvents = [];
    if (this.state.showSocial) {
      visibleEvents = visibleEvents.concat(this.state.socialEvents);
    }
    if (this.state.showBedpress) {
      visibleEvents = visibleEvents.concat(this.state.bedpressEvents);
    }
    if (this.state.showKurs) {
      visibleEvents = visibleEvents.concat(this.state.kursEvents);
    }
    if (this.state.showOther) {
      visibleEvents = visibleEvents.concat(this.state.otherEvents);
    }
    visibleEvents.sort(sortEvents);
    return visibleEvents;
  }

  setEventVisibility(e) {
    switch (e.eventType.id) {
      case 2:
        this.setState({
          showBedpress: !this.state.showBedpress,
        });
        break;
      case 3:
        this.setState({
          showKurs: !this.state.showKurs,
        });
        break;
      case 1:
        this.setState({
          showSocial: !this.state.showSocial,
        });
        break;
      case 4:
        this.setState({
          showOther: !this.state.showOther,
        });
        break;
      default:
        break;
    }
  }

  fetchEvents() {
    const apiUrl = `${this.API_URL}&format=json`;
    fetch(apiUrl)
    .then(response =>
       response.json(),
    ).then((json) => {
      this.visibleEvents = json.results;
      this.setState({
        events: json.results.map(apiEventsToEvents),
      });
    });
  }

  fetchEventsByType(eventType) {
    // problem: other, flere eventtyper
    const apiUrl = `${this.API_URL}&event_type=${eventType}&format=json`;
    fetch(apiUrl)
    .then(response =>
       response.json(),
    ).then((json) => {
      if (eventType === 1) {
        this.state.socialEvents = json.results.map(apiEventsToEvents);
      } else if (eventType === 2) {
        this.state.bedpressEvents = json.results.map(apiEventsToEvents);
      } else if (eventType === 3) {
        this.state.kursEvents = json.results.map(apiEventsToEvents);
      } else if (eventType > 3) {
        this.state.otherEvents = json.results.map(apiEventsToEvents);
      }
    }).catch((e) => {
      console.error('Failed to fetch events by type:', e);
    });
  }

  mainEvents() {
    return this.getVisibleEvents().slice(0, 2);
  }

  smallEvents() {
    return this.getVisibleEvents().slice(2, 10);
  }

  render() {
    return (
      <Events
        mainEvents={this.mainEvents()} smallEvents={this.smallEvents()}
        setEventVisibility={this.setEventVisibility}
        eventTypes={this.eventTypes}
      />
    );
  }
}

export default EventsContainer;
<commit_msg>Make loading of event types generic<commit_after>import React, { Component } from 'react';
import moment from 'moment';
import Events from '../components/Events';

const mergeEventImages = (eventImage, companyEvent) => {
  const eventImages = [];
  // Event images
  if (eventImage) {
    eventImages.push(eventImage);
  }
  // Company images
  const companyImages = companyEvent.map(company => (
    company.company.image
  ));
  return [...eventImages, ...companyImages];
};

const apiEventsToEvents = event => ({
  eventUrl: `/events/${event.id}/${event.slug}`,
  ingress: event.ingress_short,
  startDate: event.event_start,
  title: event.title,
  images: mergeEventImages(event.image, event.company_event),
});

const sortEvents = (a, b) => {
  // checks if the event is starting today or ongoing
  if (moment().isAfter(a.event_start, 'day') && moment().isBefore(a.event_end)) {
    return 1;
  }
  // checks which event comes first
  if (moment(a.event_start).isBefore(b.event_start)) {
    return 1;
  }
  return -1;
};

class EventsContainer extends Component {
  constructor(props) {
    super(props);
    this.API_URL = `/api/v1/events/?event_end__gte=${moment().format('YYYY-MM-DD')}`;
    this.state = {
      events: [],
      eventTypes: {
        1: { id: 1, name: 'Sosialt', display: true, events: [] },
        2: { id: 2, name: 'Bedriftspresentasjon', display: true, events: [] },
        3: { id: 3, name: 'Kurs', display: true, events: [] },
        4: { id: 4, name: 'Annet', display: true, events: [] },
      },
    };
    this.setEventVisibility = this.setEventVisibility.bind(this);
    this.getVisibleEvents = this.getVisibleEvents.bind(this);

    this.fetchEvents();
    // Loop over event types
    Object.keys(this.state.eventTypes).forEach((eventTypeId) => {
      const eventType = this.state.eventTypes[eventTypeId];
      this.fetchEventsByType(eventType.id);
    });
  }

  getVisibleEvents() {
    const { eventTypes } = this.state;
    const visibleEvents = Object.keys(eventTypes).reduce((events, eventTypeId) => {
      const eventType = eventTypes[eventTypeId];
      if (eventType.display) {
        return [...events, ...eventType.events];
      }
      return events;
    }, []);

    visibleEvents.sort(sortEvents);
    return visibleEvents;
  }

  setEventVisibility(e) {
    const eventTypeId = e.eventType.id;
    this.setState({
      eventTypes: Object.assign({}, this.state.eventTypes, {
        [eventTypeId]: Object.assign({}, e.eventType, {
          display: !e.eventType.display,
        }),
      }),
    });
  }

  getEventTypes() {
    const { eventTypes } = this.state;
    // Turn object into array
    return Object.keys(eventTypes).map(eventTypeId => (
      eventTypes[eventTypeId]
    ));
  }

  fetchEvents() {
    const apiUrl = `${this.API_URL}&format=json`;
    fetch(apiUrl)
    .then(response => response.json())
    .then((json) => {
      this.setState({
        events: json.results.map(apiEventsToEvents),
      });
    });
  }

  fetchEventsByType(eventType) {
    const apiUrl = `${this.API_URL}&event_type=${eventType}&format=json`;
    fetch(apiUrl)
    .then(response =>
       response.json(),
    ).then((json) => {
      const events = json.results.map(apiEventsToEvents);
      this.setState({
        eventTypes: Object.assign({}, this.state.eventTypes, {
          [eventType]: Object.assign({}, this.state.eventTypes[eventType], {
            events,
          }),
        }),
      });
    });
  }

  mainEvents() {
    return this.getVisibleEvents().slice(0, 2);
  }

  smallEvents() {
    return this.getVisibleEvents().slice(2, 10);
  }

  render() {
    return (
      <Events
        mainEvents={this.mainEvents()} smallEvents={this.smallEvents()}
        setEventVisibility={this.setEventVisibility}
        eventTypes={this.getEventTypes()}
      />
    );
  }
}

export default EventsContainer;
<|endoftext|>


<commit_before>export class BTDComponent {
  constructor(settings) {
    this.settings = settings;
  }
}
<commit_msg>:wrench:<commit_after>export class BTDComponent {
  constructor(settings) {
    if (!settings) {
      throw new Error('Please pass Better TweetDeck\'s settings to the constructor');
    }

    this.settings = settings;
  }
}
<|endoftext|>


<commit_before>// Load in dependencies
var childProcess = require('child_process');
var path = require('path');
var expect = require('chai').expect;
var sinon = require('sinon');
var wrench = require('wrench');
var Foundry = require('../bin/foundry');

// Stop exec calls from happening
var shell = require('shelljs');
var _exec = shell.exec;
shell.exec = function () {
  throw new Error('`shell.exec` was being called with ' + JSON.stringify(arguments));
};

// DEV: NEVER EVER RUN FOUNDRY VIA .exec
// DEV: WE CANNOT STOP .exec CALLS FROM OCCURRING IN ANOTHER PROCESS
// TODO: Strongly consider running tests within a Vagrant to prevent publication since nothing is configured

var tmp = shell.tempdir();
var fixtureDir = path.join(tmp, 'foundry_test');
before(function deleteFixtureDir (done) {
  wrench.rmdirRecursive(fixtureDir, false, function (err) {
    done();
  });
});
before(function createFixtureDir () {
  // DEV: There is no asynchronous flavor. We could use mkdirp but this is fine.
  wrench.mkdirSyncRecursive(fixtureDir);
});
before(function goToFixtureDir () {
  process.chdir(fixtureDir);
});

// TODO: Use this... similar to that of sexy-bash-prompt
function fixtureDir(name) {
  before(function copyFixtures (done) {

  });
  // TODO: Perform this
  // before(function moveDotgitToGit (done) {

  // });
}

function stubExec() {
  before(function stubExec () {
    this.execStub = sinon.stub(shell, 'exec', function () {
      return {};
    });
  });
  after(function () {
    this.execStub.restore();
  });
}

describe('A release', function () {
  describe('in a git folder', function () {
    before(function createGitFolder () {
      this.gitDir = path.join(fixtureDir, 'git_test');
      wrench.mkdirSyncRecursive(this.gitDir);
    });
    before(function initializeGitFolder (done) {
      var that = this;
      process.chdir(this.gitDir);
      childProcess.exec('git init', function (err, stdout, stderr) {
        that.stdout = stdout;
        done(err);
      });
    });
    stubExec();

    before(function release (done) {
      var program = new Foundry();
      program.parse(['node', '/usr/bin/foundry', 'release', '0.1.0']);
      // TODO: Figure out how to hook in better
      setTimeout(done, 1000);
    });

    it('adds a git tag', function () {
      // TODO: This does a very poor job of real world simulation. Use Vagrant
      // TODO: Inside of `npm test`, add a check for VAGRANT=TRUE || TRAVIS=TRUE. Otherwise, don't run.
      expect(this.execStub.args[0]).to.deep.equal(['git commit -a -m "Release 0.1.0"']);
      expect(this.execStub.args[1]).to.deep.equal(['git tag 0.1.0 -a -m "Release 0.1.0"']);
      expect(this.execStub.args[2]).to.deep.equal(['git push']);
      expect(this.execStub.args[3]).to.deep.equal(['git push --tags']);

      // childProcess.exec('git tag', function (err, stdout, stderr) {
      //   if (err) {
      //     return done(err);
      //   }
      //   expect(stdout).to.equal('0.1.0');
      // });
    });
  });
});
<commit_msg>Adding safeguard to childProcess.exec and spawn<commit_after>// Load in dependencies
var childProcess = require('child_process');
var path = require('path');
var expect = require('chai').expect;
var sinon = require('sinon');
var wrench = require('wrench');
var Foundry = require('../bin/foundry');

// Stop exec calls from happening
var shell = require('shelljs');
var _exec = shell.exec;
shell.exec = function () {
  throw new Error('`shell.exec` was being called with ' + JSON.stringify(arguments));
};

// Stop childProcess exec and spawn calls too unless people opt in to our methods
childProcess.iKnowWhatIAmDoingSpawn = childProcess.spawn;
childProcess.spawn = function () {
  throw new Error('`childProcess.spawn` was being called with ' + JSON.stringify(arguments));
};
childProcess.iKnowWhatIAmDoingExec = childProcess.exec;
childProcess.exec = function () {
  throw new Error('`childProcess.exec` was being called with ' + JSON.stringify(arguments));
};

// DEV: NEVER EVER RUN FOUNDRY VIA .exec
// DEV: WE CANNOT STOP .exec CALLS FROM OCCURRING IN ANOTHER PROCESS

var tmp = shell.tempdir();
var fixtureDir = path.join(tmp, 'foundry_test');
before(function deleteFixtureDir (done) {
  wrench.rmdirRecursive(fixtureDir, false, function (err) {
    done();
  });
});
before(function createFixtureDir () {
  // DEV: There is no asynchronous flavor. We could use mkdirp but this is fine.
  wrench.mkdirSyncRecursive(fixtureDir);
});
before(function goToFixtureDir () {
  process.chdir(fixtureDir);
});

// TODO: Use this... similar to that of sexy-bash-prompt
function fixtureDir(name) {
  before(function copyFixtures (done) {

  });
  // TODO: Perform this
  // before(function moveDotgitToGit (done) {

  // });
}

function stubExec() {
  before(function stubExec () {
    this.execStub = sinon.stub(shell, 'exec', function () {
      return {};
    });
  });
  after(function () {
    this.execStub.restore();
  });
}

describe('A release', function () {
  describe('in a git folder', function () {
    before(function createGitFolder () {
      this.gitDir = path.join(fixtureDir, 'git_test');
      wrench.mkdirSyncRecursive(this.gitDir);
    });
    before(function initializeGitFolder (done) {
      var that = this;
      process.chdir(this.gitDir);
      childProcess.iKnowWhatIAmDoingExec('git init', function (err, stdout, stderr) {
        that.stdout = stdout;
        done(err);
      });
    });
    stubExec();

    before(function release (done) {
      var program = new Foundry();
      program.parse(['node', '/usr/bin/foundry', 'release', '0.1.0']);
      // TODO: Figure out how to hook in better
      setTimeout(done, 1000);
    });

    it('adds a git tag', function () {
      expect(this.execStub.args[0]).to.deep.equal(['git commit -a -m "Release 0.1.0"']);
      expect(this.execStub.args[1]).to.deep.equal(['git tag 0.1.0 -a -m "Release 0.1.0"']);
      expect(this.execStub.args[2]).to.deep.equal(['git push']);
      expect(this.execStub.args[3]).to.deep.equal(['git push --tags']);

      // childProcess.exec('git tag', function (err, stdout, stderr) {
      //   if (err) {
      //     return done(err);
      //   }
      //   expect(stdout).to.equal('0.1.0');
      // });
    });
  });
});
<|endoftext|>


<commit_before>var _ = require('underscore');
var Backbone = require('backbone');
var WindshaftConfig = require('./config');
var log = require('../cdb.log');
var Request = require('./request');
var RequestTracker = require('./request-tracker');
var WindshaftError = require('./error');

/* The max number of times the same map can be instantiated */
var MAP_INSTANTIATION_LIMIT = 3;

var WindshaftMap = Backbone.Model.extend({
  initialize: function (attrs, options) {
    if (!options.client) {
      throw new Error('client option is required');
    }
    // TODO: We could use the layerGroupModel instead! Only contains layers of type 'CartoDB' and 'Torque'
    if (!options.layersCollection) {
      throw new Error('layersCollection option is required');
    }
    if (!options.dataviewsCollection) {
      throw new Error('dataviewsCollection option is required');
    }
    if (!options.analysisCollection) {
      throw new Error('analysisCollection option is required');
    }
    if (!options.modelUpdater) {
      throw new Error('modelUpdater option is required');
    }

    this.client = options.client;
    this.set({
      urlTemplate: this.client.urlTemplate,
      userName: this.client.userName
    });

    this._layersCollection = options.layersCollection;
    this._dataviewsCollection = options.dataviewsCollection;
    this._analysisCollection = options.analysisCollection;
    this._modelUpdater = options.modelUpdater;

    this._requestTracker = new RequestTracker(MAP_INSTANTIATION_LIMIT);
  },

  toJSON: function () {
    throw new Error('Subclasses of windshaft/map-base must implement .toJSON');
  },

  // TODO: Move this somewhere else and keep this class as a wrapper for windshaft responses
  createInstance: function (options) {
    options = options || {};

    try {
      var payload = this.toJSON();
      var params = this._getParams();

      var request = new Request(payload, params, options);
      if (this._canPerformRequest(request)) {
        this._performRequest(request);
      } else {
        log.error('Maximum number of subsequent equal requests to the Maps API reached (' + MAP_INSTANTIATION_LIMIT + '):', payload, params);
        options.error && options.error();
      }
    } catch (e) {
      var error = new WindshaftError({
        message: e.message
      });
      this._modelUpdater.setErrors([ error ]);

      log.error(e.message);
      options.error && options.error();
    }
  },

  _canPerformRequest: function (request) {
    return this._requestTracker.canRequestBePerformed(request);
  },

  _trackRequest: function (request, response) {
    this._requestTracker.track(request, response);
  },

  _performRequest: function (request) {
    var payload = request.payload;
    var params = request.params;
    var options = request.options;
    this.client.instantiateMap({
      mapDefinition: payload,
      params: params,
      success: function (response) {
        console.log(JSON.stringify(response.metadata.layers, null, 4));
        this._trackRequest(request, response);
        this.set(response);
        this._modelUpdater.updateModels(this, options.sourceId, options.forceFetch);
        this.trigger('instanceCreated');
        options.success && options.success(this);
      }.bind(this),
      error: function (response) {
        this._trackRequest(request, response);
        var windshaftErrors = this._getErrorsFromResponse(response);
        this._modelUpdater.setErrors(windshaftErrors);
        options.error && options.error();
      }.bind(this)
    });
  },

  _getErrorsFromResponse: function (response) {
    if (response.errors_with_context) {
      return _.map(response.errors_with_context, function (error) {
        return new WindshaftError(error);
      });
    }
    if (response.errors) {
      return [
        new WindshaftError({ message: response.errors[0] })
      ];
    }

    return [];
  },

  _getParams: function () {
    var params = {
      stat_tag: this.get('statTag')
    };

    if (this.get('apiKey')) {
      params.api_key = this.get('apiKey');
    } else if (this.get('authToken')) {
      params.auth_token = this.get('authToken');
    }

    var filters = this._getFilterParamFromDataviews();
    if (!_.isEmpty(filters)) {
      params.filters = filters;
    }

    return params;
  },

  _getFilterParamFromDataviews: function () {
    return this._dataviewsCollection.reduce(function (filters, dataview) {
      var filter = dataview.filter;
      if (filter && !filter.isEmpty()) {
        filters['dataviews'] = filters['dataviews'] || {};
        _.extend(filters['dataviews'], filter.toJSON());
      }
      return filters;
    }, {});
  },

  getBaseURL: function (subhost) {
    return [
      this._getHost(subhost),
      WindshaftConfig.MAPS_API_BASE_URL,
      this.get('layergroupid')
    ].join('/');
  },

  _getHost: function (subhost) {
    var userName = this.get('userName');
    var protocol = this._useHTTPS() ? 'https' : 'http';
    subhost = subhost ? subhost + '.' : '';
    var host = this.get('urlTemplate').replace('{user}', userName);
    var cdnHost = this.get('cdn_url') && this.get('cdn_url')[protocol];
    if (cdnHost) {
      host = [protocol, '://', subhost, cdnHost, '/', userName].join('');
    }

    return host;
  },

  _useHTTPS: function () {
    return this.get('urlTemplate').indexOf('https') === 0;
  },

  /**
   * Returns the indexes of the layer of a given type, as the tiler kwows it.
   *
   * @param {string|array} layerType - Type of layer
   */
  getLayerIndexesByType: function (layerType) {
    return _.reduce(this._getLayers(), function (layerIndexes, layer, index) {
      if (layer.type === layerType) {
        layerIndexes.push(index);
      }
      return layerIndexes;
    }, []);
  },

  getDataviewMetadata: function (dataviewId) {
    var dataviews = this._getDataviews();
    if (dataviews && dataviews[dataviewId]) {
      return dataviews[dataviewId];
    }

    // Try to get dataview's metatadta from the 'widgets' dictionary inside the metadata of each of the layers
    dataviews = {};
    var layersDataviews = _.compact(_.map(this._getLayers(), function (layer) { return layer.widgets; }));
    _.each(layersDataviews, function (layerDataviews) {
      _.extend(dataviews, layerDataviews);
    });

    if (dataviews && dataviews[dataviewId]) {
      return dataviews[dataviewId];
    }
  },

  getAnalysisNodeMetadata: function (analysisId) {
    var metadata = {};
    var nodes = _.map(this._getAnalyses(), function (analysis) {
      return analysis.nodes;
    });
    _.each(nodes, function (node) {
      _.extend(metadata, node);
    });

    return metadata[analysisId];
  },

  getSupportedSubdomains: function () {
    if (!this._useHTTPS()) {
      return ['0', '1', '2', '3'];
    }

    return [''];
  },

  getLayerMetadata: function (layerIndex) {
    var layerMeta = {};
    var layers = this._getLayers();
    if (layers && layers[layerIndex]) {
      layerMeta = layers[layerIndex].meta || {};
    }
    return layerMeta;
  },

  getBubbleLegendMetadata: function (layerIndex) {
    return _.find(this._getLegendsMetadata(layerIndex), { type: 'bubble' });
  },

  getCategoryLegendMetadata: function (layerIndex) {
    return _.find(this._getLegendsMetadata(layerIndex), { type: 'category' });
  },

  getChoroplethLegendMetadata: function (layerIndex) {
    return _.find(this._getLegendsMetadata(layerIndex), { type: 'choropleth' });
  },

  _getLegendsMetadata: function (layerIndex) {
    return this.get('metadata').legends &&
      this.get('metadata').legends[layerIndex];
  },

  _getLayers: function () {
    return (this.get('metadata') && this.get('metadata').layers) || [];
  },

  _getDataviews: function () {
    return (this.get('metadata') && this.get('metadata').dataviews) || [];
  },

  _getAnalyses: function () {
    return (this.get('metadata') && this.get('metadata').analyses) || [];
  }
});

module.exports = WindshaftMap;
<commit_msg>Removed unused methods<commit_after>var _ = require('underscore');
var Backbone = require('backbone');
var WindshaftConfig = require('./config');
var log = require('../cdb.log');
var Request = require('./request');
var RequestTracker = require('./request-tracker');
var WindshaftError = require('./error');

/* The max number of times the same map can be instantiated */
var MAP_INSTANTIATION_LIMIT = 3;

var WindshaftMap = Backbone.Model.extend({
  initialize: function (attrs, options) {
    if (!options.client) {
      throw new Error('client option is required');
    }
    // TODO: We could use the layerGroupModel instead! Only contains layers of type 'CartoDB' and 'Torque'
    if (!options.layersCollection) {
      throw new Error('layersCollection option is required');
    }
    if (!options.dataviewsCollection) {
      throw new Error('dataviewsCollection option is required');
    }
    if (!options.analysisCollection) {
      throw new Error('analysisCollection option is required');
    }
    if (!options.modelUpdater) {
      throw new Error('modelUpdater option is required');
    }

    this.client = options.client;
    this.set({
      urlTemplate: this.client.urlTemplate,
      userName: this.client.userName
    });

    this._layersCollection = options.layersCollection;
    this._dataviewsCollection = options.dataviewsCollection;
    this._analysisCollection = options.analysisCollection;
    this._modelUpdater = options.modelUpdater;

    this._requestTracker = new RequestTracker(MAP_INSTANTIATION_LIMIT);
  },

  toJSON: function () {
    throw new Error('Subclasses of windshaft/map-base must implement .toJSON');
  },

  // TODO: Move this somewhere else and keep this class as a wrapper for windshaft responses
  createInstance: function (options) {
    options = options || {};

    try {
      var payload = this.toJSON();
      var params = this._getParams();

      var request = new Request(payload, params, options);
      if (this._canPerformRequest(request)) {
        this._performRequest(request);
      } else {
        log.error('Maximum number of subsequent equal requests to the Maps API reached (' + MAP_INSTANTIATION_LIMIT + '):', payload, params);
        options.error && options.error();
      }
    } catch (e) {
      var error = new WindshaftError({
        message: e.message
      });
      this._modelUpdater.setErrors([ error ]);

      log.error(e.message);
      options.error && options.error();
    }
  },

  _canPerformRequest: function (request) {
    return this._requestTracker.canRequestBePerformed(request);
  },

  _trackRequest: function (request, response) {
    this._requestTracker.track(request, response);
  },

  _performRequest: function (request) {
    var payload = request.payload;
    var params = request.params;
    var options = request.options;
    this.client.instantiateMap({
      mapDefinition: payload,
      params: params,
      success: function (response) {
        console.log(JSON.stringify(response.metadata.layers, null, 4));
        this._trackRequest(request, response);
        this.set(response);
        this._modelUpdater.updateModels(this, options.sourceId, options.forceFetch);
        this.trigger('instanceCreated');
        options.success && options.success(this);
      }.bind(this),
      error: function (response) {
        this._trackRequest(request, response);
        var windshaftErrors = this._getErrorsFromResponse(response);
        this._modelUpdater.setErrors(windshaftErrors);
        options.error && options.error();
      }.bind(this)
    });
  },

  _getErrorsFromResponse: function (response) {
    if (response.errors_with_context) {
      return _.map(response.errors_with_context, function (error) {
        return new WindshaftError(error);
      });
    }
    if (response.errors) {
      return [
        new WindshaftError({ message: response.errors[0] })
      ];
    }

    return [];
  },

  _getParams: function () {
    var params = {
      stat_tag: this.get('statTag')
    };

    if (this.get('apiKey')) {
      params.api_key = this.get('apiKey');
    } else if (this.get('authToken')) {
      params.auth_token = this.get('authToken');
    }

    var filters = this._getFilterParamFromDataviews();
    if (!_.isEmpty(filters)) {
      params.filters = filters;
    }

    return params;
  },

  _getFilterParamFromDataviews: function () {
    return this._dataviewsCollection.reduce(function (filters, dataview) {
      var filter = dataview.filter;
      if (filter && !filter.isEmpty()) {
        filters['dataviews'] = filters['dataviews'] || {};
        _.extend(filters['dataviews'], filter.toJSON());
      }
      return filters;
    }, {});
  },

  getBaseURL: function (subhost) {
    return [
      this._getHost(subhost),
      WindshaftConfig.MAPS_API_BASE_URL,
      this.get('layergroupid')
    ].join('/');
  },

  _getHost: function (subhost) {
    var userName = this.get('userName');
    var protocol = this._useHTTPS() ? 'https' : 'http';
    subhost = subhost ? subhost + '.' : '';
    var host = this.get('urlTemplate').replace('{user}', userName);
    var cdnHost = this.get('cdn_url') && this.get('cdn_url')[protocol];
    if (cdnHost) {
      host = [protocol, '://', subhost, cdnHost, '/', userName].join('');
    }

    return host;
  },

  _useHTTPS: function () {
    return this.get('urlTemplate').indexOf('https') === 0;
  },

  /**
   * Returns the indexes of the layer of a given type, as the tiler kwows it.
   *
   * @param {string|array} layerType - Type of layer
   */
  getLayerIndexesByType: function (layerType) {
    return _.reduce(this._getLayers(), function (layerIndexes, layer, index) {
      if (layer.type === layerType) {
        layerIndexes.push(index);
      }
      return layerIndexes;
    }, []);
  },

  getDataviewMetadata: function (dataviewId) {
    var dataviews = this._getDataviews();
    if (dataviews && dataviews[dataviewId]) {
      return dataviews[dataviewId];
    }

    // Try to get dataview's metatadta from the 'widgets' dictionary inside the metadata of each of the layers
    dataviews = {};
    var layersDataviews = _.compact(_.map(this._getLayers(), function (layer) { return layer.widgets; }));
    _.each(layersDataviews, function (layerDataviews) {
      _.extend(dataviews, layerDataviews);
    });

    if (dataviews && dataviews[dataviewId]) {
      return dataviews[dataviewId];
    }
  },

  getAnalysisNodeMetadata: function (analysisId) {
    var metadata = {};
    var nodes = _.map(this._getAnalyses(), function (analysis) {
      return analysis.nodes;
    });
    _.each(nodes, function (node) {
      _.extend(metadata, node);
    });

    return metadata[analysisId];
  },

  getSupportedSubdomains: function () {
    if (!this._useHTTPS()) {
      return ['0', '1', '2', '3'];
    }

    return [''];
  },

  getLayerMetadata: function (layerIndex) {
    var layerMeta = {};
    var layers = this._getLayers();
    if (layers && layers[layerIndex]) {
      layerMeta = layers[layerIndex].meta || {};
    }
    return layerMeta;
  },

  _getLayers: function () {
    return (this.get('metadata') && this.get('metadata').layers) || [];
  },

  _getDataviews: function () {
    return (this.get('metadata') && this.get('metadata').dataviews) || [];
  },

  _getAnalyses: function () {
    return (this.get('metadata') && this.get('metadata').analyses) || [];
  }
});

module.exports = WindshaftMap;
<|endoftext|>


<commit_before>
const HOSTED_URLS = {
  model:
      'model_js/model.json',
  metadata:
      'model_js/metadata.json'
};

const examples = {
  'example1':
      'test',
  'example2':
      'test',
  'example3':
<<<<<<< HEAD
      'test'
=======
      'Well, Honor is the subiect of my Story.'
>>>>>>> 6c4abc08ae977295fb155399f04e166968d6ce2d
};

function status(statusText) {
  console.log(statusText);
  document.getElementById('status').textContent = statusText;
}

function showMetadata(metadataJSON) {
  document.getElementById('vocabularySize').textContent =
      metadataJSON['vocabulary_size'];
  document.getElementById('maxLen').textContent =
      metadataJSON['max_len'];
}

function settextField(text, predict) {
  const textField = document.getElementById('text-entry');
  textField.value = text;
  doPredict(predict);
}

function setPredictFunction(predict) {
  const textField = document.getElementById('text-entry');
  textField.addEventListener('input', () => doPredict(predict));
}

function disableLoadModelButtons() {
  document.getElementById('load-model').style.display = 'none';
}

function doPredict(predict) {
  const textField = document.getElementById('text-entry');
  const result = predict(textField.value);
  score_string = "Class scores: ";
  for (var x in result.score) {
    score_string += x + " ->  " + result.score[x].toFixed(3) + ", "
  }
  //console.log(score_string);
  status(
      score_string + ' elapsed: ' + result.elapsed.toFixed(3) + ' ms)');
}

function prepUI(predict) {
  setPredictFunction(predict);
  const testExampleSelect = document.getElementById('example-select');
  testExampleSelect.addEventListener('change', () => {
    settextField(examples[testExampleSelect.value], predict);
  });
  settextField(examples['example1'], predict);
}

async function urlExists(url) {
  status('Testing url ' + url);
  try {
    const response = await fetch(url, {method: 'HEAD'});
    return response.ok;
  } catch (err) {
    return false;
  }
}

async function loadHostedPretrainedModel(url) {
  status('Loading pretrained model from ' + url);
  try {
    const model = await tf.loadModel(url);
    status('Done loading pretrained model.');
    disableLoadModelButtons();
    return model;
  } catch (err) {
    console.error(err);
    status('Loading pretrained model failed.');
  }
}

async function loadHostedMetadata(url) {
  status('Loading metadata from ' + url);
  try {
    const metadataJson = await fetch(url);
    const metadata = await metadataJson.json();
    status('Done loading metadata.');
    return metadata;
  } catch (err) {
    console.error(err);
    status('Loading metadata failed.');
  }
}

class Classifier {

  async init(urls) {
    this.urls = urls;
    this.model = await loadHostedPretrainedModel(urls.model);
    await this.loadMetadata();
    return this;
  }

  async loadMetadata() {
    const metadata =
        await loadHostedMetadata(this.urls.metadata);
    showMetadata(metadata);
    this.maxLen = metadata['max_len'];
    console.log('maxLen = ' + this.maxLen);
    this.wordIndex = metadata['word_index']
  }

  predict(text) {
    // Convert to lower case and remove all punctuations.
    const inputText =
        text.trim().toLowerCase().replace(/(\.|\,|\!)/g, '').split(' ');
    // Look up word indices.
    const inputBuffer = tf.buffer([1, this.maxLen], 'float32');
    for (let i = 0; i < inputText.length; ++i) {
      const word = inputText[i];
      inputBuffer.set(this.wordIndex[word], 0, i);
      //console.log(word, this.wordIndex[word], inputBuffer);
    }
    const input = inputBuffer.toTensor();
    //console.log(input);

    status('Running inference');
    const beginMs = performance.now();
    const predictOut = this.model.predict(input);
    //console.log(predictOut.dataSync());
    const score = predictOut.dataSync();//[0];
    predictOut.dispose();
    const endMs = performance.now();

    return {score: score, elapsed: (endMs - beginMs)};
  }
};

async function setup() {
  if (await urlExists(HOSTED_URLS.model)) {
    status('Model available: ' + HOSTED_URLS.model);
    const button = document.getElementById('load-model');
    button.addEventListener('click', async () => {
      const predictor = await new Classifier().init(HOSTED_URLS);
      prepUI(x => predictor.predict(x));
    });
    button.style.display = 'inline-block';
  }

  status('Standing by.');
}

setup();
<commit_msg>Update index.js<commit_after>
const HOSTED_URLS = {
  model:
      'model_js/model.json',
  metadata:
      'model_js/metadata.json'
};

const examples = {
  'example1':
      'I suppose you have heard of the handsome letter Mr . Frank Churchill has written to Mrs . Weston?',
  'example2':
      'So the little Gingerbread Boy jumped on the fox tail, and the fox began to swim the river.',
  'example3':
      'Well, Honor is the subiect of my Story.'
};

function status(statusText) {
  console.log(statusText);
  document.getElementById('status').textContent = statusText;
}

function showMetadata(metadataJSON) {
  document.getElementById('vocabularySize').textContent =
      metadataJSON['vocabulary_size'];
  document.getElementById('maxLen').textContent =
      metadataJSON['max_len'];
}

function settextField(text, predict) {
  const textField = document.getElementById('text-entry');
  textField.value = text;
  doPredict(predict);
}

function setPredictFunction(predict) {
  const textField = document.getElementById('text-entry');
  textField.addEventListener('input', () => doPredict(predict));
}

function disableLoadModelButtons() {
  document.getElementById('load-model').style.display = 'none';
}

function doPredict(predict) {
  const textField = document.getElementById('text-entry');
  const result = predict(textField.value);
  score_string = "Class scores: ";
  for (var x in result.score) {
    score_string += x + " ->  " + result.score[x].toFixed(3) + ", "
  }
  //console.log(score_string);
  status(
      score_string + ' elapsed: ' + result.elapsed.toFixed(3) + ' ms)');
}

function prepUI(predict) {
  setPredictFunction(predict);
  const testExampleSelect = document.getElementById('example-select');
  testExampleSelect.addEventListener('change', () => {
    settextField(examples[testExampleSelect.value], predict);
  });
  settextField(examples['example1'], predict);
}

async function urlExists(url) {
  status('Testing url ' + url);
  try {
    const response = await fetch(url, {method: 'HEAD'});
    return response.ok;
  } catch (err) {
    return false;
  }
}

async function loadHostedPretrainedModel(url) {
  status('Loading pretrained model from ' + url);
  try {
    const model = await tf.loadModel(url);
    status('Done loading pretrained model.');
    disableLoadModelButtons();
    return model;
  } catch (err) {
    console.error(err);
    status('Loading pretrained model failed.');
  }
}

async function loadHostedMetadata(url) {
  status('Loading metadata from ' + url);
  try {
    const metadataJson = await fetch(url);
    const metadata = await metadataJson.json();
    status('Done loading metadata.');
    return metadata;
  } catch (err) {
    console.error(err);
    status('Loading metadata failed.');
  }
}

class Classifier {

  async init(urls) {
    this.urls = urls;
    this.model = await loadHostedPretrainedModel(urls.model);
    await this.loadMetadata();
    return this;
  }

  async loadMetadata() {
    const metadata =
        await loadHostedMetadata(this.urls.metadata);
    showMetadata(metadata);
    this.maxLen = metadata['max_len'];
    console.log('maxLen = ' + this.maxLen);
    this.wordIndex = metadata['word_index']
  }

  predict(text) {
    // Convert to lower case and remove all punctuations.
    const inputText =
        text.trim().toLowerCase().replace(/(\.|\,|\!)/g, '').split(' ');
    // Look up word indices.
    const inputBuffer = tf.buffer([1, this.maxLen], 'float32');
    for (let i = 0; i < inputText.length; ++i) {
      const word = inputText[i];
      inputBuffer.set(this.wordIndex[word], 0, i);
      //console.log(word, this.wordIndex[word], inputBuffer);
    }
    const input = inputBuffer.toTensor();
    //console.log(input);

    status('Running inference');
    const beginMs = performance.now();
    const predictOut = this.model.predict(input);
    //console.log(predictOut.dataSync());
    const score = predictOut.dataSync();//[0];
    predictOut.dispose();
    const endMs = performance.now();

    return {score: score, elapsed: (endMs - beginMs)};
  }
};

async function setup() {
  if (await urlExists(HOSTED_URLS.model)) {
    status('Model available: ' + HOSTED_URLS.model);
    const button = document.getElementById('load-model');
    button.addEventListener('click', async () => {
      const predictor = await new Classifier().init(HOSTED_URLS);
      prepUI(x => predictor.predict(x));
    });
    button.style.display = 'inline-block';
  }

  status('Standing by.');
}

setup();
<|endoftext|>


<commit_before>var add_image_handlers = function() {
  $("#main-image").data('selectedThumb', $('#main-image img').attr('src'));
  $('ul.thumbnails li').eq(0).addClass('selected');
  $('ul.thumbnails li a').click(function() {
    $("#main-image").data('selectedThumb', $(this).attr('href'));
    $('ul.thumbnails li').removeClass('selected');
    $(this).parent('li').addClass('selected');
    return false;
  }).hover(
          function() {
            $('#main-image img').attr('src', $(this).attr('href').replace('mini', 'product'));
          },
          function() {
            $('#main-image img').attr('src', $("#main-image").data('selectedThumb'));
          }
          );
};

jQuery(document).ready(function() {
  add_image_handlers();
});

jQuery(document).ready(function() {
  jQuery('#product-variants input[type=radio]').click(function (event) {
    var vid = this.value;
    var text = $(this).siblings(".variant-description").html();

    jQuery("#variant-thumbnails").empty();
    jQuery("#variant-images span").html(text);

    if (images[vid].length > 0) {
      $.each(imags[vid], function(i, link) {
        jQuery("#variant-thumbnails").append('
' + link + '
');
      }

      jQuery("#variant-images").show();
    } else {
      jQuery("#variant-images").hide();
    }

    add_image_handlers();

    var link = jQuery("#variant-thumbnails a")[0];

    jQuery("#main-image img").attr({src: jQuery(link).attr('href')});
    jQuery('ul.thumbnails li').removeClass('selected');
    jQuery(link).parent('li').addClass('selected');
  });
});<commit_msg>Fixes error in products.js (thanks to John Sucaet).<commit_after>var add_image_handlers = function() {
  $("#main-image").data('selectedThumb', $('#main-image img').attr('src'));
  $('ul.thumbnails li').eq(0).addClass('selected');
  $('ul.thumbnails li a').click(function() {
    $("#main-image").data('selectedThumb', $(this).attr('href'));
    $('ul.thumbnails li').removeClass('selected');
    $(this).parent('li').addClass('selected');
    return false;
  }).hover(
          function() {
            $('#main-image img').attr('src', $(this).attr('href').replace('mini', 'product'));
          },
          function() {
            $('#main-image img').attr('src', $("#main-image").data('selectedThumb'));
          }
          );
};

jQuery(document).ready(function() {
  add_image_handlers();
});

jQuery(document).ready(function() {
  jQuery('#product-variants input[type=radio]').click(function (event) {
    var vid = this.value;
    var text = $(this).siblings(".variant-description").html();

    jQuery("#variant-thumbnails").empty();
    jQuery("#variant-images span").html(text);

    if (images[vid].length > 0) {
      $.each(images[vid], function(i, link) {
        jQuery("#variant-thumbnails").append('
' + link + '
');
      });

      jQuery("#variant-images").show();
    } else {
      jQuery("#variant-images").hide();
    }

    add_image_handlers();

    var link = jQuery("#variant-thumbnails a")[0];

    jQuery("#main-image img").attr({src: jQuery(link).attr('href')});
    jQuery('ul.thumbnails li').removeClass('selected');
    jQuery(link).parent('li').addClass('selected');
  });
});<|endoftext|>


<commit_before>import fs from 'fs';
import { homedir } from 'os';
import path from 'path';
import mkdirp from 'mkdirp';
import envPaths from 'env-paths';

import { readFile, resolveHomePathToAbsolute } from 'sqlectron-db-core/utils';

export {
  createCancelablePromise,
  getPort,
  readFile,
  resolveHomePathToAbsolute,
  versionCompare,
} from 'sqlectron-db-core/utils';

let configPath = '';

export function getConfigPath() {
  if (configPath) {
    return configPath;
  }

  const configName = 'sqlectron.json';
  const oldConfigPath = path.join(homedir(), `.${configName}`);

  if (process.env.SQLECTRON_HOME) {
    configPath = path.join(process.env.SQLECTRON_HOME, configName);
  } else if (fileExistsSync(oldConfigPath)) {
    configPath = oldConfigPath;
  } else {
    const newConfigDir = envPaths('Sqlectron', { suffix: '' }).config;
    configPath = path.join(newConfigDir, configName);
  }

  return configPath;
}

export function fileExists(filename) {
  return new Promise((resolve) => {
    fs.stat(filename, (err, stats) => {
      if (err) return resolve(false);
      resolve(stats.isFile());
    });
  });
}

export function fileExistsSync(filename) {
  try {
    return fs.statSync(filename).isFile();
  } catch (e) {
    return false;
  }
}

export function writeFile(filename, data) {
  return new Promise((resolve, reject) => {
    fs.writeFile(filename, data, (err) => {
      if (err) return reject(err);
      resolve();
    });
  });
}

export function writeJSONFile(filename, data) {
  return writeFile(filename, JSON.stringify(data, null, 2));
}

export function writeJSONFileSync(filename, data) {
  return fs.writeFileSync(filename, JSON.stringify(data, null, 2));
}

export function readJSONFile(filename) {
  return readFile(filename).then((data) => JSON.parse(data));
}

export function readJSONFileSync(filename) {
  const filePath = resolveHomePathToAbsolute(filename);
  const data = fs.readFileSync(path.resolve(filePath), { enconding: 'utf-8' });
  return JSON.parse(data);
}

export function createParentDirectory(filename) {
  return mkdirp(path.dirname(filename));
}

export function createParentDirectorySync(filename) {
  mkdirp.sync(path.dirname(filename));
}
<commit_msg>fix readJSONFileSync not always using utf8<commit_after>import fs from 'fs';
import { homedir } from 'os';
import path from 'path';
import mkdirp from 'mkdirp';
import envPaths from 'env-paths';

import { readFile, resolveHomePathToAbsolute } from 'sqlectron-db-core/utils';

export {
  createCancelablePromise,
  getPort,
  readFile,
  resolveHomePathToAbsolute,
  versionCompare,
} from 'sqlectron-db-core/utils';

let configPath = '';

export function getConfigPath() {
  if (configPath) {
    return configPath;
  }

  const configName = 'sqlectron.json';
  const oldConfigPath = path.join(homedir(), `.${configName}`);

  if (process.env.SQLECTRON_HOME) {
    configPath = path.join(process.env.SQLECTRON_HOME, configName);
  } else if (fileExistsSync(oldConfigPath)) {
    configPath = oldConfigPath;
  } else {
    const newConfigDir = envPaths('Sqlectron', { suffix: '' }).config;
    configPath = path.join(newConfigDir, configName);
  }

  return configPath;
}

export function fileExists(filename) {
  return new Promise((resolve) => {
    fs.stat(filename, (err, stats) => {
      if (err) return resolve(false);
      resolve(stats.isFile());
    });
  });
}

export function fileExistsSync(filename) {
  try {
    return fs.statSync(filename).isFile();
  } catch (e) {
    return false;
  }
}

export function writeFile(filename, data) {
  return new Promise((resolve, reject) => {
    fs.writeFile(filename, data, (err) => {
      if (err) return reject(err);
      resolve();
    });
  });
}

export function writeJSONFile(filename, data) {
  return writeFile(filename, JSON.stringify(data, null, 2));
}

export function writeJSONFileSync(filename, data) {
  return fs.writeFileSync(filename, JSON.stringify(data, null, 2));
}

export function readJSONFile(filename) {
  return readFile(filename).then((data) => JSON.parse(data));
}

export function readJSONFileSync(filename) {
  const filePath = resolveHomePathToAbsolute(filename);
  const data = fs.readFileSync(path.resolve(filePath), { encoding: 'utf-8' });
  return JSON.parse(data);
}

export function createParentDirectory(filename) {
  return mkdirp(path.dirname(filename));
}

export function createParentDirectorySync(filename) {
  mkdirp.sync(path.dirname(filename));
}
<|endoftext|>


<commit_before>// Convert with http://www.professorcloud.com/svg-to-canvas/

var svg = require('./svg')
	, primitives = {
			sun: require('./primitives/sunPrimitive'),
			moon: require('./primitives/moonPrimitive'),
			cloud: require('./primitives/cloudPrimitive'),
			raindrop: require('./primitives/raindropPrimitive'),
			sleet: require('./primitives/sleetPrimitive'),
			snowflake: require('./primitives/snowflakePrimitive'),
			fog: require('./primitives/fogPrimitive'),
			lightning: require('./primitives/lightningPrimitive')
		}
	, formula = require('../../resources/weatherSymbols.json')

	, DEFAULT_BG = '#ffffff'
	, SVG = 'svg'
	, CANVAS = 'canvas'
	, IMG = 'img';

module.exports = function (container, options) {
	if (!container) return;

	options = options || {};
	var type = options.svg
				? SVG
				: (options.canvas
					? CANVAS
					: IMG)
		, element = createElement(type)
		, id = options.id || container.getAttribute('data-id')
		, w = container.offsetWidth
		, h = container.offsetHeight
		, scale = options.scale || 1
		, tScale = (type == CANVAS) ? (w/100) * scale : 1
		, bgContainer = getStyle(container, 'background-color')
		, bg = bgContainer && bgContainer !== 'rgba(0, 0, 0, 0)' ? bgContainer : DEFAULT_BG
		, f = formula[id]
		, layer, opts;

	if (type == SVG || type == CANVAS) {
		if (type == CANVAS) {
			if (w != 0) {
				element.width = w * scale;
				element.height = h * scale;
			}
		}

		if (f) {
			for (var i = 0, n = f.length; i < n; i++) {
				layer = f[i];
				opts = {
					type: type,
					x: Math.round(layer.x * tScale),
					y: Math.round(layer.y * tScale),
					scale: (layer.scale || 1) * tScale,
					small: layer.small,
					flip: layer.flip,
					tint: layer.tint,
					winter: layer.winter,
					width: w * scale,
					height: h * scale,
					bg: bg
				};

				primitives[layer.primitive].render(element, opts);
			}
		}
	// Load images
	} else {
		element.src = options.imagePath + id + '.png';
	}

	container.appendChild(element);
};

function getStyle (element, prop) {
	return window.getComputedStyle(element).getPropertyValue(prop);
}

function createElement (type) {
	var el;

	if (type == SVG) {
		el = document.createElementNS(svg.NS, type);
		el.setAttribute('x', '0px');
		el.setAttribute('y', '0px');
		el.setAttribute('viewBox', '0 0 100 100');
	} else {
		el = document.createElement(type);
	}

	return el;
}<commit_msg>add svg definitions to html<commit_after>// Convert with http://www.professorcloud.com/svg-to-canvas/

var svg = require('./svg')
	, primitives = {
			sun: require('./primitives/sunPrimitive'),
			moon: require('./primitives/moonPrimitive'),
			cloud: require('./primitives/cloudPrimitive'),
			raindrop: require('./primitives/raindropPrimitive'),
			sleet: require('./primitives/sleetPrimitive'),
			snowflake: require('./primitives/snowflakePrimitive'),
			fog: require('./primitives/fogPrimitive'),
			lightning: require('./primitives/lightningPrimitive')
		}
	, formula = require('../../resources/weatherSymbols.json')

	, DEFAULT_BG = '#ffffff'
	, SVG = 'svg'
	, CANVAS = 'canvas'
	, IMG = 'img'
	, DEFS = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="symbolDefs" x="0px" y="0px" width="0" height="0" viewBox="0 0 100 100" style="display:none;"><defs><path id="cloud" class="cloud" d="M55.6,2C46,1.7,37.1,7,34.1,17.3c-6.1-1.5-16,2.4-17.8,10.9C10.1,28,2,33.1,2,41.6C2,51,9,56,21.5,56h43.6 c5.6,0,12.9-0.5,17.3-2.6c14.9-7.2,12.3-32.3-6.4-34.6C73.7,7.9,65.1,2.3,55.6,2z"/><clipPath id="sunWinterMask"><rect y="45" width="90" height="45" /></clipPath></defs><symbol id="sun"><g class="sun-ray" ><path d="M23.5,33.2c2.2-4.1,5.6-7.5,9.7-9.7l-17-10c-1.8-1-3.8,1-2.7,2.7L23.5,33.2z"/><path d="M45,20.5c2.4,0,4.7,0.3,6.9,1l-5-19.1c-0.5-2-3.3-2-3.9,0l-5,19.1C40.3,20.8,42.6,20.5,45,20.5z"/><path d="M87.6,43.1l-19.1-5c0.6,2.2,1,4.5,1,6.9c0,2.4-0.3,4.7-1,6.9l19.1-5C89.6,46.4,89.6,43.6,87.6,43.1z"/><path d="M20.5,45c0-2.4,0.3-4.7,1-6.9l-19.1,5c-2,0.5-2,3.3,0,3.9l19.1,5C20.8,49.7,20.5,47.4,20.5,45z"/><path d="M66.5,33.2l10-17c1-1.8-1-3.8-2.7-2.7l-17,10C60.9,25.8,64.2,29.1,66.5,33.2z"/><path d="M23.5,56.8l-10,17c-1,1.8,1,3.8,2.7,2.7l17-10C29.1,64.2,25.8,60.9,23.5,56.8z"/><path d="M66.5,56.8c-2.2,4.1-5.6,7.5-9.7,9.7l17,10c1.8,1,3.8-1,2.7-2.7L66.5,56.8z"/><path d="M45,69.5c-2.4,0-4.7-0.3-6.9-1l5,19.1c0.5,2,3.3,2,3.9,0l5-19.1C49.7,69.2,47.4,69.5,45,69.5z"/></g><circle class="sun-centre" style="fill-rule:nonzero" cx="45" cy="45" r="20.5"/></symbol><symbol id="sunWinter"><path class="sun-winter-horizon" d="M2.5,0h85.1C88.9,0,90,0.9,90,2v0c0,1.1-1.1,2-2.5,2H2.5C1.1,4,0,3.1,0,2v0C0,0.9,1.1,0,2.5,0z"/><use class="sun-winter" style="clip-path:url(#sunWinterMask);" xlink:href="#sun" x="0" y="-37" width="100" height="100"></use></symbol><symbol id="moon"><path class="moon" d="M23,20c0-7.7,2.9-14.7,7.6-20c-0.2,0-0.4,0-0.6,0C13.4,0,0,13.4,0,30s13.4,30,30,30c8.9,0,16.9-3.9,22.4-10 C36.1,49.6,23,36.4,23,20z"/></symbol><symbol id="cloud-10" class="cloud-10"><use xlink:href="#cloud" x="0" y="0" width="100" height="100"></use></symbol><symbol id="cloud-15" class="cloud-15"><use xlink:href="#cloud" x="0" y="0" width="100" height="100"></use></symbol><symbol id="cloud-30" class="cloud-30"><use xlink:href="#cloud" x="0" y="0" width="100" height="100"></use></symbol><symbol id="cloud-40" class="cloud-40"><use xlink:href="#cloud" x="0" y="0" width="100" height="100"></use></symbol><symbol id="cloud-50" class="cloud-50"><use xlink:href="#cloud" x="0" y="0" width="100" height="100"></use></symbol><symbol id="fog"><path class="fog" d="M82.3,42H2.7C1.2,42,0,42.9,0,44s1.2,2,2.7,2h79.7c1.5,0,2.7-0.9,2.7-2S83.8,42,82.3,42z"/><path class="fog" d="M80.1,50H5.9C4.3,50,3,50.9,3,52c0,1.1,1.3,2,2.9,2h74.3c1.6,0,2.9-0.9,2.9-2C83,50.9,81.7,50,80.1,50z"/><path class="fog" d="M80.1,58H10.9C9.3,58,8,58.9,8,60s1.3,2,2.9,2h69.2c1.6,0,2.9-0.9,2.9-2S81.7,58,80.1,58z"/><path class="fog" d="M51.2,0c-9.1-0.3-17.6,4.8-20.5,14.6c-5.9-1.4-15.3,2.3-17,10.4C8.2,24.9,1.2,29,0.1,36C0,37,0.7,37.9,1.7,37.9l82.3,0 c1,0,1.8-0.7,1.9-1.7c1-8.9-4.1-18.7-15.2-20.1C68.5,5.6,60.2,0.3,51.2,0z"/></symbol><symbol id="raindrop"><circle class="bg" cx="9" cy="9" r="9"/><path class="raindrop" d="M20,16.8c0,3.4-2.7,6.2-6,6.2c-3.3,0-6-2.8-6-6.2C8,14.9,8,6,8,6C13.5,11.5,20,11.2,20,16.8z"/></symbol><symbol id="sleet"><circle class="bg" cx="9" cy="9" r="9"/><path class="sleet" d="M19.9,16.6c-1.8,2.3-3.4,5.5-3.9,8.9c-0.1,0.5-0.6,0.7-1,0.4c-2.3-2.1-4.8-3.3-8.5-3.8c-0.4-0.1-0.6-0.5-0.4-0.8 C8.4,17,8.6,10.1,7.8,5c2.7,4.2,7.1,9,11.8,10.7C20,15.8,20.1,16.3,19.9,16.6z"/></symbol><symbol id="snowflake"><circle class="bg" cx="9" cy="9" r="9"/><path class="snowflake" d="M6.2,6.9l1.1,3.8c-0.3,0.2-0.6,0.5-0.9,0.8C6,11.7,5.8,12,5.6,12.4l-3.8-1C1,11.2,0.2,11.7,0,12.5c-0.2,0.8,0.3,1.6,1.1,1.8 l3.8,1c0,0.8,0.3,1.6,0.6,2.3l-2.7,2.8c-0.6,0.6-0.6,1.5,0,2.1c0.6,0.6,1.5,0.6,2.1,0l2.7-2.8c0.7,0.4,1.5,0.6,2.3,0.6l1,3.8 c0.2,0.8,1,1.2,1.8,1c0.8-0.2,1.2-1,1-1.8l-1.1-3.8c0.3-0.2,0.7-0.4,1-0.7c0.3-0.3,0.5-0.6,0.7-1l3.8,1c0.8,0.2,1.6-0.3,1.8-1.1 c0.2-0.8-0.3-1.6-1.1-1.8l-3.8-1c0-0.8-0.3-1.6-0.7-2.3l2.7-2.8c0.6-0.6,0.5-1.5,0-2.1c-0.6-0.6-1.5-0.6-2.1,0l-2.7,2.8 c-0.7-0.4-1.5-0.6-2.3-0.6L9,6.1c-0.2-0.8-1-1.2-1.8-1C6.5,5.3,6,6.1,6.2,6.9z M11.8,13.2c1,1,1,2.6,0,3.6c-1,1-2.6,1-3.6,0 c-1-1-1-2.6,0-3.6C9.2,12.2,10.8,12.2,11.8,13.2z"/></symbol><symbol id="lightning"><path class="lightning" d="M10.4,0L4.2,12.5h8.3L0,25L25,8.3h-8.3L25,0H10.4z"/></symbol></svg>'

// Add svg definitions if not already present
if (hasSVG && !document.getElementById('symbolDefs')) {
	var el = document.createElement('div');

	el.innerHTML = DEFS;
	document.body.insertBefore(el.firstChild, document.body.firstChild);
}
module.exports = function (container, options) {
	if (!container) return;

	options = options || {};
	var type = options.svg
				? SVG
				: (options.canvas
					? CANVAS
					: IMG)
		, element = createElement(type)
		, id = options.id || container.getAttribute('data-id')
		, w = container.offsetWidth
		, h = container.offsetHeight
		, scale = options.scale || 1
		, tScale = (type == CANVAS) ? (w/100) * scale : 1
		, bgContainer = getStyle(container, 'background-color')
		, bg = bgContainer && bgContainer !== 'rgba(0, 0, 0, 0)' ? bgContainer : DEFAULT_BG
		, f = formula[id]
		, layer, opts;

	if (type == SVG || type == CANVAS) {
		if (type == CANVAS) {
			if (w != 0) {
				element.width = w * scale;
				element.height = h * scale;
			}
		}

		if (f) {
			for (var i = 0, n = f.length; i < n; i++) {
				layer = f[i];
				opts = {
					type: type,
					x: Math.round(layer.x * tScale),
					y: Math.round(layer.y * tScale),
					scale: (layer.scale || 1) * tScale,
					small: layer.small,
					flip: layer.flip,
					tint: layer.tint,
					winter: layer.winter,
					width: w * scale,
					height: h * scale,
					bg: bg
				};

				primitives[layer.primitive].render(element, opts);
			}
		}
	// Load images
	} else {
		element.src = options.imagePath + id + '.png';
	}

	container.appendChild(element);
};

function getStyle (element, prop) {
	return window.getComputedStyle(element).getPropertyValue(prop);
}

function createElement (type) {
	var el;

	if (type == SVG) {
		el = document.createElementNS(svg.NS, type);
		el.setAttribute('x', '0px');
		el.setAttribute('y', '0px');
		el.setAttribute('viewBox', '0 0 100 100');
	} else {
		el = document.createElement(type);
	}

	return el;
}<|endoftext|>


<commit_before>angular.module('app', [])

// Module loading
// --------------
    .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
	'use strict';

	var DEFAULT_PATH = "/";

	$routeProvider

	    .when('/', {

		templateUrl: '/javascripts/tmpl/index.html',
		controller : 'homeCtrl',

	    })

	    .when('/about', {
		templateUrl: '/javascripts/tmpl/about.html',
		controller : 'homeCtrl',
	    })

	    .when('/archives', {

		templateUrl: '/javascripts/tmpl/archives.html',
		controller : 'homeCtrl',

	    })

	    .when('/contact', {

		templateUrl: '/javascripts/tmpl/contact.html',
		controller : 'homeCtrl',

	    })

	    .when('/equiptment', {

		templateUrl: '/javascripts/tmpl/equiptment.html',
		controller : 'homeCtrl',

	    })

	    .when('/events', {

		templateUrl: '/javascripts/tmpl/events.html',
		controller : 'homeCtrl',

	    })

	    .when('/members', {

		templateUrl: '/javascripts/tmpl/members.html',
		controller : 'homeCtrl',

	    })

	    .when('/picture', {

		templateUrl: '/javascripts/tmpl/picture.html',
		controller : 'homeCtrl',

	    })

	    .when('/tutorial', {

		templateUrl: '/javascripts/tmpl/tutorial.html',
		controller : 'homeCtrl',

	    })

	    .when('/home', {

		templateUrl: '/javascripts/tmpl/home.html',
		controller : 'homeCtrl',

	    })

	    .when('/404', {
		templateUrl: '/javascripts/tmpl/404.html',
		controller : 'missingPageCtrl',
	    })

	    .otherwise({
		redirectTo : DEFAULT_PATH,
	    });

    }]);
<commit_msg>../routing.js<commit_after>angular.module('app', [])

// Module loading
// --------------
    .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
	'use strict';

	var DEFAULT_PATH = "/";

	$routeProvider

	    .when('/', {

		templateUrl: '/javascripts/tmpl/index.html',
		controller : 'homeCtrl',

	    })

	    .when('/about', {
		templateUrl: '/javascripts/tmpl/about.html',
		controller : 'homeCtrl',
	    })

	    .when('/archives', {

		templateUrl: '/javascripts/tmpl/archives.html',
		controller : 'homeCtrl',

	    })

	    .when('/contact', {

		templateUrl: '/javascripts/tmpl/contact.html',
		controller : 'homeCtrl',

	    })

	    .when('/equiptment', {

		templateUrl: '/javascripts/tmpl/equiptment.html',
		controller : 'homeCtrl',

	    })

	    .when('/events', {

		templateUrl: '/javascripts/tmpl/events.html',
		controller : 'homeCtrl',

	    })

	    .when('/members', {

		templateUrl: '/javascripts/tmpl/members.html',
		controller : 'memberCtrl',

	    })

	    .when('/picture', {

		templateUrl: '/javascripts/tmpl/picture.html',
		controller : 'homeCtrl',

	    })

	    .when('/tutorial', {

		templateUrl: '/javascripts/tmpl/tutorial.html',
		controller : 'homeCtrl',

	    })

	    .when('/home', {

		templateUrl: '/javascripts/tmpl/home.html',
		controller : 'homeCtrl',

	    })

	    .when('/404', {
		templateUrl: '/javascripts/tmpl/404.html',
		controller : 'missingPageCtrl',
	    })

	    .otherwise({
		redirectTo : DEFAULT_PATH,
	    });

    }]);
<|endoftext|>


<commit_before>define([
    "jquery"
], function($) {
    var jquery_plugin = function(pattern) {
        var plugin = function(method) {
            var $this = this;
            if ($this.length === 0)
                return $this;
            if (!method || typeof method === "object") {
                pattern.init.apply(
                    $this,
                    [$this].concat(Array.prototype.slice.call(arguments)));
            } else if (pattern[method]) {
                return pattern[method].apply(
                    $this,
                    [$this].concat(Array.prototype.slice.call(arguments, 1))
                );
            } else {
                $.error("Method " + method +
                        " does not exist on jQuery." + pattern.name);
            }
            return $this;
        };
        return plugin;
    };

    //     Underscore.js 1.3.1
    //     (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
    //     Underscore is freely distributable under the MIT license.
    //     Portions of Underscore are inspired or borrowed from Prototype,
    //     Oliver Steele's Functional, and John Resig's Micro-Templating.
    //     For all details and documentation:
    //     http://documentcloud.github.com/underscore
    //
    // Returns a function, that, as long as it continues to be invoked, will not
    // be triggered. The function will be called after it stops being called for
    // N milliseconds.
    var debounce = function(func, wait) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                func.apply(context, args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    };

    var rebaseURL = function(base, url) {
        if (url.indexOf("://")!==-1 || url[0]==="/")
            return url;
        return base.slice(0, base.lastIndexOf("/")+1) + url;
    };

    function findLabel(input) {
        for (var label=input.parentNode; label && label.nodeType!==11; label=label.parentNode)
            if (label.tagName==="LABEL")
                return label;

        var $label;

        if (input.id)
            $label = $("label[for="+input.id+"]");
        if ($label && $label.length===0 && input.form)
            $label = $("label[for="+input.name+"]", input.form);
        if ($label && $label.length)
            return $label[0];
        else
            return null;
    }

    // Taken from http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
    function elementInViewport(el) {
        var top = el.offsetTop;
        var left = el.offsetLeft;
        var width = el.offsetWidth;
        var height = el.offsetHeight;

        while (el.offsetParent) {
            el = el.offsetParent;
            top += el.offsetTop;
            left += el.offsetLeft;
        }

        return (
                top < (window.pageYOffset + window.innerHeight) &&
                left < (window.pageXOffset + window.innerWidth) &&
                (top + height) > window.pageYOffset &&
                (left + width) > window.pageXOffset
               );
    }

    // Taken from http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
    function escapeRegExp(str) {
        return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }

    var utils = {
        // pattern pimping - own module?
        jquery_plugin: jquery_plugin,
        debounce: debounce,
        escapeRegExp: escapeRegExp,
        rebaseURL: rebaseURL,
        findLabel: findLabel,
        elementInViewport: elementInViewport
    };

    return utils;
});
<commit_msg>Simpler version.<commit_after>define([
    "jquery"
], function($) {
    var jquery_plugin = function(pattern) {
        var plugin = function(method) {
            var $this = this;
            if ($this.length === 0)
                return $this;
            if (!method || typeof method === "object") {
                pattern.init.apply(
                    $this,
                    [$this].concat(Array.prototype.slice.call(arguments)));
            } else if (pattern[method]) {
                return pattern[method].apply(
                    $this,
                    [$this].concat(Array.prototype.slice.call(arguments, 1))
                );
            } else {
                $.error("Method " + method +
                        " does not exist on jQuery." + pattern.name);
            }
            return $this;
        };
        return plugin;
    };

    //     Underscore.js 1.3.1
    //     (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
    //     Underscore is freely distributable under the MIT license.
    //     Portions of Underscore are inspired or borrowed from Prototype,
    //     Oliver Steele's Functional, and John Resig's Micro-Templating.
    //     For all details and documentation:
    //     http://documentcloud.github.com/underscore
    //
    // Returns a function, that, as long as it continues to be invoked, will not
    // be triggered. The function will be called after it stops being called for
    // N milliseconds.
    var debounce = function(func, wait) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                func.apply(context, args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    };

    var rebaseURL = function(base, url) {
        if (url.indexOf("://")!==-1 || url[0]==="/")
            return url;
        return base.slice(0, base.lastIndexOf("/")+1) + url;
    };

    function findLabel(input) {
        for (var label=input.parentNode; label && label.nodeType!==11; label=label.parentNode)
            if (label.tagName==="LABEL")
                return label;

        var $label;

        if (input.id)
            $label = $("label[for="+input.id+"]");
        if ($label && $label.length===0 && input.form)
            $label = $("label[for="+input.name+"]", input.form);
        if ($label && $label.length)
            return $label[0];
        else
            return null;
    }

    // Taken from http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
    function elementInViewport(el) {
       var rect = el.getBoundingClientRect(),
           docEl = document.documentElement,
           vWidth = window.innerWidth || docEl.clientWidth,
           vHeight = window.innerHeight || docEl.clientHeight;

        if (rect.right<0 || rect.bottom<0 || rect.left>vWidth || rect.top>vHeight)
            return false;
        return true;
    }

    // Taken from http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
    function escapeRegExp(str) {
        return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }

    var utils = {
        // pattern pimping - own module?
        jquery_plugin: jquery_plugin,
        debounce: debounce,
        escapeRegExp: escapeRegExp,
        rebaseURL: rebaseURL,
        findLabel: findLabel,
        elementInViewport: elementInViewport
    };

    return utils;
});
<|endoftext|>


<commit_before>/*!
 * Select2 <%= package.version %>
 * https://select2.github.io
 *
 * Released under the MIT license
 * https://github.com/select2/select2/blob/master/LICENSE.md
 */
(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    // Node/CommonJS
    factory(require('jquery'));
  } else {
    // Browser globals
    factory(jQuery);
  }
}(function (jQuery) {
  // This is needed so we can catch the AMD loader configuration and use it
  // The inner file should be wrapped (by `banner.start.js`) in a function that
  // returns the AMD loader references.
  var S2 =
<commit_msg>Fix UMD commonjs support<commit_after>/*!
 * Select2 <%= package.version %>
 * https://select2.github.io
 *
 * Released under the MIT license
 * https://github.com/select2/select2/blob/master/LICENSE.md
 */
(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    module.exports = function (root, jQuery) {
      if (jQuery === undefined) {
        // require('jQuery') returns a factory that requires window to
        // build a jQuery instance, we normalize how we use modules
        // that require this pattern but the window provided is a noop
        // if it's defined (how jquery works)
        if (typeof window !== 'undefined') {
          jQuery = require('jquery');
        }
        else {
          jQuery = require('jquery')(root);
        }
      }
      factory(jQuery);
      return jQuery;
    };
  } else {
    // Browser globals
    factory(jQuery);
  }
} (function (jQuery) {
  // This is needed so we can catch the AMD loader configuration and use it
  // The inner file should be wrapped (by `banner.start.js`) in a function that
  // returns the AMD loader references.
  var S2 =<|endoftext|>