<commit_before>/**
 * boot.js -- loads lively in any page that inserts through a script tag
 *
 **/

/*
 #TODO refactor booting/loading/init of lively4
  - currently we have different entry points we should unify
 */

if (window.lively && window.lively4url) {
  console.log("CANCEL BOOT Lively4, because it is already loaded")
} else {

  console.group("BOOT")

  // for finding the baseURL...
  var script = document.currentScript
  var scriptURL = script.src;
  window.lively4url = scriptURL.replace("/src/client/boot.js","")

  var loadContainer = script.getAttribute("data-container") // some simple configuration
  console.log("lively4url: " + lively4url);

  // COPIED HERE BECAUSE resuse through libs does not work yet
  function loadJavaScriptThroughDOM(name, src, force) {
    return new Promise(function (resolve) {
      var scriptNode = document.querySelector(name);
      if (scriptNode) {
        scriptNode.remove();
      }
      var script = document.createElement("script");
      script.id = name;
      script.charset = "utf-8";
      script.type = "text/javascript";
      script.setAttribute("data-lively4-donotpersist","all");
      if (force) {
        src += +"?" + Date.now();
      }
      script.src = src;
      script.onload = function () {
        resolve();
      };
      document.head.appendChild(script);
    });
  }

  Promise.resolve().then( () => {
    return loadJavaScriptThroughDOM("systemjs", lively4url + "/src/external/systemjs/system.src.js");
  }).then(async () => {
    // setup var recorder object
    window._recorder_ = {_module_:{}}

    const moduleOptionsNon = {
      babelOptions: {
        es2015: false,
        stage2: false,
        stage3: false,
        plugins: []
      }
    };

    System.trace = true; // does not work in config

    // config for loading babal plugins
    SystemJS.config({
      baseURL: lively4url + '/', // needed for global refs like "src/client/lively.js", we have to refactor those before disabling this here. #TODO #Discussion
      babelOptions: {
        // stage2: false,
        // stage3: false,
        // es2015: false,
        // stage0: true,
        // stage1: true
        //presets: [
        //    ["es2015", { "loose": true, "modules": false }]
        //],
        plugins: []
      },
      meta: {
        '*.js': moduleOptionsNon
      },
      map: {
        // #Discussion have to use absolute paths here, because it is not clear what the baseURL is
        'plugin-babel': lively4url + '/src/external/babel/plugin-babel2.js',
        'systemjs-plugin-babel': lively4url + '/src/external/babel/plugin-babel.js',
        'systemjs-babel-build': lively4url + '/src/external/babel/systemjs-babel-browser.js',
        'kernel': lively4url + '/src/client/legacy-kernel.js',

        // aexpr support
        'active-expressions': lively4url + '/src/external/aexpr/active-expressions/src/active-expressions.js',
        'aexpr-source-transformation-propagation': lively4url + '/src/external/aexpr/aexpr-source-transformation-propagation/src/aexpr-source-transformation-propagation.js',
        'babel-plugin-aexpr-source-transformation': lively4url + '/src/external/aexpr/babel-plugin-aexpr-source-transformation/index.js',
        'babel-plugin-locals': lively4url + '/src/external/aexpr/babel-plugin-locals/index.js',
        'stack-es2015-modules': lively4url + '/src/external/aexpr/stack-es2015-module/src/stack.js',

        // jsx support
        'babel-plugin-syntax-jsx': lively4url + '/src/external/babel-plugin-syntax-jsx.js',
        'babel-plugin-jsx-lively': lively4url + '/src/external/babel-plugin-jsx-lively.js',

        // stage 0 support
        'babel-plugin-transform-do-expressions': lively4url + '/src/external/babel-plugin-transform-do-expressions.js',
        'babel-plugin-transform-function-bind': lively4url + '/src/external/babel-plugin-transform-function-bind.js',
        'babel-plugin-syntax-do-expressions': lively4url + '/src/external/babel-plugin-syntax-do-expressions.js',
        'babel-plugin-syntax-function-bind': lively4url + '/src/external/babel-plugin-syntax-function-bind.js',

        // support for doits
        'babel-plugin-doit-result': lively4url + '/src/external/babel-plugin-doit-result.js',
        'babel-plugin-doit-this-ref': lively4url + '/src/external/babel-plugin-doit-this-ref.js',
        'babel-plugin-locals': lively4url + '/src/external/babel-plugin-locals.js',
        'babel-plugin-var-recorder': lively4url + '/src/external/babel-plugin-var-recorder.js',
        'workspace-loader': lively4url + '/src/client/workspace-loader.js',

        // utils
        'utils': lively4url + '/src/client/utils.js'
      },
      trace: true,
      transpiler: 'plugin-babel'
    })

/*    await System.import('babel-plugin-doit-result');
    await System.import('babel-plugin-doit-this-ref');
    await System.import('babel-plugin-locals');
    await System.import('babel-plugin-var-recorder');
  */  //await System.import(lively4url + '/src/client/workspaces.js');
    //await System.import('workspace-loader');

    SystemJS.config({
      meta: {
        // plugins are not transpiled with other plugins, except for SystemJS-internal plugins
        [lively4url + '/src/external/babel-plugin-*.js']: moduleOptionsNon,
        [lively4url + '/src/external/ContextJS/src/*.js']: moduleOptionsNon,
        //['']: moduleOptionsNon,
        // blacklist all projects included for active expressions
        [lively4url + '/src/external/aexpr/*.js']: moduleOptionsNon,
        // ... except for the tests
        [lively4url + '/src/external/aexpr/test/*.spec.js']: {
          babelOptions: {
            es2015: false,
            stage2: false,
            stage3: false,
            plugins: [
              'babel-plugin-jsx-lively',
              'babel-plugin-transform-do-expressions',
              'babel-plugin-transform-function-bind',
              'babel-plugin-doit-result',
              'babel-plugin-doit-this-ref',
              'babel-plugin-var-recorder',
              'babel-plugin-aexpr-source-transformation'
            ]
          },
          loader: 'workspace-loader'
        },
        // all others
        '*.js': {
          babelOptions: {
            es2015: false,
            stage2: false,
            stage3: false,
            plugins: window.__karma__ ? [] : [ // #TODO disable plugins while testing... for now
              'babel-plugin-jsx-lively',
              'babel-plugin-transform-do-expressions',
              'babel-plugin-transform-function-bind',
              'babel-plugin-locals',
              'babel-plugin-var-recorder'
            ]
          }
        },
        'workspace:*': {
          babelOptions: {
            es2015: false,
            stage2: false,
            stage3: false,
            plugins: [
              'babel-plugin-jsx-lively',
              'babel-plugin-transform-do-expressions',
              'babel-plugin-transform-function-bind',
              'babel-plugin-locals',
              'babel-plugin-doit-result',
              'babel-plugin-doit-this-ref',
              'babel-plugin-var-recorder',
              'babel-plugin-aexpr-source-transformation'
            ]
          },
          loader: 'workspace-loader'
        },
        'workspacejs:*': {
          babelOptions: {
            es2015: false,
            stage2: false,
            stage3: false,
            plugins: [
              'babel-plugin-jsx-lively',
              'babel-plugin-transform-do-expressions',
              'babel-plugin-transform-function-bind',
              'babel-plugin-locals',
              'babel-plugin-doit-result',
              'babel-plugin-doit-this-ref',
              'babel-plugin-var-recorder'
            ]
          },
          loader: 'workspace-loader'
        },
      }
    });

    try {
      let { whenLoaded } = await System.import(lively4url + "/src/client/load.js")

      console.group("1/3: Wait for Service Worker...")
      await new Promise(whenLoaded);
      console.groupEnd();

      console.group("2/3: Look for uninitialized instances of Web Compoments");
      await lively.components.loadUnresolved();
      console.groupEnd();

      console.group("3/3: Initialize Document")
      await lively.initializeDocument(document, window.lively4chrome, loadContainer);
            console.groupEnd();

      console.log("Finally loaded!");

      document.dispatchEvent(new Event("livelyloaded"))

      console.groupEnd(); // BOOT
    } catch(err) {
      console.error("Lively Loading failed");
      console.error(err);
      alert("load Lively4 failed:" + err);
    }
  });
}
<commit_msg>disabled disabling for testing in testing or something like this<commit_after>/**
 * boot.js -- loads lively in any page that inserts through a script tag
 *
 **/

/*
 #TODO refactor booting/loading/init of lively4
  - currently we have different entry points we should unify
 */

