<commit_before>'use strict';

import slack from 'slack';
import Storage from 'electron-json-storage';

const ChannelCache = 'channel_cache';
const UserCache = 'user_cache';
const AppConfig = require('../assets/conf.json');
const MIN_IN_SEC = 60;
const HOUR_IN_SEC = MIN_IN_SEC * 60;
const DAY_IN_SEC = HOUR_IN_SEC * 24;
const CHANNEL_UPDATE_IN_SEC = 2000;
const TEAM_UPDATE_IN_SEC = 60 * CHANNEL_UPDATE_IN_SEC;

export default class SlackHandler {

  constructor() {
    this.onRefresh = null;
    this._sortedChannelIds = [];
    this._channels = {};
    this._users = {};
    this._teams = {};
    this._tokens = AppConfig['tokens'];
    this._updatedTime = new Date();
    this._loadCache(() => {
      this._updateTeam();
    });
  }

  getChannels() {
    return this._sortedChannelIds.map((channelId) => {
      const channel = this._channels[channelId];
      return {
        id: channel.id,
        team: channel.team,
        channel: channel.name,
        is_new: channel.is_new,
        link: this._deeplink(channel.team,channel.id),
        date: this._formatedDate(channel.last_message.post_time),
        userName: this.getUser(channel.last_message.user_id),
        lastMessage: channel.last_message.text,
      };
    });
  }

  getSize() {
    return this._sortedChannelIds.length;
  }

  getUser(userId) {
    return this._users[userId];
  }

  _loadCache(callback) {
    Promise
      .resolve()
      .then(() => {
        Storage.get(ChannelCache,(error, data) => {
          if (error) {
            console.log(error);
          }
          else {
            this._channels = data;
          }
          return Promise.resolve();
        });
      })
      .then(() => {
        Storage.get(UserCache,(error, data) => {
          if (error) {
            console.log(error);
          }
          else {
            this._users = data;
          }
          return Promise.resolve();
        });
      })
      .then(callback);
  }

  _cacheChannels() {
    Storage.set(ChannelCache,this._channels,(error, data) => {
      if (error) console.log(error);
    });
  }

  _cacheUsers() {
    Storage.set(UserCache,this._users,(error, data) => {
      if (error) console.log(error);
    });
  }

  _formatedDate(date) {
    if (!date) return '';
    const base = Math.round(this._updatedTime.getTime() / 1000);
    const diff = base - date;
    if (diff > DAY_IN_SEC) {
      const day = Math.floor( diff / DAY_IN_SEC );
      if (day > 1) {
        return day + ' days ago';
      }
      return 'Yesterday';
    }
    if (diff > HOUR_IN_SEC) {
      const hour = Math.floor( diff / HOUR_IN_SEC );
      if (hour > 1) {
        return hour + ' hours ago';
      }
      return '1 hour ago';
    }
    const min = Math.floor( diff / MIN_IN_SEC );
    if (min > 1) {
      return min + ' mins ago';
    }
    return min + ' min ago';
  }

  _deeplink(team,channel) {
    if (!this._teams[team]) return 'slack://open';
    return 'slack://channel?team=' + this._teams[team] + '&id=' + channel;
  }

  _sortData() {
    let channelIds = Object.keys(this._channels);
    channelIds = channelIds.filter((id) => {
      return !this._channels[id].is_ignored;
    });
    channelIds.sort((idA, idB) => {
      const dateA = this._channels[idA].last_message.post_time;
      const dateB = this._channels[idB].last_message.post_time;
      return dateB - dateA;
    });
    this._updatedTime = new Date();
    this._sortedChannelIds = channelIds;
    if (this.onRefresh) {
      this.onRefresh();
    }
  }

  _updateTeam() {
    Object.keys(this._tokens).forEach((key) => {
      this._getTeamInfo(key);
      this._updateChannels(key);
    });
  }

  _updateChannels(team) {
    slack.groups.list({token: this._tokens[team]}, (error, data) => {
      if (error) {
        console.log(error);
        this._sortData();
        return;
      }
      data.groups.forEach((channelInfo, index, array) => {
        this._getChannelInfo(team, channelInfo.id);
        if (index == array.length - 1) {
          this._reserveNextListUpdate(team);
        }
      });
    });
  }

  _reserveNextListUpdate(team) {
    setTimeout(() => {
      this._updateChannels(team);
    }, TEAM_UPDATE_IN_SEC);
  }

  _getChannelInfo(team, channelId) {
    const param = {
      token: this._tokens[team],
      channel: channelId,
    };
    slack.groups.info(param, (error, data) => {
      if (error) {
        console.log(error);
        return;
      }
      const channel = {
        id: data.group.id,
        team: team,
        name: data.group.name,
        is_new: data.group.unread_count > 0,
        is_ignored: SlackHandler.shouldIgnoreChannel(data.group),
        last_message: SlackHandler.convertMessage(data.group.latest),
      };
      const cache = this._channels[channel.id];
      this._channels[channel.id] = channel;
      if (!cache || cache.last_message.post_time != channel.last_message.post_time) {
        this._cacheChannels();
        this._sortData();
      }
      else {
        this._updatedTime = new Date();
        if (this.onRefresh) {
          this.onRefresh();
        }
      }
      if (!this._users[channel.last_message.user_id]) {
        this._getUserInfo(team, channel.last_message.user_id);
      }
      if (!channel.is_ignored) {
        this._reserveNextChannelUpdate(team, channel.id);
      }
    });
  }

  _reserveNextChannelUpdate(team, channelId) {
    setTimeout(() => {
      this._getChannelInfo(team, channelId);
    }, CHANNEL_UPDATE_IN_SEC);
  }

  _getTeamInfo(team) {
    slack.team.info({token: this._tokens[team]}, (error, data) => {
      if (error) {
        console.log(error);
        return;
      }
      this._teams[team] = data.team.id;
    });
  }

  _getUserInfo(team, userId) {
    const updateName = (name) => {
      this._users[userId] = name;
      if (this.onRefresh) {
        this.onRefresh();
      }
      this._cacheUsers();
    };
    let param = { token: this._tokens[team] };
    if (userId.startsWith('user_')) {
      param.user = userId.replace(/^user_/,'');
      slack.users.info(param, (error, data) => {
        if (error) {
          console.log(error);
          return;
        }
        updateName(data.user.name);
      });
    }
    else if (userId.startsWith('bot_')) {
      param.bot = userId.replace(/^bot_/,'');
      slack.bots.info(param, (error, data) => {
        if (error) {
          console.log(error);
          return;
        }
        updateName(data.bot.name);
      });
    }
  }

  static convertMessage(info) {
    let userId = info.user ? 'user_' + info.user : undefined;
    if (!userId && info.bot_id) {
      userId = 'bot_' + info.bot_id;
    }
    return {
      user_id: userId,
      post_time: info.ts,
      text: info.text.replace(/\n/,' '),
    };
  }

  static shouldIgnoreChannel(info) {
    if (info.is_archived) return true;
    const ignore = AppConfig['ignore'];
    for (let i=0,n=ignore.length;i<n;i++) {
      if (info.name.indexOf(ignore[i]) > -1) return true;
    }
    return false;
  }

}
<commit_msg>minor code optimization<commit_after>'use strict';

import slack from 'slack';
import Storage from 'electron-json-storage';

const ChannelCache = 'channel_cache';
const UserCache = 'user_cache';
const AppConfig = require('../assets/conf.json');
const MIN_IN_SEC = 60;
const HOUR_IN_SEC = MIN_IN_SEC * 60;
const DAY_IN_SEC = HOUR_IN_SEC * 24;
const CHANNEL_UPDATE_IN_SEC = 2000;
const TEAM_UPDATE_IN_SEC = 60 * CHANNEL_UPDATE_IN_SEC;
const MAX_REFRESH_WAIT_IN_SEC = 5000;

export default class SlackHandler {

  constructor() {
    this.onRefresh = null;
    this._sortedChannelIds = [];
    this._channels = {};
    this._users = {};
    this._teams = {};
    this._tokens = AppConfig['tokens'];
    this._updatedTime = new Date();
    this._loadCache(() => {
      this._updateTeam();
    });
  }

  getChannels() {
    return this._sortedChannelIds.map((channelId) => {
      const channel = this._channels[channelId];
      return {
        id: channel.id,
        team: channel.team,
        channel: channel.name,
        is_new: channel.is_new,
        link: this._deeplink(channel.team,channel.id),
        date: this._formatedDate(channel.last_message.post_time),
        userName: this.getUser(channel.last_message.user_id),
        lastMessage: channel.last_message.text,
      };
    });
  }

  getSize() {
    return this._sortedChannelIds.length;
  }

  getUser(userId) {
    return this._users[userId];
  }

  _loadCache(callback) {
    Promise
      .resolve()
      .then(() => {
        Storage.get(ChannelCache,(error, data) => {
          if (error) {
            console.log(error);
          }
          else {
            this._channels = data;
          }
          return Promise.resolve();
        });
      })
      .then(() => {
        Storage.get(UserCache,(error, data) => {
          if (error) {
            console.log(error);
          }
          else {
            this._users = data;
          }
          return Promise.resolve();
        });
      })
      .then(callback);
  }

  _cacheChannels() {
    Storage.set(ChannelCache,this._channels,(error, data) => {
      if (error) console.log(error);
    });
  }

  _cacheUsers() {
    Storage.set(UserCache,this._users,(error, data) => {
      if (error) console.log(error);
    });
  }

  _formatedDate(date) {
    if (!date) return '';
    const base = Math.round(this._updatedTime.getTime() / 1000);
    const diff = base - date;
    if (diff > DAY_IN_SEC) {
      const day = Math.floor( diff / DAY_IN_SEC );
      if (day > 1) {
        return day + ' days ago';
      }
      return 'Yesterday';
    }
    if (diff > HOUR_IN_SEC) {
      const hour = Math.floor( diff / HOUR_IN_SEC );
      if (hour > 1) {
        return hour + ' hours ago';
      }
      return '1 hour ago';
    }
    const min = Math.floor( diff / MIN_IN_SEC );
    if (min > 1) {
      return min + ' mins ago';
    }
    return min + ' min ago';
  }

  _deeplink(team,channel) {
    if (!this._teams[team]) return 'slack://open';
    return 'slack://channel?team=' + this._teams[team] + '&id=' + channel;
  }

  _handleRefresh(forceRefresh) {
    const now = new Date();
    if (forceRefresh || this._updatedTime.getTime() + MAX_REFRESH_WAIT_IN_SEC < now.getTime()) {
      this._updatedTime = now;
      if (this.onRefresh) {
        this.onRefresh();
      }
    }
  }

  _sortData() {
    let channelIds = Object.keys(this._channels);
    channelIds = channelIds.filter((id) => {
      return !this._channels[id].is_ignored;
    });
    channelIds.sort((idA, idB) => {
      const dateA = this._channels[idA].last_message.post_time;
      const dateB = this._channels[idB].last_message.post_time;
      return dateB - dateA;
    });
    this._sortedChannelIds = channelIds;
    this._handleRefresh(true);
  }

  _updateTeam() {
    Object.keys(this._tokens).forEach((key) => {
      this._getTeamInfo(key);
      this._updateChannels(key);
    });
  }

  _updateChannels(team) {
    slack.groups.list({token: this._tokens[team]}, (error, data) => {
      if (error) {
        console.log(error);
        this._sortData();
        return;
      }
      data.groups.forEach((channelInfo, index, array) => {
        this._getChannelInfo(team, channelInfo.id);
        if (index == array.length - 1) {
          this._reserveNextListUpdate(team);
        }
      });
    });
  }

