<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { IconChevronUpSmallOutline, IconChevronDownSmallOutline } from '@teamleader/ui-icons';
import Icon from '../icon';
import InputBase from './InputBase';
import theme from './theme.css';

class SpinnerControls extends PureComponent {
  render() {
    const { inverse, handleOnSpinnerUpClick, handleOnSpinnerDownClick } = this.props;
    const iconProps = {
      color: inverse ? 'teal' : 'neutral',
      element: 'button',
      tint: inverse ? 'lightest' : 'darkest',
    };

    return (

        <Icon className={theme['spinner-up']} onClick={handleOnSpinnerUpClick} {...iconProps}>
          <IconChevronUpSmallOutline />
        </Icon>
        <Icon className={theme['spinner-down']} onClick={handleOnSpinnerDownClick} {...iconProps}>
          <IconChevronDownSmallOutline />
        </Icon>

    );
  }
}

class NumericInput extends PureComponent {
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.value !== undefined) {
      const newValue = nextProps.value || '';
      if (newValue !== prevState.value) {
        return {
          value: newValue,
        };
      }
    }
    return null;
  }

  state = {
    value: '',
  };

  handleOnChange = event => {
    this.setState({ value: this.parseValue(event.currentTarget.value) });
  };

  updateStep = n => {
    const { step } = this.props;

    const currentValue = this.toNumber(this.state.value || 0);
    const newValue = this.parseValue(currentValue + step * n);

    if (newValue !== currentValue) {
      this.setState({ value: newValue });
    }
  };

  parseValue = value => this.bindToMinMax(this.toNumber(value));

  toNumber = rawNumber => {
    let number = parseFloat(rawNumber);
    if (isNaN(number) || !isFinite(number)) {
      number = 0;
    }
    return number;
  };

  bindToMinMax = value => {
    const { min, max } = this.props;
    return Math.min(Math.max(value, min), max);
  };

  handleIncreaseValue = () => {
    this.updateStep(1);
  };

  handleDecreaseValue = () => {
    this.updateStep(-1);
  };

  getSuffixWithSpinner = () => [
    ...this.props.suffix,
    <SpinnerControls
      handleOnSpinnerUpClick={this.handleIncreaseValue}
      handleOnSpinnerDownClick={this.handleDecreaseValue}
    />,
  ];

  render() {
    const { spinner, suffix, onChange, ...others } = this.props;

    return (
      <InputBase
        type="number"
        value={this.state.value}
        suffix={spinner ? this.getSuffixWithSpinner() : suffix}
        onChange={event => {
          this.handleOnChange(event);
          onChange && onChange(event, event.currentTarget.value);
        }}
        {...others}
      />
    );
  }
}

NumericInput.propTypes = {
  /** Sets a class name for the wrapper to give custom styles. */
  className: PropTypes.string,
  /** The maximum value that can be inputted */
  max: PropTypes.number,
  /** The minimum value that can be inputted */
  min: PropTypes.number,
  /** Boolean indicating whether to number type input should render spinner controls */
  spinner: PropTypes.bool,
  /** Limit increment value for numeric inputs. */
  step: PropTypes.number,
};

NumericInput.defaultProps = {
  min: Number.MIN_SAFE_INTEGER,
  max: Number.MAX_SAFE_INTEGER,
  step: 1,
  suffix: [],
  spinner: true,
};

export default NumericInput;
<commit_msg>Fix spinner color for inverse input by passing down the inverse prop<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { IconChevronUpSmallOutline, IconChevronDownSmallOutline } from '@teamleader/ui-icons';
import Icon from '../icon';
import InputBase from './InputBase';
import theme from './theme.css';

class SpinnerControls extends PureComponent {
  render() {
    const { inverse, handleOnSpinnerUpClick, handleOnSpinnerDownClick } = this.props;
    const iconProps = {
      color: inverse ? 'teal' : 'neutral',
      element: 'button',
      tint: inverse ? 'lightest' : 'darkest',
    };

    return (

        <Icon className={theme['spinner-up']} onClick={handleOnSpinnerUpClick} {...iconProps}>
          <IconChevronUpSmallOutline />
        </Icon>
        <Icon className={theme['spinner-down']} onClick={handleOnSpinnerDownClick} {...iconProps}>
          <IconChevronDownSmallOutline />
        </Icon>

    );
  }
}

class NumericInput extends PureComponent {
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.value !== undefined) {
      const newValue = nextProps.value || '';
      if (newValue !== prevState.value) {
        return {
          value: newValue,
        };
      }
    }
    return null;
  }

  state = {
    value: '',
  };

  handleOnChange = event => {
    this.setState({ value: this.parseValue(event.currentTarget.value) });
  };

  updateStep = n => {
    const { step } = this.props;

    const currentValue = this.toNumber(this.state.value || 0);
    const newValue = this.parseValue(currentValue + step * n);

    if (newValue !== currentValue) {
      this.setState({ value: newValue });
    }
  };

  parseValue = value => this.bindToMinMax(this.toNumber(value));

  toNumber = rawNumber => {
    let number = parseFloat(rawNumber);
    if (isNaN(number) || !isFinite(number)) {
      number = 0;
    }
    return number;
  };

  bindToMinMax = value => {
    const { min, max } = this.props;
    return Math.min(Math.max(value, min), max);
  };

  handleIncreaseValue = () => {
    this.updateStep(1);
  };

  handleDecreaseValue = () => {
    this.updateStep(-1);
  };

  getSuffixWithSpinner = () => [
    ...this.props.suffix,
    <SpinnerControls
      inverse={this.props.inverse}
      handleOnSpinnerUpClick={this.handleIncreaseValue}
      handleOnSpinnerDownClick={this.handleDecreaseValue}
    />,
  ];

  render() {
    const { spinner, suffix, onChange, ...others } = this.props;

    return (
      <InputBase
        type="number"
        value={this.state.value}
        suffix={spinner ? this.getSuffixWithSpinner() : suffix}
        onChange={event => {
          this.handleOnChange(event);
          onChange && onChange(event, event.currentTarget.value);
        }}
        {...others}
      />
    );
  }
}

NumericInput.propTypes = {
  /** Sets a class name for the wrapper to give custom styles. */
  className: PropTypes.string,
  /** The maximum value that can be inputted */
  max: PropTypes.number,
  /** The minimum value that can be inputted */
  min: PropTypes.number,
  /** Boolean indicating whether to number type input should render spinner controls */
  spinner: PropTypes.bool,
  /** Limit increment value for numeric inputs. */
  step: PropTypes.number,
};

NumericInput.defaultProps = {
  min: Number.MIN_SAFE_INTEGER,
  max: Number.MAX_SAFE_INTEGER,
  step: 1,
  suffix: [],
  spinner: true,
};

export default NumericInput;
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import Box from '../box';
import theme from './theme.css';
import Island from './Island';
import { elementIsDark } from '../utils/utils';

class IslandGroup extends PureComponent {
  render() {
    const { children, className, color, dark, size } = this.props;

    const isDark = elementIsDark(color, dark);

    const classNames = cx(theme['segmented'], theme['island'], theme[color], { [theme['dark']]: isDark }, className);

    return (
      <Box className={classNames} padding={0}>
        {React.Children.map(children, child => {
          return (
            <Island {...child.props} color={color} dark={isDark} size={size}>
              {child.props.children}
            </Island>
          );
        })}
      </Box>
    );
  }
}

IslandGroup.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string,
  color: PropTypes.oneOf(['neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua', 'white']),
  dark: PropTypes.bool,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
};

IslandGroup.defaultProps = {
  color: 'white',
};

export default IslandGroup;
<commit_msg>Apply box props to the Box wrapper<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import Box, { pickBoxProps } from '../box';
import theme from './theme.css';
import Island from './Island';
import { elementIsDark } from '../utils/utils';

class IslandGroup extends PureComponent {
  render() {
    const { children, className, color, dark, size, ...otherProps } = this.props;

    const boxProps = pickBoxProps(otherProps);
    const isDark = elementIsDark(color, dark);

    const classNames = cx(theme['segmented'], theme['island'], theme[color], { [theme['dark']]: isDark }, className);

    return (
      <Box {...boxProps} className={classNames} padding={0}>
        {React.Children.map(children, child => {
          return (
            <Island {...child.props} color={color} dark={isDark} size={size}>
              {child.props.children}
            </Island>
          );
        })}
      </Box>
    );
  }
}

IslandGroup.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string,
  color: PropTypes.oneOf(['neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua', 'white']),
  dark: PropTypes.bool,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
};

IslandGroup.defaultProps = {
  color: 'white',
};

export default IslandGroup;
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs')
  , log = require('npmlog')
  , args = process.argv.splice(2)
  , path = require('path')

if (args.length !== 1) {
  log.error('invalid args')
  log.error('usage', 'stripline <file>')
  process.exit(1)
}

var contents = fs.readFileSync(args[0], 'utf8')

var lines = contents.split('\n')

lines = lines.filter(function(line) {
  return (line && line !== '' && line !== '\n')
})