if (window.lively && window.lively4url) {
  console.log("CANCEL BOOT Lively4, because it is already loaded")
} else {

  console.group("BOOT")

  // for finding the baseURL...
  var script = document.currentScript
  var scriptURL = script.src;
  window.lively4url = scriptURL.replace("/src/client/boot.js","")

  var loadContainer = script.getAttribute("data-container") // some simple configuration
  console.log("lively4url: " + lively4url);

  // COPIED HERE BECAUSE resuse through libs does not work yet
  function loadJavaScriptThroughDOM(name, src, force) {
    return new Promise(function (resolve) {
      var scriptNode = document.querySelector(name);
      if (scriptNode) {
        scriptNode.remove();
      }
      var script = document.createElement("script");
      script.id = name;
      script.charset = "utf-8";
      script.type = "text/javascript";
      script.setAttribute("data-lively4-donotpersist","all");
      if (force) {
        src += +"?" + Date.now();
      }
      script.src = src;
      script.onload = function () {
        resolve();
      };
      document.head.appendChild(script);
    });
  }

  Promise.resolve().then( () => {
    return loadJavaScriptThroughDOM("systemjs", lively4url + "/src/external/systemjs/system.src.js");
  }).then(async () => {
    // setup var recorder object
    window._recorder_ = {_module_:{}}

    const moduleOptionsNon = {
      babelOptions: {
        es2015: false,
        stage2: false,
        stage3: false,
        plugins: []
      }
    };

    System.trace = true; // does not work in config

    // config for loading babal plugins
    SystemJS.config({
      baseURL: lively4url + '/', // needed for global refs like "src/client/lively.js", we have to refactor those before disabling this here. #TODO #Discussion
      babelOptions: {
        // stage2: false,
        // stage3: false,
        // es2015: false,
        // stage0: true,
        // stage1: true
        //presets: [
        //    ["es2015", { "loose": true, "modules": false }]
        //],
        plugins: []
      },
      meta: {
        '*.js': moduleOptionsNon
      },
      map: {
        // #Discussion have to use absolute paths here, because it is not clear what the baseURL is
        'plugin-babel': lively4url + '/src/external/babel/plugin-babel2.js',
        'systemjs-plugin-babel': lively4url + '/src/external/babel/plugin-babel.js',
        'systemjs-babel-build': lively4url + '/src/external/babel/systemjs-babel-browser.js',
        'kernel': lively4url + '/src/client/legacy-kernel.js',

        // aexpr support
        'active-expressions': lively4url + '/src/external/aexpr/active-expressions/src/active-expressions.js',
        'aexpr-source-transformation-propagation': lively4url + '/src/external/aexpr/aexpr-source-transformation-propagation/src/aexpr-source-transformation-propagation.js',
        'babel-plugin-aexpr-source-transformation': lively4url + '/src/external/aexpr/babel-plugin-aexpr-source-transformation/index.js',
        'babel-plugin-locals': lively4url + '/src/external/aexpr/babel-plugin-locals/index.js',
        'stack-es2015-modules': lively4url + '/src/external/aexpr/stack-es2015-module/src/stack.js',

        // jsx support
        'babel-plugin-syntax-jsx': lively4url + '/src/external/babel-plugin-syntax-jsx.js',
        'babel-plugin-jsx-lively': lively4url + '/src/external/babel-plugin-jsx-lively.js',

        // stage 0 support
        'babel-plugin-transform-do-expressions': lively4url + '/src/external/babel-plugin-transform-do-expressions.js',
        'babel-plugin-transform-function-bind': lively4url + '/src/external/babel-plugin-transform-function-bind.js',
        'babel-plugin-syntax-do-expressions': lively4url + '/src/external/babel-plugin-syntax-do-expressions.js',
        'babel-plugin-syntax-function-bind': lively4url + '/src/external/babel-plugin-syntax-function-bind.js',

        // support for doits
        'babel-plugin-doit-result': lively4url + '/src/external/babel-plugin-doit-result.js',
        'babel-plugin-doit-this-ref': lively4url + '/src/external/babel-plugin-doit-this-ref.js',
        'babel-plugin-locals': lively4url + '/src/external/babel-plugin-locals.js',
        'babel-plugin-var-recorder': lively4url + '/src/external/babel-plugin-var-recorder.js',
        'workspace-loader': lively4url + '/src/client/workspace-loader.js',

        // utils
        'utils': lively4url + '/src/client/utils.js'
      },
      trace: true,
      transpiler: 'plugin-babel'
    })

/*    await System.import('babel-plugin-doit-result');
    await System.import('babel-plugin-doit-this-ref');
    await System.import('babel-plugin-locals');
    await System.import('babel-plugin-var-recorder');
  */  //await System.import(lively4url + '/src/client/workspaces.js');
    //await System.import('workspace-loader');

    SystemJS.config({
      meta: {
        // plugins are not transpiled with other plugins, except for SystemJS-internal plugins
        [lively4url + '/src/external/babel-plugin-*.js']: moduleOptionsNon,
        [lively4url + '/src/external/ContextJS/src/*.js']: moduleOptionsNon,
        //['']: moduleOptionsNon,
        // blacklist all projects included for active expressions
        [lively4url + '/src/external/aexpr/*.js']: moduleOptionsNon,
        // ... except for the tests
        [lively4url + '/src/external/aexpr/test/*.spec.js']: {
          babelOptions: {
            es2015: false,
            stage2: false,
            stage3: false,
            plugins: [
              'babel-plugin-jsx-lively',
              'babel-plugin-transform-do-expressions',
              'babel-plugin-transform-function-bind',
              'babel-plugin-doit-result',
              'babel-plugin-doit-this-ref',
              'babel-plugin-var-recorder',
              'babel-plugin-aexpr-source-transformation'
            ]
          },
          loader: 'workspace-loader'
        },
        // all others
        '*.js': {
          babelOptions: {
            es2015: false,
            stage2: false,
            stage3: false,
            plugins: [ // window.__karma__ ? [] :
              'babel-plugin-jsx-lively',
              'babel-plugin-transform-do-expressions',
              'babel-plugin-transform-function-bind',
              'babel-plugin-locals',
              'babel-plugin-var-recorder'
            ]
          }
        },
        'workspace:*': {
          babelOptions: {
            es2015: false,
            stage2: false,
            stage3: false,
            plugins: [
              'babel-plugin-jsx-lively',
              'babel-plugin-transform-do-expressions',
              'babel-plugin-transform-function-bind',
              'babel-plugin-locals',
              'babel-plugin-doit-result',
              'babel-plugin-doit-this-ref',
              'babel-plugin-var-recorder',
              'babel-plugin-aexpr-source-transformation'
            ]
          },
          loader: 'workspace-loader'
        },
        'workspacejs:*': {
          babelOptions: {
            es2015: false,
            stage2: false,
            stage3: false,
            plugins: [
              'babel-plugin-jsx-lively',
              'babel-plugin-transform-do-expressions',
              'babel-plugin-transform-function-bind',
              'babel-plugin-locals',
              'babel-plugin-doit-result',
              'babel-plugin-doit-this-ref',
              'babel-plugin-var-recorder'
            ]
          },
          loader: 'workspace-loader'
        },
      }
    });

    try {
      let { whenLoaded } = await System.import(lively4url + "/src/client/load.js")

      console.group("1/3: Wait for Service Worker...")
      await new Promise(whenLoaded);
      console.groupEnd();

      console.group("2/3: Look for uninitialized instances of Web Compoments");
      await lively.components.loadUnresolved();
      console.groupEnd();

      console.group("3/3: Initialize Document")
      await lively.initializeDocument(document, window.lively4chrome, loadContainer);
            console.groupEnd();

      console.log("Finally loaded!");

      document.dispatchEvent(new Event("livelyloaded"))

      console.groupEnd(); // BOOT
    } catch(err) {
      console.error("Lively Loading failed");
      console.error(err);
      alert("load Lively4 failed:" + err);
    }
  });
}
<|endoftext|>


<commit_before>/*!
 * Copyright 2009 Appcelerator, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Appcelerator Message Queue (Appcelerator MQ)
 * --------------------------------------------
 * Author:
 * Appcelerator Inc.
 *
 * Description:
 * Lightweight client-side or client-server message queue
 *
 **/