  _reserveNextListUpdate(team) {
    setTimeout(() => {
      this._updateChannels(team);
    }, TEAM_UPDATE_IN_SEC);
  }

  _getChannelInfo(team, channelId) {
    const param = {
      token: this._tokens[team],
      channel: channelId,
    };
    slack.groups.info(param, (error, data) => {
      if (error) {
        console.log(error);
        return;
      }
      const channel = {
        id: data.group.id,
        team: team,
        name: data.group.name,
        is_new: data.group.unread_count > 0,
        is_ignored: SlackHandler.shouldIgnoreChannel(data.group),
        last_message: SlackHandler.convertMessage(data.group.latest),
      };
      const cache = this._channels[channel.id];
      this._channels[channel.id] = channel;
      if (!cache || cache.last_message.post_time != channel.last_message.post_time) {
        this._cacheChannels();
        this._sortData();
      }
      else {
        this._handleRefresh(false);
      }
      if (!this._users[channel.last_message.user_id]) {
        this._getUserInfo(team, channel.last_message.user_id);
      }
      if (!channel.is_ignored) {
        this._reserveNextChannelUpdate(team, channel.id);
      }
    });
  }

  _reserveNextChannelUpdate(team, channelId) {
    setTimeout(() => {
      this._getChannelInfo(team, channelId);
    }, CHANNEL_UPDATE_IN_SEC);
  }

  _getTeamInfo(team) {
    slack.team.info({token: this._tokens[team]}, (error, data) => {
      if (error) {
        console.log(error);
        return;
      }
      this._teams[team] = data.team.id;
    });
  }

  _getUserInfo(team, userId) {
    const updateName = (name) => {
      this._users[userId] = name;
      this._cacheUsers();
      this._handleRefresh(true);
    };
    let param = { token: this._tokens[team] };
    if (userId.startsWith('user_')) {
      param.user = userId.replace(/^user_/,'');
      slack.users.info(param, (error, data) => {
        if (error) {
          console.log(error);
          return;
        }
        updateName(data.user.name);
      });
    }
    else if (userId.startsWith('bot_')) {
      param.bot = userId.replace(/^bot_/,'');
      slack.bots.info(param, (error, data) => {
        if (error) {
          console.log(error);
          return;
        }
        updateName(data.bot.name);
      });
    }
  }

  static convertMessage(info) {
    let userId = info.user ? 'user_' + info.user : undefined;
    if (!userId && info.bot_id) {
      userId = 'bot_' + info.bot_id;
    }
    return {
      user_id: userId,
      post_time: info.ts,
      text: info.text.replace(/\n/,' '),
    };
  }

  static shouldIgnoreChannel(info) {
    if (info.is_archived) return true;
    const ignore = AppConfig['ignore'];
    for (let i=0,n=ignore.length;i<n;i++) {
      if (info.name.indexOf(ignore[i]) > -1) return true;
    }
    return false;
  }

}
<|endoftext|>


<commit_before>$(document).ready(function()
{
    $('.all_checked').click(function ()
    {
        if($(this).attr("checked") === "checked")
        {
            $('.person_id_checkbox').attr("checked","checked");
            $('.person_id_checkbox').prop("checked","checked");
            $('.person_id_checkbox').parent('span').addClass("checked");
        }
        else
        {
            $('.person_id_checkbox').removeAttr("checked");
            $('.person_id_checkbox').parent('span').removeClass("checked");
        }

        if($(this).attr("checked") === "checked")
        {
            $('.company_id_checkbox').attr("checked","checked");
            $('.company_id_checkbox').prop("checked","checked");
            $('.company_id_checkbox').parent('span').addClass("checked");
        }
        else
        {
            $('.company_id_checkbox').removeAttr("checked");
            $('.company_id_checkbox').parent('span').removeClass("checked");
        }

        if($(this).attr("checked") === "checked")
        {
            $('.vacancy_id_checkbox').attr("checked","checked");
            $('.vacancy_id_checkbox').prop("checked","checked");
            $('.vacancy_id_checkbox').parent('span').addClass("checked");
        }
        else
        {
            $('.vacancy_id_checkbox').removeAttr("checked");
            $('.vacancy_id_checkbox').parent('span').removeClass("checked");
        }

        if($(this).attr("checked") === "checked")
        {
            $('.user_id_checkbox').attr("checked","checked");
            $('.user_id_checkbox').prop("checked","checked");
            $('.user_id_checkbox').parent('span').addClass("checked");
        }
        else
        {
            $('.user_id_checkbox').removeAttr("checked");
            $('.user_id_checkbox').parent('span').removeClass("checked");
        }

    });
});<commit_msg>file updated<commit_after>$(document).ready(function()
{
    $('.all_checked').click(function ()
    {
        if($(this).is(':checked'))
        {
            $('.person_id_checkbox').attr("checked","checked");
            $('.person_id_checkbox').prop("checked","checked");
            $('.person_id_checkbox').parent('span').addClass("checked");
        }
        else
        {
            $('.person_id_checkbox').removeAttr("checked");
            $('.person_id_checkbox').parent('span').removeClass("checked");
        }

        if($(this).is(':checked'))
        {
            $('.company_id_checkbox').attr("checked","checked");
            $('.company_id_checkbox').prop("checked","checked");
            $('.company_id_checkbox').parent('span').addClass("checked");
        }
        else
        {
            $('.company_id_checkbox').removeAttr("checked");
            $('.company_id_checkbox').parent('span').removeClass("checked");
        }

        if($(this).is(':checked'))
        {
            $('.vacancy_id_checkbox').attr("checked","checked");
            $('.vacancy_id_checkbox').prop("checked","checked");
            $('.vacancy_id_checkbox').parent('span').addClass("checked");
        }
        else
        {
            $('.vacancy_id_checkbox').removeAttr("checked");
            $('.vacancy_id_checkbox').parent('span').removeClass("checked");
        }

        if($(this).is(':checked'))
        {
            $('.user_id_checkbox').attr("checked","checked");
            $('.user_id_checkbox').prop("checked","checked");
            $('.user_id_checkbox').parent('span').addClass("checked");
        }
        else
        {
            $('.user_id_checkbox').removeAttr("checked");
            $('.user_id_checkbox').parent('span').removeClass("checked");
        }

        if($(this).is(':checked'))
        {
            $('.role_id_checkbox').attr("checked","checked");
            $('.role_id_checkbox').prop("checked","checked");
            $('.role_id_checkbox').parent('span').addClass("checked");
        }
        else
        {
            $('.role_id_checkbox').removeAttr("checked");
            $('.role_id_checkbox').parent('span').removeClass("checked");
        }

    });
});<|endoftext|>


<commit_before>'use strict';

module.exports = {
  template: require('./about.html'),
  controller: ['$log', '$location', AboutController],
  controllerAs: 'aboutCtrl'
};

function AboutController($log, $location) {
  $log.debug('AboutController');
  this.image = 'app/assets/bhavya2.jpg';
}
<commit_msg>github pic added to about<commit_after>'use strict';

module.exports = {
  template: require('./about.html'),
  controller: ['$log', '$location', AboutController],
  controllerAs: 'aboutCtrl'
};

function AboutController($log, $location) {
  $log.debug('AboutController');
  this.image = 'https://avatars3.githubusercontent.com/u/20171729?v=3&u=a418448e141c9b43bd34aa4d1dcb80623cf7649d&s=400';
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import * as COLORS from 'shared/styles/colors';
import ICONS from './constants';
import { SVGWrapper, SVG } from './styles';

Icon.propTypes = {
  inline: PropTypes.bool,
  name: PropTypes.oneOf(Object.keys(ICONS)).isRequired,
  color: PropTypes.oneOf(Object.keys(COLORS)),
  size: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
  ]),
};

Icon.defaultProps = {
  inline: true,
  color: 'currentColor',
  size: '1.5em',
};

function Icon({ name, inline, color, size, ...props }) {
  return (
    <SVGWrapper
      inline={inline}
      color={color}
      size={size}
      {...props}
    >
      <SVG
        title={name}
        width="100%"
        height="100%"
        preserveAspectRatio="xMidYMid meet"
        viewBox={ICONS[name].viewBox}
      >
        {ICONS[name].path}
      </SVG>
    </SVGWrapper>
  );
}

export default Icon;
<commit_msg>refactor: simplify proptype<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import * as COLORS from 'shared/styles/colors';
import ICONS from './constants';
import { SVGWrapper, SVG } from './styles';

Icon.propTypes = {
  inline: PropTypes.bool,
  name: PropTypes.oneOf(Object.keys(ICONS)).isRequired,
  color: PropTypes.oneOf(Object.keys(COLORS)),
  size: PropTypes.string,
};

Icon.defaultProps = {
  inline: true,
  color: 'currentColor',
  size: '1.5em',
};

function Icon({ name, inline, color, size, ...props }) {
  return (
    <SVGWrapper
      inline={inline}
      color={color}
      size={size}
      {...props}
    >
      <SVG
        title={name}
        width="100%"
        height="100%"
        preserveAspectRatio="xMidYMid meet"
        viewBox={ICONS[name].viewBox}
      >
        {ICONS[name].path}
      </SVG>
    </SVGWrapper>
  );
}

export default Icon;
<|endoftext|>


<commit_before>import {Rotation} from './gates';

const layoutInputs = (inputs, height) => {
  return {
    height: 25,
    width: 12 + 10 * inputs.length,
    gates: inputs.map((name, index) => ({
      type: 'negator',
      center: {x: -10 * index - 15, y: -height / 2 - 15},
      inputCount: 1,
      rotation: Rotation.SOUTH,
    })),
    wires: Array.prototype.concat.apply([],
      inputs.map((name, index) => [
        {
          type: 'vertical',
          from: {x: -10 * index - 19, y: -height / 2 - 23},
          toY: height / 2 - 5,
          input: 0,
          inputCount: 1,
          soderStart: true,
        },
        {
          type: 'vertical',
          from: {x: -10 * index - 15, y: -height / 2 - 15 + 5},
          toY: height / 2 - 5,
          input: 0,
          inputCount: 1,
        },
        {
          type: 'horizontal',
          from: {x: -10 * index - 19, y: -height / 2 - 15 - 5},
          toX: -10 * index - 15,
          input: 0,
          inputCount: 1,
          soderStart: true,
        },
      ])
    ),
  };
};

const layoutOutputs = (pla, height, loopCount) => {
  const outputGateWidth = (2 + Math.max(7, loopCount));
  const gateWidth = (2 + Math.max(7, pla.inputs.length));
  const outputWireCount = pla.outputs.map(
    (_, index) => pla.loops
      .filter((loop) =>
        loop[index + pla.inputs.length] === 1
      ).length
    )
  ;

  return {
    width: 12 + outputGateWidth * pla.outputs.length,
    gates: pla.outputs.map((name, index) => ({
      type: 'or',
      center: {
        x: outputGateWidth * index + 15,
        y: -height / 2 - 15,
      },
      inputCount: outputWireCount[index],
      rotation: Rotation.NORTH,
      soderOutput: true,
    })),
    wires: Array.prototype.concat.apply([],
      pla.outputs.map((_, index) =>
        Array.prototype.concat.apply([],
          pla.loops
            .map((loop, idx) => ({idx, loop}))
            .filter(({loop}) => loop[index + pla.inputs.length] === 1)
            .map(({loop, idx}, wireIndex, all) => [{
              type: 'vertical',
              from: {x: outputGateWidth * index + 15, y: -height / 2 - 15 + 5},
              toY: -height / 2 + gateWidth * idx,
              input: wireIndex,
              inputCount: all.length,
              soderEnd: true,
            }]
            )
        )
      )
    ),
  };
};