lines = lines.map(function(line, idx) {
  if (matches = line.match(/SetID ?\-.../)) {
    line = 'SetID'
  }
  line = line.replace(/[\-\*\s\/\'\’\.\(\)\+\#]/g, '')
  return "  , '"+line+"'"
})

var name = path.basename(args[0])
var file = [
    "exports.name = '"+name+"'"
  , ''
  , 'exports.fields = ['
  , "    'SegmentType'"
]

file = file.concat(lines)
file.push(']')
console.log(file.join('\n'))
<commit_msg>Fixed segmentdef script<commit_after>#!/usr/bin/env node

var fs = require('fs')
  , log = require('npmlog')
  , args = process.argv.splice(2)
  , path = require('path')

if (args.length !== 1) {
  log.error('invalid args')
  log.error('usage', 'stripline <file>')
  process.exit(1)
}

var contents = fs.readFileSync(args[0], 'utf8')

var lines = contents.split('\n')

lines = lines.filter(function(line) {
  return (line && line !== '' && line !== '\n')
})

lines = lines.map(function(line, idx) {
  if (matches = line.match(/SetID ?\- ?.../)) {
    line = 'SetID'
  }
  line = line.replace(/[\-\*\s\/\'\’\.\(\)\+\#]/g, '')
  return "  , '"+line+"'"
})

var name = path.basename(args[0])
var file = [
    "exports.name = '"+name+"'"
  , ''
  , 'exports.fields = ['
  , "    'SegmentType'"
]

file = file.concat(lines)
file.push(']')
console.log(file.join('\n'))
<|endoftext|>


<commit_before>(function() {

IV.tools.Line = {
    onActive: function() {
        var obj1 = null;
        var obj2 = null;
        IV.vis.clearSelection();
        IV.triggerRender("main,back");

        IV.tools.beginSelectObject(function(context) {
            var path = IV.get("selected-path");
            if(!context) {
                obj1 = null;
                obj2 = null;
                IV.vis.clearSelection();
                IV.triggerRender("main,back");
                return;
            }
            if(!obj1) {
                obj1 = context.obj;
                IV.vis.appendSelection(context);
                IV.triggerRender("main,back");
            } else if(!obj2) {
                obj2 = context.obj;
                if(IV.data.schemaAtPath(path)) {
                    if(obj1.can("get-point") && obj2.can("get-point")) {
                        var line = new IV.objects.Line(path, {
                            point1: obj1,
                            point2: obj2,
                            style: IV.panels.style.createStyle()
                        });
                        IV.vis.addObject(line);
                    }
                }
                obj1 = null;
                obj2 = null;
                IV.vis.clearSelection();
                IV.triggerRender("main,back");
            }
        }, "tools:Line");
    },
    onInactive: function() {
        IV.tools.endSelectObject("tools:Line");
    }
};

IV.tools.LineThrough = {
    onActive: function() {
        var $this = this;
        IV.tools.beginSelectLocation(function(loc) {
            var path = IV.get("selected-path");
            if(IV.data.schemaAtPath(path)) {
                var circle = new IV.objects.LineThrough(path, {
                    points: loc,
                    style: IV.panels.style.createStyle()
                });
                IV.vis.addObject(circle);
                IV.triggerRender("main");
            }
        }, "tools:LineThrough");
    },
    onInactive: function() {
        IV.tools.endSelectLocation("tools:LineThrough");
    }
};

})();
<commit_msg>Changed the line tool to beginSelectObject.<commit_after>(function() {

IV.tools.Line = {
    onActive: function() {
        var $this = this;
        $this.loc1 = null;
        $this.loc2 = null;
        IV.tools.beginSelectLocation(function(loc) {
            if(!$this.loc1) {
                $this.loc1 = loc;
                return;
            } else {
                $this.loc2 = loc;
                var path = IV.get("selected-path");
                var line = new IV.objects.Line(path, {
                    point1: $this.loc1,
                    point2: $this.loc2,
                    style: IV.panels.style.createStyle()
                });
                IV.vis.addObject(line);
                IV.triggerRender("main,back");
                $this.loc1 = null;
                $this.loc2 = null;
            }
        }, "tools:Line");
    },
    onInactive: function() {
        IV.tools.endSelectLocation("tools:Line");
    }
};
/*
IV.tools.Line = {
    onActive: function() {
        var obj1 = null;
        var obj2 = null;
        IV.vis.clearSelection();
        IV.triggerRender("main,back");

        IV.tools.beginSelectObject(function(context) {
            var path = IV.get("selected-path");
            if(!context) {
                obj1 = null;
                obj2 = null;
                IV.vis.clearSelection();
                IV.triggerRender("main,back");
                return;
            }
            if(!obj1) {
                obj1 = context.obj;
                IV.vis.appendSelection(context);
                IV.triggerRender("main,back");
            } else if(!obj2) {
                obj2 = context.obj;
                if(IV.data.schemaAtPath(path)) {
                    if(obj1.can("get-point") && obj2.can("get-point")) {
                        var line = new IV.objects.Line(path, {
                            point1: obj1,
                            point2: obj2,
                            style: IV.panels.style.createStyle()
                        });
                        IV.vis.addObject(line);
                    }
                }
                obj1 = null;
                obj2 = null;
                IV.vis.clearSelection();
                IV.triggerRender("main,back");
            }
        }, "tools:Line");
    },
    onInactive: function() {
        IV.tools.endSelectObject("tools:Line");
    }
};
*/
IV.tools.LineThrough = {
    onActive: function() {
        var $this = this;
        IV.tools.beginSelectLocation(function(loc) {
            var path = IV.get("selected-path");
            if(IV.data.schemaAtPath(path)) {
                var circle = new IV.objects.LineThrough(path, {
                    points: loc,
                    style: IV.panels.style.createStyle()
                });
                IV.vis.addObject(circle);
                IV.triggerRender("main");
            }
        }, "tools:LineThrough");
    },
    onInactive: function() {
        IV.tools.endSelectLocation("tools:LineThrough");
    }
};

})();
<|endoftext|>


<commit_before>var fs = require('fs');
var nodePath = require('path');
var files = require('./files');
var objects = require('./objects');

var refs = module.exports = {
  isRef: function(ref) {
    return ref === "HEAD" || isLocalHeadRef(ref);
  },

  readTerminalRef: function(ref) {
    if (ref === "HEAD" && isLocalHeadRef(readHead())) {
      return readHead();
    } else if (isLocalHeadRef(ref)) {
      return ref;
    } else {
      return refs.nameToBranchRef(ref);
    }
  },

  readHash: function(refOrHash) {
    if (refOrHash !== undefined) {
      if (objects.readExists(refOrHash)) {
        return refOrHash;
      } else if (refs.readExists(refs.readTerminalRef(refOrHash))) {
        return files.read(nodePath.join(files.gitletDir(), refs.readTerminalRef(refOrHash)));
      } else if (refs.readExists(refs.nameToBranchRef(refOrHash))) {
        return files.read(nodePath.join(files.gitletDir(), refs.nameToBranchRef(refOrHash)));
      }
    }
  },

  readIsHash: function(possibleHash) {
    return objects.read(possibleHash) !== undefined;
  },

  readIsHeadDetached: function() {
    return readHead().match("refs") === null;
  },

  nameToBranchRef: function(name) {
    return "refs/heads/" + name;
  },

  write: function(ref, content) {
    if (ref === "HEAD") {
      files.write(nodePath.join(files.gitletDir(), "HEAD"), content);
    } else if (isLocalHeadRef(ref)) {
      files.write(nodePath.join(files.gitletDir(), ref), content);
    }
  },

  readLocalHeads: function() {
    return fs.readdirSync(nodePath.join(files.gitletDir(), "refs/heads/"));
  },

  readExists: function(ref) {
    return ref !== undefined &&
      isLocalHeadRef(ref) &&
      fs.existsSync(nodePath.join(files.gitletDir(), ref));
  },

  readCurrentBranchName: function() {
    if (readHead().match("refs")) {
      return readHead().match("refs/heads/(.+)")[1];
    }
  }
};

function readHead() {
  var content = files.read(nodePath.join(files.gitletDir(), "HEAD"));
  var refMatch = content.match("ref: (refs/heads/.+)");
  return refMatch ? refMatch[1] : content;
};

function isLocalHeadRef(ref) {
  return ref.match("refs/heads/[A-Za-z-]+");
};
<commit_msg>Make readHash() handle detached HEAD<commit_after>var fs = require('fs');
var nodePath = require('path');
var files = require('./files');
var objects = require('./objects');

var refs = module.exports = {
  isRef: function(ref) {
    return ref === "HEAD" || isLocalHeadRef(ref);
  },

  readTerminalRef: function(ref) {
    if (ref === "HEAD" && isLocalHeadRef(readHead())) {
      return readHead();
    } else if (isLocalHeadRef(ref)) {
      return ref;
    } else {
      return refs.nameToBranchRef(ref);
    }
  },

  readHash: function(refOrHash) {
    if (refOrHash !== undefined) {
      if (objects.readExists(refOrHash)) {
        return refOrHash;
      } else if (refOrHash === "HEAD" && refs.readIsHeadDetached()) {
        return readHead();
      } else if (refs.readExists(refs.readTerminalRef(refOrHash))) {
        return files.read(nodePath.join(files.gitletDir(), refs.readTerminalRef(refOrHash)));
      } else if (refs.readExists(refs.nameToBranchRef(refOrHash))) {
        return files.read(nodePath.join(files.gitletDir(), refs.nameToBranchRef(refOrHash)));
      }
    }
  },

  readIsHash: function(possibleHash) {
    return objects.read(possibleHash) !== undefined;
  },

  readIsHeadDetached: function() {
    return readHead().match("refs") === null;
  },

  nameToBranchRef: function(name) {
    return "refs/heads/" + name;
  },

  write: function(ref, content) {
    if (ref === "HEAD") {
      files.write(nodePath.join(files.gitletDir(), "HEAD"), content);
    } else if (isLocalHeadRef(ref)) {
      files.write(nodePath.join(files.gitletDir(), ref), content);
    }
  },

  readLocalHeads: function() {
    return fs.readdirSync(nodePath.join(files.gitletDir(), "refs/heads/"));
  },

  readExists: function(ref) {
    return ref !== undefined &&
      isLocalHeadRef(ref) &&
      fs.existsSync(nodePath.join(files.gitletDir(), ref));
  },

  readCurrentBranchName: function() {
    if (readHead().match("refs")) {
      return readHead().match("refs/heads/(.+)")[1];
    }
  }
};

function readHead() {
  var content = files.read(nodePath.join(files.gitletDir(), "HEAD"));
  var refMatch = content.match("ref: (refs/heads/.+)");
  return refMatch ? refMatch[1] : content;
};

function isLocalHeadRef(ref) {
  return ref.match("refs/heads/[A-Za-z-]+");
};
<|endoftext|>


<commit_before>// Just trying to do the manual checking of the method existenance
// Will remove the file when we can communicate with the real libarary
// and can add the mocha test files.

var ECLib = require('../node-eclib.js');
var enums = require('../eclib-enum.js');
var ECLibUtil = require('../eclib-util.js');
var buffertools = require("buffertools");
var crypto = require('crypto');
var hexdump = require('hexdump-nodejs');

console.log("ECLib testing");

function test_one(opts) {
    var eclib = new ECLib(opts);

    desc = eclib.init();

    eclib.testpad(42, function (param) {
	console.log("CALLBACK! " + param);
    });

    console.log("out\n");
}

//EC_BACKEND_NULL
//EC_BACKEND_JERASURE_RS_VAND
//EC_BACKEND_JERASURE_RS_CAUCHY
//EC_BACKEND_FLAT_XOR_HD
//EC_BACKEND_ISA_L_RS_VAND
//EC_BACKEND_SHSS
//EC_BACKEND_ISA_L_RS_CAUCHY

test_one({
    "bc_id": enums.BackendId["EC_BACKEND_FLAT_XOR_HD"],
    "k": 3,
    "m": 3,
    "hd": 3
});

//global.gc(); //requires --expose-gc
<commit_msg>shows that scope is not properly set on the callback<commit_after>// Just trying to do the manual checking of the method existenance
// Will remove the file when we can communicate with the real libarary
// and can add the mocha test files.

var ECLib = require('../node-eclib.js');
var enums = require('../eclib-enum.js');
var ECLibUtil = require('../eclib-util.js');
var buffertools = require("buffertools");
var crypto = require('crypto');
var hexdump = require('hexdump-nodejs');

console.log("ECLib testing");

function test_one(opts) {
    var eclib = new ECLib(opts);
    var done = false;
    desc = eclib.init();

    eclib.testpad(42, function (param) {
        console.log(done); // Should not be undefined, should be false
        done = true;
	   console.log("CALLBACK! " + param);
    });
    var i = 0;

    var work = function(dosomestuff) {
        console.log("dosomestuff in JS "+ (i++));
        if (!done)
            	process.nextTick(work);
    }
    work();
    console.log("out\n");
}

//EC_BACKEND_NULL
//EC_BACKEND_JERASURE_RS_VAND
//EC_BACKEND_JERASURE_RS_CAUCHY
//EC_BACKEND_FLAT_XOR_HD
//EC_BACKEND_ISA_L_RS_VAND
//EC_BACKEND_SHSS
//EC_BACKEND_ISA_L_RS_CAUCHY

test_one({
    "bc_id": enums.BackendId["EC_BACKEND_FLAT_XOR_HD"],
    "k": 3,
    "m": 3,
    "hd": 3
});

//global.gc(); //requires --expose-gc
<|endoftext|>


<commit_before>import edge from 'edge';

export const reflect = edge.func(function() {/*
#r "System.Xml.dll"
#r "System.Reflection.dll"
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;

public class Argument
{
    public string Name { get; set; }
    public string Type { get; set; }
}

public class ArgumentComment
{
    public string Name { get; set; }
    public string Comment { get; set; }
}

public class Comment
{
    public Comment()
    {

    }

    public Comment(XmlDocument doc, string xpath)
    {
        var summary = doc.SelectSingleNode(xpath + "/summary");
        if(summary != null)
            this.Summary = summary.InnerText.Trim();
        var returns = doc.SelectSingleNode(xpath + "/returns");
        if (returns != null)
            this.Returns = returns.InnerText.Trim();
        var arguments = doc.SelectNodes(xpath + "/param");
        if(arguments != null)
        {
            this.Arguments = new Dictionary<string, string>();
            foreach(var arg in arguments.OfType<XmlNode>())
                this.Arguments[arg.Attributes["name"].Value] = arg.InnerText.Trim();
        }
    }

    public string Summary { get; set; }
    public string Returns { get; set; }
    public Dictionary<string, string> Arguments { get; set; }
}

public class Method
{
    public string Name { get; set; }
    public Argument[] Arguments { get; set; }
    public string Returns { get; set; }
    public Comment Comment { get; set; }

}

public class Hub
{
    public string Name { get; set; }
    public Comment Comment { get; set; }
    public Method[] Server { get; set; }
    public Method[] Client { get; set; }
}

public class Startup
{
    static bool IsDerivedOfGenericType(Type type, Type genericType)
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
            return true;
        return type.BaseType != null && IsDerivedOfGenericType(type.BaseType, genericType);
    }
    static Type GetDerivedGenericTypeParameter(Type type, Type genericType)
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
            return type.GenericTypeArguments.First();
        return type.BaseType != null
            ? GetDerivedGenericTypeParameter(type.BaseType, genericType)
            : null;
    }

    private static readonly Type[] _numberTypes = new[] { typeof(byte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(decimal), typeof(double) };
    private static readonly Type[] _dateTypes = new[] { typeof(DateTime), typeof(DateTimeOffset) };

    private static string MapToJavaScriptType(Type type)
    {
      if (typeof(System.Collections.IEnumerable).IsAssignableFrom(type))
      {
        return "Array";
      }
      if (!type.IsPrimitive && !(type == typeof(string)))
      {
        return "Object";
      }
      if (type == typeof(string))
      {
        return "String";
      }
      if (_numberTypes.Contains(type))
      {
        return "Number";
      }
      if (_dateTypes.Contains(type))
      {
        return "Date";
      }
        return type.Name;
    }

    static string GetReturnType(MethodInfo y)
    {
      if (y.ReturnParameter != null && y.ReturnParameter.ParameterType != typeof(Task) && y.ReturnParameter.ParameterType != typeof(void))
      {
          if (IsDerivedOfGenericType(y.ReturnParameter.ParameterType, typeof(Task<>)))
              return MapToJavaScriptType(y.ReturnParameter.ParameterType.GenericTypeArguments.First());
          return MapToJavaScriptType(y.ReturnParameter.ParameterType);
      }
      return null;
    }

    public async Task<object> Invoke(object input)
    {
        var extension = "." + input.ToString().Split(new[] { '.' }).Last();
        if (string.IsNullOrEmpty(extension))
            extension = ".dll";
        AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += (sender, args) =>
        {
            try
            {
                return Assembly.ReflectionOnlyLoad(args.Name);
            }
            catch
            {
                try
                {
                    var path = Path.Combine(Path.GetDirectoryName(input.ToString()) ?? "", args.Name.Split(new[] { ',' })[0] + extension);
                    return Assembly.ReflectionOnlyLoadFrom(path);
                }
                catch
                {
                    return null;
                }
            }
        };

        var assemblyPath = input.ToString();
        var ass = Assembly.ReflectionOnlyLoadFrom(assemblyPath);
        var docPath = assemblyPath.Substring(0, assemblyPath.LastIndexOf(".", StringComparison.Ordinal)) + ".XML";
        var xml = new XmlDocument();
        if (File.Exists(docPath))
            xml.Load(docPath);
        var hubType = Type.ReflectionOnlyGetType("Microsoft.AspNet.SignalR.Hub, Microsoft.AspNet.SignalR.Core", true, true);
        var hubGenericType = Type.ReflectionOnlyGetType("Microsoft.AspNet.SignalR.Hub`1, Microsoft.AspNet.SignalR.Core", false, true);
        return ass.DefinedTypes.Where(x => IsDerivedOfGenericType(x, hubGenericType)).Select(x => new Hub
        {
            Name = x.Name,
            Comment = new Comment(xml, "//member[@name='T:" + x.FullName + "']"),
            Server = x.GetMethods().Where(y => y.IsPublic && !y.IsStatic && y.DeclaringType != hubType && y.DeclaringType != typeof(object) && y.Name != "OnConnected" && !(y.DeclaringType.IsGenericType && y.DeclaringType.GetGenericTypeDefinition() == hubGenericType)).Select(y => new Method
            {
                Name = y.Name,
                Comment = new Comment(xml, "//member[starts-with(@name, 'M:" + x.FullName + "." + y.Name + "')]"),
                Arguments = y.GetParameters().Select(z => new Argument() { Name = z.Name, Type = MapToJavaScriptType(z.ParameterType) }).ToArray(),
                Returns = GetReturnType(y)
            }).ToArray(),
            Client = GetDerivedGenericTypeParameter(x, hubGenericType).GetTypeInfo().DeclaredMethods.Where(y => y.IsPublic && !y.IsStatic && y.GetBaseDefinition() == y).Select(y => new Method
            {
                Name = y.Name,
                Arguments = y.GetParameters().Select(z => new Argument() { Name = z.Name, Type = MapToJavaScriptType(z.ParameterType) }).ToArray(),
                Comment = new Comment(xml, "//member[starts-with(@name, 'M:" + y.DeclaringType.FullName + "." + y.Name + "')]"),
                Returns = GetReturnType(y)
            }).ToArray()
        }).ToArray();
    }
}
*/
});

export function scan(assembly) {
  return new Promise((resolve, reject) => {
    reflect(assembly, (error, result) => {
      if(error) {
        return reject(error);
      }
      resolve(result);
    });
  });
}<commit_msg>excluding abstract hubs<commit_after>import edge from 'edge';

export const reflect = edge.func(function() {/*
#r "System.Xml.dll"
#r "System.Reflection.dll"
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;

public class Argument
{
    public string Name { get; set; }
    public string Type { get; set; }
}

public class ArgumentComment
{
    public string Name { get; set; }
    public string Comment { get; set; }
}

public class Comment
{
    public Comment()
    {

    }

    public Comment(XmlDocument doc, string xpath)
    {
        var summary = doc.SelectSingleNode(xpath + "/summary");
        if(summary != null)
            this.Summary = summary.InnerText.Trim();
        var returns = doc.SelectSingleNode(xpath + "/returns");
        if (returns != null)
            this.Returns = returns.InnerText.Trim();
        var arguments = doc.SelectNodes(xpath + "/param");
        if(arguments != null)
        {
            this.Arguments = new Dictionary<string, string>();
            foreach(var arg in arguments.OfType<XmlNode>())
                this.Arguments[arg.Attributes["name"].Value] = arg.InnerText.Trim();
        }
    }

    public string Summary { get; set; }
    public string Returns { get; set; }
    public Dictionary<string, string> Arguments { get; set; }
}

public class Method
{
    public string Name { get; set; }
    public Argument[] Arguments { get; set; }
    public string Returns { get; set; }
    public Comment Comment { get; set; }

}

public class Hub
{
    public string Name { get; set; }
    public Comment Comment { get; set; }
    public Method[] Server { get; set; }
    public Method[] Client { get; set; }
}

public class Startup
{
    static bool IsDerivedOfGenericType(Type type, Type genericType)
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
            return true;
        return type.BaseType != null && IsDerivedOfGenericType(type.BaseType, genericType);
    }
    static Type GetDerivedGenericTypeParameter(Type type, Type genericType)
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
            return type.GenericTypeArguments.First();
        return type.BaseType != null
            ? GetDerivedGenericTypeParameter(type.BaseType, genericType)
            : null;
    }

    private static readonly Type[] _numberTypes = new[] { typeof(byte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(decimal), typeof(double) };
    private static readonly Type[] _dateTypes = new[] { typeof(DateTime), typeof(DateTimeOffset) };

    private static string MapToJavaScriptType(Type type)
    {
      if (typeof(System.Collections.IEnumerable).IsAssignableFrom(type))
      {
        return "Array";
      }
      if (!type.IsPrimitive && !(type == typeof(string)))
      {
        return "Object";
      }
      if (type == typeof(string))
      {
        return "String";
      }
      if (_numberTypes.Contains(type))
      {
        return "Number";
      }
      if (_dateTypes.Contains(type))
      {
        return "Date";
      }
        return type.Name;
    }

    static string GetReturnType(MethodInfo y)
    {
      if (y.ReturnParameter != null && y.ReturnParameter.ParameterType != typeof(Task) && y.ReturnParameter.ParameterType != typeof(void))
      {
          if (IsDerivedOfGenericType(y.ReturnParameter.ParameterType, typeof(Task<>)))
              return MapToJavaScriptType(y.ReturnParameter.ParameterType.GenericTypeArguments.First());
          return MapToJavaScriptType(y.ReturnParameter.ParameterType);
      }
      return null;
    }

    public async Task<object> Invoke(object input)
    {
        var extension = "." + input.ToString().Split(new[] { '.' }).Last();
        if (string.IsNullOrEmpty(extension))
            extension = ".dll";
        AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += (sender, args) =>
        {
            try
            {
                return Assembly.ReflectionOnlyLoad(args.Name);
            }
            catch
            {
                try
                {
                    var path = Path.Combine(Path.GetDirectoryName(input.ToString()) ?? "", args.Name.Split(new[] { ',' })[0] + extension);
                    return Assembly.ReflectionOnlyLoadFrom(path);
                }
                catch
                {
                    return null;
                }
            }
        };

        var assemblyPath = input.ToString();
        var ass = Assembly.ReflectionOnlyLoadFrom(assemblyPath);
        var docPath = assemblyPath.Substring(0, assemblyPath.LastIndexOf(".", StringComparison.Ordinal)) + ".XML";
        var xml = new XmlDocument();
        if (File.Exists(docPath))
            xml.Load(docPath);
        var hubType = Type.ReflectionOnlyGetType("Microsoft.AspNet.SignalR.Hub, Microsoft.AspNet.SignalR.Core", true, true);
        var hubGenericType = Type.ReflectionOnlyGetType("Microsoft.AspNet.SignalR.Hub`1, Microsoft.AspNet.SignalR.Core", false, true);
        return ass.DefinedTypes.Where(x => !x.IsAbstract && IsDerivedOfGenericType(x, hubGenericType)).Select(x => new Hub
        {
            Name = x.Name,
            Comment = new Comment(xml, "//member[@name='T:" + x.FullName + "']"),
            Server = x.GetMethods().Where(y => y.IsPublic && !y.IsStatic && y.DeclaringType != hubType && y.DeclaringType != typeof(object) && y.Name != "OnConnected" && !(y.DeclaringType.IsGenericType && y.DeclaringType.GetGenericTypeDefinition() == hubGenericType)).Select(y => new Method
            {
                Name = y.Name,
                Comment = new Comment(xml, "//member[starts-with(@name, 'M:" + x.FullName + "." + y.Name + "')]"),
                Arguments = y.GetParameters().Select(z => new Argument() { Name = z.Name, Type = MapToJavaScriptType(z.ParameterType) }).ToArray(),
                Returns = GetReturnType(y)
            }).ToArray(),
            Client = GetDerivedGenericTypeParameter(x, hubGenericType).GetTypeInfo().DeclaredMethods.Where(y => y.IsPublic && !y.IsStatic && y.GetBaseDefinition() == y).Select(y => new Method
            {
                Name = y.Name,
                Arguments = y.GetParameters().Select(z => new Argument() { Name = z.Name, Type = MapToJavaScriptType(z.ParameterType) }).ToArray(),
                Comment = new Comment(xml, "//member[starts-with(@name, 'M:" + y.DeclaringType.FullName + "." + y.Name + "')]"),
                Returns = GetReturnType(y)
            }).ToArray()
        }).ToArray();
    }
}
*/
});

export function scan(assembly) {
  return new Promise((resolve, reject) => {
    reflect(assembly, (error, result) => {
      if(error) {
        return reject(error);
      }
      resolve(result);
    });
  });
}<|endoftext|>


<commit_before>NCI.socialGraph = function(socialGraphID, params){
	if (!params)
	    params = {}
	var me = $(socialGraphID);
	var force;
	var selectedDots = {};
	var socialGraphSelector = socialGraphID + " .socialGraph"
	var color = d3.scale.category10();
	var notNetworkColor = params.notNetworkColor || "#000000";
	var isClustered = params.isClustered || false ;
	var isDevided = params.isDevided || false ;
	var isFiltered = false;
	var graphWidth = params.width || me.width();
	var graphHeight =  params.height || $('#nciDetails').height() - 200;
	var radius = params.radius || function() { return 4};
	var charge = params.charge || function() { return -20};
	var linkDistance = params.linkDistance || function() { return 30};
	var graphBuilder = params.graphBuilder || undefined;
	var numOfPoints = params.numOfPoints || 0;
	var isExpandable = params.isExpandable || false;
	var tooltip;

	me.find('.byactivities').on('click', function(event){
		isDevided = this.checked;
		me.show();
	});
	me.find('.pretty').on('click', function(event){
		isClustered = this.checked;
		me.show();
	});
	me.find('.internal').on('click', function(event){
		isFiltered = this.checked;
		me.show();
	});

	me.show = function(needDraw){
		if (tooltip === undefined)
			tooltip = d3.select(socialGraphSelector).append("div").attr("class", "endpoint-tooltip");
		if (NCI.Communities.length == 0){
			return;
		};
		if (needDraw) {
		    d3.select("#activities_graph").remove();
			if (numOfPoints > NCI.max_vertices) {
				d3.select(socialGraphSelector).append('text')
				.attr("id","activities_graph")
				.html('Too many endpoints to draw');
			} else {
			    me.draw();
			}
		//otherwise just change appearance
		} else {
		    me.setupNodes();
		    force.start();
		}
	};

	//colorify and set radius
	me.setupNodes = function(){
		me.node.style("fill", function(d) {
			//if this dot is selected on Activities graph, draw it in red
		    if ( isFiltered && NCI.isExternal(d.name)){
			    return notNetworkColor;
		    };
		    return isDevided ? color(d.group) : color(0);
		});
		me.node.attr("r", function(d) {
			return radius(d);
		});
		force.linkStrength(isClustered ? 1 : 0);
	};

	me.draw = function(){
		force = d3.layout.force()
		    .charge(charge())
			.linkDistance(linkDistance())
			.size([graphWidth,  graphHeight])
			.linkStrength(isClustered ? 1 : 0);

	    me.activitiesGraphSvg = d3.select(socialGraphSelector).append("svg")
		    .attr("id","activities_graph")
			.attr("width", graphWidth)
			.attr("height", graphHeight);

		var setupLinks = function(){
			force.links(graphBuilder.graph.links);
			me.activitiesGraphSvg.selectAll("line").remove();
			var linksData = me.activitiesGraphSvg.selectAll(".link").data(graphBuilder.graph.links);
			me.link = linksData.enter().append("line")
		    .attr("class", "activities_link");
			linksData.exit().remove();
		};

		var setupNodes = function(){
			force.nodes(graphBuilder.graph.nodes);
			me.activitiesGraphSvg.selectAll("circle").remove();
			var nodesData =  me.activitiesGraphSvg.selectAll(".node").data(graphBuilder.graph.nodes);
            me.node = nodesData.enter().append("circle").call(force.drag);
            nodesData.exit().remove();
			me.setupNodes(isFiltered, isDevided, isClustered);
			me.node.on('mouseover', function(d){
				var info = d.fullname;
				if (NCI.isExternal(d.fullname)){
					info += "
doesn't belong to activity";
				};
				info += "
" + d.connections + " connections";
				tooltip.html(info).style("top", d.py - 5).
				style("left", d.px + 10).style("display", "inline");
			}).on('mouseout', function(){
				tooltip.style("display", "none");
			});
			if (isExpandable) {
				me.node.on('click', function(d){
					var label = d.name.split(":")[0];
					var group = selectedDots[label]
					if (group !== undefined){
						delete selectedDots[selectedDots[label]]
						delete selectedDots[label]
						graphBuilder.removeCommunity(group);
						setupLinks();
						setupNodes();
						force.start();
						return;
					}
					for (var i=0; i < Object.keys(selectedDots).length + 1; i++){
						if (selectedDots[i + 1] === undefined){
							selectedDots[i + 1] = true;
							selectedDots[label] =  i + 1;
							break
						}
					}
					$.each(NCI.Communities, function(index, community){
						if (community.Label == label){
							graphBuilder.addCommunity(community, label, selectedDots[label] );
							setupLinks();
							setupNodes();
							force.start();
							return false;
						}
					});
	 		    });
			};
		};

		setupLinks();
		setupNodes();
	    force.on("tick", function() {
	        me.link.attr("x1", function(d) { return d.source.x; })
	            .attr("y1", function(d) { return d.source.y; })
	            .attr("x2", function(d) { return d.target.x; })
	            .attr("y2", function(d) { return d.target.y; });

	        me.node.attr("cx", function(d) { return d.x; })
	            .attr("cy", function(d) { return d.y; });
		});
		force.start();
	};

	return me;
};

NCI.graphBuilder = function(communities){
	var thisBuilder = this;
	var endpointsHash = {};
	var groupCount = 0;
    thisBuilder.graph = { "nodes":[], "links": []};
	NCI.maxActivitySize = 0;

	//add community
	thisBuilder.addCommunity = function(community, mainEndpoint, group){
		var communityEndpoints = {};
		var startIndex = Object.keys(endpointsHash).length
		var addConnection = function(endPoint, endpoints){
			var ip = endPoint.split(":")[0];
			if (!endpointsHash[ip]){
			    if (!communityEndpoints[ip]){
					var size = endPoint.split(":")[1];
				    var index = Object.keys(communityEndpoints).length + startIndex
				    communityEndpoints[ip] = {
						fullname: endPoint,
					    index: index,
					    external: !endpoints.indexOf(endPoint),
					    connections: 0,
						size: size};
			    };
			    communityEndpoints[ip].connections++;
			    return communityEndpoints[ip].index;
		    } else {
		    	return endpointsHash[ip].index;
		    }
		};

		$.each(community.Interactions, function(index, interacton){
			thisBuilder.graph.links.push({
				source: addConnection(interacton[0], community.Endpoints),
				target: addConnection(interacton[1], community.Endpoints),
				value: 1});
		});

		$.each(Object.keys(communityEndpoints), function(index, key){
			if (mainEndpoint == key)
			   return
			var endpoint = communityEndpoints[key];
			if (NCI.maxActivitySize < parseInt(endpoint.size))
			    NCI.maxActivitySize = parseInt(endpoint.size);
			thisBuilder.graph.nodes[endpoint.index] = {
				name: key,
				fullname: endpoint.fullname,
				group: group,
				connections: endpoint.connections,
				external: endpoint.external,
				size: endpoint.size
			};
			endpointsHash[key] = communityEndpoints[key];
		});
	};

	//remove community
	thisBuilder.removeCommunity = function(group){
	    thisBuilder.graph.nodes = $.grep(thisBuilder.graph.nodes, function(node, index){
			var remove = node.group == group
			if (remove)
			  delete endpointsHash[node.name];
			return !remove;
		});

	    thisBuilder.graph.links = $.grep(thisBuilder.graph.links, function(link, index){
			var remove = endpointsHash[link.target.name] === undefined || endpointsHash[link.source.name] === undefined;
			return !remove;
		});
		groupCount--;
	};

	$.each(communities, function(index, community){
		thisBuilder.addCommunity(community, undefined, groupCount);
		groupCount++;
	});
};<commit_msg>Centrate "Too many endpoints to draw" message<commit_after>NCI.socialGraph = function(socialGraphID, params){
	if (!params)
	    params = {}
	var me = $(socialGraphID);
	var force;
	var selectedDots = {};
	var socialGraphSelector = socialGraphID + " .socialGraph"
	var color = d3.scale.category10();
	var notNetworkColor = params.notNetworkColor || "#000000";
	var isClustered = params.isClustered || false ;
	var isDevided = params.isDevided || false ;
	var isFiltered = false;
	var graphWidth = params.width || me.width();
	var graphHeight =  params.height || $('#nciDetails').height() - 200;
	var radius = params.radius || function() { return 4};
	var charge = params.charge || function() { return -20};
	var linkDistance = params.linkDistance || function() { return 30};
	var graphBuilder = params.graphBuilder || undefined;
	var numOfPoints = params.numOfPoints || 0;
	var isExpandable = params.isExpandable || false;
	var tooltip;

	me.find('.byactivities').on('click', function(event){
		isDevided = this.checked;
		me.show();
	});
	me.find('.pretty').on('click', function(event){
		isClustered = this.checked;
		me.show();
	});
	me.find('.internal').on('click', function(event){
		isFiltered = this.checked;
		me.show();
	});

	me.show = function(needDraw){
		if (tooltip === undefined)
			tooltip = d3.select(socialGraphSelector).append("div").attr("class", "endpoint-tooltip");
		if (NCI.Communities.length == 0){
			return;
		};
		if (needDraw) {
		    d3.select("#activities_graph").remove();
			if (numOfPoints > NCI.max_vertices) {
				d3.select(socialGraphSelector).append('text')
				.attr("id","activities_graph")
				.html('Too many endpoints to draw')
				.attr('class', 'centrate');
			} else {
			    me.draw();
			}
		//otherwise just change appearance
		} else {
		    me.setupNodes();
		    force.start();
		}
	};

	//colorify and set radius
	me.setupNodes = function(){
		me.node.style("fill", function(d) {
		    if ( isFiltered && NCI.isExternal(d.name)){
			    return notNetworkColor;
		    };
			//if this dot is selected on Activities graph, draw it in red
			if (d.external)
			    return "red"
		    return isDevided ? color(d.group) : color(0);
		});
		me.node.attr("r", function(d) {
			return radius(d);
		});
		force.linkStrength(isClustered ? 1 : 0);
	};

	me.draw = function(){
		force = d3.layout.force()
		    .charge(charge())
			.linkDistance(linkDistance())
			.size([graphWidth,  graphHeight])
			.linkStrength(isClustered ? 1 : 0);

	    me.activitiesGraphSvg = d3.select(socialGraphSelector).append("svg")
		    .attr("id","activities_graph")
			.attr("width", graphWidth)
			.attr("height", graphHeight);

		var setupLinks = function(){
			force.links(graphBuilder.graph.links);
			me.activitiesGraphSvg.selectAll("line").remove();
			var linksData = me.activitiesGraphSvg.selectAll(".link").data(graphBuilder.graph.links);
			me.link = linksData.enter().append("line")
		    .attr("class", "activities_link");
			linksData.exit().remove();
		};

		var setupNodes = function(){
			force.nodes(graphBuilder.graph.nodes);
			me.activitiesGraphSvg.selectAll("circle").remove();
			var nodesData =  me.activitiesGraphSvg.selectAll(".node").data(graphBuilder.graph.nodes);
            me.node = nodesData.enter().append("circle").call(force.drag);
            nodesData.exit().remove();
			me.setupNodes(isFiltered, isDevided, isClustered);
			me.node.on('mouseover', function(d){
				var info = d.fullname;
				if (d.external){
					info += "
doesn't belong to activity";
				};
				info += "
" + d.connections + " connections";
				tooltip.html(info).style("top", d.py - 5).
				style("left", d.px + 10).style("display", "inline");
			}).on('mouseout', function(){
				tooltip.style("display", "none");
			});
			if (isExpandable) {
				me.node.on('click', function(d){
					var label = d.name.split(":")[0];
					var group = selectedDots[label]
					if (group !== undefined){
						delete selectedDots[selectedDots[label]]
						delete selectedDots[label]
						graphBuilder.removeCommunity(group);
						setupLinks();
						setupNodes();
						force.start();
						return;
					}
					for (var i=0; i < Object.keys(selectedDots).length + 1; i++){
						if (selectedDots[i + 1] === undefined){
							selectedDots[i + 1] = true;
							selectedDots[label] =  i + 1;
							break
						}
					}
					$.each(NCI.Communities, function(index, community){
						if (community.Label == label){
							graphBuilder.addCommunity(community, label, selectedDots[label] );
							setupLinks();
							setupNodes();
							force.start();
							return false;
						}
					});
	 		    });
			};
		};

		setupLinks();
		setupNodes();
	    force.on("tick", function() {
	        me.link.attr("x1", function(d) { return d.source.x; })
	            .attr("y1", function(d) { return d.source.y; })
	            .attr("x2", function(d) { return d.target.x; })
	            .attr("y2", function(d) { return d.target.y; });

	        me.node.attr("cx", function(d) { return d.x; })
	            .attr("cy", function(d) { return d.y; });
		});
		force.start();
	};

	return me;
};

NCI.graphBuilder = function(communities){
	var thisBuilder = this;
	var endpointsHash = {};
	var groupCount = 0;
    thisBuilder.graph = { "nodes":[], "links": []};
	NCI.maxActivitySize = 0;

	//add community
	thisBuilder.addCommunity = function(community, mainEndpoint, group){
		var communityEndpoints = {};
		var startIndex = Object.keys(endpointsHash).length
		var addConnection = function(endPoint, endpoints){
			var ip = endPoint.split(":")[0];
			if (!endpointsHash[ip]){
			    if (!communityEndpoints[ip]){
					var size = endPoint.split(":")[1];
				    var index = Object.keys(communityEndpoints).length + startIndex
				    communityEndpoints[ip] = {
						fullname: endPoint,
					    index: index,
					    external: endpoints.indexOf(endPoint) == -1,
					    connections: 0,
						size: size};
			    };
			    communityEndpoints[ip].connections++;
			    return communityEndpoints[ip].index;
		    } else {
		    	return endpointsHash[ip].index;
		    }
		};

		$.each(community.Interactions, function(index, interacton){
			thisBuilder.graph.links.push({
				source: addConnection(interacton[0], community.Endpoints),
				target: addConnection(interacton[1], community.Endpoints),
				value: 1});
		});

		$.each(Object.keys(communityEndpoints), function(index, key){
			if (mainEndpoint == key)
			   return
			var endpoint = communityEndpoints[key];
			if (NCI.maxActivitySize < parseInt(endpoint.size))
			    NCI.maxActivitySize = parseInt(endpoint.size);
			thisBuilder.graph.nodes[endpoint.index] = {
				name: key,
				fullname: endpoint.fullname,
				group: group,
				connections: endpoint.connections,
				external: endpoint.external,
				size: endpoint.size
			};
			endpointsHash[key] = communityEndpoints[key];
		});
	};

	//remove community
	thisBuilder.removeCommunity = function(group){
	    thisBuilder.graph.nodes = $.grep(thisBuilder.graph.nodes, function(node, index){
			var remove = node.group == group
			if (remove)
			  delete endpointsHash[node.name];
			return !remove;
		});

	    thisBuilder.graph.links = $.grep(thisBuilder.graph.links, function(link, index){
			var remove = endpointsHash[link.target.name] === undefined || endpointsHash[link.source.name] === undefined;
			return !remove;
		});
		groupCount--;
	};

	$.each(communities, function(index, community){
		thisBuilder.addCommunity(community, undefined, groupCount);
		groupCount++;
	});
};<|endoftext|>


<commit_before>
var ss = require('../');

exports['Start and Stop Empty Topology'] = function(test)
{
	var builder = ss.createTopologyBuilder();
	var topology = builder.createTopology();
	topology.start();
	topology.stop();
	test.done();
}

exports['Create Simple Topology'] = function(test)
{
	var builder = ss.createTopologyBuilder();
    builder.setSpout("spout", new Spout());
    builder.setBolt("bolt", new Bolt()).shuffleGrouping("spout");
	var topology = builder.createTopology();
    test.ok(topology);
	test.done();
}

function Spout() {
    var controller;

    this.prepare = function(contr) {
        controller = contr;
    }
}

function Bolt(test) {
    var controller;

    this.prepare = function(contr) {
        controller = contr;
    }

    this.execute = function(msg) {
        test.ok(msg);
        test.done();
    }
}<commit_msg>Launch simple topology, first test<commit_after>
var ss = require('../');

exports['Start and Stop Empty Topology'] = function(test)
{
	var builder = ss.createTopologyBuilder();
	var topology = builder.createTopology();
	topology.start();
	topology.stop();
	test.done();
}

exports['Create Simple Topology'] = function(test)
{
	var builder = ss.createTopologyBuilder();
    builder.setSpout("spout", new Spout());
    builder.setBolt("bolt", new Bolt()).shuffleGrouping("spout");
	var topology = builder.createTopology();
    test.ok(topology);
	test.done();
}

exports['Create and Run Simple Topology'] = function(test)
{
	var builder = ss.createTopologyBuilder();
    var spout = new Spout();
    builder.setSpout("spout", spout);
    builder.setBolt("bolt", new Bolt(test, "foo")).shuffleGrouping("spout");
	var topology = builder.createTopology();
    test.expect(3);
    test.ok(topology);
    spout.emitMessage("foo");
}

function Spout() {
    var controller;

    this.prepare = function(contr) {
        controller = contr;
    }

    this.emitMessage = function(msg)
    {
        controller.emit(msg);
    }
}

function Bolt(test, expected) {
    var controller;

    this.prepare = function(contr) {
        controller = contr;
    }

    this.execute = function(msg) {
        test.ok(msg);
        test.equal(msg, expected);
        test.done();
    }
}<|endoftext|>


<commit_before>import {expect} from 'chai';
import transmog from '../src/index';
import identity from 'lodash/identity';
import assert from '../src/assert';

describe('transmog', () => {
    context('object rules', () => {
        it('should map the property at sourcePath to the destination path given by the key', () => {
            let rules = {
                'mapped.a': {
                    converter: identity,
                    sourcePath: 'a'
                },
                'C': {
                    converter: identity,
                    sourcePath: 'b.c'
                }
            };

            let obj = {
                a: 1,
                b: {
                    c: 2
                }
            };

            expect(transmog(rules, obj)).to.deep.equal({
                mapped: {
                    a: 1
                },
                C: 2
            });
        });

        it('should convert the value using the given converter function', () => {
            let rules = {
                A: {
                    converter: (a) => a + 1,
                    sourcePath: 'a'
                },
                'hello.world': {
                    converter: (b) => `Hello, ${b}!`,
                    sourcePath: 'b'
                }
            };

            let obj = {
                a: 41,
                b: 'world'
            };

            expect(transmog(rules, obj)).to.deep.equal({
                A: 42,
                hello: {
                    world: 'Hello, world!'
                }
            });
        });

        it('should use identity if converter is omitted', () => {
            let rules = {
                b: {
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: 1
            };

            expect(transmog(rules, obj)).to.deep.equal({
                b: 1
            });
        });

        it('should use destination path as source path if sourcePath is omitted', () => {
            let rules = {
                a: {
                    converter: (a) => a + 1
                }
            };

            let obj = {
                a: 1
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: 2
            });
        });

        describe('defaultTo property', () => {
            it('should use defaultTo function for non-existing source path', () => {
                let rules = {
                    a: {
                        converter: identity,
                        defaultTo: () => 1,
                        sourcePath: 'a'
                    }
                };

                let obj = {
                    b: 10
                };

                expect(transmog(rules, obj)).to.deep.equal({
                    a: 1
                });
            });

            it('should use defaultTo function if source value is undefined', () => {
                let rules = {
                    a: {
                        converter: identity,
                        defaultTo: () => 1,
                        sourcePath: 'a'
                    }
                };

                let obj = {
                    a: undefined,
                    b: 10
                };

                expect(transmog(rules, obj)).to.deep.equal({
                    a: 1
                });
            });

            it('should use defaultTo function if source value is null', () => {
                let rules = {
                    a: {
                        converter: identity,
                        defaultTo: () => 1,
                        sourcePath: 'a'
                    }
                };

                let obj = {
                    a: null,
                    b: 10
                };

                expect(transmog(rules, obj)).to.deep.equal({
                    a: 1
                });
            });

            it('should call defaultTo function with source object as argument', () => {
                let arg;

                let defaultToFunction = (o) => {
                    arg = o;
                    return 1;
                };

                let rules = {
                    a: {
                        converter: identity,
                        defaultTo: defaultToFunction,
                        sourcePath: 'a'
                    }
                };

                let obj = {
                    b: 10
                };

                transmog(rules, obj);

                expect(arg).to.equal(obj);
            });
        });
    });

    context('property paths', () => {
        it('should read from deep paths', () => {
            let rules = {
                abc: {
                    converter: identity,
                    sourcePath: 'a.b.c'
                }
            };

            let obj = {
                a: {
                    b: {
                        c: 1
                    }
                }
            };

            expect(transmog(rules, obj)).to.deep.equal({
                abc: 1
            });
        });

        it('should write to deep path', () => {
            let rules = {
                'a.b.c': {
                    converter: identity,
                    sourcePath: 'abc'
                }
            };

            let obj = {
                abc: 1
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: {
                    b: {
                        c: 1
                    }
                }
            });
        });

        it('should ignore non-existing source paths', () => {
            let rules = {
                A: {
                    converter: identity,
                    sourcePath: 'a'
                },
                BC: {
                    converter: identity,
                    sourcePath: 'b.c'
                }
            };

            let obj = {
                a: 1,
                b: {
                    d: 2
                }
            };

            expect(transmog(rules, obj)).to.deep.equal({
                A: 1
            });
        });

        it('should convert undefined values', () => {
            let rules = {
                a: {
                    converter: identity,
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: undefined
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: undefined
            });
        });

        it('should convert null values', () => {
            let rules = {
                a: {
                    converter: identity,
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: null
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: null
            });
        });
    });

    context('boolean rules', () => {
        it('should take property when rule is true', () => {
            let rules = {
                a: true,
                c: true
            };

            let obj = {
                a: 1,
                b: 2,
                c: 3
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: 1,
                c: 3
            });
        });

        it('should ignore property when rule is false', () => {
            let rules = {
                a: false,
                c: true
            };

            let obj = {
                a: 1,
                b: 2,
                c: 3
            };

            expect(transmog(rules, obj)).to.deep.equal({
                c: 3
            });
        });
    });

    context('function rules', () => {
        it('should transform the value using the given function', () => {
            let rules = {
                a: (a) => 10 * a
            };

            let obj = {
                a: 4.2
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: 42
            });
        });
    });

    context('string rules', () => {
        it('should move the property from source path given by the value to destination path given by the key', () => {
            let rules = {
                'b.c': 'a'
            };

            let obj = {
                a: 1
            }

            expect(transmog(rules, obj)).to.deep.equal({
                b: {
                    c: 1
                }
            });
        });
    });

    context('rule format assertion', () => {
        it('should throw AssertionError if converter is not a function', () => {
            let rules = {
                a: {
                    converter: 3,
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: 1
            };

            expect(() => transmog(rules, obj)).to.throw('AssertionError');
        });

        it('should throw AssertionError if sourcePath is not a string', () => {
            let rules = {
                a: {
                    converter: identity,
                    sourcePath: 1
                }
            };

            let obj = {
                a: 2
            };

            expect(() => transmog(rules, obj)).to.throw('AssertionError');
        });
    });

    context('conversion function', () => {
        it('should be called with source property value as first argument', () => {
            let firstArgument;

            let converterFunction = (a) => {
                firstArgument = a;
                return a;
            };

            let rules = {
                a: {
                    converter: converterFunction,
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: {}
            };

            transmog(rules, obj);

            expect(firstArgument).to.equal(obj.a);
        });

        it('should be called with source object as second argument', () => {
            let secondArgument;

            let converterFunction = (a, o) => {
                secondArgument = o;
                return a;
            };

            let rules = {
                a: {
                    converter: converterFunction,
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: 1
            };

            transmog(rules, obj);

            expect(secondArgument).to.equal(obj);
        });
    });
});
<commit_msg>remove unused require<commit_after>import {expect} from 'chai';
import transmog from '../src/index';
import identity from 'lodash/identity';

describe('transmog', () => {
    context('object rules', () => {
        it('should map the property at sourcePath to the destination path given by the key', () => {
            let rules = {
                'mapped.a': {
                    converter: identity,
                    sourcePath: 'a'
                },
                'C': {
                    converter: identity,
                    sourcePath: 'b.c'
                }
            };

            let obj = {
                a: 1,
                b: {
                    c: 2
                }
            };

            expect(transmog(rules, obj)).to.deep.equal({
                mapped: {
                    a: 1
                },
                C: 2
            });
        });

        it('should convert the value using the given converter function', () => {
            let rules = {
                A: {
                    converter: (a) => a + 1,
                    sourcePath: 'a'
                },
                'hello.world': {
                    converter: (b) => `Hello, ${b}!`,
                    sourcePath: 'b'
                }
            };

            let obj = {
                a: 41,
                b: 'world'
            };

            expect(transmog(rules, obj)).to.deep.equal({
                A: 42,
                hello: {
                    world: 'Hello, world!'
                }
            });
        });

        it('should use identity if converter is omitted', () => {
            let rules = {
                b: {
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: 1
            };

            expect(transmog(rules, obj)).to.deep.equal({
                b: 1
            });
        });

        it('should use destination path as source path if sourcePath is omitted', () => {
            let rules = {
                a: {
                    converter: (a) => a + 1
                }
            };

            let obj = {
                a: 1
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: 2
            });
        });

        describe('defaultTo property', () => {
            it('should use defaultTo function for non-existing source path', () => {
                let rules = {
                    a: {
                        converter: identity,
                        defaultTo: () => 1,
                        sourcePath: 'a'
                    }
                };

                let obj = {
                    b: 10
                };

                expect(transmog(rules, obj)).to.deep.equal({
                    a: 1
                });
            });

            it('should use defaultTo function if source value is undefined', () => {
                let rules = {
                    a: {
                        converter: identity,
                        defaultTo: () => 1,
                        sourcePath: 'a'
                    }
                };

                let obj = {
                    a: undefined,
                    b: 10
                };

                expect(transmog(rules, obj)).to.deep.equal({
                    a: 1
                });
            });

            it('should use defaultTo function if source value is null', () => {
                let rules = {
                    a: {
                        converter: identity,
                        defaultTo: () => 1,
                        sourcePath: 'a'
                    }
                };

                let obj = {
                    a: null,
                    b: 10
                };

                expect(transmog(rules, obj)).to.deep.equal({
                    a: 1
                });
            });

            it('should call defaultTo function with source object as argument', () => {
                let arg;

                let defaultToFunction = (o) => {
                    arg = o;
                    return 1;
                };

                let rules = {
                    a: {
                        converter: identity,
                        defaultTo: defaultToFunction,
                        sourcePath: 'a'
                    }
                };

                let obj = {
                    b: 10
                };

                transmog(rules, obj);

                expect(arg).to.equal(obj);
            });
        });
    });

    context('property paths', () => {
        it('should read from deep paths', () => {
            let rules = {
                abc: {
                    converter: identity,
                    sourcePath: 'a.b.c'
                }
            };

            let obj = {
                a: {
                    b: {
                        c: 1
                    }
                }
            };

            expect(transmog(rules, obj)).to.deep.equal({
                abc: 1
            });
        });

        it('should write to deep path', () => {
            let rules = {
                'a.b.c': {
                    converter: identity,
                    sourcePath: 'abc'
                }
            };

            let obj = {
                abc: 1
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: {
                    b: {
                        c: 1
                    }
                }
            });
        });

        it('should ignore non-existing source paths', () => {
            let rules = {
                A: {
                    converter: identity,
                    sourcePath: 'a'
                },
                BC: {
                    converter: identity,
                    sourcePath: 'b.c'
                }
            };

            let obj = {
                a: 1,
                b: {
                    d: 2
                }
            };

            expect(transmog(rules, obj)).to.deep.equal({
                A: 1
            });
        });

        it('should convert undefined values', () => {
            let rules = {
                a: {
                    converter: identity,
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: undefined
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: undefined
            });
        });

        it('should convert null values', () => {
            let rules = {
                a: {
                    converter: identity,
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: null
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: null
            });
        });
    });

    context('boolean rules', () => {
        it('should take property when rule is true', () => {
            let rules = {
                a: true,
                c: true
            };

            let obj = {
                a: 1,
                b: 2,
                c: 3
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: 1,
                c: 3
            });
        });

        it('should ignore property when rule is false', () => {
            let rules = {
                a: false,
                c: true
            };

            let obj = {
                a: 1,
                b: 2,
                c: 3
            };

            expect(transmog(rules, obj)).to.deep.equal({
                c: 3
            });
        });
    });

    context('function rules', () => {
        it('should transform the value using the given function', () => {
            let rules = {
                a: (a) => 10 * a
            };

            let obj = {
                a: 4.2
            };

            expect(transmog(rules, obj)).to.deep.equal({
                a: 42
            });
        });
    });

    context('string rules', () => {
        it('should move the property from source path given by the value to destination path given by the key', () => {
            let rules = {
                'b.c': 'a'
            };

            let obj = {
                a: 1
            }

            expect(transmog(rules, obj)).to.deep.equal({
                b: {
                    c: 1
                }
            });
        });
    });

    context('rule format assertion', () => {
        it('should throw AssertionError if converter is not a function', () => {
            let rules = {
                a: {
                    converter: 3,
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: 1
            };

            expect(() => transmog(rules, obj)).to.throw('AssertionError');
        });

        it('should throw AssertionError if sourcePath is not a string', () => {
            let rules = {
                a: {
                    converter: identity,
                    sourcePath: 1
                }
            };

            let obj = {
                a: 2
            };

            expect(() => transmog(rules, obj)).to.throw('AssertionError');
        });
    });

    context('conversion function', () => {
        it('should be called with source property value as first argument', () => {
            let firstArgument;

            let converterFunction = (a) => {
                firstArgument = a;
                return a;
            };

            let rules = {
                a: {
                    converter: converterFunction,
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: {}
            };

            transmog(rules, obj);

            expect(firstArgument).to.equal(obj.a);
        });

        it('should be called with source object as second argument', () => {
            let secondArgument;

            let converterFunction = (a, o) => {
                secondArgument = o;
                return a;
            };

            let rules = {
                a: {
                    converter: converterFunction,
                    sourcePath: 'a'
                }
            };

            let obj = {
                a: 1
            };

            transmog(rules, obj);

            expect(secondArgument).to.equal(obj);
        });
    });
});
<|endoftext|>


<commit_before>/**
 *  Copyright (c) 2010 Alethia Inc,
 *  http://www.alethia-inc.com
 *  Developed by Travis Tidwell | travist at alethia-inc.com
 *
 *  License:  GPL version 3.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.

 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 *
 *  This file serves as a starting point for new template designs.  Below you will
 *  see a listing of all media player "hooks" that can be implemented by the
 *  template to customize the functionality of this template.
 */
(function($) {
  jQuery.media = jQuery.media ? jQuery.media : {};
  jQuery.media.templates = jQuery.extend( {}, {
    "simpleblack" : function( mediaplayer, settings ) {
      return new (function( mediaplayer, settings ) {

        settings = jQuery.media.utils.getSettings(settings);
        var _this = this;

        this.mediaDisplay = null;
        this.player = null;
        this.logo = null;
        this.fullScreenButton = null;

        /**
         * Called just before the mediaplayer is ready to show this template to the user.
         * This function is used to initialize the template given the current state of
         * settings passed to the player.  You can use this function to initialize variables,
         * change width's and height's of elements based on certain parameters passed to the
         * media player.
         *
         * @param - The settings object.
         */
        this.initialize = function( settings ) {

          // Get the player elements.
          this.mediaDisplay = mediaplayer.node.player.media;
          this.player = mediaplayer.node.player;
          this.volumeBar = $('#mediaplayer_audioBar');
          this.logo = this.player.logo;
          this.fullScreenButton = mediaplayer.display.find("#mediafront_resizeScreen").click( function( event ) {
            event.preventDefault();
            mediaplayer.onFullScreen(!mediaplayer.fullScreen);
          });

          // Hide the volume bar by default.
          this.volumeBar.hide();
          this.fullScreenButton.find(".off").hide();

          // Show the control bar, and then hide it after 5 seconds of inactivity.
          jQuery.media.utils.showThenHide( mediaplayer.controller.display, "display", null, "slow", function() {
            mediaplayer.node.player.play.css("bottom", "5px");
          });

          jQuery.media.utils.showThenHide( this.fullScreenButton, "fullscreen" );

          // Make sure that we show the volume bar when they hover over the mute button.
          // Add a timer to the mouse move of the display to show the control bar and logo on mouse move.
          mediaplayer.display.bind("mousemove", function() {
            jQuery.media.utils.showThenHide( _this.fullScreenButton, "fullscreen" );
            mediaplayer.node.player.play.css("bottom", "45px");
            if( jQuery.media.hasMedia ) {
              jQuery.media.utils.showThenHide( mediaplayer.controller.display, "display", "fast", "slow", function() {
                mediaplayer.node.player.play.css("bottom", "5px");
              });
            }
            jQuery.media.utils.showThenHide( _this.logo.display, "logo", "fast", "slow" );
          });

          // Show the volume bar when they hover over the mute button.
          mediaplayer.controller.mute.display.bind("mousemove", function() {
            if( jQuery.media.hasMedia ) {
              jQuery.media.utils.showThenHide( _this.volumeBar, "volumeBar", "fast", "fast" );
            }
          });

          // Stop the hide on both the control bar and the volumeBar.
          jQuery.media.utils.stopHideOnOver( mediaplayer.controller.display, "display" );
          jQuery.media.utils.stopHideOnOver( this.fullScreenButton, "fullscreen" );
          jQuery.media.utils.stopHideOnOver( this.volumeBar, "volumeBar" );
        };

        /**
         * Returns our template settings overrides.  This is used to force a particular
         * setting to be a certain value if the user does not provide that parameter.
         *
         * @return - An associative array of our settings.  We can use this to override any
         *           default settings for the player as well as default ids.
         */
        this.getSettings = function() {
          return {
            volumeVertical:true
          };
        };

        /**
         * Called when the user presses the menu button.
         *
         * @param - If the menu should be on (true) or off (false).
         */
        this.onMenu = function( on ) {
          if( mediaplayer.menu ) {
            if( on ) {
              mediaplayer.menu.display.show( "normal" );
            }
            else {
              mediaplayer.menu.display.hide( "normal" );
            }
          }
        };

        /**
         * Called when the user presses the fullscreen button.
         *
         * @param - If the player is in fullscreen (true) or normal mode (false).
         */
        this.onFullScreen = function( on ) {
          if( on ) {
            this.fullScreenButton.find(".on").hide();
            this.fullScreenButton.find(".off").show();
            this.player.display.addClass("fullscreen");
            mediaplayer.menu.display.addClass("fullscreen");

            // Hide the players controls, and show the HTML controls.
            if( this.player ) {
              this.player.showControls(true);
            }
          }
          else {
            this.fullScreenButton.find(".on").show();
            this.fullScreenButton.find(".off").hide();
            this.player.display.removeClass("fullscreen");
            mediaplayer.menu.display.removeClass("fullscreen");

            // Hide the players controls, and show the HTML controls.
            if( this.player ) {
              this.player.showControls(false);
            }
          }
        };

        /**
         * Selects or Deselects a menu item.
         *
         * @param - The link jQuery object
         */
        this.onMenuSelect = function( link, contents, selected ) {
          if( selected ) {
            contents.show("normal");
            link.addClass('active');
          }
          else {
            contents.hide("normal");
            link.removeClass('active');
          }
        };

        this.onNodeLoad = function( data ) {
          mediaplayer.node.player.play.show();
        };

        this.onMediaUpdate = function( data ) {
          if( mediaplayer.controller && mediaplayer.node ) {
            if( data.type == "reset" ) {
              jQuery.media.hasMedia = true;
              mediaplayer.controller.display.show();
              this.player.display.removeClass("nomedia");
            }
            else if( data.type == "nomedia" ) {
              jQuery.media.hasMedia = false;
              mediaplayer.controller.display.hide();
              this.player.display.addClass("nomedia");
            }
          }
        };

        /**
         * This function is currently stubbed out.
         * You can implement it and hook into the time display by
         * reassigning this as follows...
         *
         *  this.formatTime = function( time ) {
         *  }
         *
         *  You can see the default implementation of this function
         *  by opening js/source/jquery.media.control.js on the line
         *  after it says this.formatTime = ...
         */
        this.formatTime = false;
      })( mediaplayer, settings );
    }
  }, jQuery.media.templates );
})(jQuery);
<commit_msg>Fixed the simpleblack template from offsetting the play button overlay.<commit_after>/**
 *  Copyright (c) 2010 Alethia Inc,
 *  http://www.alethia-inc.com
 *  Developed by Travis Tidwell | travist at alethia-inc.com
 *
 *  License:  GPL version 3.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.

 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 *
 *  This file serves as a starting point for new template designs.  Below you will
 *  see a listing of all media player "hooks" that can be implemented by the
 *  template to customize the functionality of this template.
 */
(function($) {
  jQuery.media = jQuery.media ? jQuery.media : {};
  jQuery.media.templates = jQuery.extend( {}, {
    "simpleblack" : function( mediaplayer, settings ) {
      return new (function( mediaplayer, settings ) {

        settings = jQuery.media.utils.getSettings(settings);
        var _this = this;

        this.mediaDisplay = null;
        this.player = null;
        this.logo = null;
        this.fullScreenButton = null;

        /**
         * Called just before the mediaplayer is ready to show this template to the user.
         * This function is used to initialize the template given the current state of
         * settings passed to the player.  You can use this function to initialize variables,
         * change width's and height's of elements based on certain parameters passed to the
         * media player.
         *
         * @param - The settings object.
         */
        this.initialize = function( settings ) {

          // Get the player elements.
          this.mediaDisplay = mediaplayer.node.player.media;
          this.player = mediaplayer.node.player;
          this.volumeBar = $('#mediaplayer_audioBar');
          this.logo = this.player.logo;
          this.fullScreenButton = mediaplayer.display.find("#mediafront_resizeScreen").click( function( event ) {
            event.preventDefault();
            mediaplayer.onFullScreen(!mediaplayer.fullScreen);
          });

          // Hide the volume bar by default.
          this.volumeBar.hide();
          this.fullScreenButton.find(".off").hide();

          // Show the control bar, and then hide it after 5 seconds of inactivity.
          jQuery.media.utils.showThenHide( mediaplayer.controller.display, "display", null, "slow");

          jQuery.media.utils.showThenHide( this.fullScreenButton, "fullscreen" );

          // Make sure that we show the volume bar when they hover over the mute button.
          // Add a timer to the mouse move of the display to show the control bar and logo on mouse move.
          mediaplayer.display.bind("mousemove", function() {
            jQuery.media.utils.showThenHide( _this.fullScreenButton, "fullscreen" );
            if( jQuery.media.hasMedia ) {
              jQuery.media.utils.showThenHide( mediaplayer.controller.display, "display", "fast", "slow");
            }
            jQuery.media.utils.showThenHide( _this.logo.display, "logo", "fast", "slow" );
          });

          // Show the volume bar when they hover over the mute button.
          mediaplayer.controller.mute.display.bind("mousemove", function() {
            if( jQuery.media.hasMedia ) {
              jQuery.media.utils.showThenHide( _this.volumeBar, "volumeBar", "fast", "fast" );
            }
          });

          // Stop the hide on both the control bar and the volumeBar.
          jQuery.media.utils.stopHideOnOver( mediaplayer.controller.display, "display" );
          jQuery.media.utils.stopHideOnOver( this.fullScreenButton, "fullscreen" );
          jQuery.media.utils.stopHideOnOver( this.volumeBar, "volumeBar" );
        };

        /**
         * Returns our template settings overrides.  This is used to force a particular
         * setting to be a certain value if the user does not provide that parameter.
         *
         * @return - An associative array of our settings.  We can use this to override any
         *           default settings for the player as well as default ids.
         */
        this.getSettings = function() {
          return {
            volumeVertical:true
          };
        };

        /**
         * Called when the user presses the menu button.
         *
         * @param - If the menu should be on (true) or off (false).
         */
        this.onMenu = function( on ) {
          if( mediaplayer.menu ) {
            if( on ) {
              mediaplayer.menu.display.show( "normal" );
            }
            else {
              mediaplayer.menu.display.hide( "normal" );
            }
          }
        };

        /**
         * Called when the user presses the fullscreen button.
         *
         * @param - If the player is in fullscreen (true) or normal mode (false).
         */
        this.onFullScreen = function( on ) {
          if( on ) {
            this.fullScreenButton.find(".on").hide();
            this.fullScreenButton.find(".off").show();
            this.player.display.addClass("fullscreen");
            mediaplayer.menu.display.addClass("fullscreen");

            // Hide the players controls, and show the HTML controls.
            if( this.player ) {
              this.player.showControls(true);
            }
          }
          else {
            this.fullScreenButton.find(".on").show();
            this.fullScreenButton.find(".off").hide();
            this.player.display.removeClass("fullscreen");
            mediaplayer.menu.display.removeClass("fullscreen");

            // Hide the players controls, and show the HTML controls.
            if( this.player ) {
              this.player.showControls(false);
            }
          }
        };

        /**
         * Selects or Deselects a menu item.
         *
         * @param - The link jQuery object
         */
        this.onMenuSelect = function( link, contents, selected ) {
          if( selected ) {
            contents.show("normal");
            link.addClass('active');
          }
          else {
            contents.hide("normal");
            link.removeClass('active');
          }
        };

        this.onNodeLoad = function( data ) {
          mediaplayer.node.player.play.show();
        };

        this.onMediaUpdate = function( data ) {
          if( mediaplayer.controller && mediaplayer.node ) {
            if( data.type == "reset" ) {
              jQuery.media.hasMedia = true;
              mediaplayer.controller.display.show();
              this.player.display.removeClass("nomedia");
            }
            else if( data.type == "nomedia" ) {
              jQuery.media.hasMedia = false;
              mediaplayer.controller.display.hide();
              this.player.display.addClass("nomedia");
            }
          }
        };

        /**
         * This function is currently stubbed out.
         * You can implement it and hook into the time display by
         * reassigning this as follows...
         *
         *  this.formatTime = function( time ) {
         *  }
         *
         *  You can see the default implementation of this function
         *  by opening js/source/jquery.media.control.js on the line
         *  after it says this.formatTime = ...
         */
        this.formatTime = false;
      })( mediaplayer, settings );
    }
  }, jQuery.media.templates );
})(jQuery);
<|endoftext|>