(function() {
  window.mq = {};
  // The following are, um, adapted from jQuery Core
  // Extend serves two functions - 1 to extend an object with the properties of another, and 2
  // to alow mq to be extended.
  mq.extend = function() {
    // copy reference to target object
    var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;

    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
      deep = target;
      target = arguments[1] || {};
      // skip the boolean and the target
      i = 2;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !mq.isFunction(target) ) {
      target = {};
    }

    // extend mq itself if only one argument is passed
    if ( length === i ) {
      target = this;
      --i;
    }

    for ( ; i < length; i++ ) {
      // Only deal with non-null/undefined values
      if ( (options = arguments[ i ]) != null ) {
        // Extend the base object
        for ( name in options ) {
          src = target[ name ];
          copy = options[ name ];

          // Prevent never-ending loop
          if ( target === copy ) {
            continue;
          }

          // Recurse if we're merging object values
          if ( deep && copy && typeof copy === "object" && !copy.nodeType ) {
            var clone;

            if ( src ) {
              clone = src;
            } else if ( mq.isArray(copy) ) {
              clone = [];
            } else if ( mq.isObject(copy) ) {
              clone = {};
            } else {
              clone = copy;
            }

            // Never move original objects, clone them
            target[ name ] = mq.extend( deep, clone, copy );

            // Don't bring in undefined values
          } else if ( copy !== undefined ) {
            target[ name ] = copy;
          }
        }
      }
    }

    // Return the modified object
    return target;
  };

  //Add top-level utility functions
  mq.extend({
    isFunction: function( obj ) {
      return toString.call(obj) === "[object Function]";
    },

    isArray: function( obj ) {
      return toString.call(obj) === "[object Array]";
    },

    isObject: function( obj ) {
      return this.constructor.call(obj) === Object;
    }
  });
})();<commit_msg>Testing gitodo for node knockout<commit_after>/*!
 * Copyright 2009 Appcelerator, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Appcelerator Message Queue (Appcelerator MQ)
 * --------------------------------------------
 * Author:
 * Appcelerator Inc.
 *
 * Description:
 * Lightweight client-side or client-server message queue
 * @todo: testing gittodo
 *
 **/
(function() {
  window.mq = {};
  // The following are, um, adapted from jQuery Core
  // Extend serves two functions - 1 to extend an object with the properties of another, and 2
  // to alow mq to be extended.
  mq.extend = function() {
    // copy reference to target object
    var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;

    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
      deep = target;
      target = arguments[1] || {};
      // skip the boolean and the target
      i = 2;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !mq.isFunction(target) ) {
      target = {};
    }

    // extend mq itself if only one argument is passed
    if ( length === i ) {
      target = this;
      --i;
    }

    for ( ; i < length; i++ ) {
      // Only deal with non-null/undefined values
      if ( (options = arguments[ i ]) != null ) {
        // Extend the base object
        for ( name in options ) {
          src = target[ name ];
          copy = options[ name ];

          // Prevent never-ending loop
          if ( target === copy ) {
            continue;
          }

          // Recurse if we're merging object values
          if ( deep && copy && typeof copy === "object" && !copy.nodeType ) {
            var clone;

            if ( src ) {
              clone = src;
            } else if ( mq.isArray(copy) ) {
              clone = [];
            } else if ( mq.isObject(copy) ) {
              clone = {};
            } else {
              clone = copy;
            }

            // Never move original objects, clone them
            target[ name ] = mq.extend( deep, clone, copy );

            // Don't bring in undefined values
          } else if ( copy !== undefined ) {
            target[ name ] = copy;
          }
        }
      }
    }

    // Return the modified object
    return target;
  };

  //Add top-level utility functions
  mq.extend({
    isFunction: function( obj ) {
      return toString.call(obj) === "[object Function]";
    },

    isArray: function( obj ) {
      return toString.call(obj) === "[object Array]";
    },

    isObject: function( obj ) {
      return this.constructor.call(obj) === Object;
    }
  });
})();
<|endoftext|>


<commit_before>// createService is a plugin for SkyDock that customizes the way container
// data is translated to a DNS entry.
function createService(container) {
    return {
        Port: 80,
        Environment: defaultEnvironment,
        TTL: defaultTTL,
        Service: container.Name.split('_')[1],
        Instance: removeSlash(container.Name.split('_')[0]),
        Host: container.NetworkSettings.IpAddress
    };
}
<commit_msg>VFS-1056 Modify createJson.js to accept container names with multiple '_'.<commit_after>// Author: Konrad Zemek
// Copyright (C) 2015 ACK CYFRONET AGH
// This software is released under the MIT license cited in 'LICENSE.txt'
//
// createService is a plugin for SkyDock that customizes the way container
// data is translated to a DNS entry.

function createService(container) {
    return {
        Port: 80,
        Environment: defaultEnvironment,
        TTL: defaultTTL,
        Service: container.Name.split('_').slice(-1),
        Instance: removeSlash(container.Name.split('_').slice(0, -1).join('_')),
        Host: container.NetworkSettings.IpAddress
    };
}
<|endoftext|>


<commit_before>// eslint-disable react/jsx-indent rule added for proper <Markdown /> formatting
/* eslint-disable react/jsx-indent */
const React = require('react');
const { Link } = require('react-router');

const { Button, SimpleSelect } = require('mx-react-components');

const Markdown = require('components/Markdown');

class SimpleSelectDocs extends React.Component {
  state = {
    selectedItem: null,
    showMenu: false
  };

  _handleItemClick = (e, item) => {
    this._toggleMenu();
    this.setState({ selectedItem: item });
  };

  _toggleMenu = () => {
    this.setState({
      showMenu: !this.state.showMenu
    });
  };

  render () {
    return (

          SimpleSelect
          A simple menu used to display a list of icons and/or text. Usually used in conjunction with a Button to toggle show/hide.

Demo

          <Button
            icon='gear'
            onClick={this._toggleMenu}
            type='neutral'
          >
            Settings
          </Button>
          {this.state.showMenu ? (
            <SimpleSelect
              aria-label='Select a category'
              items={[
                { icon: 'auto', text: 'Auto', onClick: this._handleItemClick },
                { icon: 'kids', isSelected: true, text: 'Kids', onClick: this._handleItemClick },
                { icon: 'pets', text: 'Pets', onClick: this._handleItemClick }
              ]}
              onScrimClick={this._toggleMenu}
            />
          ) : null}

Usage

iconSize Number

Default: 20

The icon size used for icons in menu items if used.

items Array Required

An array of objects that specify icon, isSelected, text, and/or onClick of the item..

onScrimClick function

onClick handler for the menu scrim.

scrimClickOnSelect boolean

Boolean that triggers a scrim click on select. Can be used to auto-close.

styles Object

A nested styles object to override/append any of the styled elements.

theme Object

Customize the component's look. See <Link to='/components/theme'>Theme</Link> for more information.

Example

        <Markdown>
  {`
    _handleItemClick (e, item) {
      this._toggleMenu();
      alert(\`You clicked $\{item.text\}\`);
    },

    _toggleMenu () {
      this.setState({
        showMenu: !this.state.showMenu
      });
    },

      <Button
        icon='gear'
        onClick={this._toggleMenu}
        type='neutral'
      >
        Settings
      </Button>
      {this.state.showMenu ? (
        <SimpleSelect
          aria-label='Select a category'
          items={[
            { icon: 'auto', text: 'Auto', onClick: this._handleItemClick },
            { icon: 'kids', isSelected: true, text: 'Kids', onClick: this._handleItemClick },
            { icon: 'pets', text: 'Pets', onClick: this._handleItemClick }
          ]}
          onScrimClick={this._toggleMenu}
        />
      ) : null}

  `}
        </Markdown>

    );
  }
}

module.exports = SimpleSelectDocs;
<commit_msg>Update docs for SimpleSelect<commit_after>// eslint-disable react/jsx-indent rule added for proper <Markdown /> formatting
/* eslint-disable react/jsx-indent */
const React = require('react');
const { Link } = require('react-router');

const { Button, SimpleSelect } = require('mx-react-components');

const Markdown = require('components/Markdown');

class SimpleSelectDocs extends React.Component {
  state = {
    selectedItem: null,
    showMenu: false
  };

  _handleItemClick = (e, item) => {
    this._toggleMenu();
    this.setState({ selectedItem: item });
  };

  _toggleMenu = () => {
    this.setState({
      showMenu: !this.state.showMenu
    });
  };