const layoutLoops = (pla) => {
  const outputGateWidth = (2 + Math.max(7, pla.loops.length));
  const gateWidth = (2 + Math.max(7, pla.inputs.length));
  const height = pla.loops.length * gateWidth;

  const loopInputs = pla.loops.map((loop) =>
    Array.prototype.concat.apply([],
      loop.slice(0, pla.inputs.length)
      .map((cell, idx) => {
        if (cell === 1) {
          return [2 * idx * 5 + 4];
        } else if (cell === 0) {
          return [2 * idx * 5];
        } else {
          return [];
        }
      }))
  );

  return {
    height: height,
    gates: loopInputs.map((loop, index) => ({
      type: 'and',
      center: {x: 0, y: -height / 2 + gateWidth * index},
      inputCount: loop.length,
      rotation: Rotation.EAST,
    })),
    wires: Array.prototype.concat.apply([],
      loopInputs
        .map((loop, index) =>
        Array.prototype.concat.apply([], loop.map((inputOffset, idx) => ({
          type: 'horizontal',
          from: {x: -15 - inputOffset, y: -height / 2 + gateWidth * index},
          toX: -5,
          input: idx,
          inputCount: loop.length,
          soderStart: true,
        }))
      )).concat(
        pla.loops.map((name, index) => [
          {
            type: 'horizontal',
            from: {
              x: 5,
              y: -height / 2 + gateWidth * index,
            },
            toX: 10 + pla.outputs.length * outputGateWidth,
            input: 0,
            inputCount: 1,
          },
        ])
      )
    ),
  };
};

export default (pla) => {
  const loops = layoutLoops(pla);
  const inputs = layoutInputs(pla.inputs, loops.height);
  const outputs = layoutOutputs(pla, loops.height, pla.loops.length);

  return {
    gates: Array.prototype.concat.call(
      loops.gates,
      inputs.gates,
      outputs.gates
    ),
    wires: Array.prototype.concat.call(
      loops.wires,
      inputs.wires,
      outputs.wires
    ),
    bounds: {
      minX: -inputs.width,
      maxX: outputs.width,
      minY: -loops.height / 2 - inputs.height,
      maxY: loops.height / 2,
    },
  };
};
<commit_msg>ceil values for better pla layout<commit_after>import {Rotation} from './gates';

const layoutInputs = (inputs, height) => {
  return {
    height: 25,
    width: 12 + 10 * inputs.length,
    gates: inputs.map((name, index) => ({
      type: 'negator',
      center: {x: -10 * index - 15, y: -Math.ceil(height / 2) - 15},
      inputCount: 1,
      rotation: Rotation.SOUTH,
    })),
    wires: Array.prototype.concat.apply([],
      inputs.map((name, index) => [
        {
          type: 'vertical',
          from: {x: -10 * index - 19, y: -Math.ceil(height / 2) - 23},
          toY: Math.ceil(height / 2) - 5,
          input: 0,
          inputCount: 1,
          soderStart: true,
        },
        {
          type: 'vertical',
          from: {x: -10 * index - 15, y: -Math.ceil(height / 2) - 15 + 5},
          toY: Math.ceil(height / 2) - 5,
          input: 0,
          inputCount: 1,
        },
        {
          type: 'horizontal',
          from: {x: -10 * index - 19, y: -Math.ceil(height / 2) - 15 - 5},
          toX: -10 * index - 15,
          input: 0,
          inputCount: 1,
          soderStart: true,
        },
      ])
    ),
  };
};

const layoutOutputs = (pla, height, loopCount) => {
  const outputGateWidth = (2 + Math.max(7, loopCount));
  const gateWidth = (2 + Math.max(7, pla.inputs.length));
  const outputWireCount = pla.outputs.map(
    (_, index) => pla.loops
      .filter((loop) =>
        loop[index + pla.inputs.length] === 1
      ).length
    )
  ;

  return {
    width: 12 + outputGateWidth * pla.outputs.length,
    gates: pla.outputs.map((name, index) => ({
      type: 'or',
      center: {
        x: outputGateWidth * index + 15,
        y: -Math.ceil(height / 2) - 15,
      },
      inputCount: outputWireCount[index],
      rotation: Rotation.NORTH,
      soderOutput: true,
    })),
    wires: Array.prototype.concat.apply([],
      pla.outputs.map((_, index) =>
        Array.prototype.concat.apply([],
          pla.loops
            .map((loop, idx) => ({idx, loop}))
            .filter(({loop}) => loop[index + pla.inputs.length] === 1)
            .map(({loop, idx}, wireIndex, all) => [{
              type: 'vertical',
              from: {x: outputGateWidth * index + 15, y: -Math.ceil(height / 2) - 15 + 5},
              toY: -Math.ceil(height / 2) + gateWidth * idx,
              input: wireIndex,
              inputCount: all.length,
              soderEnd: true,
            }]
            )
        )
      )
    ),
  };
};

const layoutLoops = (pla) => {
  const outputGateWidth = (2 + Math.max(7, pla.loops.length));
  const gateWidth = (2 + Math.max(7, pla.inputs.length));
  const height = pla.loops.length * gateWidth;

  const loopInputs = pla.loops.map((loop) =>
    Array.prototype.concat.apply([],
      loop.slice(0, pla.inputs.length)
      .map((cell, idx) => {
        if (cell === 1) {
          return [2 * idx * 5 + 4];
        } else if (cell === 0) {
          return [2 * idx * 5];
        } else {
          return [];
        }
      }))
  );

  return {
    height: height,
    gates: loopInputs.map((loop, index) => ({
      type: 'and',
      center: {x: 0, y: -Math.ceil(height / 2) + gateWidth * index},
      inputCount: loop.length,
      rotation: Rotation.EAST,
    })),
    wires: Array.prototype.concat.apply([],
      loopInputs
        .map((loop, index) =>
        Array.prototype.concat.apply([], loop.map((inputOffset, idx) => ({
          type: 'horizontal',
          from: {x: -15 - inputOffset, y: -Math.ceil(height / 2) + gateWidth * index},
          toX: -5,
          input: idx,
          inputCount: loop.length,
          soderStart: true,
        }))
      )).concat(
        pla.loops.map((name, index) => [
          {
            type: 'horizontal',
            from: {
              x: 5,
              y: -Math.ceil(height / 2) + gateWidth * index,
            },
            toX: 10 + pla.outputs.length * outputGateWidth,
            input: 0,
            inputCount: 1,
          },
        ])
      )
    ),
  };
};

export default (pla) => {
  const loops = layoutLoops(pla);
  const inputs = layoutInputs(pla.inputs, loops.height);
  const outputs = layoutOutputs(pla, loops.height, pla.loops.length);

  return {
    gates: Array.prototype.concat.call(
      loops.gates,
      inputs.gates,
      outputs.gates
    ),
    wires: Array.prototype.concat.call(
      loops.wires,
      inputs.wires,
      outputs.wires
    ),
    bounds: {
      minX: -inputs.width,
      maxX: outputs.width,
      minY: -loops.height / 2 - inputs.height,
      maxY: loops.height / 2,
    },
  };
};
<|endoftext|>


<commit_before>/* global _:true */
import Ember from 'ember';

export default Ember.Controller.extend({
  startReady: false,
  startComplete: function(){
    var startReady = this.get('startReady');
    var manifestId = this.get('model.manifestId');
    return startReady && manifestId;
  }.property('startReady','model.isSaving', 'model.manifestId'),
  formattedManifest: function () {
    var model = this.get('model');
    var code = model.get('manifest');

    var _code = JSON.stringify(code);
    _code = JSON.parse(_code);

    _code.icons.map(function (icon) {
      if (icon.src.indexOf('data:') === 0){
        icon.src = "[Embedded]";
      }
      if (icon.fileName) {
        delete icon.fileName;
      }
      if (icon.generated) {
        delete icon.generated;
      }
    });

    return new Ember.Handlebars.SafeString('' + JSON.stringify(_code, null, 2) + '');
  }.property('model.manifest'),
  formattedServiceWorkerWebsiteCode : function() {
    var model = this.get('model');
    var codePreview = model.get('serviceWorkerCodePreview');
    var code = codePreview.forWebSite;
    return new Ember.Handlebars.SafeString('' + code + '');
  }.property('model.serviceWorkerCodePreview.forWebSite'),
  formattedServiceWorkerCode : function() {
    var model = this.get('model');
    var codePreview = model.get('serviceWorkerCodePreview');
    var code = codePreview.forServiceWorker;
    return new Ember.Handlebars.SafeString('' + code + '');
  }.property('model.serviceWorkerCodePreview.forServiceWorker'),
  isProcessing: function() {
    var model = this.get('model');
    return model.get('isBuilding') || model.get('isSaving');
  }.property('model.isBuilding', 'model.isSaving'),
  steps: Ember.A(),
  activeStep: null,
  showCustomMembers: false,
  showRelatedApps: false,
  selectedDisplay: null,
  selectedOrientation: null,
  valueOrEmptyString: function (value) {
    if(value) {
      return value;
    } else {
      return '';
    }
  },
  updateSelect: function(property, value) {
    this.model.set(property, value);
    this.model.save();
  },
  customMembers: function(){
    var staticValues = ['lang','name','short_name','scope','icons','display','orientation','start_url','theme_color','related_applications','prefer_related_applications', 'background_color'];
    var model = this.get('model');
    var keys = _.filter(_.keys(model.manifest),function(key){
      return key.indexOf('_') !== -1;
    });
    var customKeys = _.difference(keys,staticValues);
    var customProps = _.map(customKeys,function(key){
      var data = {
        member_name: key,
        member_value: model.manifest[key]
      };
      return data;
    });
    return customProps;
  }.property('model'),
  relatedApplications: function() {
    var model = this.get('model');
    return model.get('relatedApplications');
  }.property('model'),
  setActiveStep: function(stepId) {
    if (this.get('activeStep') !== null) {
      if (stepId !== this.get('activeStep')) {
        this.set('activeStep', stepId);
      }
    } else {
      this.set('activeStep', stepId);
    }
  },

  actions: {
    startOver: function(){
      this.ga('send', 'event', 'item', 'click', 'generator-startover-trigger');
      this.set('startReady', false);
      this.set('model.manifestId', null);
      this.set('activeStep', "1");

      var model = this.get('model');
      model.get('platforms').forEach(function(item) {
        Ember.set(item, 'isSelected', true);
      });
      model.save();

      return true;
    },
    updateStep: function(nextStep){
      this.ga('send', 'event', 'item', 'click', 'generator-nextStep-trigger');
      this.setActiveStep(nextStep);
      window.scrollTo(0,0);
    },
    startComplete: function() {
      this.set('startReady', true);
      this.set('activeStep', "1");
      this.set("showCustomMembers", false);

      return true;
    },
    updateSelection: function() {
      var allSelected = true;
      var model = this.get('model');
      model.get('platforms').forEach(function(item) {
        if (!item.isSelected) {
          allSelected = false;
        }
      });
      model.get('platforms').forEach(function(item) {
        Ember.set(item, 'isSelected', !allSelected);
      });
      model.save();
    },

    toggleCustomMembers: function() {
      var current = this.get("showCustomMembers");
      this.set("showCustomMembers", !current);
    },
    toggleRelatedApps: function() {
      var current = this.get("showRelatedApps");
      this.set("showRelatedApps", !current);
    }
  }
});<commit_msg>Fix #223 and other minor js errors<commit_after>/* global _:true */
import Ember from 'ember';