  render () {
    return (

          SimpleSelect
          A simple menu used to display a list of icons and/or text. Usually used in conjunction with a Button to toggle show/hide.

Demo

          <Button
            icon='gear'
            onClick={this._toggleMenu}
            type='neutral'
          >
            Settings
          </Button>
          {this.state.showMenu ? (
            <SimpleSelect
              aria-label='Select a category'
              items={[
                { icon: 'auto', text: 'Auto', onClick: this._handleItemClick },
                { icon: 'kids', isSelected: true, text: 'Kids', onClick: this._handleItemClick },
                { icon: 'pets', text: 'Pets', onClick: this._handleItemClick }
              ]}
              onScrimClick={this._toggleMenu}
            />
          ) : null}

Usage

focusTrapPropsObject

Default: Empty Object

The SimpleSelect component uses the Focus Trap React library to prevent a user from tabing outside the SimpleSelect for accessibility reasons.

The focusTrapProps object provides a mechanism for passing the focus trap component props.

See the library documentation for details on what props it accepts and how to use them.

iconSize Number

Default: 20

The icon size used for icons in menu items if used.

items Array Required

An array of objects that specify icon, isSelected, text, and/or onClick of the item..

onScrimClick function

onClick handler for the menu scrim.

scrimClickOnSelect boolean

Boolean that triggers a scrim click on select. Can be used to auto-close.

styles Object

A nested styles object to override/append any of the styled elements.

theme Object

Customize the component's look. See <Link to='/components/theme'>Theme</Link> for more information.

Example

        <Markdown>
  {`
    _handleItemClick (e, item) {
      this._toggleMenu();
      alert(\`You clicked $\{item.text\}\`);
    },

    _toggleMenu () {
      this.setState({
        showMenu: !this.state.showMenu
      });
    },

      <Button
        icon='gear'
        onClick={this._toggleMenu}
        type='neutral'
      >
        Settings
      </Button>
      {this.state.showMenu ? (
        <SimpleSelect
          aria-label='Select a category'
          items={[
            { icon: 'auto', text: 'Auto', onClick: this._handleItemClick },
            { icon: 'kids', isSelected: true, text: 'Kids', onClick: this._handleItemClick },
            { icon: 'pets', text: 'Pets', onClick: this._handleItemClick }
          ]}
          onScrimClick={this._toggleMenu}
        />
      ) : null}

  `}
        </Markdown>

    );
  }
}

module.exports = SimpleSelectDocs;
<|endoftext|>


<commit_before>/* eslint react/no-multi-comp: 0, react/prop-types: 0, react/prefer-stateless-function: 0 */
import React from 'react';
import { PrismCode } from 'react-prism';
import { Table, Alert } from 'reactstrap';
import Helmet from 'react-helmet';
import ShortcutExample from '../examples/Shortcut';

const ShortcutExampleSource = require('!!raw-loader!../examples/Shortcut');

export default class ShortcutPage extends React.Component {
  render() {
    return (

        <Helmet title="Shortcut" />

Shortcut

Using keyboard shortcut to control the player.

        <Alert color="warning">
          Warning!The shortcut can work only if the player is
          in active.
        </Alert>

Properties

          <PrismCode className="language-jsx">
            {`Shortcut.propTypes = {

  // Add your own shortcuts
  shortcuts: PropTypes.array,
  clickable: PropTypes.bool,
  dblclickable: PropTypes.bool,
}`}
          </PrismCode>

Keyboard Shortcuts

                Action

                Shortcut

              Toggle play/pause the video
              k or Spacebar

              Go back 5 seconds
              Left arrow

              Go back 10 seconds
              j

              Go forward 5 seconds
              Right arrow

              Go forward 10 seconds
              l

              Restart video
              0

              Go to Full Screen mode
              f

              Exit Full Screen mode
              Escape

              Increase volume 5%
              Up arrow

              Decrease volume 5%
              Down arrow

              Increase speed
              Shift + {'>'}

              Decrease speed
              Shift + {'<'}

Example

          <ShortcutExample />

          <PrismCode className="language-jsx">
            {ShortcutExampleSource}
          </PrismCode>

    );
  }
}
<commit_msg>fix docs for ShortcutPage<commit_after>/* eslint react/no-multi-comp: 0, react/prop-types: 0, react/prefer-stateless-function: 0 */
import React from 'react';
import { PrismCode } from 'react-prism';
import { Table, Alert } from 'reactstrap';
import Helmet from 'react-helmet';
import ShortcutExample from '../examples/Shortcut';

const ShortcutExampleSource = require('!!raw-loader!../examples/Shortcut');

export default class ShortcutPage extends React.Component {
  render() {
    return (

        <Helmet title="Shortcut" />

Shortcut

Using keyboard shortcut to control the player.

        <Alert color="warning">
          Warning! The shortcut can work only when the player
          is active.
        </Alert>

Properties

          <PrismCode className="language-jsx">
            {`Shortcut.propTypes = {
  // Allow click to play/pause, by default true
  clickable: PropTypes.bool,
  // Allow double click to toggle fullscreen state, by default true
  dblclickable: PropTypes.bool,
  // Add your own shortcuts
  shortcuts: PropTypes.array
}`}
          </PrismCode>

Default Keyboard Shortcuts

                Action

                Shortcut

              Toggle play/pause the video
              k or Spacebar

              Go back 5 seconds
              Left arrow

              Go back 10 seconds
              j

              Go forward 5 seconds
              Right arrow

              Go forward 10 seconds
              l

              Restart video
              Home

              Bring video to the end
              End

              Go to Full Screen mode
              f

              Exit Full Screen mode
              Escape

              Increase volume 5%
              Up arrow

              Decrease volume 5%
              Down arrow

              Increase speed
              Shift + {'>'}

              Decrease speed
              Shift + {'<'}

Example

          <ShortcutExample />

          <PrismCode className="language-jsx">
            {ShortcutExampleSource}
          </PrismCode>

    );
  }
}
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var findremove = require('find-remove');
var capture = require('./commandLineCapture');

exports.captureTimelapse = function (settings) {
    try {
        var imagePath = capture.getImagePath(settings);
        var directory = path.dirname(imagePath);
        var fullFileName = capture.getImageFileName(settings);
        var extension = path.extname(fullFileName);
        var baseName = path.basename(fullFileName, extension);
        var timestamp = new Date().getTime().toString();

        var timelapseFileName = path.join(directory, "timelapse");
        timelapseFileName = path.join(timelapseFileName, baseName + "_" + timestamp + extension);

        fs.createReadStream(imagePath).pipe(fs.createWriteStream(timelapseFileName));
        console.log("Saved timelapse image " + timelapseFileName);

        var result = findremove(directory, { age: { seconds: settings.TimelapseMaxHistoryHours * 60 * 60 }, extensions: extension });
        console.log("Deleted timelapse files: " + result);
    } catch (err) {
        console.log("Error capturing time lapse: " + err);
    }
}<commit_msg>fix timelapse delete<commit_after>var fs = require('fs');
var path = require('path');
var findremove = require('find-remove');
var capture = require('./commandLineCapture');

exports.captureTimelapse = function (settings) {
    try {
        var imagePath = capture.getImagePath(settings);
        var directory = path.dirname(imagePath);
        var fullFileName = capture.getImageFileName(settings);
        var extension = path.extname(fullFileName);
        var baseName = path.basename(fullFileName, extension);
        var timestamp = new Date().getTime().toString();

        directory = path.join(directory, "timelapse")
        var timelapseFileName = timelapseFileName = path.join(directory, baseName + "_" + timestamp + extension);

        fs.createReadStream(imagePath).pipe(fs.createWriteStream(timelapseFileName));
        console.log("Saved timelapse image " + timelapseFileName);

        var result = findremove(directory, { age: { seconds: settings.TimelapseMaxHistoryHours * 60 * 60 }, extensions: extension });
        console.log("Deleted timelapse files: " + result);
    } catch (err) {
        console.log("Error capturing time lapse: " + err);
    }
}<|endoftext|>


<commit_before><commit_msg>Solved "04. Product of 3 Numbers"<commit_after><|endoftext|>