export default Ember.Controller.extend({
  startReady: false,
  startComplete: function(){
    var startReady = this.get('startReady');
    var manifestId = this.get('model.manifestId');
    return startReady && manifestId;
  }.property('startReady','model.isSaving', 'model.manifestId'),
  formattedManifest: function () {
    var model = this.get('model');
    var code = model.get('manifest');

    var _code = JSON.stringify(code);
    _code = JSON.parse(_code);

    if(_code && _code.icons){
      _code.icons.map(function (icon) {
        if (icon.src.indexOf('data:') === 0){
          icon.src = "[Embedded]";
        }
        if (icon.fileName) {
          delete icon.fileName;
        }
        if (icon.generated) {
          delete icon.generated;
        }
      });
    }

    return new Ember.Handlebars.SafeString('' + JSON.stringify(_code, null, 2) + '');
  }.property('model.manifest'),
  formattedServiceWorkerWebsiteCode : function() {
    var model = this.get('model');
    var codePreview = model.get('serviceWorkerCodePreview');
    var code = codePreview.forWebSite;
    return new Ember.Handlebars.SafeString('' + code + '');
  }.property('model.serviceWorkerCodePreview.forWebSite'),
  formattedServiceWorkerCode : function() {
    var model = this.get('model');
    var codePreview = model.get('serviceWorkerCodePreview');
    var code = codePreview.forServiceWorker;
    return new Ember.Handlebars.SafeString('' + code + '');
  }.property('model.serviceWorkerCodePreview.forServiceWorker'),
  isProcessing: function() {
    var model = this.get('model');
    return model.get('isBuilding') || model.get('isSaving');
  }.property('model.isBuilding', 'model.isSaving'),
  steps: Ember.A(),
  activeStep: null,
  showCustomMembers: false,
  showRelatedApps: false,
  selectedDisplay: null,
  selectedOrientation: null,
  valueOrEmptyString: function (value) {
    if(value) {
      return value;
    } else {
      return '';
    }
  },
  updateSelect: function(property, value) {
    this.model.set(property, value);
    this.model.save();
  },
  customMembers: function(){
    var staticValues = ['lang','name','short_name','scope','icons','display','orientation','start_url','theme_color','related_applications','prefer_related_applications', 'background_color'];
    var model = this.get('model');
    var keys = _.filter(_.keys(model.manifest),function(key){
      return key.indexOf('_') !== -1;
    });
    var customKeys = _.difference(keys,staticValues);
    var customProps = _.map(customKeys,function(key){
      var data = {
        member_name: key,
        member_value: model.manifest[key]
      };
      return data;
    });
    return customProps;
  }.property('model'),
  relatedApplications: function() {
    var model = this.get('model');
    return model.get('relatedApplications');
  }.property('model'),
  setActiveStep: function(stepId) {
    if (this.get('activeStep') !== null) {
      if (stepId !== this.get('activeStep')) {
        this.set('activeStep', stepId);
      }
    } else {
      this.set('activeStep', stepId);
    }
  },

  actions: {
    startOver: function(){
      this.ga('send', 'event', 'item', 'click', 'generator-startover-trigger');
      this.set('startReady', false);
      this.set('model.manifestId', null);
      this.set('activeStep', "1");

      var model = this.get('model');
      var platforms = model.get('platforms');
      if(platforms){
        platforms.forEach(function(item) {
          Ember.set(item, 'isSelected', true);
        });
      }

      model.save();

      return true;
    },
    updateStep: function(nextStep){
      this.ga('send', 'event', 'item', 'click', 'generator-nextStep-trigger');
      this.setActiveStep(nextStep);
      window.scrollTo(0,0);
    },
    startComplete: function() {
      this.set('startReady', true);
      this.set('activeStep', "1");
      this.set("showCustomMembers", false);

      return true;
    },
    updateSelection: function() {
      var allSelected = true;
      var model = this.get('model');
      model.get('platforms').forEach(function(item) {
        if (!item.isSelected) {
          allSelected = false;
        }
      });
      model.get('platforms').forEach(function(item) {
        Ember.set(item, 'isSelected', !allSelected);
      });
      model.save();
    },

    toggleCustomMembers: function() {
      var current = this.get("showCustomMembers");
      this.set("showCustomMembers", !current);
    },
    toggleRelatedApps: function() {
      var current = this.get("showRelatedApps");
      this.set("showRelatedApps", !current);
    }
  }
});<|endoftext|>


<commit_before>'use strict';

angular.module('Frontend.Devolucion', ['ngRoute','angular-jwt','angular-storage'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/devolucion', {
    templateUrl: 'devolucion/devolucion.html',
    controller: 'DevolucionController'
  });
}])

.controller('DevolucionController', function($scope, store, jwtHelper, $http, backendAPIservice, $location) {
    //$scope.cargado=false;
    $scope.terminado=false;
    $scope.base21original=0.00;
    $scope.iva21original=0.00;
    $scope.base10original=0.00;
    $scope.iva10original=0.00;
    $scope.base4original=0.00;
    $scope.iva4original=0.00;
    $scope.totaloriginal=0.00;
    $scope.base21modificado=0.00;
    $scope.iva21modificado=0.00;
    $scope.base10modificado=0.00;
    $scope.iva10modificado=0.00;
    $scope.base4modificado=0.00;
    $scope.iva4modificado=0.00;
    $scope.totalmodificado=0.00;
    $scope.diferencia=0.00;
    $scope.idventa;
    $scope.codigorecibido;
    $scope.respuesta;

    $scope.ventaOriginal = [];
    $scope.lineasModificada = [];
    $scope.lineasOriginal = [];
    $scope.listaProducto = [];

    //if(store.get('token') && store.get('token')!=" ")
    if(store.get('token'))
    {
      var token = store.get('token');
      if(!jwtHelper.isTokenExpired(token))
      {
        backendAPIservice.getProductos().success(function (recibe) {
          var productosArray = recibe.response.productos;
          console.log(JSON.stringify(productosArray));
          $scope.listaProducto = productosArray;
        });
      }
      else
      {
        store.remove('token');
        $location.path("/login");
      }
    }
    else
    {
      store.remove('token');
      $location.path("/login");
    }

    $scope.BuscarVenta=function(idventa) {
      //if(store.get('token') && store.get('token')!=" "){
      if(store.get('token')){
        var token = store.get('token');
        if(!jwtHelper.isTokenExpired(token))
        {
          backendAPIservice.getBuscaVenta(idventa).success(function(recibe){
            var codigo = recibe.code;
            console.log(JSON.stringify(codigo));
            $scope.codigorecibido=codigo;
            if($scope.codigorecibido==0)
            {
              var recibeVenta = recibe.response.venta;
              console.log(JSON.stringify(recibeVenta));
              $scope.ventaOriginal = recibeVenta;
              backendAPIservice.getBuscaListaVenta(idventa).success(function(recibe){
                var recibeLista = recibe.response.lineas;
                console.log(JSON.stringify(recibeLista));
                $scope.lineasOriginal = recibeLista;
                store.set('token',recibe.response.token);
                $scope.TotalesOriginal();
              });
              backendAPIservice.getBuscaListaVenta(idventa).success(function(recibe){
                var recibeLista2 = recibe.response.lineas;
                console.log(JSON.stringify(recibeLista2));
                $scope.lineasModificada = recibeLista2;
                store.set('token',recibe.response.token);
                $scope.TotalesModificado();
                //$scope.cargado==true;
              });
            }
            else
            {
              if($scope.codigorecibido==3) $scope.respuesta="La venta indicada no existe";
              if($scope.codigorecibido==4) $scope.respuesta="Las devoluciones solo se pueden tramitar el mismo dia de la venta";
            }
          });
        }
        else
        {
          store.remove('token');
          store.set('nombre', "Sin conexion");
          $location.path("/login");
        }
      }
      else
      {
        store.remove('token');
        store.set('nombre', "Sin conexion");
        $location.path("/login");
      }
    };

    $scope.TotalesOriginal=function() {
      var elemento;
      $scope.base21original=0.00;
      $scope.iva21original=0.00;
      $scope.base10original=0.00;
      $scope.iva10original=0.00;
      $scope.base4original=0.00;
      $scope.iva4original=0.00;
      $scope.totaloriginal=0.00;
      for(elemento in $scope.lineasOriginal) {
        if($scope.lineasOriginal[elemento].iva=="21") {
         $scope.base21original += ($scope.lineasOriginal[elemento].precio * $scope.lineasOriginal[elemento].cantidad);
         $scope.iva21original = ($scope.base21original * 21.00 )/100.00;
        };
        if($scope.lineasOriginal[elemento].iva==10) {
         $scope.base10original  += ($scope.lineasOriginal[elemento].precio * $scope.lineasOriginal[elemento].cantidad);
         $scope.iva10original = ($scope.base10original * 10.00 )/100.00;
        };
        if($scope.lineasOriginal[elemento].iva==4) {
         $scope.base4original  += ($scope.lineasOriginal[elemento].precio * $scope.lineasOriginal[elemento].cantidad);
         $scope.iva4original = ($scope.base4original * 4.00 )/100.00;
        };
      }
      $scope.totaloriginal = $scope.base21original + $scope.iva21original + $scope.base10original + $scope.iva10original + $scope.base4original + $scope.iva4original;
    };

    $scope.TotalesModificado=function() {
      var elemento;
      $scope.base21modificado=0.00;
      $scope.iva21modificado=0.00;
      $scope.base10modificado=0.00;
      $scope.iva10modificado=0.00;
      $scope.base4modificado=0.00;
      $scope.iva4modificado=0.00;
      $scope.totalmodificado = 0.00;
      $scope.diferencia = 0.00;
      for(elemento in $scope.lineasModificada) {
        if($scope.lineasModificada[elemento].iva=="21") {
         $scope.base21modificado += ($scope.lineasModificada[elemento].precio * $scope.lineasModificada[elemento].cantidad);
         $scope.iva21modificado = ($scope.base21modificado * 21.00 )/100.00;
        };
        if($scope.lineasModificada[elemento].iva==10) {
         $scope.base10modificado  += ($scope.lineasModificada[elemento].precio * $scope.lineasModificada[elemento].cantidad);
         $scope.iva10modificado = ($scope.base10modificado * 10.00 )/100.00;
        };
        if($scope.lineasModificada[elemento].iva==4) {
         $scope.base4modificado  += ($scope.lineasModificada[elemento].precio * $scope.lineasModificada[elemento].cantidad);
         $scope.iva4modificado = ($scope.base4modificado * 4.00 )/100.00;
        };
      }
      $scope.totalmodificado = $scope.base21modificado + $scope.iva21modificado + $scope.base10modificado + $scope.iva10modificado + $scope.base4modificado + $scope.iva4modificado;
      $scope.diferencia = $scope.totalmodificado - $scope.totaloriginal;
    };

    $scope.Borrar=function(index) {
      $scope.lineasModificada[index].borrar=true;
      $scope.lineasModificada[index].cantidad=0;
      $scope.TotalesModificado();
    };

    $scope.CambiarProducto=function(index) {
      var elemento=0;
      for(elemento in $scope.listaProducto) {
        if($scope.listaProducto[elemento].id == $scope.lineasModificada[index].idproducto){
          $scope.lineasModificada[index].nombre = $scope.listaProducto[elemento].nombre;
          $scope.lineasModificada[index].precio = $scope.listaProducto[elemento].precio;
          $scope.lineasModificada[index].iva = $scope.listaProducto[elemento].iva;
        }
      }
      $scope.TotalesModificado();
    };

    $scope.Finalizar=function() {
      backendAPIservice.postDevolucion($scope.lineasModificada, $scope.diferencia, $scope.ventaOriginal.socio, $scope.ventaOriginal.contado).success(function(recibe){
        var respuesta1 = recibe.response.respuesta;
        console.log(JSON.stringify(respuesta1));
        $scope.respuesta = respuesta1;
        if(recibe.code==0) store.set('token',recibe.response.token);
        $scope.terminado=true;
      });
    }
});
<commit_msg>20160903-1709<commit_after>'use strict';

angular.module('Frontend.Devolucion', ['ngRoute','angular-jwt','angular-storage'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/devolucion', {
    templateUrl: 'devolucion/devolucion.html',
    controller: 'DevolucionController'
  });
}])

.controller('DevolucionController', function($scope, store, jwtHelper, $http, backendAPIservice, $location) {
    //$scope.cargado=false;
    $scope.terminado=false;
    $scope.base21original=0.00;
    $scope.iva21original=0.00;
    $scope.base10original=0.00;
    $scope.iva10original=0.00;
    $scope.base4original=0.00;
    $scope.iva4original=0.00;
    $scope.totaloriginal=0.00;
    $scope.base21modificado=0.00;
    $scope.iva21modificado=0.00;
    $scope.base10modificado=0.00;
    $scope.iva10modificado=0.00;
    $scope.base4modificado=0.00;
    $scope.iva4modificado=0.00;
    $scope.totalmodificado=0.00;
    $scope.diferencia=0.00;
    $scope.idventa;
    $scope.codigorecibido;
    $scope.respuesta;

    $scope.ventaOriginal = [];
    $scope.lineasModificada = [];
    $scope.lineasOriginal = [];
    $scope.listaProducto = [];

    //if(store.get('token') && store.get('token')!=" ")
    if(store.get('token'))
    {
      var token = store.get('token');
      if(!jwtHelper.isTokenExpired(token))
      {
        backendAPIservice.getProductos().success(function (recibe) {
          var productosArray = recibe.response.productos;
          console.log(JSON.stringify(productosArray));
          $scope.listaProducto = productosArray;
        });
      }
      else
      {
        store.remove('token');
        $location.path("/login");
      }
    }
    else
    {
      store.remove('token');
      $location.path("/login");
    }

    $scope.BuscarVenta=function(idventa) {
      //if(store.get('token') && store.get('token')!=" "){
      if(store.get('token')){
        var token = store.get('token');
        if(!jwtHelper.isTokenExpired(token))
        {
          backendAPIservice.getBuscaVenta(idventa).success(function(recibe){
            var codigo = recibe.code;
            console.log(JSON.stringify(codigo));
            $scope.codigorecibido=codigo;
            if($scope.codigorecibido==0)
            {
              var recibeVenta = recibe.response.venta;
              console.log(JSON.stringify(recibeVenta));
              $scope.ventaOriginal = recibeVenta;
              backendAPIservice.getBuscaListaVenta(idventa).success(function(recibe){
                var recibeLista = recibe.response.lineas;
                console.log(JSON.stringify(recibeLista));
                $scope.lineasOriginal = recibeLista;
                store.set('token',recibe.response.token);
                $scope.TotalesOriginal();
              });
              backendAPIservice.getBuscaListaVenta(idventa).success(function(recibe){
                var recibeLista2 = recibe.response.lineas;
                console.log(JSON.stringify(recibeLista2));
                $scope.lineasModificada = recibeLista2;
                store.set('token',recibe.response.token);
                $scope.TotalesModificado();
                //$scope.cargado==true;
              });
            }
            else
            {
              if($scope.codigorecibido==3) $scope.respuesta="La venta indicada no existe";
              if($scope.codigorecibido==4) $scope.respuesta="Las devoluciones solo se pueden tramitar el mismo dia de la venta";
              //if($scope.codigorecibido==5) $scope.respuesta="La caja ya está cerrada, la devolución no se puede tramitar";
            }
          });
        }
        else
        {
          store.remove('token');
          store.set('nombre', "Sin conexion");
          $location.path("/login");
        }
      }
      else
      {
        store.remove('token');
        store.set('nombre', "Sin conexion");
        $location.path("/login");
      }
    };

    $scope.TotalesOriginal=function() {
      var elemento;
      $scope.base21original=0.00;
      $scope.iva21original=0.00;
      $scope.base10original=0.00;
      $scope.iva10original=0.00;
      $scope.base4original=0.00;
      $scope.iva4original=0.00;
      $scope.totaloriginal=0.00;
      for(elemento in $scope.lineasOriginal) {
        if($scope.lineasOriginal[elemento].iva=="21") {
         $scope.base21original += ($scope.lineasOriginal[elemento].precio * $scope.lineasOriginal[elemento].cantidad);
         $scope.iva21original = ($scope.base21original * 21.00 )/100.00;
        };
        if($scope.lineasOriginal[elemento].iva==10) {
         $scope.base10original  += ($scope.lineasOriginal[elemento].precio * $scope.lineasOriginal[elemento].cantidad);
         $scope.iva10original = ($scope.base10original * 10.00 )/100.00;
        };
        if($scope.lineasOriginal[elemento].iva==4) {
         $scope.base4original  += ($scope.lineasOriginal[elemento].precio * $scope.lineasOriginal[elemento].cantidad);
         $scope.iva4original = ($scope.base4original * 4.00 )/100.00;
        };
      }
      $scope.totaloriginal = $scope.base21original + $scope.iva21original + $scope.base10original + $scope.iva10original + $scope.base4original + $scope.iva4original;
    };

    $scope.TotalesModificado=function() {
      var elemento;
      $scope.base21modificado=0.00;
      $scope.iva21modificado=0.00;
      $scope.base10modificado=0.00;
      $scope.iva10modificado=0.00;
      $scope.base4modificado=0.00;
      $scope.iva4modificado=0.00;
      $scope.totalmodificado = 0.00;
      $scope.diferencia = 0.00;
      for(elemento in $scope.lineasModificada) {
        if($scope.lineasModificada[elemento].iva=="21") {
         $scope.base21modificado += ($scope.lineasModificada[elemento].precio * $scope.lineasModificada[elemento].cantidad);
         $scope.iva21modificado = ($scope.base21modificado * 21.00 )/100.00;
        };
        if($scope.lineasModificada[elemento].iva==10) {
         $scope.base10modificado  += ($scope.lineasModificada[elemento].precio * $scope.lineasModificada[elemento].cantidad);
         $scope.iva10modificado = ($scope.base10modificado * 10.00 )/100.00;
        };
        if($scope.lineasModificada[elemento].iva==4) {
         $scope.base4modificado  += ($scope.lineasModificada[elemento].precio * $scope.lineasModificada[elemento].cantidad);
         $scope.iva4modificado = ($scope.base4modificado * 4.00 )/100.00;
        };
      }
      $scope.totalmodificado = $scope.base21modificado + $scope.iva21modificado + $scope.base10modificado + $scope.iva10modificado + $scope.base4modificado + $scope.iva4modificado;
      $scope.diferencia = $scope.totalmodificado - $scope.totaloriginal;
    };

    $scope.Borrar=function(index) {
      $scope.lineasModificada[index].borrar=true;
      $scope.lineasModificada[index].cantidad=0;
      $scope.TotalesModificado();
    };

    $scope.CambiarProducto=function(index) {
      var elemento=0;
      for(elemento in $scope.listaProducto) {
        if($scope.listaProducto[elemento].id == $scope.lineasModificada[index].idproducto){
          $scope.lineasModificada[index].nombre = $scope.listaProducto[elemento].nombre;
          $scope.lineasModificada[index].precio = $scope.listaProducto[elemento].precio;
          $scope.lineasModificada[index].iva = $scope.listaProducto[elemento].iva;
        }
      }
      $scope.TotalesModificado();
    };

    $scope.Finalizar=function() {
      backendAPIservice.postDevolucion($scope.lineasModificada, $scope.diferencia, $scope.ventaOriginal.socio, $scope.ventaOriginal.contado).success(function(recibe){
        var respuesta1 = recibe.response.respuesta;
        console.log(JSON.stringify(respuesta1));
        $scope.respuesta = respuesta1;
        if(recibe.code==0) store.set('token',recibe.response.token);
        $scope.terminado=true;
      });
    }
});
<|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-minimap@breunigs
// @name           IITC plugin: Mini map
// @category       Controls
// @version        0.1.0.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Shows a mini map on the corner of the map
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @grant          none
// ==/UserScript==

@@PLUGINSTART@@

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.miniMap = function() {};

window.plugin.miniMap.setup  = function() {

  try { console.log('Loading leaflet.draw JS now'); } catch(e) {}
  @@INCLUDERAW:external/Control.MiniMap.js@@
  try { console.log('done loading leaflet.draw JS'); } catch(e) {}

  // we can't use the same TileLayer as the main map uses - it causes issues.
  // stick with the MapQuest tiles for now

  //OpenStreetMap attribution - required by several of the layers
  osmAttribution = 'Map data © OpenStreetMap contributors';

  //MapQuest offer tiles - http://developer.mapquest.com/web/products/open/map
  //their usage policy has no limits (except required notification above 4000 tiles/sec - we're perhaps at 50 tiles/sec based on CloudMade stats)
  var mqSubdomains = [ 'otile1','otile2', 'otile3', 'otile4' ];
  var mqTileUrlPrefix = window.location.protocol !== 'https:' ? 'http://{s}.mqcdn.com' : 'https://{s}-s.mqcdn.com';
  var mqMapOpt = {attribution: osmAttribution+', Tiles Courtesy of MapQuest', maxZoom: 18, subdomains: mqSubdomains};
  var mqMap = new L.TileLayer(mqTileUrlPrefix+'/tiles/1.0.0/map/{z}/{x}/{y}.jpg',mqMapOpt);

  if(!isSmartphone()) {
    // desktop mode - bottom-left, so it doesn't clash with the sidebar
    new L.Control.MiniMap(mqMap, {toggleDisplay: true, position: 'bottomleft'}).addTo(window.map);
  } else {
    // mobile mode - bottom-right - so it floats above the map copyright text
    new L.Control.MiniMap(mqMap, {toggleDisplay: true, position: 'bottomright'}).addTo(window.map);
  }

  $('head').append('<style>@@INCLUDESTRING:external/Control.MiniMap.css@@</style>');

};

var setup =  window.plugin.miniMap.setup;

// PLUGIN END //////////////////////////////////////////////////////////

@@PLUGINEND@@
<commit_msg>Minimap: Fix bug where map whould be centered on 0,0 on startup<commit_after>// ==UserScript==
// @id             iitc-plugin-minimap@breunigs
// @name           IITC plugin: Mini map
// @category       Controls
// @version        0.1.0.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Shows a mini map on the corner of the map
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @grant          none
// ==/UserScript==

@@PLUGINSTART@@

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.miniMap = function() {};

window.plugin.miniMap.setup  = function() {

  try { console.log('Loading leaflet.draw JS now'); } catch(e) {}
  @@INCLUDERAW:external/Control.MiniMap.js@@
  try { console.log('done loading leaflet.draw JS'); } catch(e) {}

  // we can't use the same TileLayer as the main map uses - it causes issues.
  // stick with the MapQuest tiles for now

  //OpenStreetMap attribution - required by several of the layers
  osmAttribution = 'Map data © OpenStreetMap contributors';

  //MapQuest offer tiles - http://developer.mapquest.com/web/products/open/map
  //their usage policy has no limits (except required notification above 4000 tiles/sec - we're perhaps at 50 tiles/sec based on CloudMade stats)
  var mqSubdomains = [ 'otile1','otile2', 'otile3', 'otile4' ];
  var mqTileUrlPrefix = window.location.protocol !== 'https:' ? 'http://{s}.mqcdn.com' : 'https://{s}-s.mqcdn.com';
  var mqMapOpt = {attribution: osmAttribution+', Tiles Courtesy of MapQuest', maxZoom: 18, subdomains: mqSubdomains};
  var mqMap = new L.TileLayer(mqTileUrlPrefix+'/tiles/1.0.0/map/{z}/{x}/{y}.jpg',mqMapOpt);

  setTimeout(function() {
    if(!isSmartphone()) {
      // desktop mode - bottom-left, so it doesn't clash with the sidebar
      new L.Control.MiniMap(mqMap, {toggleDisplay: true, position: 'bottomleft'}).addTo(window.map);
    } else {
      // mobile mode - bottom-right - so it floats above the map copyright text
      new L.Control.MiniMap(mqMap, {toggleDisplay: true, position: 'bottomright'}).addTo(window.map);
    }
  }, 0);

  $('head').append('<style>@@INCLUDESTRING:external/Control.MiniMap.css@@</style>');
};