<commit_before>'use strict';
define(['angular-mocks', 'portal'], function() {
    describe('NotificationService', function() {
        var notificationsService, httpBackend, backendURL;

        beforeEach(function() {
          module('portal');
        });

        beforeEach(inject(function(_notificationsService_, _$httpBackend_, SERVICE_LOC) {
            notificationsService = _notificationsService_;
            httpBackend = _$httpBackend_;
            backendURL = SERVICE_LOC.notificationsURL;
        }));

        it("should return an empty set", function() {
            //setup
            httpBackend.whenGET(backendURL).respond({"notifications" :[]});

            //begin test
            notificationsService.getAllNotifications().then(function(results){
                expect(results).toBeTruthy();
                expect(results.length).toEqual(0);
            });
            httpBackend.flush();
        });

        it("should have one result", function() {
            //setup
            httpBackend.whenGET(backendURL).respond(
                {"notifications" :
                    [
                     {
                       "id"     : 1,
                       "groups" : ["Portal Administrators"],
                       "title"  : "This is an admin notification smoke test",
                       "actionURL" : "http://www.google.com",
                       "actionAlt" : "Google"
                     }
                   ]
               });

            //begin test
            notificationsService.getAllNotifications().then(function(results){
                expect(results).toBeTruthy();
                expect(results.length).toEqual(1);
            });
            httpBackend.flush();
        });
    });
});
<commit_msg>fix unit tests<commit_after>'use strict';
define(['angular-mocks', 'portal'], function() {
    describe('NotificationService', function() {
        var notificationsService, httpBackend, backendURL, groupURL;

        beforeEach(function() {
          module('portal');
        });

        beforeEach(inject(function(_notificationsService_, _$httpBackend_, SERVICE_LOC) {
            notificationsService = _notificationsService_;
            httpBackend = _$httpBackend_;
            backendURL = SERVICE_LOC.notificationsURL;
            groupURL   = SERVICE_LOC.groupURL;
        }));

        it("should return an empty set", function() {

            //setup
            httpBackend.whenGET(backendURL).respond({"notifications" :[]});
            httpBackend.whenGet(groupURL).respond({"groups" :[]});
            //begin test
            notificationsService.getAllNotifications().then(function(results){
                expect(results).toBeTruthy();
                expect(results.length).toEqual(0);
            });
            httpBackend.flush();
        });

        it("should have one result", function() {
            //setup
            httpBackend.whenGet(groupURL).respond({"groups" :[]});
            httpBackend.whenGET(backendURL).respond(
                {"notifications" :
                    [
                     {
                       "id"     : 1,
                       "groups" : ["Portal Administrators"],
                       "title"  : "This is an admin notification smoke test",
                       "actionURL" : "http://www.google.com",
                       "actionAlt" : "Google"
                     }
                   ]
               });

            //begin test
            notificationsService.getAllNotifications().then(function(results){
                expect(results).toBeTruthy();
                expect(results.length).toEqual(1);
            });
            httpBackend.flush();
        });
    });
});
<|endoftext|>


<commit_before>CKEDITOR.dialog.add( 'highlight_js', function( editor ) {
    return {
        title: "test",
        minWidth: 800,
        minHeight: 500,
        contents: [
            {
                id: 'tab-basic',
                label: 'Basic Settings',
                elements: [
                    {
                        type: 'select',
                        id: 'code_lan',
                        label: 'Select code language',
                        items: [
                                [ 'Auto' ],
                                [ 'Bash' ],
                                [ 'Diff' ],
                                [ 'JSON' ],
                                [ 'C#' ],
                                [ 'HTML' ],
                                [ 'JAVA' ],
                                [ 'Python' ],
                                [ 'C++' ],
                                [ 'HTTP' ],
                                [ 'JavaScript' ],
                                [ 'Ruby' ],
                                [ 'CSS' ],
                                [ 'PHP' ],
                                [ 'ini' ],
                                [ 'SQL' ],
                                [ 'Perl' ],
                                [ " 1C " ],
                                [ "AVR Assembler" ],
                                [ "ActionScript" ],
                                [ "Apache" ],
                                [ "AppleScript" ],
                                [ "Axapta" ],
                                [ "Brainfuck" ],
                                [ "CMake" ],
                                [ "Clojure" ],
                                [ "CoffeeScript" ],
                                [ "D" ],
                                [ "DOS .bat" ],
                                [ "Delphi" ],
                                [ "Django" ],
                                [ "Erlang" ],
                                [ "Erlang REPL" ],
                                [ "GLSL" ],
                                [ "Go" ],
                                [ 'Haskell' ],
                                [ "Lisp" ],
                                [ "Lua" ],
                                [ "MEL" ],
                                [ "Markdown" ],
                                [ "Matlab" ],
                                [ "Nginx" ],
                                [ "Objective C" ],
                                [ "Parser3" ],
                                [ "Python profile" ],
                                [ "R" ],
                                [ "RenderMan RIB" ],
                                [ "RenderMan RSL" ],
                                [ "Rust" ],
                                [ "Scala" ],
                                [ "Smalltalk" ],
                                [ "TeX" ],
                                [ "VBScript" ],
                                [ "VHDL" ],
                                [ "Vala" ]
                              ],
                        'default': 'Auto',
                        onChange: function( api ) {
                        // this = CKEDITOR.ui.dialog.select
                         alert( 'Current value: ' + this.getValue() );
                        }
                    },
                    {
                        type: 'textarea',
                        id: 'pre_code',
                        rows: 22,
                        style: "width: 100%"
                        /*setup: function(data) {
                            if (data.code)
                                this.setValue(data.code);
                        },
                        commit: function(data) {
                            data.code = this.getValue();
                        }*/
                    }
                ]
            }

        ],
        onOk: function() {
            var dialog = this;

            var pre = editor.document.createElement( 'pre' );
            var code = editor.document.createElement( 'code' );
            var code_class = dialog.getValueOf( 'tab-basic', 'code_lan' ).toLowerCase();

            if(code_class !== "auto"){
                code.setAttribute( 'class', code_class );
            }

            code.setText( dialog.getValueOf( 'tab-basic', 'pre_code' ) );

            pre.append(code);

            editor.insertElement(pre);
        }
    };
});
<commit_msg>Added no-highlight class<commit_after>CKEDITOR.dialog.add( 'highlight_js', function( editor ) {
    return {
        title: "test",
        minWidth: 800,
        minHeight: 500,
        contents: [
            {
                id: 'tab-basic',
                label: 'Basic Settings',
                elements: [
                    {
                        type: 'select',
                        id: 'code_lan',
                        label: 'Select code language',
                        items: [
                                [ 'Auto' ],
                                [ 'no-highlight' ],
                                [ 'Bash' ],
                                [ 'Diff' ],
                                [ 'JSON' ],
                                [ 'C#' ],
                                [ 'HTML' ],
                                [ 'JAVA' ],
                                [ 'Python' ],
                                [ 'C++' ],
                                [ 'HTTP' ],
                                [ 'JavaScript' ],
                                [ 'Ruby' ],
                                [ 'CSS' ],
                                [ 'PHP' ],
                                [ 'ini' ],
                                [ 'SQL' ],
                                [ 'Perl' ],
                                [ " 1C " ],
                                [ "AVR Assembler" ],
                                [ "ActionScript" ],
                                [ "Apache" ],
                                [ "AppleScript" ],
                                [ "Axapta" ],
                                [ "Brainfuck" ],
                                [ "CMake" ],
                                [ "Clojure" ],
                                [ "CoffeeScript" ],
                                [ "D" ],
                                [ "DOS .bat" ],
                                [ "Delphi" ],
                                [ "Django" ],
                                [ "Erlang" ],
                                [ "Erlang REPL" ],
                                [ "GLSL" ],
                                [ "Go" ],
                                [ 'Haskell' ],
                                [ "Lisp" ],
                                [ "Lua" ],
                                [ "MEL" ],
                                [ "Markdown" ],
                                [ "Matlab" ],
                                [ "Nginx" ],
                                [ "Objective C" ],
                                [ "Parser3" ],
                                [ "Python profile" ],
                                [ "R" ],
                                [ "RenderMan RIB" ],
                                [ "RenderMan RSL" ],
                                [ "Rust" ],
                                [ "Scala" ],
                                [ "Smalltalk" ],
                                [ "TeX" ],
                                [ "VBScript" ],
                                [ "VHDL" ],
                                [ "Vala" ]
                              ],
                        'default': 'Auto',
                        onChange: function( api ) {
                        // this = CKEDITOR.ui.dialog.select
                         alert( 'Current value: ' + this.getValue() );
                        }
                    },
                    {
                        type: 'textarea',
                        id: 'pre_code',
                        rows: 22,
                        style: "width: 100%"
                        /*setup: function(data) {
                            if (data.code)
                                this.setValue(data.code);
                        },
                        commit: function(data) {
                            data.code = this.getValue();
                        }*/
                    }
                ]
            }

        ],
        onOk: function() {
            var dialog = this;

            var pre = editor.document.createElement( 'pre' );
            var code = editor.document.createElement( 'code' );
            var code_class = dialog.getValueOf( 'tab-basic', 'code_lan' ).toLowerCase();

            if(code_class !== "auto"){
                code.setAttribute( 'class', code_class );
            }

            code.setText( dialog.getValueOf( 'tab-basic', 'pre_code' ) );

            pre.append(code);

            editor.insertElement(pre);
        }
    };
});
<|endoftext|>