var setup =  window.plugin.miniMap.setup;

// PLUGIN END //////////////////////////////////////////////////////////

@@PLUGINEND@@
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

var env = require('../../../config/environment');
/**
 * GET home page.
 */
exports.index = function( req, res ){
  res.render('site/index');
};

/**
 * Get account page
 */
exports.account = function( req, res ){
  res.render('site/account', {
    email: req.session.email || "",
    audience: env.get( "AUDIENCE" ),
    csrf: req.session._csrf,
    ga_account: env.get( "GA_ACCOUNT" ),
    ga_domain: env.get( "GA_DOMAIN" )
  });
};

/**
 * Signin page for admin console
 */
exports.signin = function( req, res ){
  res.render( 'site/login.html.ejs', {
    csrf: req.session._csrf,
    login: req.session.email || "",
    sso_include: env.get( "SSO_INCLUDE_URL" ),
    loginServer: env.get("HOSTNAME"),
    audience: env.get("AUDIENCE")
  });
};
/**
 * Get admin console
 */
exports.console = function( req, res ){
  res.render( 'site/console.html.ejs', {
    csrf: req.session._csrf,
    login: req.session.email || "",
    sso_include: env.get( "SSO_INCLUDE_URL" ),
    loginServer: env.get("HOSTNAME"),
    audience: env.get("AUDIENCE")
  });
};

/**
 * Get js files
 */
exports.js = function( filename ) {
  return function( req, res ){
    res.set('Content-Type', 'application/javascript');
    res.render( 'js/' + filename + '.js.ejs', {
      hostname: env.get( "HOSTNAME" ),
      audience: env.get( "AUDIENCE" )
    });
  };
};

/**
 * GET health check for app
 */
exports.healthcheck = function( req, res ){
  res.json({ http: 'okay' });
};
<commit_msg>Fix bug 886483 - Add application version to healthcheck<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

var env = require('../../../config/environment');
/**
 * GET home page.
 */
exports.index = function( req, res ){
  res.render('site/index');
};

/**
 * Get account page
 */
exports.account = function( req, res ){
  res.render('site/account', {
    email: req.session.email || "",
    audience: env.get( "AUDIENCE" ),
    csrf: req.session._csrf,
    ga_account: env.get( "GA_ACCOUNT" ),
    ga_domain: env.get( "GA_DOMAIN" )
  });
};

/**
 * Signin page for admin console
 */
exports.signin = function( req, res ){
  res.render( 'site/login.html.ejs', {
    csrf: req.session._csrf,
    login: req.session.email || "",
    sso_include: env.get( "SSO_INCLUDE_URL" ),
    loginServer: env.get("HOSTNAME"),
    audience: env.get("AUDIENCE")
  });
};
/**
 * Get admin console
 */
exports.console = function( req, res ){
  res.render( 'site/console.html.ejs', {
    csrf: req.session._csrf,
    login: req.session.email || "",
    sso_include: env.get( "SSO_INCLUDE_URL" ),
    loginServer: env.get("HOSTNAME"),
    audience: env.get("AUDIENCE")
  });
};

/**
 * Get js files
 */
exports.js = function( filename ) {
  return function( req, res ){
    res.set('Content-Type', 'application/javascript');
    res.render( 'js/' + filename + '.js.ejs', {
      hostname: env.get( "HOSTNAME" ),
      audience: env.get( "AUDIENCE" )
    });
  };
};

/**
 * GET health check for app
 */
 var version = require("../../../package").version;

exports.healthcheck = function( req, res ){
  res.json({
    http: 'okay',
    version: version
  });
};
<|endoftext|>


<commit_before>export { BoundsArraySet };

import * as ConvBiasActivation from "../ConvBiasActivation.js";
import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as Weights from "../../Unpacker/Weights.js";
import { ChannelPartInfo } from  "./Pointwise_ChannelPartInfo.js";

/**
 * The element value bounds for pointwise convolution-bias-activation.
 *
 */
class BoundsArraySet extends ConvBiasActivation.BoundsArraySet {

  /**
   */
  constructor( inputChannelCount, outputChannelCount ) {
    super( inputChannelCount, outputChannelCount );
  }

//!!! ...unfinished... (2022/01/09)
// Even if ( this.outputChannelCount <= 0 ),
// this function should work correctly and BoundsArraySet should result in pass-through input to output.

  /**
   *
   * @param {ConvBiasActivation.BoundsArraySet} previous_ConvBiasActivation_BoundsArraySet
   *   The value bounds set of the previous convolution-bias-activation.
   *
   * @param {Pointwise.ChannelPartInfo[]} inChannelPartInfoArray
   *   The input channel range array which describe lower/higher half channels index range.
   *
   * @param {number} nActivationId
   *   The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) of this depthwise convolution.
   *
   * @param {number[]} biasesArray
   *   The weights of the bias. Its content will not be used. Only be tested against null. If ( biasesArray != null ),
   * there is bias operation. If ( biasesArray == null ), there is no bias operation.
   */
  set_all_by_inChannelPartInfoArray(
    previous_ConvBiasActivation_BoundsArraySet, inChannelPartInfoArray,
    nActivationId, biasesArray
  ) {

    // Because they are extracted from Weights which should have been regulated by Weights.Base.ValueBounds.Float32Array_RestrictedClone().
    const filtersValueBounds = Weights.Base.ValueBounds;
    const biasesValueBounds = Weights.Base.ValueBounds;

    let theActivationFunctionInfo = ValueDesc.ActivationFunction.Singleton.getInfoById( nActivationId );

    // 1. Determine .input
    this.input.set_all_byBoundsArray( previous_ConvBiasActivation_BoundsArraySet.output );

//!!! ...unfinished... (2022/01/09)
    {
      let tBounds = new FloatValue.Bounds( 0, 0 );

//!!! ...unfinished... (2022/01/09)
      this.afterFilter.set_all_byN( 0 ); // Initialize .afterFilter

      for ( let inChannel = 0; inChannel < this.inputChannelCount; ++inChannel ) {
        let undoPreviousEscapingScale = previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.scales[ inChannel ];

        // 2. Determine .afterUndoPreviousActivationEscaping
        this.afterUndoPreviousActivationEscaping.set_one_byBoundsArray( inChannel, this.input, inChannel );
        this.afterUndoPreviousActivationEscaping.multiply_one_byN( inChannel, undoPreviousEscapingScale );

        let outChannel = 0;

        InChannelPartIndexLoop:
        for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) {
          let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ];
          let inChannelToBegin = inChannel - inChannelPartInfo.inChannelBegin;

//!!! ...unfinished... (2022/01/09) Where to initialize this.afterFilter?
          // 3. Determine .afterFilter
//          this.afterFilter.set_one_byBoundsArray( outChannel, this.afterUndoPreviousActivationEscaping, inChannel );

          for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) {
            if ( outChannel >= this.outputChannelCount )
              break InChannelPartIndexLoop; // Never exceeds the total output channel count.

//!!! ...unfinished... (2022/01/09)
            if ( ( inChannelToBegin >= 0 ) && ( inChannel < inChannelPartInfo.inChannelEnd ) ) {

              if ( inChannelPartInfo.bPassThrough ) { // For pass-through half channels.
                // Do nothing. The value bounds does not change at all because it is just be past through.

                if ( inChannelToBegin == outChannelSub ) {
                  this.afterFilter.set_one_by ???; // The only one position with non-zero value.
//!!! ...unfinished... (2022/01/09) should set to the same as .afterUndoPreviousActivationEscaping? since pass through?
                } else {
//!!! ...unfinished... (2022/01/09)
                }

              } else { // Non-pass-through half channels.

//!!! ...unfinished... (2022/01/09) ???
                tBounds.set_byBoundsArray( this.afterUndoPreviousActivationEscaping, inChannel );
                tBounds.multiply_byBounds( filtersValueBounds );
                this.afterFilter.add_one_byBounds( outChannel, tBounds )

              }

            } else {
              // Do nothing. The value bounds does not change for all input channels which is not in range (since these inputs are ignored).
            }

          }
        }
      }

  }

//!!! (2022/01/09 Remarked) seems not used. because should be channel by channel.
//   /**
//    *
//    * @param {ConvBiasActivation.BoundsArraySet} previous_ConvBiasActivation_BoundsArraySet
//    *   The previous convolution-bias-activation value bounds set of this pointwise convolution.
//    *
//    * @param {boolean} bPointwise
//    *   If true, the pointwise convolution (with/without bias, with/without activation) exists.
//    *
//    * @param {number} inputChannelCount
//    *   The input channel count of the pointwise convolution.
//    *
//    * @param {boolean} bBias
//    *   If true, the bias operation exists.
//    *
//    * @param {number} nActivationId
//    *   The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) after the bias operation.
//    */
//   set_by( previous_ConvBiasActivation_BoundsArraySet, bPointwise, inputChannelCount, bBias, nActivationId ) {
//
//     // 0. Default as BoundsArraySet.output of previous convolution-bias-activation.
//     this.resetBy_Bounds( previous_ConvBiasActivation_BoundsArraySet.output );
//
//     // 1. No operation at all.
//     if ( !bPointwise )
//       return;
//
//     // 2. Before activation function.
//     {
//       // Because they are extracted from Weights which should have been regulated by Weights.Base.ValueBounds.Float32Array_RestrictedClone().
//       const filtersValueBounds = Weights.Base.ValueBounds;
//       const biasesValueBounds = Weights.Base.ValueBounds;
//
//       this.beforeActivation.multiply_all_byBounds( filtersValueBounds ).multiply_all_byN( inputChannelCount );
//
//       if ( bBias )
//         this.beforeActivation.add_byBounds( biasesValueBounds );
//
//
// //!!! ...unfinished... (2021/12/26)
// // The .undo should also be applied to the real filter value and bias value of this convolution-bias (i.e. not just applied here ScaleTranslate).
// //
// // Problem: What if this convolution-bias-activation could only undo partially (e.g. this convolution does not have bias)?
// //   How should the .undo of this convolution-bias-activation be calculated?
//       {
//         this.beforeActivation.multiply_all_byN(
//           previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleTranslateArraySet.undo.scale );
//
//         if ( this.bBias )
//           this.beforeActivation.add_all_byN(
//             previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleTranslateArraySet.undo.translate );
//       }
//
//     }
//
//     // 3. Output.
//     this.set_output_by_beforeActivation_ActivationId( nActivationId );
//
//     // 4. ActivationEscaping.ScaleTranslateArraySet.
//     this.activationEscaping_ScaleTranslateArraySet.setBy_currentBoundsArraySet_previousActivationEscaping(
//       this, previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleTranslateArraySet );
//   }

}

<commit_msg>Update Pointwise_BoundsArraySet.js<commit_after>export { BoundsArraySet };

import * as ConvBiasActivation from "../ConvBiasActivation.js";
import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as Weights from "../../Unpacker/Weights.js";
import { ChannelPartInfo } from  "./Pointwise_ChannelPartInfo.js";

/**
 * The element value bounds for pointwise convolution-bias-activation.
 *
 */
class BoundsArraySet extends ConvBiasActivation.BoundsArraySet {

  /**
   */
  constructor( inputChannelCount, outputChannelCount ) {
    super( inputChannelCount, outputChannelCount );
  }

//!!! ...unfinished... (2022/01/09)
// Even if ( this.outputChannelCount <= 0 ),
// this function should work correctly and BoundsArraySet should result in pass-through input to output.

  /**
   *
   * @param {ConvBiasActivation.BoundsArraySet} previous_ConvBiasActivation_BoundsArraySet
   *   The value bounds set of the previous convolution-bias-activation.
   *
   * @param {Pointwise.ChannelPartInfo[]} inChannelPartInfoArray
   *   The input channel range array which describe lower/higher half channels index range.
   *
   * @param {number} nActivationId
   *   The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) of this depthwise convolution.
   *
   * @param {number[]} biasesArray
   *   The weights of the bias. Its content will not be used. Only be tested against null. If ( biasesArray != null ),
   * there is bias operation. If ( biasesArray == null ), there is no bias operation.
   */
  set_all_by_inChannelPartInfoArray(
    previous_ConvBiasActivation_BoundsArraySet, inChannelPartInfoArray,
    nActivationId, biasesArray
  ) {

    // Because they are extracted from Weights which should have been regulated by Weights.Base.ValueBounds.Float32Array_RestrictedClone().
    const filtersValueBounds = Weights.Base.ValueBounds;
    const biasesValueBounds = Weights.Base.ValueBounds;

    let theActivationFunctionInfo = ValueDesc.ActivationFunction.Singleton.getInfoById( nActivationId );

    // 1. Determine .input
    this.input.set_all_byBoundsArray( previous_ConvBiasActivation_BoundsArraySet.output );

//!!! ...unfinished... (2022/01/09)
    {
      let tBounds = new FloatValue.Bounds( 0, 0 );

//!!! ...unfinished... (2022/01/09)
      this.afterFilter.set_all_byN( 0 ); // Initialize .afterFilter

      for ( let inChannel = 0; inChannel < this.inputChannelCount; ++inChannel ) {
        let undoPreviousEscapingScale = previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleArraySet.undo.scales[ inChannel ];

        // 2. Determine .afterUndoPreviousActivationEscaping
        this.afterUndoPreviousActivationEscaping.set_one_byBoundsArray( inChannel, this.input, inChannel );
        this.afterUndoPreviousActivationEscaping.multiply_one_byN( inChannel, undoPreviousEscapingScale );

        let outChannel = 0;

        InChannelPartIndexLoop:
        for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) {
          let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ];
          let inChannelToBegin = inChannel - inChannelPartInfo.inChannelBegin;

          for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) {
            if ( outChannel >= this.outputChannelCount )
              break InChannelPartIndexLoop; // Never exceeds the total output channel count.

            if ( ( inChannelToBegin >= 0 ) && ( inChannel < inChannelPartInfo.inChannelEnd ) ) {

              if ( inChannelPartInfo.bPassThrough ) { // For pass-through half channels.
                // Do nothing. The value bounds does not change at all because it is just be past through.

                if ( inChannelToBegin == outChannelSub ) {

                  // The only one filter position (in the pass-through part) has non-zero value.
                  this.afterFilter.add_one_byBoundsArray( outChannel, this.afterUndoPreviousActivationEscaping, inChannel );

                } else {
                  // Do nothing. All other filter positions (in the pass-through part) are zero.
                }

              } else { // Non-pass-through half channels.
                tBounds.set_byBoundsArray( this.afterUndoPreviousActivationEscaping, inChannel ).multiply_byBounds( filtersValueBounds );
                this.afterFilter.add_one_byBounds( outChannel, tBounds )

              }

            } else {
              // Do nothing. The value bounds does not change for all input channels which is not in range (since these inputs are ignored).
            }

//!!! ...unfinished... (2022/01/09)

          }
        }
      }

  }

//!!! (2022/01/09 Remarked) seems not used. because should be channel by channel.
//   /**
//    *
//    * @param {ConvBiasActivation.BoundsArraySet} previous_ConvBiasActivation_BoundsArraySet
//    *   The previous convolution-bias-activation value bounds set of this pointwise convolution.
//    *
//    * @param {boolean} bPointwise
//    *   If true, the pointwise convolution (with/without bias, with/without activation) exists.
//    *
//    * @param {number} inputChannelCount
//    *   The input channel count of the pointwise convolution.
//    *
//    * @param {boolean} bBias
//    *   If true, the bias operation exists.
//    *
//    * @param {number} nActivationId
//    *   The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) after the bias operation.
//    */
//   set_by( previous_ConvBiasActivation_BoundsArraySet, bPointwise, inputChannelCount, bBias, nActivationId ) {
//
//     // 0. Default as BoundsArraySet.output of previous convolution-bias-activation.
//     this.resetBy_Bounds( previous_ConvBiasActivation_BoundsArraySet.output );
//
//     // 1. No operation at all.
//     if ( !bPointwise )
//       return;
//
//     // 2. Before activation function.
//     {
//       // Because they are extracted from Weights which should have been regulated by Weights.Base.ValueBounds.Float32Array_RestrictedClone().
//       const filtersValueBounds = Weights.Base.ValueBounds;
//       const biasesValueBounds = Weights.Base.ValueBounds;
//
//       this.beforeActivation.multiply_all_byBounds( filtersValueBounds ).multiply_all_byN( inputChannelCount );
//
//       if ( bBias )
//         this.beforeActivation.add_byBounds( biasesValueBounds );
//
//
// //!!! ...unfinished... (2021/12/26)
// // The .undo should also be applied to the real filter value and bias value of this convolution-bias (i.e. not just applied here ScaleTranslate).
// //
// // Problem: What if this convolution-bias-activation could only undo partially (e.g. this convolution does not have bias)?
// //   How should the .undo of this convolution-bias-activation be calculated?
//       {
//         this.beforeActivation.multiply_all_byN(
//           previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleTranslateArraySet.undo.scale );
//
//         if ( this.bBias )
//           this.beforeActivation.add_all_byN(
//             previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleTranslateArraySet.undo.translate );
//       }
//
//     }
//
//     // 3. Output.
//     this.set_output_by_beforeActivation_ActivationId( nActivationId );
//
//     // 4. ActivationEscaping.ScaleTranslateArraySet.
//     this.activationEscaping_ScaleTranslateArraySet.setBy_currentBoundsArraySet_previousActivationEscaping(
//       this, previous_ConvBiasActivation_BoundsArraySet.activationEscaping_ScaleTranslateArraySet );
//   }

}

<|endoftext|>


<commit_before>const fork = require('child_process').fork;
const path = require('path');
const reactDocs = require('react-docgen');
const isString = require('lodash/isString');
const isNaN = require('lodash/isNaN');
const defaults = require('lodash/defaults');
const styleguideResolver = require('./resolver.js').default;

function ReactPlugin(options) {
  // Make sure the plugin was instantiated as a constructor, i.e. new ReactPlugin()
  if (!(this instanceof ReactPlugin)) {
    throw new Error(
      'The ReactPlugin must be instantiated with the "new" keyword, i.e. "new ReactPlugin()"\n\n'
    );
  }

  this.options = options || {};

  // The hostname option must be a string
  if (this.options.hostname && !isString(this.options.hostname)) {
    throw new Error('The "hostname" option of the ReactPlugin must be a string!\n\n');
  }

  const parsedPort = parseFloat(this.options.port);
  // The port option must be something that can be made a number
  if (this.options.port && !isNaN(parsedPort)) {
    throw new Error('The "port" option of the ReactPlugin must be a number!\n\n');
  }

  // If the port can be interpreted as a number, it must be above 0 and below 65535
  if (parsedPort < 0 || parsedPort > 65535) {
    throw new Error('The "port" must be between 0 and 65535 (inc)!\n\n');
  }

  // The variationFolderName option must be a string
  if (this.options.variationFolderName && !isString(this.options.variationFolderName)) {
    throw new Error(
      'The "variationFolderName" option of the ReactPlugin must be a string!\n\n'
    );
  }
}
/**
 * Initializes the plugin, called after the main StyleguidePlugin function above
 */
ReactPlugin.prototype.apply = function apply(compiler) {
  // Default options
  const options = defaults({}, this.options, {
    hostname: 'localhost',
    // The default port is not really used by a popular service:
    // https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
    port: 8082,
    variationFolderName: 'variations',
  });
  const projectBasePath = compiler.options.context;
  const variationBasePath = path.join(projectBasePath, options.variationFolderName);
  options.variationBasePath = variationBasePath;

  fork(path.resolve(__dirname, './server/run.js'), [
    projectBasePath, // process.argv[2]
    JSON.stringify(options), // process.argv[3]
  ]);

  compiler.plugin('compilation', (compilation) => {
    // Expose the react parse result to all other styleguide plugins
    compilation.plugin(
      'styleguide-plugin-before-processing',
      (data) => {
        // eslint-disable-next-line no-param-reassign
        data.reactDocs = reactDocs.parse(data.source, styleguideResolver);
      }
    );

    // The source styleguide plugin
    compilation.plugin(
      'styleguide-plugin-processing',
      (renderToClient) => {
        renderToClient({
          name: 'react',
          frontendData: { options },
          frontendPlugin: `${require.resolve('./frontend/index.js')}`,
        });
      }
    );
  });
};

export default ReactPlugin;
<commit_msg>Kill server on ReactPlugin exit, closes #193<commit_after>const fork = require('child_process').fork;
const path = require('path');
const reactDocs = require('react-docgen');
const isString = require('lodash/isString');
const isNaN = require('lodash/isNaN');
const defaults = require('lodash/defaults');
const styleguideResolver = require('./resolver.js').default;

function ReactPlugin(options) {
  // Make sure the plugin was instantiated as a constructor, i.e. new ReactPlugin()
  if (!(this instanceof ReactPlugin)) {
    throw new Error(
      'The ReactPlugin must be instantiated with the "new" keyword, i.e. "new ReactPlugin()"\n\n'
    );
  }

  this.options = options || {};

  // The hostname option must be a string
  if (this.options.hostname && !isString(this.options.hostname)) {
    throw new Error('The "hostname" option of the ReactPlugin must be a string!\n\n');
  }

  const parsedPort = parseFloat(this.options.port);
  // The port option must be something that can be made a number
  if (this.options.port && !isNaN(parsedPort)) {
    throw new Error('The "port" option of the ReactPlugin must be a number!\n\n');
  }

  // If the port can be interpreted as a number, it must be above 0 and below 65535
  if (parsedPort < 0 || parsedPort > 65535) {
    throw new Error('The "port" must be between 0 and 65535 (inc)!\n\n');
  }

  // The variationFolderName option must be a string
  if (this.options.variationFolderName && !isString(this.options.variationFolderName)) {
    throw new Error(
      'The "variationFolderName" option of the ReactPlugin must be a string!\n\n'
    );
  }
}

/**
 * Kill a Node.js process
 */
function killProcess(proc) {
  proc.kill('SIGINT');
}

/**
 * Initializes the plugin, called after the main StyleguidePlugin function above
 */