<commit_before>//used for the media picker dialog
angular.module("umbraco")
    .controller("Umbraco.Overlays.MediaPickerController",
        function ($scope, mediaResource, umbRequestHelper, entityResource, $log, mediaHelper, eventsService, treeService, $element, $timeout, $cookies, $cookieStore, localizationService) {

            if(!$scope.model.title) {
                $scope.model.title = localizationService.localize("defaultdialogs_selectMedia");
            }

            var dialogOptions = $scope.model;

            $scope.disableFolderSelect = dialogOptions.disableFolderSelect;
            $scope.onlyImages = dialogOptions.onlyImages;
            $scope.showDetails = dialogOptions.showDetails;
            $scope.multiPicker = (dialogOptions.multiPicker && dialogOptions.multiPicker !== "0") ? true : false;
            $scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1;
            $scope.cropSize = dialogOptions.cropSize;
            $scope.lastOpenedNode = $cookieStore.get("umbLastOpenedMediaNodeId");
            $scope.acceptedFileTypes = mediaHelper.formatFileTypes(Umbraco.Sys.ServerVariables.umbracoSettings.imageFileTypes);
            $scope.maxFileSize = Umbraco.Sys.ServerVariables.umbracoSettings.maxFileSize + "KB";

            $scope.model.selectedImages = [];

            //preload selected item
            $scope.target = undefined;
            if(dialogOptions.currentTarget){
                $scope.target = dialogOptions.currentTarget;
            }

            $scope.upload = function(v){
               angular.element(".umb-file-dropzone-directive .file-select").click();
            };

            $scope.dragLeave = function(el, event){
                $scope.activeDrag = false;
            };

            $scope.dragEnter = function(el, event){
                $scope.activeDrag = true;
            };

            $scope.submitFolder = function() {

               if ($scope.newFolderName) {

                  mediaResource
                     .addFolder($scope.newFolderName, $scope.currentFolder.id)
                     .then(function(data) {

                        //we've added a new folder so lets clear the tree cache for that specific item
                        treeService.clearCache({
                           cacheKey: "__media", //this is the main media tree cache key
                           childrenOf: data.parentId //clear the children of the parent
                        });

                        $scope.gotoFolder(data);

                        $scope.showFolderInput = false;

                        $scope.newFolderName = "";

                     });

               } else {
                  $scope.showFolderInput = false;
               }

            };

            $scope.enterSubmitFolder = function(event) {
                if (event.keyCode === 13) {
                    $scope.submitFolder();
                    event.stopPropagation();
                }
            };

            $scope.gotoFolder = function(folder) {

                if(!$scope.multiPicker) {
                    deselectAllImages($scope.model.selectedImages);
                }

                if(!folder){
                    folder = {id: -1, name: "Media", icon: "icon-folder"};
                }

                if (folder.id > 0) {
                    entityResource.getAncestors(folder.id, "media")
                        .then(function(anc) {
                            // anc.splice(0,1);
                            $scope.path = _.filter(anc, function (f) {
                                return f.path.indexOf($scope.startNodeId) !== -1;
                            });
                        });
                }
                else {
                    $scope.path = [];
                }

                //mediaResource.rootMedia()
                mediaResource.getChildren(folder.id)
                   .then(function(data) {
                      $scope.searchTerm = "";
                      $scope.images = data.items ? data.items : [];

                      // set already selected images to selected
                      for (var folderImageIndex = 0; folderImageIndex < $scope.images.length; folderImageIndex++) {

                         var folderImage = $scope.images[folderImageIndex];
                         var imageIsSelected = false;

                         for (var selectedImageIndex = 0; selectedImageIndex < $scope.model.selectedImages.length; selectedImageIndex++) {
                            var selectedImage = $scope.model.selectedImages[selectedImageIndex];

                            if(folderImage.key === selectedImage.key) {
                               imageIsSelected = true;
                            }
                         }

                         if(imageIsSelected) {
                            folderImage.selected = true;
                         }
                      }

                   });

                $scope.currentFolder = folder;

                // for some reason i cannot set cookies with cookieStore
                document.cookie="umbLastOpenedMediaNodeId=" + folder.id;

            };

            $scope.clickHandler = function(image, event, index) {
                if (image.isFolder) {
                    if ($scope.disableFolderSelect) {
                        $scope.gotoFolder(image);
                    } else {
                        eventsService.emit("dialogs.mediaPicker.select", image);
                        selectImage(image);
                    }

                } else {

                    eventsService.emit("dialogs.mediaPicker.select", image);

                    if($scope.showDetails) {
                        $scope.target = image;
                        $scope.target.url = mediaHelper.resolveFile(image);
                        $scope.openDetailsDialog();
                    } else {
                        selectImage(image);
                    }

                }

            };

            $scope.clickItemName = function(item) {
                if(item.isFolder) {
                    $scope.gotoFolder(item);
                }
            };

            function selectImage(image) {

                if(image.selected) {

                    for(var i = 0; $scope.model.selectedImages.length > i; i++) {

                        var imageInSelection = $scope.model.selectedImages[i];
                        if(image.key === imageInSelection.key) {
                            image.selected = false;
                            $scope.model.selectedImages.splice(i, 1);
                        }
                    }

                } else {

                    if(!$scope.multiPicker) {
                        deselectAllImages($scope.model.selectedImages);
                    }

                    image.selected = true;
                    $scope.model.selectedImages.push(image);
                }

            }

            function deselectAllImages(images) {
                for (var i = 0; i < images.length; i++) {
                    var image = images[i];
                    image.selected = false;
                }
                images.length = 0;
            }

            $scope.onUploadComplete = function () {
                $scope.gotoFolder($scope.currentFolder);
            };

            $scope.onFilesQueue = function(){
                $scope.activeDrag = false;
            };

            //default root item
            if (!$scope.target) {

               if($scope.lastOpenedNode && $scope.lastOpenedNode !== -1) {

                  entityResource.getById($scope.lastOpenedNode, "media")
                     .then(function(node){

                        // make sure that las opened node is on the same path as start node
                        var nodePath = node.path.split(",");

                        if(nodePath.indexOf($scope.startNodeId.toString()) !== -1) {
                           $scope.gotoFolder({id: $scope.lastOpenedNode, name: "Media", icon: "icon-folder"});
                        } else {
                           $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"});
                        }

                    }, function (err) {
                        $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"});
                    });

               } else {

                  $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"});

               }

            }

            $scope.openDetailsDialog = function() {

               $scope.mediaPickerDetailsOverlay = {};
               $scope.mediaPickerDetailsOverlay.show = true;

               $scope.mediaPickerDetailsOverlay.submit = function(model) {

                  $scope.model.selectedImages.push($scope.target);
                  $scope.model.submit($scope.model);

                  $scope.mediaPickerDetailsOverlay.show = false;
                  $scope.mediaPickerDetailsOverlay = null;

               };

               $scope.mediaPickerDetailsOverlay.close = function(oldModel) {
                  $scope.mediaPickerDetailsOverlay.show = false;
                  $scope.mediaPickerDetailsOverlay = null;
               };

            };

        });