ReactPlugin.prototype.apply = function apply(compiler) {
  // Default options
  const options = defaults({}, this.options, {
    hostname: 'localhost',
    // The default port is not really used by a popular service:
    // https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
    port: 8082,
    variationFolderName: 'variations',
  });
  const projectBasePath = compiler.options.context;
  const variationBasePath = path.join(projectBasePath, options.variationFolderName);
  options.variationBasePath = variationBasePath;

  const server = fork(path.resolve(__dirname, './server/run.js'), [
    projectBasePath, // process.argv[2]
    JSON.stringify(options), // process.argv[3]
  ]);

  // Prevent the process from exiting immediately
  process.stdin.resume();

  // When the plugin exits for any reason, kill the forked Node.js process
  // with the server. (exit = process.exit(), SIGINT = CTRL+C, uncaughtException =
  // error in the code)
  process.on('exit', killProcess.bind(null, server));
  process.on('SIGINT', killProcess.bind(null, server));
  process.on('uncaughtException', killProcess.bind(null, server));

  compiler.plugin('compilation', (compilation) => {
    // Expose the react parse result to all other styleguide plugins
    compilation.plugin(
      'styleguide-plugin-before-processing',
      (data) => {
        // eslint-disable-next-line no-param-reassign
        data.reactDocs = reactDocs.parse(data.source, styleguideResolver);
      }
    );

    // The source styleguide plugin
    compilation.plugin(
      'styleguide-plugin-processing',
      (renderToClient) => {
        renderToClient({
          name: 'react',
          frontendData: { options },
          frontendPlugin: `${require.resolve('./frontend/index.js')}`,
        });
      }
    );
  });
};

export default ReactPlugin;
<|endoftext|>


<commit_before>module.exports = {
  icons: [
    'addAccount',
    'agent',
    'americanExpress',
    'americanExpressSq',
    'americanExpressSquare',
    'animal',
    'application',
    'applicationColor',
    'armchair',
    'autoColor3X',
    'autogenius',
    'autogenius',
    'back',
    'backRebrand',
    'badWeather',
    'bag',
    'bandagedFinger',
    'bandagedHead',
    'basicChair',
    'bbb',
    'birthdayHat',
    'boneJar',
    'bookSearch',
    'books',
    'calculator',
    'calculatorOrange',
    'calendar',
    'camera',
    'car',
    'carrier',
    'cart',
    'chat',
    'checkCircle',
    'checkMark-1',
    'checklist',
    'checklistFolded',
    'checkmark',
    'checkmark-thin',
    'chevronDown',
    'chevronLeft',
    'chevronRight',
    'chevronUp',
    'circlePlus',
    'clock',
    'close',
    'closeAccent',
    'computer',
    'computerColor',
    'dashboard',
    'digicert',
    'disability',
    'disabilityColor3X',
    'discount',
    'discountBadge',
    'discountBadge-shadow',
    'discountBlue',
    'discountGreen',
    'discountGreenCircle',
    'discountPill',
    'discover',
    'discoverSquare',
    'documentSmColor',
    'docUploadColor',
    'dog-1',
    'dog',
    'dogBones',
    'dogBowl',
    'dogCone',
    'down',
    'earch',
    'earchRebrand',
    'earthquake',
    'ellipsis',
    'email',
    'emailColor',
    'emailLock',
    'excellentFace',
    'excellentFaceGreen',
    'eyePatch',
    'facebook',
    'fallingObjects',
    'fastTrack',
    'family',
    'fineArt',
    'fireExtinguisher',
    'firearm',
    'flood',
    'forYou',
    'foundation',
    'fourBedroom',
    'furCoat',
    'furCoatGray',
    'golfEquipment',
    'goodFace',
    'goodFaceGrey',
    'googlePlus',
    'greenCar',
    'greenCheckWithCircle',
    'greenCheckmark',
    'greenCircleDown',
    'greenCirclePlus',
    'guaranteedIssue',
    'hamburger',
    'hamburgerRebrand',
    'headAside',
    'health-1',
    'health',
    'healthColor3X',
    'healthPlan',
    'healthgenius',
    'healthgenius',
    'heart',
    'hmoPpo',
    'home',
    'homeAutoBundleColor',
    'homeBlack',
    'homeownersColor',
    'homeWhite',
    'hsaFsa',
    'hurricane',
    'idTheft',
    'ignOut',
    'ilverware',
    'ilverwareGray',
    'infinity',
    'instruments',
    'insurancegenius',
    'insurancegenius',
    'invite',
    'jewelry',
    'largeHome',
    'lifeAgentsOff',
    'lifeAgentsOn',
    'life',
    'lifeColor3X',
    'lightbulb',
    'linkedin',
    'lock',
    'lockBlue',
    'lockOrange',
    'luxurySofa',
    'madeInNy',
    'mastercard',
    'mastercardSquare',
    'medExam',
    'medicalExam',
    'medicalPayments',
    'medicalPaymentsBlue',
    'metlife',
    'moneyCloud',
    'moneygenius',
    'moneygenius',
    'more',
    'moreColor',
    'noMedExamNeededGreen',
    'noMedicalExamNeeded',
    'norton',
    'nortonSecured',
    'nortonW',
    'openBook',
    'overflow',
    'pawprint',
    'pencil',
    'personalLiability',
    'pet',
    'petColor3X',
    'petgenius',
    'petgenius',
    'pgLogo',
    'pgLogoBlack',
    'pgLogoOrange',
    'phone',
    'phoneRebrand',
    'pinterest',
    'plus',
    'policygeniusSymbol',
    'policygeniusSymbolCenter',
    'priceSticker',
    'priceTag',
    'questionMark',
    'questionMarkWhite',
    'quoteCards',
    'quotes',
    'quotes2',
    'quotesColor',
    'rclLogo',
    'redCircleUp',
    'renters',
    'rentersColor3X',
    'returnOfPremium',
    'scales-1',
    'scales',
    'search',
    'searchRebrand',
    'shoppingCart',
    'signOut',
    'silverware',
    'silverwareGray',
    'spousal',
    'star',
    'star2',
    'starLight',
    'steeringWheel',
    'stethoscope',
    'stillwaterLogoBlack',
    'stillwaterLogoWhite',
    'studio',
    'stuff',
    'tar',
    'techgenius',
    'techgenius',
    'theftProtection',
    'thumbsDown',
    'thumbsDownSelected',
    'thumbsUp-1',
    'thumbsUp',
    'thumbsUp2',
    'thumbsUpSelected',
    'tooltip',
    'tooltipBlack',
    'travelersColor3X',
    'tudio',
    'tuff',
    'tv',
    'twitter',
    'twoBedroom',
    'user',
    'usingTablet',
    'vandalizism',
    'veryPopular',
    'visa',
    'visaSquare',
    'visionColor3X',
    'waterDamage',
    'who',
    'xCircleSmBlack',
    'xIcon',
    'yellowTriangle',
  ]
};
<commit_msg>Add chatQuestion Icon<commit_after>module.exports = {
  icons: [
    'addAccount',
    'agent',
    'americanExpress',
    'americanExpressSq',
    'americanExpressSquare',
    'animal',
    'application',
    'applicationColor',
    'armchair',
    'autoColor3X',
    'autogenius',
    'autogenius',
    'back',
    'backRebrand',
    'badWeather',
    'bag',
    'bandagedFinger',
    'bandagedHead',
    'basicChair',
    'bbb',
    'birthdayHat',
    'boneJar',
    'bookSearch',
    'books',
    'calculator',
    'calculatorOrange',
    'calendar',
    'camera',
    'car',
    'carrier',
    'cart',
    'chat',
    'chatQuestion',
    'checkCircle',
    'checkMark-1',
    'checklist',
    'checklistFolded',
    'checkmark',
    'checkmark-thin',
    'chevronDown',
    'chevronLeft',
    'chevronRight',
    'chevronUp',
    'circlePlus',
    'clock',
    'close',
    'closeAccent',
    'computer',
    'computerColor',
    'dashboard',
    'digicert',
    'disability',
    'disabilityColor3X',
    'discount',
    'discountBadge',
    'discountBadge-shadow',
    'discountBlue',
    'discountGreen',
    'discountGreenCircle',
    'discountPill',
    'discover',
    'discoverSquare',
    'documentSmColor',
    'docUploadColor',
    'dog-1',
    'dog',
    'dogBones',
    'dogBowl',
    'dogCone',
    'down',
    'earch',
    'earchRebrand',
    'earthquake',
    'ellipsis',
    'email',
    'emailColor',
    'emailLock',
    'excellentFace',
    'excellentFaceGreen',
    'eyePatch',
    'facebook',
    'fallingObjects',
    'fastTrack',
    'family',
    'fineArt',
    'fireExtinguisher',
    'firearm',
    'flood',
    'forYou',
    'foundation',
    'fourBedroom',
    'furCoat',
    'furCoatGray',
    'golfEquipment',
    'goodFace',
    'goodFaceGrey',
    'googlePlus',
    'greenCar',
    'greenCheckWithCircle',
    'greenCheckmark',
    'greenCircleDown',
    'greenCirclePlus',
    'guaranteedIssue',
    'hamburger',
    'hamburgerRebrand',
    'headAside',
    'health-1',
    'health',
    'healthColor3X',
    'healthPlan',
    'healthgenius',
    'healthgenius',
    'heart',
    'hmoPpo',
    'home',
    'homeAutoBundleColor',
    'homeBlack',
    'homeownersColor',
    'homeWhite',
    'hsaFsa',
    'hurricane',
    'idTheft',
    'ignOut',
    'ilverware',
    'ilverwareGray',
    'infinity',
    'instruments',
    'insurancegenius',
    'insurancegenius',
    'invite',
    'jewelry',
    'largeHome',
    'lifeAgentsOff',
    'lifeAgentsOn',
    'life',
    'lifeColor3X',
    'lightbulb',
    'linkedin',
    'lock',
    'lockBlue',
    'lockOrange',
    'luxurySofa',
    'madeInNy',
    'mastercard',
    'mastercardSquare',
    'medExam',
    'medicalExam',
    'medicalPayments',
    'medicalPaymentsBlue',
    'metlife',
    'moneyCloud',
    'moneygenius',
    'moneygenius',
    'more',
    'moreColor',
    'noMedExamNeededGreen',
    'noMedicalExamNeeded',
    'norton',
    'nortonSecured',
    'nortonW',
    'openBook',
    'overflow',
    'pawprint',
    'pencil',
    'personalLiability',
    'pet',
    'petColor3X',
    'petgenius',
    'petgenius',
    'pgLogo',
    'pgLogoBlack',
    'pgLogoOrange',
    'phone',
    'phoneRebrand',
    'pinterest',
    'plus',
    'policygeniusSymbol',
    'policygeniusSymbolCenter',
    'priceSticker',
    'priceTag',
    'questionMark',
    'questionMarkWhite',
    'quoteCards',
    'quotes',
    'quotes2',
    'quotesColor',
    'rclLogo',
    'redCircleUp',
    'renters',
    'rentersColor3X',
    'returnOfPremium',
    'scales-1',
    'scales',
    'search',
    'searchRebrand',
    'shoppingCart',
    'signOut',
    'silverware',
    'silverwareGray',
    'spousal',
    'star',
    'star2',
    'starLight',
    'steeringWheel',
    'stethoscope',
    'stillwaterLogoBlack',
    'stillwaterLogoWhite',
    'studio',
    'stuff',
    'tar',
    'techgenius',
    'techgenius',
    'theftProtection',
    'thumbsDown',
    'thumbsDownSelected',
    'thumbsUp-1',
    'thumbsUp',
    'thumbsUp2',
    'thumbsUpSelected',
    'tooltip',
    'tooltipBlack',
    'travelersColor3X',
    'tudio',
    'tuff',
    'tv',
    'twitter',
    'twoBedroom',
    'user',
    'usingTablet',
    'vandalizism',
    'veryPopular',
    'visa',
    'visaSquare',
    'visionColor3X',
    'waterDamage',
    'who',
    'xCircleSmBlack',
    'xIcon',
    'yellowTriangle',
  ]
};
<|endoftext|>