<commit_msg>* Only restrict to image files when onlyImages is active* Handle disallowed filetypes as per other upload controls<commit_after>//used for the media picker dialog
angular.module("umbraco")
    .controller("Umbraco.Overlays.MediaPickerController",
        function ($scope, mediaResource, umbRequestHelper, entityResource, $log, mediaHelper, eventsService, treeService, $element, $timeout, $cookies, $cookieStore, localizationService) {

            if(!$scope.model.title) {
                $scope.model.title = localizationService.localize("defaultdialogs_selectMedia");
            }

            var dialogOptions = $scope.model;

            $scope.disableFolderSelect = dialogOptions.disableFolderSelect;
            $scope.onlyImages = dialogOptions.onlyImages;
            $scope.showDetails = dialogOptions.showDetails;
            $scope.multiPicker = (dialogOptions.multiPicker && dialogOptions.multiPicker !== "0") ? true : false;
            $scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1;
            $scope.cropSize = dialogOptions.cropSize;
            $scope.lastOpenedNode = $cookieStore.get("umbLastOpenedMediaNodeId");
            if($scope.onlyImages){
                $scope.acceptedFileTypes = mediaHelper.formatFileTypes(Umbraco.Sys.ServerVariables.umbracoSettings.imageFileTypes);
            }
            else {
                $scope.acceptedFileTypes = mediaHelper.formatFileTypes(Umbraco.Sys.ServerVariables.umbracoSettings.disallowedUploadFiles).replace(/\./g, "!.");
            }
            $scope.maxFileSize = Umbraco.Sys.ServerVariables.umbracoSettings.maxFileSize + "KB";

            $scope.model.selectedImages = [];

            //preload selected item
            $scope.target = undefined;
            if(dialogOptions.currentTarget){
                $scope.target = dialogOptions.currentTarget;
            }

            $scope.upload = function(v){
               angular.element(".umb-file-dropzone-directive .file-select").click();
            };

            $scope.dragLeave = function(el, event){
                $scope.activeDrag = false;
            };

            $scope.dragEnter = function(el, event){
                $scope.activeDrag = true;
            };

            $scope.submitFolder = function() {

               if ($scope.newFolderName) {

                  mediaResource
                     .addFolder($scope.newFolderName, $scope.currentFolder.id)
                     .then(function(data) {

                        //we've added a new folder so lets clear the tree cache for that specific item
                        treeService.clearCache({
                           cacheKey: "__media", //this is the main media tree cache key
                           childrenOf: data.parentId //clear the children of the parent
                        });

                        $scope.gotoFolder(data);

                        $scope.showFolderInput = false;

                        $scope.newFolderName = "";

                     });

               } else {
                  $scope.showFolderInput = false;
               }

            };

            $scope.enterSubmitFolder = function(event) {
                if (event.keyCode === 13) {
                    $scope.submitFolder();
                    event.stopPropagation();
                }
            };

            $scope.gotoFolder = function(folder) {

                if(!$scope.multiPicker) {
                    deselectAllImages($scope.model.selectedImages);
                }

                if(!folder){
                    folder = {id: -1, name: "Media", icon: "icon-folder"};
                }

                if (folder.id > 0) {
                    entityResource.getAncestors(folder.id, "media")
                        .then(function(anc) {
                            // anc.splice(0,1);
                            $scope.path = _.filter(anc, function (f) {
                                return f.path.indexOf($scope.startNodeId) !== -1;
                            });
                        });
                }
                else {
                    $scope.path = [];
                }

                //mediaResource.rootMedia()
                mediaResource.getChildren(folder.id)
                   .then(function(data) {
                      $scope.searchTerm = "";
                      $scope.images = data.items ? data.items : [];

                      // set already selected images to selected
                      for (var folderImageIndex = 0; folderImageIndex < $scope.images.length; folderImageIndex++) {

                         var folderImage = $scope.images[folderImageIndex];
                         var imageIsSelected = false;

                         for (var selectedImageIndex = 0; selectedImageIndex < $scope.model.selectedImages.length; selectedImageIndex++) {
                            var selectedImage = $scope.model.selectedImages[selectedImageIndex];

                            if(folderImage.key === selectedImage.key) {
                               imageIsSelected = true;
                            }
                         }

                         if(imageIsSelected) {
                            folderImage.selected = true;
                         }
                      }

                   });

                $scope.currentFolder = folder;

                // for some reason i cannot set cookies with cookieStore
                document.cookie="umbLastOpenedMediaNodeId=" + folder.id;

            };

            $scope.clickHandler = function(image, event, index) {
                if (image.isFolder) {
                    if ($scope.disableFolderSelect) {
                        $scope.gotoFolder(image);
                    } else {
                        eventsService.emit("dialogs.mediaPicker.select", image);
                        selectImage(image);
                    }

                } else {

                    eventsService.emit("dialogs.mediaPicker.select", image);

                    if($scope.showDetails) {
                        $scope.target = image;
                        $scope.target.url = mediaHelper.resolveFile(image);
                        $scope.openDetailsDialog();
                    } else {
                        selectImage(image);
                    }

                }

            };

            $scope.clickItemName = function(item) {
                if(item.isFolder) {
                    $scope.gotoFolder(item);
                }
            };

            function selectImage(image) {

                if(image.selected) {

                    for(var i = 0; $scope.model.selectedImages.length > i; i++) {

                        var imageInSelection = $scope.model.selectedImages[i];
                        if(image.key === imageInSelection.key) {
                            image.selected = false;
                            $scope.model.selectedImages.splice(i, 1);
                        }
                    }

                } else {

                    if(!$scope.multiPicker) {
                        deselectAllImages($scope.model.selectedImages);
                    }

                    image.selected = true;
                    $scope.model.selectedImages.push(image);
                }

            }

            function deselectAllImages(images) {
                for (var i = 0; i < images.length; i++) {
                    var image = images[i];
                    image.selected = false;
                }
                images.length = 0;
            }

            $scope.onUploadComplete = function () {
                $scope.gotoFolder($scope.currentFolder);
            };

            $scope.onFilesQueue = function(){
                $scope.activeDrag = false;
            };

            //default root item
            if (!$scope.target) {

               if($scope.lastOpenedNode && $scope.lastOpenedNode !== -1) {

                  entityResource.getById($scope.lastOpenedNode, "media")
                     .then(function(node){

                        // make sure that las opened node is on the same path as start node
                        var nodePath = node.path.split(",");

                        if(nodePath.indexOf($scope.startNodeId.toString()) !== -1) {
                           $scope.gotoFolder({id: $scope.lastOpenedNode, name: "Media", icon: "icon-folder"});
                        } else {
                           $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"});
                        }

                    }, function (err) {
                        $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"});
                    });

               } else {

                  $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"});

               }

            }

            $scope.openDetailsDialog = function() {

               $scope.mediaPickerDetailsOverlay = {};
               $scope.mediaPickerDetailsOverlay.show = true;

               $scope.mediaPickerDetailsOverlay.submit = function(model) {

                  $scope.model.selectedImages.push($scope.target);
                  $scope.model.submit($scope.model);

                  $scope.mediaPickerDetailsOverlay.show = false;
                  $scope.mediaPickerDetailsOverlay = null;

               };

               $scope.mediaPickerDetailsOverlay.close = function(oldModel) {
                  $scope.mediaPickerDetailsOverlay.show = false;
                  $scope.mediaPickerDetailsOverlay = null;
               };

            };

        });
<|endoftext|>


<commit_before>
var path = require('path')
  ;

exports.require = function _require(what) {
  if (process.env.npm_config_coverage || process.env.BUILDTYPE === 'Coverage') {
    return require(path.join('../../build/Coverage/lib/' + what))
  }
  return require('../../lib/' + what)
}

var mdns  = exports.require('mdns');

var legal_chars = "abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

exports.suffixedServiceType = function suffixedServiceType(serviceName, protocol) {
  serviceName += '-';
  while (serviceName.length < 14) {
    serviceName += legal_chars[Math.floor(Math.random() * legal_chars.length)];
  }
  return mdns.makeServiceType.apply(this, arguments)
}

exports.runTestAd = function runTestAd(type, port, uptime, cooltime, cb) {
  if ( ! cb ) {
    cb = cooltime;
    cooltime = uptime;
  }
  if ( ! cb) {
    cb = cooltime;
    uptime = cooltime = 2000;
  }
  var ad = new mdns.createAdvertisement(type, port, function(error, service) {
        if (error) throw error;
        setTimeout(function() { ad.stop(); setTimeout(cb, cooltime); }, uptime);
      });
  ad.start();
  return ad;
}

if (0) {
exports.lifeExpectancy = 5000;

var lifeTimer;

process.nextTick(function() {
  lifeTimer = setTimeout(function() {
    throw new Error("test did not finish within " + (exports.lifeExpectancy / 1000) + " seconds.");
    process.exit(-1);
  }, exports.lifeExpectancy);
});

exports.done = function done() { clearTimeout( lifeTimer ); }
}
<commit_msg>service type must be lowercase, numbers, or hyphens.<commit_after>
var path = require('path')
  ;

exports.require = function _require(what) {
  if (process.env.npm_config_coverage || process.env.BUILDTYPE === 'Coverage') {
    return require(path.join('../../build/Coverage/lib/' + what))
  }
  return require('../../lib/' + what)
}

var mdns  = exports.require('mdns');

var legal_chars = "abcefghijklmnopqrstuvwxyz"

exports.suffixedServiceType = function suffixedServiceType(serviceName, protocol) {
  serviceName += '-';
  while (serviceName.length < 14) {
    serviceName += legal_chars[Math.floor(Math.random() * legal_chars.length)];
  }
  return mdns.makeServiceType.apply(this, arguments)
}

exports.runTestAd = function runTestAd(type, port, uptime, cooltime, cb) {
  if ( ! cb ) {
    cb = cooltime;
    cooltime = uptime;
  }
  if ( ! cb) {
    cb = cooltime;
    uptime = cooltime = 2000;
  }
  var ad = new mdns.createAdvertisement(type, port, function(error, service) {
        if (error) throw error;
        setTimeout(function() { ad.stop(); setTimeout(cb, cooltime); }, uptime);
      });
  ad.start();
  return ad;
}

if (0) {
exports.lifeExpectancy = 5000;

var lifeTimer;

process.nextTick(function() {
  lifeTimer = setTimeout(function() {
    throw new Error("test did not finish within " + (exports.lifeExpectancy / 1000) + " seconds.");
    process.exit(-1);
  }, exports.lifeExpectancy);
});

exports.done = function done() { clearTimeout( lifeTimer ); }
}
<|endoftext|>


<commit_before>
/*
//Reference prior, cached database
var dbOLD = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
//Destroy it
dbOLD.remove();
*/
//Install new database
var db;

    if (Ti.Platform.name === 'android' && Ti.Filesystem.isExternalStoragePresent()) {

	 db = Titanium.Database.install('/PuntaCana.sqlite','PuntaCana.sqlite');
	 //db.execute('CREATE TABLE "Categorias" ("id" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "nombre" TEXT NOT NULL  UNIQUE )');
	 //db.execute('INSERT INTO Categorias (id,nombre) VALUES (?,?)',1,'Comidas');
	 db = Ti.Database.open('PuntaCana.sqlite');
    }else{
    	var dbOLD = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
		//Destroy it
		if(dbOLD){
			Ti.API.info('remove');
			dbOLD.close();
			dbOLD.remove();
		}
      db = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
    }

/*
db.execute('CREATE TABLE "Categorias" ("id" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "nombre" TEXT NOT NULL  UNIQUE )');
db.execute('INSERT INTO Categorias (id,nombre) VALUES (?,?)',1,'Comidas');
*/
function ApplicationWindow(title,id) {

	var titleBg = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/top-bar-bg.png');
	var self = Ti.UI.createWindow({
		title:title,
		backgroundColor:'black',
		barImage:titleBg
	});

	var table = Ti.UI.createTableView({
		data:generarTabla(id)
	});

	table.addEventListener('click', function(e){
		/*
		 	For example, some of the key properties of that event object include:
			 *index 	– the ordinal index number of the row that received the event
			 *row 		– the object representing the row that received the event
			 *rowData 	– the properties of the row that received the event
			 *source 	– the object that received the original event
			 *section 	– the table section that received the event
		 */
		//alert('You clicked row '+e.index+' with id:'+e.row.id);
		if(e.row.hijo !== 0){
		var GuideWindows = require('ui/common/GuideWindows');
		var win = new GuideWindows(L('tabName1'),e.row.id)
		self.containingTab.open(win);
		}else{
			alert('You clicked row '+e.index+' with id:'+e.row.id);
		}
	});

	self.add(table);

	return self;
};

module.exports = ApplicationWindow;

function generarTabla(id){

	dataBD = db.execute('SELECT * FROM Categorias WHERE padre='+id);

	var tbl_data = crearFilasTabla(dataBD);

	dataBD.close();

	return tbl_data;
}

function crearFilasTabla(dataBD){
	Ti.API.info('datos');

	var tbl_data = [];
	var fieldCount;
	var row = {
		id:undefined,
		nombre:undefined,
		icon:undefined
	}

	// fieldCount is a property on Android.
	if (Ti.Platform.name === 'android') {
	    fieldCount = dataBD.fieldCount;
	} else {
	    fieldCount = dataBD.fieldCount();
	}
	Ti.API.info('Field count: ' + fieldCount);

	while (dataBD.isValidRow())
	{

	  var cellBg = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/cell-bg.png');
	  var fila = Ti.UI.createTableViewRow({
	  	hasChild:true,
	  	backgroundImage:cellBg,
	  	height:60
	  	//backgroundColor: 'red'
	  });

	  for(i=0;i<fieldCount;i++){
		var name =  dataBD.fieldName(i);
		switch(name){
			case 'id':
				row.id = dataBD.fieldByName(name);
				fila.id = row.id;
				break;
			case 'icono':
				row.icon = dataBD.fieldByName(name);
				var icono = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/KS_nav_ui.png');//row.icon);

	  			var imagen = Ti.UI.createImageView({
					image: icono,
					height:40,
					width:40,
					top:10,
					left:5
				});
	  			fila.add(imagen);
				break;
			case 'nombre':
				row.nombre = dataBD.fieldByName(name);
				var nombre = Ti.UI.createLabel({
					top:2,
	  				left: 45,
					text:row.nombre,
					font: { fontSize:15 },
					height:40,
  					shadowColor: '#aaa',
  					shadowOffset: {x:0.4, y:0.4},
	  			});
	  			fila.add(nombre);
				break;
			default:
				break;
		}
	  }
	  var subtitulo = Ti.UI.createLabel({
					top:25,
	  				left: 45,
					text: 'Subtitulo con las estrellas del hotel',
					height:30,
					color: 'gray',
					font: { fontSize:12 }
	  			});
	  			fila.add(subtitulo);

	  tbl_data.push(fila);
	  dataBD.next();
	}
	//dataBD.close();
	return tbl_data;
}
<commit_msg>avanzando con las listas multiples<commit_after>
/*
//Reference prior, cached database
var dbOLD = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
//Destroy it
dbOLD.remove();
*/
//Install new database
var db;

    if (Ti.Platform.name === 'android' && Ti.Filesystem.isExternalStoragePresent()) {

	 db = Titanium.Database.install('/PuntaCana.sqlite','PuntaCana.sqlite');
	 //db.execute('CREATE TABLE "Categorias" ("id" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "nombre" TEXT NOT NULL  UNIQUE )');
	 //db.execute('INSERT INTO Categorias (id,nombre) VALUES (?,?)',1,'Comidas');
	 db = Ti.Database.open('PuntaCana.sqlite');
    }else{
    	var dbOLD = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
		//Destroy it
		if(dbOLD){
			Ti.API.info('remove');
			dbOLD.close();
			dbOLD.remove();
		}
      db = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
    }

/*
db.execute('CREATE TABLE "Categorias" ("id" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "nombre" TEXT NOT NULL  UNIQUE )');
db.execute('INSERT INTO Categorias (id,nombre) VALUES (?,?)',1,'Comidas');
*/
function ApplicationWindow(title,id) {

	var titleBg = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/top-bar-bg.png');
	var self = Ti.UI.createWindow({
		title:title,
		backgroundColor:'black',
		barImage:titleBg
	});

	var table = Ti.UI.createTableView({
		data:generarTabla(id)
	});

	table.addEventListener('click', function(e){
		/*
		 	For example, some of the key properties of that event object include:
			 *index 	– the ordinal index number of the row that received the event
			 *row 		– the object representing the row that received the event
			 *rowData 	– the properties of the row that received the event
			 *source 	– the object that received the original event
			 *section 	– the table section that received the event
		 */
		//alert('You clicked row '+e.index+' with id:'+e.row.id);

		var GuideWindows = require('ui/common/GuideWindows');
		var win = new GuideWindows(L('tabName1'),e.row.id)
		win.containingTab = self.containingTab;
		self.containingTab.open(win);

	});

	self.add(table);

	return self;
};

module.exports = ApplicationWindow;

function generarTabla(id){

	dataBD = db.execute('SELECT * FROM Categorias WHERE padre='+id);

	var tbl_data = crearFilasTabla(dataBD);

	dataBD.close();

	return tbl_data;
}

function crearFilasTabla(dataBD){
	Ti.API.info('datos');

	var tbl_data = [];
	var fieldCount;
	var row = {
		id:undefined,
		nombre:undefined,
		icon:undefined
	}

	// fieldCount is a property on Android.
	if (Ti.Platform.name === 'android') {
	    fieldCount = dataBD.fieldCount;
	} else {
	    fieldCount = dataBD.fieldCount();
	}
	Ti.API.info('Field count: ' + fieldCount);

	while (dataBD.isValidRow())
	{

	  var cellBg = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/cell-bg.png');
	  var fila = Ti.UI.createTableViewRow({
	  	hasChild:true,
	  	backgroundImage:cellBg,
	  	height:60
	  	//backgroundColor: 'red'
	  });

	  for(i=0;i<fieldCount;i++){
		var name =  dataBD.fieldName(i);
		switch(name){
			case 'id':
				row.id = dataBD.fieldByName(name);
				fila.id = row.id;
				break;
			case 'icono':
				row.icon = dataBD.fieldByName(name);
				var icono = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/KS_nav_ui.png');//row.icon);

	  			var imagen = Ti.UI.createImageView({
					image: icono,
					height:40,
					width:40,
					top:10,
					left:5
				});
	  			fila.add(imagen);
				break;
			case 'nombre':
				row.nombre = dataBD.fieldByName(name);
				var nombre = Ti.UI.createLabel({
					top:2,
	  				left: 45,
					text:row.nombre,
					font: { fontSize:15 },
					height:40,
  					shadowColor: '#aaa',
  					shadowOffset: {x:0.4, y:0.4},
	  			});
	  			fila.add(nombre);
				break;
			default:
				break;
		}
	  }
	  var subtitulo = Ti.UI.createLabel({
					top:25,
	  				left: 45,
					text: 'Subtitulo con las estrellas del hotel',
					height:30,
					color: 'gray',
					font: { fontSize:12 }
	  			});
	  			fila.add(subtitulo);

	  tbl_data.push(fila);
	  dataBD.next();
	}
	//dataBD.close();
	return tbl_data;
}
<|endoftext|>