<commit_before>import './config/i18n';

import React, { Component } from 'react';
import { View, StatusBar } from 'react-native';
import { Provider } from 'react-redux';

import store from './store';
import NavigationRootContainer from './containers/NavigationRootContainer';
import theme from './themes/ApplicationStyles';
import colors from './themes/Colors';
// import PushNotification from './config/gcm';
import { MessageBar, MessageBarManager } from 'react-native-message-bar';

class EBudgie extends Component {
  alert = null;

  componentDidMount() {
    MessageBarManager.registerMessageBar(this.alert);
  }

  componentWillUnmount() {
    MessageBarManager.unregisterMessageBar();
  }

  render() {
    return (
      <View style={theme.mainContainer}>
        <StatusBar
          backgroundColor={colors.windowTint}
          translucent
        />
        <Provider store={store}>
          <NavigationRootContainer />
        </Provider>
        <MessageBar ref={ref => { this.alert = ref; }} />
      </View>
    );
  }
}

// PushNotification.localNotification({id: '0', // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
//     ticker: "My Notification Ticker", // (optional)
//     autoCancel: true, // (optional) default: true
//     largeIcon: "ic_launcher", // (optional) default: "ic_launcher"
//     smallIcon: "ic_notification", // (optional) default: "ic_notification" with fallback for "ic_launcher"
//     bigText: "My big text that will be shown when notification is expanded", // (optional) default: "message" prop
//     subText: "This is a subText", // (optional) default: none
//     color: "#023365", // (optional) default: system default
//     vibrate: true, // (optional) default: true
//     vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
//     tag: 'some_tag', // (optional) add tag to message
//     // group: "group", // (optional) add group to message
//     ongoing: false, // (optional) set whether this is an "ongoing" notification

//     /* iOS and Android properties */
//     title: "My Notification Title", // (optional, for iOS this is only used in apple watch, the title will be the app name on other iOS devices)
//     message: "My Notification Message", // (required)
//     playSound: false, // (optional) default: true
//     soundName: 'default', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
//     number: '10', // (optional) Valid 32 bit integer specified as string. default: none (Cannot be zero)
//     repeatType: 'day', // (Android only) Repeating interval. Could be one of `week`, `day`, `hour`, `minute, `time`. If specified as time, it should be accompanied by one more parameter 'repeatTime` which should the number of milliseconds between each interval

// });

// PushNotification.localNotificationSchedule({
//     ticker: "My Notification Ticker", // (optional)
//     autoCancel: true, // (optional) default: true
//     largeIcon: "ic_launcher", // (optional) default: "ic_launcher"
//     smallIcon: "ic_notification", // (optional) default: "ic_notification" with fallback for "ic_launcher"
//     bigText: "My big text that will be shown when notification is expanded", // (optional) default: "message" prop
//     subText: "This is a subText", // (optional) default: none
//     color: "#023365", // (optional) default: system default
//     vibrate: true, // (optional) default: true
//     vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
//     tag: 'some_tag', // (optional) add tag to message
//     // group: "group", // (optional) add group to message
//     ongoing: false, // (optional) set whether this is an "ongoing" notification

//     /* iOS and Android properties */
//     title: "My Notification Title", // (optional, for iOS this is only used in apple watch, the title will be the app name on other iOS devices)
//     message: "My Notification Message", // (required)
//     playSound: false, // (optional) default: true
//     soundName: 'default', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
//     number: '10', // (optional) Valid 32 bit integer specified as string. default: none (Cannot be zero)
//     repeatType: 'day', // (Android only) Repeating interval. Could be one of `week`, `day`, `hour`, `minute, `time`. If specified as time, it should be accompanied by one more parameter 'repeatTime` which should the number of milliseconds between each interval

//   date: new Date(Date.now() + (10*1000)) // in 60 secs
// });
export default EBudgie;
<commit_msg>Initialize fcm config in main file before ui part<commit_after>import './config/i18n';
import './config/fcm';

import React, { Component } from 'react';
import { View, StatusBar } from 'react-native';
import { Provider } from 'react-redux';

import store from './store';
import NavigationRootContainer from './containers/NavigationRootContainer';
import theme from './themes/ApplicationStyles';
import colors from './themes/Colors';
import { MessageBar, MessageBarManager } from 'react-native-message-bar';

class EBudgie extends Component {
  alert = null;

  componentDidMount() {
    MessageBarManager.registerMessageBar(this.alert);
  }

  componentWillUnmount() {
    MessageBarManager.unregisterMessageBar();
  }

  render() {
    return (
      <View style={theme.mainContainer}>
        <StatusBar
          backgroundColor={colors.windowTint}
          translucent
        />
        <Provider store={store}>
          <NavigationRootContainer />
        </Provider>
        <MessageBar ref={ref => { this.alert = ref; }} />
      </View>
    );
  }
}

export default EBudgie;
<|endoftext|>


<commit_before>import Preloader from "./Preloader"

var preloader = new Preloader([
  "dude/arm.png",
  "dude/body.png",
  "dude/foot.png",
  "dude/hand.png",
  "dude/head.png",
  "dude/leg.png"
]);

class Bone {

  constructor(img, width, height, rect) {
    this.img = img;
    this.width = width;
    this.height = height;
    this.x = 0;
    this.y = 0;
    this.a = 0;
    this.rect = rect;
    this.selected = false;
  }

  apply() {
    let tx = `translate(${this.x} ${this.y}) rotate(${this.a} ${0.5 *this.w} ${0.5*this.h})`
    this.img.transform(tx);
    this.rect.transform(tx);
    this.rect.attr({"stroke": this.selected ? "blue" : "transparent"});
  }

}

class Manipulator {

  constructor(svg, bones) {
    this.svg = svg;
    this.bones = bones,
    this.bone = null;
    this.mode = "Select";
    this.modeStatus = document.getElementById("mode");
    this.startPos = null;
    this.zoom = 1;
    this.panX = 400;
    this.panY = 300;
  }

  setMode(mode) {
    this.mode = mode;
    this.modeStatus.innerHTML = mode;
  }

  getMousePos(e) {
    return {
      "x": (e.pageX - this.panX) / this.zoom,
      "y": (e.pageY - this.panY) / this.zoom
    }
  }

  init() {
    document.addEventListener("keydown", (e) => {
      switch (e.keyCode) {
        case 77:
          this.setMode("Move");
          break;
        case 82:
          this.setMode("Rotate");
          break;
      }
    })

    document.addEventListener("keyup", (e) => {

      switch (e.keyCode) {
        case 77:
        case 82:
          this.setMode("Select");
          break;

        case 107:
          this.zoom *= 2;
          this.svg.transform(`translate(${this.panX}, ${this.panY}) scale(${this.zoom}, ${this.zoom})`);
          break;

        case 109:
          this.zoom *= 0.5;
          this.svg.transform(`translate(${this.panX}, ${this.panY}) scale(${this.zoom}, ${this.zoom})`);
          break;

        case 33:
          if (this.bone) {
            this.svg.append(this.bone.img);
          }
          break;

        case 34:
          if (this.bone) {
            this.svg.prepend(this.bone.img);
          }

      }

    });

    document.addEventListener("mousedown", (e) => {
      let m = this.getMousePos(e);

      if (this.bone == null) {
        this.startPos = {
          "x": this.panX,
          "y": this.panY,
          "mx": m.x,
          "my": m.y,
        }
        return;
      }

      switch (this.mode) {
        case "Move":
        case "Rotate":
          var mx = m.x;
          var my = m.y;
          var x = this.bone.x;
          var y = this.bone.y;
          var a = this.bone.a;
          var w2 = this.bone.width *  0.5;
          var h2 = this.bone.height *  0.5;

          var ma = Snap.angle(x + w2, y + h2, mx, my);

          this.startPos = {
            "x": x,
            "y": y,
            "a": a,
            "mx" : mx,
            "my" : my,
            "ma" : ma
          }

          break;
      }
    });

    document.addEventListener("mouseup", (e) => {
      this.startPos = null;
    });

    document.addEventListener("mousemove", (e) => {
      if (this.startPos == null) return;

      let m = this.getMousePos(e);

      if (this.bone == null) {
        let dx = (m.x - this.startPos.mx) * this.zoom;
        let dy = (m.y - this.startPos.my) * this.zoom;
        this.panX = this.startPos.x + dx;
        this.panY = this.startPos.y + dy;
        console.log(`${this.panX}, ${this.panY} - ${dx}, ${dy}`)
        this.svg.transform(`translate(${this.panX}, ${this.panY}) scale(${this.zoom}, ${this.zoom})`);
        return;
      }

      switch (this.mode) {
        case "Move":
          var mx = m.x;
          var my = m.y;
          var dx = mx - this.startPos.mx;
          var dy = my - this.startPos.my;
          var x = this.startPos.x + dx;
          var y = this.startPos.y + dy;
          this.bone.x = x;
          this.bone.y = y;
          this.bone.apply();
          break;

        case "Rotate":
          var mx = m.x;
          var my = m.y;
          var dx = mx - this.startPos.mx;
          var dy = my - this.startPos.my;

          var w2 = this.bone.width *  0.5;
          var h2 = this.bone.height *  0.5;

          var ma = Snap.angle(this.startPos.x + w2, this.startPos.y + h2, mx, my);
          var da = ma - this.startPos.ma;
          var a = this.startPos.a + da;

          this.bone.a = a;
          this.bone.apply();

          break;
      }

    });

    document.addEventListener("click", (e) => {
      switch (this.mode) {
        case "Select":
          if (this.bone) {
            this.bone.selected = false;
            this.bone.apply();
          }

          this.bone = null;
          let pos = this.getMousePos(e);

          for (let bone of this.bones) {
            let hit = (pos.x > bone.x &&
                       pos.x < bone.x + bone.width &&
                       pos.y > bone.y &&
                       pos.y < bone.y + bone.height);
             if (hit) {
               this.bone = bone;
               this.bone.selected = true;
               this.bone.apply();
             }
          }
          break;
      }
    });

  }

}

function start(assets) {

  var s = Snap("#canvas");
  s.transform("translate(400, 300) scale(1, 1)");

  function createBone(path, x, y) {
    var asset = assets[path];
    var img = s.image(path, 0, 0, asset.width, asset.height);
    var rect = s.rect(0, 0, asset.width, asset.height);
    rect.attr({"fill": "transparent", "stroke": "transparent", "strokeWidth": 2});

    var bone = new Bone(img, asset.width, asset.height, rect);
    bone.x = x;
    bone.y = y;
    bone.a = 0;
    bone.apply();

    return bone;
  }

  let bones = [];
  bones.push(createBone("dude/arm.png", 100 - 400, 0));
  bones.push(createBone("dude/body.png", 200 - 400, 0));
  bones.push(createBone("dude/foot.png", 300 - 400, 0));
  bones.push(createBone("dude/hand.png", 400 - 400, 0));
  bones.push(createBone("dude/head.png", 500 - 400, 0));
  bones.push(createBone("dude/leg.png", 600 - 400, 0));

  var manipulator = new Manipulator(s, bones);
  manipulator.init();
}

preloader.load(start);
<commit_msg>fixed jitter problem<commit_after>import Preloader from "./Preloader"

var preloader = new Preloader([
  "dude/arm.png",
  "dude/body.png",
  "dude/foot.png",
  "dude/hand.png",
  "dude/head.png",
  "dude/leg.png"
]);

class Bone {

  constructor(img, width, height, rect) {
    this.img = img;
    this.width = width;
    this.height = height;
    this.x = 0;
    this.y = 0;
    this.a = 0;
    this.rect = rect;
    this.selected = false;
  }

  apply() {
    let tx = `translate(${this.x} ${this.y}) rotate(${this.a} ${0.5 *this.w} ${0.5*this.h})`
    this.img.transform(tx);
    this.rect.transform(tx);
    this.rect.attr({"stroke": this.selected ? "blue" : "transparent"});
  }

}

class Manipulator {

  constructor(svg, bones) {
    this.svg = svg;
    this.bones = bones,
    this.bone = null;
    this.mode = "Select";
    this.modeStatus = document.getElementById("mode");
    this.startPos = null;
    this.zoom = 1;
    this.panX = 400;
    this.panY = 300;
  }

  setMode(mode) {
    this.mode = mode;
    this.modeStatus.innerHTML = mode;
  }

  getMousePos(e) {
    return {
      "x": (e.pageX - this.panX) / this.zoom,
      "y": (e.pageY - this.panY) / this.zoom
    }
  }

  init() {
    document.addEventListener("keydown", (e) => {
      switch (e.keyCode) {
        case 77:
          this.setMode("Move");
          break;
        case 82:
          this.setMode("Rotate");
          break;
      }
    })

    document.addEventListener("keyup", (e) => {

      switch (e.keyCode) {
        case 77:
        case 82:
          this.setMode("Select");
          break;

        case 107:
          this.zoom *= 2;
          this.svg.transform(`translate(${this.panX}, ${this.panY}) scale(${this.zoom}, ${this.zoom})`);
          break;

        case 109:
          this.zoom *= 0.5;
          this.svg.transform(`translate(${this.panX}, ${this.panY}) scale(${this.zoom}, ${this.zoom})`);
          break;

        case 33:
          if (this.bone) {
            this.svg.append(this.bone.img);
          }
          break;

        case 34:
          if (this.bone) {
            this.svg.prepend(this.bone.img);
          }

      }

    });

    document.addEventListener("mousedown", (e) => {
      let m = this.getMousePos(e);

      if (this.bone == null) {
        this.startPos = {
          "x": this.panX,
          "y": this.panY,
          "mx": m.x,
          "my": m.y,
        }
        return;
      }

      switch (this.mode) {
        case "Move":
        case "Rotate":
          var mx = m.x;
          var my = m.y;
          var x = this.bone.x;
          var y = this.bone.y;
          var a = this.bone.a;
          var w2 = this.bone.width *  0.5;
          var h2 = this.bone.height *  0.5;

          var ma = Snap.angle(x + w2, y + h2, mx, my);

          this.startPos = {
            "x": x,
            "y": y,
            "a": a,
            "mx" : mx,
            "my" : my,
            "ma" : ma
          }

          break;
      }
    });

    document.addEventListener("mouseup", (e) => {
      this.startPos = null;
    });

    document.addEventListener("mousemove", (e) => {
      if (this.startPos == null) return;

      if (this.bone == null) {
        // cannot use getMousePos() because it shifts origin when panning, so the delta gets wrong
        let m = {
          "x": (e.pageX - this.startPos.x) / this.zoom,
          "y": (e.pageY - this.startPos.y) / this.zoom
        };

        let dx = (m.x - this.startPos.mx) * this.zoom;
        let dy = (m.y - this.startPos.my) * this.zoom;
        this.panX = this.startPos.x + dx;
        this.panY = this.startPos.y + dy;
        console.log(`${this.panX}, ${this.panY} - ${dx}, ${dy} :: m: ${m.x}, ${m.y}  s: ${this.startPos.mx},${this.startPos.my}`)
        requestAnimationFrame(() => {
          this.svg.transform(`translate(${this.panX}, ${this.panY}) scale(${this.zoom}, ${this.zoom})`);
        });
        return;
      }

      let m = this.getMousePos(e);

      switch (this.mode) {
        case "Move":
          var mx = m.x;
          var my = m.y;
          var dx = mx - this.startPos.mx;
          var dy = my - this.startPos.my;
          var x = this.startPos.x + dx;
          var y = this.startPos.y + dy;
          this.bone.x = x;
          this.bone.y = y;
          this.bone.apply();
          break;

        case "Rotate":
          var mx = m.x;
          var my = m.y;
          var dx = mx - this.startPos.mx;
          var dy = my - this.startPos.my;

          var w2 = this.bone.width *  0.5;
          var h2 = this.bone.height *  0.5;

          var ma = Snap.angle(this.startPos.x + w2, this.startPos.y + h2, mx, my);
          var da = ma - this.startPos.ma;
          var a = this.startPos.a + da;

          this.bone.a = a;
          this.bone.apply();

          break;
      }

    });

    document.addEventListener("click", (e) => {
      switch (this.mode) {
        case "Select":
          if (this.bone) {
            this.bone.selected = false;
            this.bone.apply();
          }

          this.bone = null;
          let pos = this.getMousePos(e);

          for (let bone of this.bones) {
            let hit = (pos.x > bone.x &&
                       pos.x < bone.x + bone.width &&
                       pos.y > bone.y &&
                       pos.y < bone.y + bone.height);
             if (hit) {
               this.bone = bone;
               this.bone.selected = true;
               this.bone.apply();
             }
          }
          break;
      }
    });

  }

}

function start(assets) {

  var s = Snap("#canvas");
  s.transform("translate(400, 300) scale(1, 1)");

  function createBone(path, x, y) {
    var asset = assets[path];
    var img = s.image(path, 0, 0, asset.width, asset.height);
    var rect = s.rect(0, 0, asset.width, asset.height);
    rect.attr({"fill": "transparent", "stroke": "transparent", "strokeWidth": 2});

    var bone = new Bone(img, asset.width, asset.height, rect);
    bone.x = x;
    bone.y = y;
    bone.a = 0;
    bone.apply();

    return bone;
  }

  let bones = [];
  bones.push(createBone("dude/arm.png", 100 - 400, 0));
  bones.push(createBone("dude/body.png", 200 - 400, 0));
  bones.push(createBone("dude/foot.png", 300 - 400, 0));
  bones.push(createBone("dude/hand.png", 400 - 400, 0));
  bones.push(createBone("dude/head.png", 500 - 400, 0));
  bones.push(createBone("dude/leg.png", 600 - 400, 0));

  var manipulator = new Manipulator(s, bones);
  manipulator.init();
}

preloader.load(start);
<|endoftext|>


<commit_before>requirejs.config({
    paths: {
        "jquery": "3rdparty/require-jquery"
        //
        // XXX: we do not have a nested config solution yet. Until
        // then we stick with require-jquery and relative dependency
        // paths.
        //
        //"prefixfree": "3rdparty/prefixfree.min",
        //"modernizr": "3rdparty/modernizr-2.0.6",
        //"jquery.anythingslider": "3rdparty/jquery.anythingslider",
        //"jquery.autoSuggest": "3rdparty/jquery.autosuggest",
        //"jquery.form": "lib/jquery.form/jquery.form",
        //"jquery.placeholder": "3rdparty/jquery.placeholder",
        //"jquery.tools": "3rdparty/jquery.tools.min"
    // },
    // shim: {
    //     "jquery.form": {
    //         deps: ["jquery"],
    //         exports: "jQuery.fn.ajaxSubmit"
    //     },

    //     "jquery.anythingslider": {
    //         deps: ["jquery"],
    //         exports: "jQuery.fn.anythingSlider"
    //     },
    //     "jquery.autoSuggests": {
    //         deps: ["jquery"],
    //         exports: "jQuery.fn.autoSuggest"
    //     },
    //     "jquery.placeholder": {
    //         deps: ["jquery"],
    //         exports: "jQuery.fn.placeholder"
    //     },
    //     "jquery-ext": {
    //         deps: ["jquery"],
    //         exports: "jQuery.fn.simplePlaceholder"
    //     }
    }
});

define([
    'require',
    'jquery',
    './3rdparty/prefixfree',
    './3rdparty/modernizr-2.0.6',
    './core/init',
    './patterns/autofocus',
    './patterns/autoload',
    './patterns/autosubmit',
    './patterns/autosuggest',
    './patterns/breadcrumbs',
    './patterns/carousel',
    './patterns/checkedflag',
    './patterns/checklist',
    './patterns/chosen',
    './patterns/collapsible',
    './patterns/depends',
    './patterns/edit-tinymce',
    './patterns/expandable',
    './patterns/floatingpanel',
    './patterns/focus',
    './patterns/fullcalendar',
    //'./patterns/inject',
    './patterns/menu',
    './patterns/modal',
    './patterns/navigation',
    './patterns/old_modal',
    './patterns/placeholder',
    './patterns/selfhealing',
    './patterns/setclass',
    './patterns/sorting',
    './patterns/switch',
    './patterns/toggle',
    './patterns/tooltip',
    './patterns/transforms',
    './patterns/ultimate',
    './patterns/validate',
    './patterns/width'
], function(require, $) {
    var mapal = require('./core/init'),
        width = require('./patterns/width');
    width.register("narrow", 0, 780);
    width.register("medium", 0, 1109);
    width.register("wide", 1110, null);

    // Register these so data-injection can execute actions from these patterns
    mapal.patterns.floatingPanelContextual = require('./patterns/floatingpanel');
    mapal.patterns.modal = require('./patterns/old_modal');
    mapal.patterns.selfHealing = require('./patterns/selfhealing');

    $(document).on('inject.patterns.scan', function(ev, opts) {
        mapal.initContent(ev.target, opts);
        $(ev.target).trigger('patterns-inject-scanned', opts);
    });

    // wait for the DOM to be ready and initialize
    $(document).ready(function(){
        mapal.init();
        mapal.initContent(document.body);
        $(document).trigger("setupFinished", document);
    });

    return mapal;
});
<commit_msg>We are not ultimate for now.<commit_after>requirejs.config({
    paths: {
        "jquery": "3rdparty/require-jquery"
        //
        // XXX: we do not have a nested config solution yet. Until
        // then we stick with require-jquery and relative dependency
        // paths.
        //
        //"prefixfree": "3rdparty/prefixfree.min",
        //"modernizr": "3rdparty/modernizr-2.0.6",
        //"jquery.anythingslider": "3rdparty/jquery.anythingslider",
        //"jquery.autoSuggest": "3rdparty/jquery.autosuggest",
        //"jquery.form": "lib/jquery.form/jquery.form",
        //"jquery.placeholder": "3rdparty/jquery.placeholder",
        //"jquery.tools": "3rdparty/jquery.tools.min"
    // },
    // shim: {
    //     "jquery.form": {
    //         deps: ["jquery"],
    //         exports: "jQuery.fn.ajaxSubmit"
    //     },

    //     "jquery.anythingslider": {
    //         deps: ["jquery"],
    //         exports: "jQuery.fn.anythingSlider"
    //     },
    //     "jquery.autoSuggests": {
    //         deps: ["jquery"],
    //         exports: "jQuery.fn.autoSuggest"
    //     },
    //     "jquery.placeholder": {
    //         deps: ["jquery"],
    //         exports: "jQuery.fn.placeholder"
    //     },
    //     "jquery-ext": {
    //         deps: ["jquery"],
    //         exports: "jQuery.fn.simplePlaceholder"
    //     }
    }
});

define([
    'require',
    'jquery',
    './3rdparty/prefixfree',
    './3rdparty/modernizr-2.0.6',
    './core/init',
    './patterns/autofocus',
    './patterns/autoload',
    './patterns/autosubmit',
    './patterns/autosuggest',
    './patterns/breadcrumbs',
    './patterns/carousel',
    './patterns/checkedflag',
    './patterns/checklist',
    './patterns/chosen',
    './patterns/collapsible',
    './patterns/depends',
    './patterns/edit-tinymce',
    './patterns/expandable',
    './patterns/floatingpanel',
    './patterns/focus',
    './patterns/fullcalendar',
    //'./patterns/inject',
    './patterns/menu',
    './patterns/modal',
    './patterns/navigation',
    './patterns/old_modal',
    './patterns/placeholder',
    './patterns/selfhealing',
    './patterns/setclass',
    './patterns/sorting',
    './patterns/switch',
    './patterns/toggle',
    './patterns/tooltip',
    './patterns/transforms',
    './patterns/validate',
    './patterns/width'
], function(require, $) {
    var mapal = require('./core/init'),
        width = require('./patterns/width');
    width.register("narrow", 0, 780);
    width.register("medium", 0, 1109);
    width.register("wide", 1110, null);

    // Register these so data-injection can execute actions from these patterns
    mapal.patterns.floatingPanelContextual = require('./patterns/floatingpanel');
    mapal.patterns.modal = require('./patterns/old_modal');
    mapal.patterns.selfHealing = require('./patterns/selfhealing');

    $(document).on('inject.patterns.scan', function(ev, opts) {
        mapal.initContent(ev.target, opts);
        $(ev.target).trigger('patterns-inject-scanned', opts);
    });

    // wait for the DOM to be ready and initialize
    $(document).ready(function(){
        mapal.init();
        mapal.initContent(document.body);
        $(document).trigger("setupFinished", document);
    });

    return mapal;
});
<|endoftext|>


<commit_before>"use strict";

let fs = require("fs");

// Get controller file
exports.ctrl = function(name) {
	return require(process.env.CONTROLLER_PATH + name + "Controller");
};

// Get helper file
exports.helper = function(name) {
	return require(process.env.HELPER_PATH + name);
};

// Get model file
exports.model = function(name) {
	return require(process.env.MODEL_PATH + name);
};

// Get path files

exports.getFiles = function(path) {
	let files = [];

	fs.readdirSync(path).forEach(function(file) {
		file = path + (path.substr(path.length-1) ==="/" ? "" : "/") + file;
		if (fs.lstatSync(file).isFile() && file.indexOf(".js") > -1) files.push(file);
	});

	return files;
};
<commit_msg>Retrieve son and js files only<commit_after>"use strict";

let fs = require("fs");

// Get controller file
exports.ctrl = function(name) {
	return require(process.env.CONTROLLER_PATH + name + "Controller");
};

// Get helper file
exports.helper = function(name) {
	return require(process.env.HELPER_PATH + name);
};

// Get model file
exports.model = function(name) {
	return require(process.env.MODEL_PATH + name);
};

// Get path files

exports.getFiles = function(path) {
	let files = [];

  if (fs.existsSync(path)) {
  	fs.readdirSync(path).forEach(function(file) {
  		file = path + (path.substr(path.length-1) ==="/" ? "" : "/") + file;
  		if (fs.lstatSync(file).isFile() && (file.indexOf(".js") > -1 || file.indexOf(".json") > -1)) files.push(file);
  	});
  }

	return files;
};<|endoftext|>


<commit_before>var _global = require('global');
var _extension = require('extension');
const RoomManager = require('manager_room');
const profiler = require('lib_screeps-profiler');

// This line monkey patches the global prototypes.
const EnableProfiler = Config.EnableProfiler;
if(EnableProfiler) profiler.enable();
module.exports.loop = function() {
  profiler.wrap(loop0);
}

const loop0 = function () {
    //Validate and clear data
    Util.GC.loop();
    Util.Mark.loop();
    Util.Stat.loop();
    //Run rooms
    var entry = {};
    _.forEach(Game.rooms, function(room) {
        RoomManager.loop(room);
        entry[room.name] = room.energyAvailable;
    });
    Util.Stat.memorize('last-energyAvailable', entry);
    //Run creeps
    for(var name in Game.creeps) {
        var creep = Game.creeps[name];
        var role = creep.memory.role;
        var roleModule = Role[_.capitalize(role)];

        if(roleModule) {
            roleModule.loop(creep);
        } else {
            console.log('[Error] Undefined role module is in memory of creep -> '+name);
        }
    }
}
<commit_msg>make sure run SourceMark.loop() instead of Mark.loop() which currently do nothing<commit_after>var _global = require('global');
var _extension = require('extension');
const RoomManager = require('manager_room');
const profiler = require('lib_screeps-profiler');

// This line monkey patches the global prototypes.
const EnableProfiler = Config.EnableProfiler;
if(EnableProfiler) profiler.enable();
module.exports.loop = function() {
  profiler.wrap(loop0);
}

const loop0 = function () {
    //Validate and clear data
    Util.GC.loop();
    Util.SourceMark.loop();
    Util.Stat.loop();
    //Run rooms
    var entry = {};
    _.forEach(Game.rooms, function(room) {
        RoomManager.loop(room);
        entry[room.name] = room.energyAvailable;
    });
    Util.Stat.memorize('last-energyAvailable', entry);
    //Run creeps
    for(var name in Game.creeps) {
        var creep = Game.creeps[name];
        var role = creep.memory.role;
        var roleModule = Role[_.capitalize(role)];

        if(roleModule) {
            roleModule.loop(creep);
        } else {
            console.log('[Error] Undefined role module is in memory of creep -> '+name);
        }
    }
}
<|endoftext|>


<commit_before>function r() {
  var metas = document.getElementsByTagName(/* @mangle */'meta'/* @/mangle */);
  for (var i=0; i<metas.length; i++) {
    if (metas[i].getAttribute(/* @mangle */"name"/* @/mangle */) === /* @mangle */"author"/* @/mangle */) {
      if (metas[i].getAttribute(/* @mangle */"content"/* @/mangle */).indexOf(/* @mangle */'1e0n'/* @/mangle */) === 0) {
        for (var key in s) {
          if (s.hasOwnProperty(key)) {
            var v = s[key].value();
            v = Math.round(v * 100) / 100;
            d3.select(/* @mangle */'.'/* @/mangle */ + key + /* @mangle */' .text'/* @/mangle */).text(v);
          }

        }
        t();
      }
      break;
    }
  }
}

var s = {};

function g(name, ticks, min, max, value, step) {
  s[name] = d3.slider().axis(d3.svg.axis().ticks(ticks))
    .min(min).max(max).value(value).step(step)
    .on("slide", function(evt, value) {
      if (name == /* @mangle */'percent-for-teaching'/* @/mangle */) {
        s[/* @mangle */'percent-for-office'/* @/mangle */].value(100 - value);
      }
      if (name == /* @mangle */'percent-for-office'/* @/mangle */) {
        s[/* @mangle */'percent-for-teaching'/* @/mangle */].value(100 - value);
      }
      var metas = document.getElementsByTagName(/* @mangle */'meta'/* @/mangle */);
      var meta = '';
      for (var i=0; i<metas.length; i++) {
        if (metas[i].getAttribute(/* @mangle */"name"/* @/mangle */) === /* @mangle */"author"/* @/mangle */) {
          if (metas[i].getAttribute(/* @mangle */"content"/* @/mangle */).indexOf(/* @mangle */'1e0n'/* @/mangle */) >= 0 && d3.select(/* @mangle */'.footer'/* @/mangle */).text().indexOf(/* @mangle */'Mala'/* @/mangle */) > 30) {
            r();
          }
        }
      }
    });
  d3.select(/* @mangle */'.'/* @/mangle */ + name + /* @mangle */' .graph'/* @/mangle */).call(s[name]);
}
function o(k, v) {
  v = Math.round(v * 100) / 100;
  d3.selectAll(/* @mangle */'.'/* @/mangle */ + k + /* @mangle */'.text'/* @/mangle */).text(v);
}

function w(k) {
  return Math.round(parseFloat(d3.select('.' + k + '.text').text()) * 100) / 100;
}

function ss() {
  var i;
  var sum = 0;
  for (i = 0; i < arguments.length; ++i) {
    //console.log(arguments[i]);
    sum += w(arguments[i]);
  }
  return sum;
}

function t() {
  o('start-fund', s['start-fund-in-10k'].value() * 10000);
  o('rent-deposite', s['rent-deposite-in-k'].value() * 1000);
  o('rent-first-year', s['area'].value() * s['rent-per-square'].value() * s['op-month-first-year'].value());
  o('property-cost-first-year', s['area'].value() * s['op-month-first-year'].value() * s['property-cost-per-square'].value());
  o('decoration-cost', s['area'].value() * s['decoration-cost-per-square'].value());
  o('device-cost', s['device-price'].value() * s['classrooms'].value());
  o('desk-cost', s['desks'].value() * s['desk-price'].value());
  var v = s['salary'].value() * s['hr-first-year'].value() * s['op-month-first-year'].value();
  o('salary-cost', v);
  o('social-security-cost', v * s['social-security'].value() / 100);
  o('cpf-cost', v * s['cpf'].value() / 100);

  o('initial-fee', s['initial-fee-in-10k'].value() * 10000);
  o('constant-cost-first-year', ss('rent-deposite', 'rent-first-year', 'property-cost-first-year', 'decoration-cost', 'device-cost', 'desk-cost', 'salary-cost', 'social-security-cost', 'cpf-cost'));
  o('first-year-constant-reminder', w('start-fund') - w('constant-cost-first-year'));

  o('p2p-income-first-year', s['p2p-students'].value() * s['p2p-avg-charge'].value());
  o('sm-income-first-year', s['sm-students'].value() * s['sm-avg-charge'].value());
  o('bg-income-first-year', s['bg-students'].value() * s['bg-avg-charge'].value());

  o('total-income-first-year', ss('p2p-income-first-year', 'sm-income-first-year', 'bg-income-first-year'));

  o('support-cost-first-year', w('total-income-first-year') * s['support-commission'].value() / 100);

  v = (w('p2p-income-first-year') * s['p2p-avg-complete-rate'].value() + w('sm-income-first-year') * s['sm-avg-complete-rate'].value() + w('bg-income-first-year') * s['bg-avg-complete-rate'].value()) / 100;
  o('vat-first-year', v * s['vat'].value() / 100);
  o('local-tax-first-year', w('vat-first-year') * s['local-tax'].value() / 100);
  o('sales-commission-first-year', w('total-income-first-year') * s['sales-commission'].value() / 100);

  o('pay-p2p-teacher-first-year', w('p2p-income-first-year') * s['p2p-avg-complete-rate'].value() * s['pay-teacher-percent-for-p2p'].value() / 10000);
  o('pay-class-teacher-first-year', (w('sm-income-first-year') * s['sm-avg-complete-rate'].value() + w('bg-income-first-year') * s['bg-avg-complete-rate'].value()) * s['pay-teacher-percent-for-class'].value() / 10000);
  o('market-cost-first-year', v * s['market-cost-percent'].value() / 100);

  o('tutoring-cost-first-year', 0);
  o('water-elec-cost-first-year', 0);

  o('office-material-cost-first-year', s['hr-first-year'].value() * s['op-month-first-year'].value() * s['office-material-cost-per-person'].value());
  o('finance-cost-first-year', w('total-income-first-year') * s['credit-card-fee-percent'].value() * s['credit-card-contrib'].value() / 10000);

  o('var-cost-first-year', ss('support-cost-first-year', 'vat-first-year', 'local-tax-first-year', 'sales-commission-first-year', 'pay-p2p-teacher-first-year', 'pay-class-teacher-first-year', 'market-cost-first-year', 'tutoring-cost-first-year', 'water-elec-cost-first-year', 'office-material-cost-first-year', 'finance-cost-first-year'));

  o('first-year-var-reminder', w('total-income-first-year') - w('var-cost-first-year'));
  o('first-year-reminder', w('first-year-var-reminder') + w('first-year-constant-reminder'));
}
g(/* @mangle */'area'/* @/mangle */, 10, 200, 2000, 300, 50);
g(/* @mangle */'rent-per-square'/* @/mangle */, 7, 0, 300, 40, 1);
g(/* @mangle */'rent-months'/* @/mangle */, 10, 0, 120, 36, 6);
g(/* @mangle */'property-cost-per-square'/* @/mangle */, 11, 0, 20, 2, 1);
g(/* @mangle */'op-month-first-year'/* @/mangle */, 13, 0, 12, 6, 1);
g(/* @mangle */'classrooms'/* @/mangle */, 13, 0, 100, 18, 1);
g(/* @mangle */'decoration-cost-per-square'/* @/mangle */, 11, 0, 2000, 700, 10);
g(/* @mangle */'hr-first-year'/* @/mangle */, 11, 0, 100, 10, 1);
g(/* @mangle */'salary'/* @/mangle */, 11, 1000, 5000, 2000, 100);
g(/* @mangle */'desks'/* @/mangle */, 11, 0, 200, 30, 1);
g(/* @mangle */'desk-price'/* @/mangle */, 10, 100, 1000, 500, 10);
g(/* @mangle */'device-price'/* @/mangle */, 10, 500, 5000, 3000, 100);
g(/* @mangle */'p2p-students'/* @/mangle */, 10, 0, 500, 80, 10);
g(/* @mangle */'p2p-avg-charge'/* @/mangle */, 9, 0, 16000, 8000, 1000);
g(/* @mangle */'p2p-avg-complete-rate'/* @/mangle */, 10, 0, 100, 80, 5);

g(/* @mangle */'sm-students'/* @/mangle */, 10, 0, 500, 60, 10);
g(/* @mangle */'sm-avg-charge'/* @/mangle */, 5, 0, 4000, 2000, 100);
g(/* @mangle */'sm-avg-complete-rate'/* @/mangle */, 10, 0, 100, 95, 5);

g(/* @mangle */'bg-students'/* @/mangle */, 10, 0, 500, 100, 10);
g(/* @mangle */'bg-avg-charge'/* @/mangle */, 9, 0, 1600, 800, 100);
g(/* @mangle */'bg-avg-complete-rate'/* @/mangle */, 10, 0, 100, 95, 5);

g(/* @mangle */'sales-commission'/* @/mangle */, 10, 0, 50, 5, 1);
g(/* @mangle */'course-material-cost'/* @/mangle */, 10, 0, 100, 20, 5);

g(/* @mangle */'pay-teacher-percent-for-p2p'/* @/mangle */, 10, 0, 100, 40, 1);
g(/* @mangle */'pay-teacher-percent-for-class'/* @/mangle */, 10, 0, 100, 30, 1);

g(/* @mangle */'vat'/* @/mangle */, 3, 0, 6, 3, 3);
g(/* @mangle */'local-tax'/* @/mangle */, 10, 0, 30, 12, 1);

g(/* @mangle */'credit-card-fee-percent'/* @/mangle */, 10, 0, 3, 0.78, 0.01);
g(/* @mangle */'credit-card-contrib'/* @/mangle */, 10, 0, 100, 70, 1);
g(/* @mangle */'support-commission'/* @/mangle */, 10, 0, 50, 5, 1);

g(/* @mangle */'social-security'/* @/mangle */, 10, 0, 30, 8, 1);
g(/* @mangle */'cpf'/* @/mangle */, 10, 0, 20, 4, 1);

g(/* @mangle */'office-material-cost-per-person'/* @/mangle */, 10, 0, 200, 50, 10);

g(/* @mangle */'percent-for-teaching'/* @/mangle */, 10, 0, 100, 80, 1);
g(/* @mangle */'percent-for-office'/* @/mangle */, 10, 0, 100, 20, 1);

g(/* @mangle */'market-cost-percent'/* @/mangle */, 10, 0, 30, 7, 1);

g(/* @mangle */'start-fund-in-10k'/* @/mangle */, 10, 0, 100, 50, 1);

g(/* @mangle */'rent-deposite-in-k'/* @/mangle */, 10, 0, 50, 0, 1);
g(/* @mangle */'initial-fee-in-10k'/* @/mangle */, 10, 0, 100, 12, 1);

r();
<commit_msg>Fill income for the first year.<commit_after>function r() {
  var metas = document.getElementsByTagName(/* @mangle */'meta'/* @/mangle */);
  for (var i=0; i<metas.length; i++) {
    if (metas[i].getAttribute(/* @mangle */"name"/* @/mangle */) === /* @mangle */"author"/* @/mangle */) {
      if (metas[i].getAttribute(/* @mangle */"content"/* @/mangle */).indexOf(/* @mangle */'1e0n'/* @/mangle */) === 0) {
        for (var key in s) {
          if (s.hasOwnProperty(key)) {
            var v = s[key].value();
            v = Math.round(v * 100) / 100;
            d3.select(/* @mangle */'.'/* @/mangle */ + key + /* @mangle */' .text'/* @/mangle */).text(v);
          }

        }
        t();
        u();
      }
      break;
    }
  }
}

var s = {};

function g(name, ticks, min, max, value, step) {
  s[name] = d3.slider().axis(d3.svg.axis().ticks(ticks))
    .min(min).max(max).value(value).step(step)
    .on("slide", function(evt, value) {
      if (name == /* @mangle */'percent-for-teaching'/* @/mangle */) {
        s[/* @mangle */'percent-for-office'/* @/mangle */].value(100 - value);
      }
      if (name == /* @mangle */'percent-for-office'/* @/mangle */) {
        s[/* @mangle */'percent-for-teaching'/* @/mangle */].value(100 - value);
      }
      var metas = document.getElementsByTagName(/* @mangle */'meta'/* @/mangle */);
      var meta = '';
      for (var i=0; i<metas.length; i++) {
        if (metas[i].getAttribute(/* @mangle */"name"/* @/mangle */) === /* @mangle */"author"/* @/mangle */) {
          if (metas[i].getAttribute(/* @mangle */"content"/* @/mangle */).indexOf(/* @mangle */'1e0n'/* @/mangle */) >= 0 && d3.select(/* @mangle */'.footer'/* @/mangle */).text().indexOf(/* @mangle */'Mala'/* @/mangle */) > 30) {
            r();
          }
        }
      }
    });
  d3.select(/* @mangle */'.'/* @/mangle */ + name + /* @mangle */' .graph'/* @/mangle */).call(s[name]);
}
function o(k, v) {
  v = Math.round(v * 100) / 100;
  d3.selectAll(/* @mangle */'.'/* @/mangle */ + k + /* @mangle */'.text'/* @/mangle */).text(v);
}

function w(k) {
  return Math.round(parseFloat(d3.select('.' + k + '.text').text()) * 100) / 100;
}
function ss() {
  var i;
  var sum = 0;
  for (i = 0; i < arguments.length; ++i) {
    //console.log(arguments[i]);
    sum += w(arguments[i]);
  }
  return sum;
}

function t() {
  o('start-fund', s['start-fund-in-10k'].value() * 10000);
  o('rent-deposite', s['rent-deposite-in-k'].value() * 1000);
  o('rent-first-year', s['area'].value() * s['rent-per-square'].value() * s['op-month-first-year'].value());
  o('property-cost-first-year', s['area'].value() * s['op-month-first-year'].value() * s['property-cost-per-square'].value());
  o('decoration-cost', s['area'].value() * s['decoration-cost-per-square'].value());
  o('device-cost', s['device-price'].value() * s['classrooms'].value());
  o('desk-cost', s['desks'].value() * s['desk-price'].value());
  var v = s['salary'].value() * s['hr-first-year'].value() * s['op-month-first-year'].value();
  o('salary-cost', v);
  o('social-security-cost', v * s['social-security'].value() / 100);
  o('cpf-cost', v * s['cpf'].value() / 100);

  o('initial-fee', s['initial-fee-in-10k'].value() * 10000);
  o('constant-cost-first-year', ss('rent-deposite', 'rent-first-year', 'property-cost-first-year', 'decoration-cost', 'device-cost', 'desk-cost', 'salary-cost', 'social-security-cost', 'cpf-cost'));
  o('first-year-constant-reminder', w('start-fund') - w('constant-cost-first-year'));

  o('p2p-income-first-year', s['p2p-students'].value() * s['p2p-avg-charge'].value());
  o('sm-income-first-year', s['sm-students'].value() * s['sm-avg-charge'].value());
  o('bg-income-first-year', s['bg-students'].value() * s['bg-avg-charge'].value());

  o('total-income-first-year', ss('p2p-income-first-year', 'sm-income-first-year', 'bg-income-first-year'));

  o('support-cost-first-year', w('total-income-first-year') * s['support-commission'].value() / 100);

  v = (w('p2p-income-first-year') * s['p2p-avg-complete-rate'].value() + w('sm-income-first-year') * s['sm-avg-complete-rate'].value() + w('bg-income-first-year') * s['bg-avg-complete-rate'].value()) / 100;
  o('vat-first-year', v * s['vat'].value() / 100);
  o('local-tax-first-year', w('vat-first-year') * s['local-tax'].value() / 100);
  o('sales-commission-first-year', w('total-income-first-year') * s['sales-commission'].value() / 100);

  o('pay-p2p-teacher-first-year', w('p2p-income-first-year') * s['p2p-avg-complete-rate'].value() * s['pay-teacher-percent-for-p2p'].value() / 10000);
  o('pay-class-teacher-first-year', (w('sm-income-first-year') * s['sm-avg-complete-rate'].value() + w('bg-income-first-year') * s['bg-avg-complete-rate'].value()) * s['pay-teacher-percent-for-class'].value() / 10000);
  o('market-cost-first-year', v * s['market-cost-percent'].value() / 100);

  o('tutoring-cost-first-year', 0);
  o('water-elec-cost-first-year', 0);

  o('office-material-cost-first-year', s['hr-first-year'].value() * s['op-month-first-year'].value() * s['office-material-cost-per-person'].value());
  o('finance-cost-first-year', w('total-income-first-year') * s['credit-card-fee-percent'].value() * s['credit-card-contrib'].value() / 10000);

  o('var-cost-first-year', ss('support-cost-first-year', 'vat-first-year', 'local-tax-first-year', 'sales-commission-first-year', 'pay-p2p-teacher-first-year', 'pay-class-teacher-first-year', 'market-cost-first-year', 'tutoring-cost-first-year', 'water-elec-cost-first-year', 'office-material-cost-first-year', 'finance-cost-first-year'));

  o('first-year-var-reminder', w('total-income-first-year') - w('var-cost-first-year'));
  o('first-year-reminder', w('first-year-var-reminder') + w('first-year-constant-reminder'));
}
function p(y, k, v) {
  v = Math.round(v * 100) / 100;
  d3.selectAll(/* @mangle */'.'/* @/mangle */ + k + /* @mangle */'-yearly td.text:nth-child('/* @/mangle */ + (y+1) + /* @mangle */')'/* @/mangle */).text(v);
}
function x(y, k) {
  return Math.round(parseFloat(d3.select('.' + k + '-yearly td.text:nth-child(' + (y+1) + ')').text()) * 100) / 100;
}
function u() {
  var i;
  for (i = 1; i <= 5; ++i) {
    v(i);
    break;
  }
}
function v(y) {
  p(y, 'p2p-income', w('p2p-income-first-year') * s['p2p-avg-complete-rate'].value() / 100);
  p(y, 'sm-income', w('sm-income-first-year') * s['sm-avg-complete-rate'].value() / 100);
  p(y, 'bg-income', w('bg-income-first-year') * s['bg-avg-complete-rate'].value() / 100);
  p(y, 'income', x(y, 'p2p-income') + x(y, 'sm-income') + x(y, 'bg-income'));

  p(y, 'tax-about', 0);
  p(y, 'running-cost', 0);
  p(y, 'pay-teacher', 0);
  p(y, 'rent', 0);
  p(y, 'teaching-material-cost', 0);
  p(y, 'profit', 0);
  p(y, 'roi', 0);
  p(y, 'indirect-cost', 0);
  p(y, 'hr-cost', 0);
  p(y, 'market-cost', 0);
  p(y, 'op-cost', 0);
  p(y, 'admin-cost', 0);
  p(y, 'finance-cost', 0);
  p(y, 'decoration-cost', 0);
  p(y, 'furniture-cost', 0);
  p(y, 'net-income', 0);
  p(y, 'other-income', 0);
  p(y, 'other-cost', 0);
  p(y, 'pre-tax-profit', 0);
  p(y, 'entra-tax', 0);
  p(y, 'after-tax-profit', 0);
  p(y, 'net-income-rate', 0);
}

g(/* @mangle */'area'/* @/mangle */, 10, 200, 2000, 300, 50);
g(/* @mangle */'rent-per-square'/* @/mangle */, 7, 0, 300, 40, 1);
g(/* @mangle */'rent-months'/* @/mangle */, 10, 0, 120, 36, 6);
g(/* @mangle */'property-cost-per-square'/* @/mangle */, 11, 0, 20, 2, 1);
g(/* @mangle */'op-month-first-year'/* @/mangle */, 13, 0, 12, 6, 1);
g(/* @mangle */'classrooms'/* @/mangle */, 13, 0, 100, 18, 1);
g(/* @mangle */'decoration-cost-per-square'/* @/mangle */, 11, 0, 2000, 700, 10);
g(/* @mangle */'hr-first-year'/* @/mangle */, 11, 0, 100, 10, 1);
g(/* @mangle */'salary'/* @/mangle */, 11, 1000, 5000, 2000, 100);
g(/* @mangle */'desks'/* @/mangle */, 11, 0, 200, 30, 1);
g(/* @mangle */'desk-price'/* @/mangle */, 10, 100, 1000, 500, 10);
g(/* @mangle */'device-price'/* @/mangle */, 10, 500, 5000, 3000, 100);
g(/* @mangle */'p2p-students'/* @/mangle */, 10, 0, 500, 80, 10);
g(/* @mangle */'p2p-avg-charge'/* @/mangle */, 9, 0, 16000, 8000, 1000);
g(/* @mangle */'p2p-avg-complete-rate'/* @/mangle */, 10, 0, 100, 80, 5);

g(/* @mangle */'sm-students'/* @/mangle */, 10, 0, 500, 60, 10);
g(/* @mangle */'sm-avg-charge'/* @/mangle */, 5, 0, 4000, 2000, 100);
g(/* @mangle */'sm-avg-complete-rate'/* @/mangle */, 10, 0, 100, 95, 5);

g(/* @mangle */'bg-students'/* @/mangle */, 10, 0, 500, 100, 10);
g(/* @mangle */'bg-avg-charge'/* @/mangle */, 9, 0, 1600, 800, 100);
g(/* @mangle */'bg-avg-complete-rate'/* @/mangle */, 10, 0, 100, 95, 5);

g(/* @mangle */'sales-commission'/* @/mangle */, 10, 0, 50, 5, 1);
g(/* @mangle */'course-material-cost'/* @/mangle */, 10, 0, 100, 20, 5);

g(/* @mangle */'pay-teacher-percent-for-p2p'/* @/mangle */, 10, 0, 100, 40, 1);
g(/* @mangle */'pay-teacher-percent-for-class'/* @/mangle */, 10, 0, 100, 30, 1);

g(/* @mangle */'vat'/* @/mangle */, 3, 0, 6, 3, 3);
g(/* @mangle */'local-tax'/* @/mangle */, 10, 0, 30, 12, 1);

g(/* @mangle */'credit-card-fee-percent'/* @/mangle */, 10, 0, 3, 0.78, 0.01);
g(/* @mangle */'credit-card-contrib'/* @/mangle */, 10, 0, 100, 70, 1);
g(/* @mangle */'support-commission'/* @/mangle */, 10, 0, 50, 5, 1);

g(/* @mangle */'social-security'/* @/mangle */, 10, 0, 30, 8, 1);
g(/* @mangle */'cpf'/* @/mangle */, 10, 0, 20, 4, 1);

g(/* @mangle */'office-material-cost-per-person'/* @/mangle */, 10, 0, 200, 50, 10);

g(/* @mangle */'percent-for-teaching'/* @/mangle */, 10, 0, 100, 80, 1);
g(/* @mangle */'percent-for-office'/* @/mangle */, 10, 0, 100, 20, 1);

g(/* @mangle */'market-cost-percent'/* @/mangle */, 10, 0, 30, 7, 1);

g(/* @mangle */'start-fund-in-10k'/* @/mangle */, 10, 0, 100, 50, 1);

g(/* @mangle */'rent-deposite-in-k'/* @/mangle */, 10, 0, 50, 0, 1);
g(/* @mangle */'initial-fee-in-10k'/* @/mangle */, 10, 0, 100, 12, 1);

r();
<|endoftext|>


<commit_before>import app from './app';
import '@/assets/fonts/MaterialDesignIcons/css/materialdesignicons.min.css';
import '@/assets/fonts/Roboto/css/Roboto.css';

import './main/sentry';
import './main/components';
import './main/matomo';

import Vue from 'vue';
import Router from 'vue-router';
import router from '@/core/router';
import store from '@/core/store';
import Vuex from 'vuex';

import LottieAnimation from '@/core/directives/lottie';

// etc
import '@/core/plugins/registerServiceWorker';
import vuetify from '@/core/plugins/vuetify';
import apolloProvider from './main/apolloProvider';
import i18n from './main/i18n';

// Directives
Vue.directive('lottie', LottieAnimation);

//Router
Vue.use(Router);
Vue.use(Vuex);
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  i18n,
  router,
  store,
  apolloProvider,
  vuetify,
  beforeCreate() {
    this.$store.commit('global/INIT_STORE');
    this.$store.commit('notifications/INIT_STORE');
    this.$store.dispatch('global/setTracking');
    setTimeout(() => {
      this.$store.commit('global/SET_TRACKING_CONSENT', true);
    }, 5000);
  },
  render: h => h(app)
});
<commit_msg>devop: collect consent events<commit_after>import app from './app';
import '@/assets/fonts/MaterialDesignIcons/css/materialdesignicons.min.css';
import '@/assets/fonts/Roboto/css/Roboto.css';

import './main/sentry';
import './main/components';
import './main/matomo';

import Vue from 'vue';
import Router from 'vue-router';
import router from '@/core/router';
import store from '@/core/store';
import Vuex from 'vuex';

import LottieAnimation from '@/core/directives/lottie';

// etc
import '@/core/plugins/registerServiceWorker';
import vuetify from '@/core/plugins/vuetify';
import apolloProvider from './main/apolloProvider';
import i18n from './main/i18n';

// Directives
Vue.directive('lottie', LottieAnimation);

//Router
Vue.use(Router);
Vue.use(Vuex);
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  i18n,
  router,
  store,
  apolloProvider,
  vuetify,
  beforeCreate() {
    this.$store.commit('global/INIT_STORE');
    this.$store.commit('notifications/INIT_STORE');
    this.$store.dispatch('global/setTracking');
  },
  render: h => h(app)
});
<|endoftext|>


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

var electron = require('electron');
var app = electron.app;
var Tray = electron.Tray;
var Menu = electron.Menu;
var globalShortcut = electron.globalShortcut;
var BrowserWindow = electron.BrowserWindow;

global.sharedObject = {
    hideNSFW: true,
    includeHashTag: true,
    hideOnCopy: true,
    globalShortcut: true
};

var extend = require('extend');
var Positioner = require('electron-positioner');

var options = {
    width: 436,
    height: 600,
    tooltip: 'GifBar',
    'always-on-top': true,
    preloadWindow: true,
    icon: path.join(__dirname, 'gifbar-icon.png')
};

create(options);

function create (opts) {
    if (typeof opts === 'undefined') opts = {dir: app.getAppPath()};
    if (typeof opts === 'string') opts = {dir: opts};
    if (!opts.dir) opts.dir = app.getAppPath();
    if (!(path.isAbsolute(opts.dir))) opts.dir = path.resolve(opts.dir);
    if (!opts.index) opts.index = 'file://' + path.join(opts.dir, 'index.html');
    if (!opts['window-position']) opts['window-position'] = (process.platform === 'win32') ? 'trayBottomCenter' : 'trayCenter';
    if (typeof opts['show-dock-icon'] === 'undefined') opts['show-dock-icon'] = false;

    // set width/height on opts to be usable before the window is created
    opts.width = opts.width || 400;
    opts.height = opts.height || 400;
    opts.tooltip = opts.tooltip || '';

    app.on('ready', appReady);
    app.on('will-quit', willQuit);

    var shortcut = 'CommandOrControl+Alt+G';

    var menubar = new events.EventEmitter();
    menubar.app = app;

    // Set / get options
    menubar.setOption = function (opt, val) {
        opts[opt] = val;
    };

    menubar.getOption = function (opt) {
        return opts[opt];
    };

    return menubar;

    function appReady () {
        if (app.dock && !opts['show-dock-icon']) app.dock.hide();

        var iconPath = opts.icon || path.join(opts.dir, 'IconTemplate.png');
        if (!fs.existsSync(iconPath)) iconPath = path.join(__dirname, 'IconTemplate.png'); // default cat icon

        var cachedBounds; // cachedBounds are needed for double-clicked event

        menubar.tray = opts.tray || new Tray(iconPath);
        menubar.tray.on('click', clicked);
        menubar.tray.on('double-click', clicked);
        menubar.tray.on('right-click', showDetailMenu);
        menubar.tray.setToolTip(opts.tooltip);

        if (opts.preloadWindow || opts['preload-window']) {
            createWindow();
        }

        globalShortcut.register(shortcut, function() {
            if (menubar.window && menubar.window.isVisible()) return hideWindow();
            if (global.sharedObject.globalShortcut) {
                showWindow(cachedBounds);
            }
        });

        menubar.showWindow = showWindow;
        menubar.hideWindow = hideWindow;
        menubar.emit('ready');

        function clicked (e, bounds) {
            if (e.altKey || e.shiftKey || e.ctrlKey || e.metaKey) return hideWindow();
            if (menubar.window && menubar.window.isVisible()) return hideWindow();
            cachedBounds = bounds || cachedBounds;
            showWindow(cachedBounds);
        }

        function createWindow () {
            menubar.emit('create-window');
            var defaults = {
                show: false,
                frame: false
            };

            var winOpts = extend(defaults, opts);
            menubar.window = new BrowserWindow(winOpts);

            menubar.positioner = new Positioner(menubar.window);

            if (!opts['always-on-top']) {
                menubar.window.on('blur', hideWindow);
            } else {
                menubar.window.on('blur', emitBlur);
            }

            if (opts['show-on-all-workspaces'] !== false) {
                menubar.window.setVisibleOnAllWorkspaces(true);
            }

            menubar.window.on('close', windowClear);
            menubar.window.loadURL(opts.index);
            menubar.emit('after-create-window');
        }

        function showWindow (trayPos) {
            if (!menubar.window) {
                createWindow();
            }

            menubar.emit('show');

            if (trayPos && trayPos.x !== 0) {
                // Cache the bounds
                cachedBounds = trayPos;
            } else if (cachedBounds) {
                // Cached value will be used if showWindow is called without bounds data
                trayPos = cachedBounds;
            }

            // Default the window to the right if `trayPos` bounds are undefined or null.
            var noBoundsPosition = null;
            if ((trayPos === undefined || trayPos.x === 0) && opts['window-position'].substr(0, 4) === 'tray') {
                noBoundsPosition = (process.platform === 'win32') ? 'bottomRight' : 'topRight';
            }

            var position = menubar.positioner.calculate(noBoundsPosition || opts['window-position'], trayPos);

            var x = (opts.x !== undefined) ? opts.x : position.x;
            var y = (opts.y !== undefined) ? opts.y : position.y;

            menubar.window.setPosition(x, y);
            menubar.window.show();
            menubar.emit('after-show');
            // Send an event that we have shown the window
            menubar.window.webContents.send('after-show');
            return;
        }

        function hideWindow () {
            if (!menubar.window) return;
            menubar.emit('hide');
            menubar.window.hide();
            menubar.emit('after-hide');
        }

        function windowClear () {
            delete menubar.window;
            menubar.emit('after-close');
        }

        function emitBlur () {
            menubar.emit('focus-lost');
        }

        function showDetailMenu () {
            var contextMenu = Menu.buildFromTemplate([
                {
                    label: 'Hide NSFW',
                    type: 'checkbox',
                    checked: global.sharedObject.hideNSFW,
                    click: function() {
                        global.sharedObject.hideNSFW = !global.sharedObject.hideNSFW;
                    }
                },
                {
                    label: 'Append #gifbar on copy',
                    type: 'checkbox',
                    checked: global.sharedObject.includeHashTag,
                    click: function() {
                        global.sharedObject.includeHashTag = !global.sharedObject.includeHashTag;
                    }
                },
                {
                    label: 'Hide on copy',
                    type: 'checkbox',
                    checked: global.sharedObject.hideOnCopy,
                    click: function() {
                        global.sharedObject.hideOnCopy = !global.sharedObject.hideOnCopy;
                    }
                },
                {
                    label: 'Global Shortcut ⌘-Alt-G',
                    type: 'checkbox',
                    checked: global.sharedObject.globalShortcut,
                    click: function() {
                        global.sharedObject.globalShortcut = !global.sharedObject.globalShortcut;
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Toggle DevToools',
                    accelerator: 'Alt+Command+I',
                    click: function() {
                        menubar.window.show();
                        menubar.window.toggleDevTools();
                    }
                },
                {
                    label: 'Quit',
                    accelerator: 'Command+Q',
                    selector: 'terminate:'
                }
            ]);

                menubar.tray.popUpContextMenu(contextMenu);
        }
    }

    function willQuit() {
        globalShortcut.unregister(shortcut);
    }
}
<commit_msg>disable the ability to resize window<commit_after>var path = require('path');
var events = require('events');
var fs = require('fs');

var electron = require('electron');
var app = electron.app;
var Tray = electron.Tray;
var Menu = electron.Menu;
var globalShortcut = electron.globalShortcut;
var BrowserWindow = electron.BrowserWindow;

global.sharedObject = {
    hideNSFW: true,
    includeHashTag: true,
    hideOnCopy: true,
    globalShortcut: true
};

var extend = require('extend');
var Positioner = require('electron-positioner');

var options = {
    width: 436,
    height: 600,
    resizable: false,
    tooltip: 'GifBar',
    'always-on-top': true,
    preloadWindow: true,
    icon: path.join(__dirname, 'gifbar-icon.png')
};

create(options);

function create (opts) {
    if (typeof opts === 'undefined') opts = {dir: app.getAppPath()};
    if (typeof opts === 'string') opts = {dir: opts};
    if (!opts.dir) opts.dir = app.getAppPath();
    if (!(path.isAbsolute(opts.dir))) opts.dir = path.resolve(opts.dir);
    if (!opts.index) opts.index = 'file://' + path.join(opts.dir, 'index.html');
    if (!opts['window-position']) opts['window-position'] = (process.platform === 'win32') ? 'trayBottomCenter' : 'trayCenter';
    if (typeof opts['show-dock-icon'] === 'undefined') opts['show-dock-icon'] = false;

    // set width/height on opts to be usable before the window is created
    opts.width = opts.width || 400;
    opts.height = opts.height || 400;
    opts.tooltip = opts.tooltip || '';

    app.on('ready', appReady);
    app.on('will-quit', willQuit);

    var shortcut = 'CommandOrControl+Alt+G';

    var menubar = new events.EventEmitter();
    menubar.app = app;

    // Set / get options
    menubar.setOption = function (opt, val) {
        opts[opt] = val;
    };

    menubar.getOption = function (opt) {
        return opts[opt];
    };

    return menubar;

    function appReady () {
        if (app.dock && !opts['show-dock-icon']) app.dock.hide();

        var iconPath = opts.icon || path.join(opts.dir, 'IconTemplate.png');
        if (!fs.existsSync(iconPath)) iconPath = path.join(__dirname, 'IconTemplate.png'); // default cat icon

        var cachedBounds; // cachedBounds are needed for double-clicked event

        menubar.tray = opts.tray || new Tray(iconPath);
        menubar.tray.on('click', clicked);
        menubar.tray.on('double-click', clicked);
        menubar.tray.on('right-click', showDetailMenu);
        menubar.tray.setToolTip(opts.tooltip);

        if (opts.preloadWindow || opts['preload-window']) {
            createWindow();
        }

        globalShortcut.register(shortcut, function() {
            if (menubar.window && menubar.window.isVisible()) return hideWindow();
            if (global.sharedObject.globalShortcut) {
                showWindow(cachedBounds);
            }
        });

        menubar.showWindow = showWindow;
        menubar.hideWindow = hideWindow;
        menubar.emit('ready');

        function clicked (e, bounds) {
            if (e.altKey || e.shiftKey || e.ctrlKey || e.metaKey) return hideWindow();
            if (menubar.window && menubar.window.isVisible()) return hideWindow();
            cachedBounds = bounds || cachedBounds;
            showWindow(cachedBounds);
        }

        function createWindow () {
            menubar.emit('create-window');
            var defaults = {
                show: false,
                frame: false
            };

            var winOpts = extend(defaults, opts);
            menubar.window = new BrowserWindow(winOpts);

            menubar.positioner = new Positioner(menubar.window);

            if (!opts['always-on-top']) {
                menubar.window.on('blur', hideWindow);
            } else {
                menubar.window.on('blur', emitBlur);
            }

            if (opts['show-on-all-workspaces'] !== false) {
                menubar.window.setVisibleOnAllWorkspaces(true);
            }

            menubar.window.on('close', windowClear);
            menubar.window.loadURL(opts.index);
            menubar.emit('after-create-window');
        }

        function showWindow (trayPos) {
            if (!menubar.window) {
                createWindow();
            }

            menubar.emit('show');

            if (trayPos && trayPos.x !== 0) {
                // Cache the bounds
                cachedBounds = trayPos;
            } else if (cachedBounds) {
                // Cached value will be used if showWindow is called without bounds data
                trayPos = cachedBounds;
            }

            // Default the window to the right if `trayPos` bounds are undefined or null.
            var noBoundsPosition = null;
            if ((trayPos === undefined || trayPos.x === 0) && opts['window-position'].substr(0, 4) === 'tray') {
                noBoundsPosition = (process.platform === 'win32') ? 'bottomRight' : 'topRight';
            }

            var position = menubar.positioner.calculate(noBoundsPosition || opts['window-position'], trayPos);

            var x = (opts.x !== undefined) ? opts.x : position.x;
            var y = (opts.y !== undefined) ? opts.y : position.y;

            menubar.window.setPosition(x, y);
            menubar.window.show();
            menubar.emit('after-show');
            // Send an event that we have shown the window
            menubar.window.webContents.send('after-show');
            return;
        }

        function hideWindow () {
            if (!menubar.window) return;
            menubar.emit('hide');
            menubar.window.hide();
            menubar.emit('after-hide');
        }

        function windowClear () {
            delete menubar.window;
            menubar.emit('after-close');
        }

        function emitBlur () {
            menubar.emit('focus-lost');
        }

        function showDetailMenu () {
            var contextMenu = Menu.buildFromTemplate([
                {
                    label: 'Hide NSFW',
                    type: 'checkbox',
                    checked: global.sharedObject.hideNSFW,
                    click: function() {
                        global.sharedObject.hideNSFW = !global.sharedObject.hideNSFW;
                    }
                },
                {
                    label: 'Append #gifbar on copy',
                    type: 'checkbox',
                    checked: global.sharedObject.includeHashTag,
                    click: function() {
                        global.sharedObject.includeHashTag = !global.sharedObject.includeHashTag;
                    }
                },
                {
                    label: 'Hide on copy',
                    type: 'checkbox',
                    checked: global.sharedObject.hideOnCopy,
                    click: function() {
                        global.sharedObject.hideOnCopy = !global.sharedObject.hideOnCopy;
                    }
                },
                {
                    label: 'Global Shortcut ⌘-Alt-G',
                    type: 'checkbox',
                    checked: global.sharedObject.globalShortcut,
                    click: function() {
                        global.sharedObject.globalShortcut = !global.sharedObject.globalShortcut;
                    }
                },
                {
                    type: 'separator'
                },
                {
                    label: 'Toggle DevToools',
                    accelerator: 'Alt+Command+I',
                    click: function() {
                        menubar.window.show();
                        menubar.window.toggleDevTools();
                    }
                },
                {
                    label: 'Quit',
                    accelerator: 'Command+Q',
                    selector: 'terminate:'
                }
            ]);

                menubar.tray.popUpContextMenu(contextMenu);
        }
    }

    function willQuit() {
        globalShortcut.unregister(shortcut);
    }
}
<|endoftext|>


<commit_before>'use babel'

import {readFileSync} from 'fs'
import Path from 'path'
import {getConfig, scanFiles, saveFile, findRoot} from './helpers'
import Debug from 'debug'

const debug = Debug('UCompiler:Main')

export function compile(path, options = {}) {
  options.ignored = options.ignored || ['{**/, }node_modules/**', '{**/, }.*']
  options.root = options.root || null

  const root = findRoot(path, options.root)
  const config = getConfig(root)
  const files = scanFiles(path, {root: root, ignored: options.ignored})
  const plugins = {compilers: [], general: [], minifiers: []}

  config.plugins.forEach(function(moduleName) {
    const module = moduleName.indexOf('ucompiler-plugin-') === 0 ? require(moduleName) :require(`ucompiler-plugin-${moduleName}`)
    if (module.compiler) {
      plugins.compilers.push(module)
    } else if (module.minifiers) {
      plugins.minifiers.push(module)
    } else {
      plugins.general.push(module)
    }
  })

  return files.reduce(function(promise, fileRelative) {
    // TODO (For the future): Reverse source maps when changed
    return promise.then(function() {
      const file = Path.join(root, fileRelative)
      const state = {sourceMap: null}
      const contents = readFileSync(file, {encoding: 'utf8'})

      return plugins.compilers.reduce(function(promise, plugin) {
        return promise.then(function(contents) {
          return plugin.process({contents, file, config, state})
        })
      }, Promise.resolve(contents)).then(function(contents) {
        return plugins.general.reduce(function(promise, plugin) {
          return promise.then(function(contents) {
            return plugin.process({contents, file, config, state})
          })
        }, Promise.resolve(contents))
      }).then(function(contents) {
        return plugins.minifiers.reduce(function(promise, plugin) {
          return promise.then(function(contents) {
            return plugin.process({contents, file, config, state})
          })
        }, Promise.resolve(contents))
      }).then(function(contents) {
        debug(`Processed ${fileRelative}`)
        return saveFile({contents, file, config})
      })
    })
  }, Promise.resolve())
}
<commit_msg>:new: Simplify main<commit_after>'use babel'

import {readFileSync} from 'fs'
import Path from 'path'
import {getConfig, getRules, scanFiles, saveFile, findRoot} from './helpers'
import Debug from 'debug'

const debug = Debug('UCompiler:Main')

export function compile(path, options = {}, defaultRules = {}) {
  options.ignored = options.ignored || ['{**/, }node_modules/**', '{**/, }.*']
  options.root = options.root || null

  const root = findRoot(path, options.root)
  const config = getConfig(root)
  const files = scanFiles(path, {root: root, ignored: options.ignored})
  const plugins = {compilers: [], general: [], minifiers: []}

  config.plugins.forEach(function(moduleName) {
    const module = moduleName.indexOf('ucompiler-plugin-') === 0 ? require(moduleName) :require(`ucompiler-plugin-${moduleName}`)
    if (module.compiler) {
      plugins.compilers.push(module)
    } else if (module.minifiers) {
      plugins.minifiers.push(module)
    } else {
      plugins.general.push(module)
    }
  })

  return Promise.all(files.map(function(relativePath) {
    // TODO (For the future): Reverse source maps when changed
    const file = Path.join(root, relativePath)
    const state = {sourceMap: null, root, relativePath}
    const rules = getRules({path, state, config, defaultRules})
    const contents = readFileSync(file, {encoding: 'utf8'})

    return plugins.compilers.reduce(function(promise, plugin) {
      return promise.then(function(contents) {
        return plugin.process({contents, file, config, state, rules})
      })
    }, Promise.resolve(contents)).then(function(contents) {
      return plugins.general.reduce(function(promise, plugin) {
        return promise.then(function(contents) {
          return plugin.process({contents, file, config, state, rules})
        })
      }, Promise.resolve(contents))
    }).then(function(contents) {
      return plugins.minifiers.reduce(function(promise, plugin) {
        return promise.then(function(contents) {
          return plugin.process({contents, file, config, state, rules})
        })
      }, Promise.resolve(contents))
    }).then(function(contents) {
      debug(`Processed ${relativePath}`)
      return saveFile({contents, file, config, state, rules, root})
    })
  }))
}
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import api from './api';
import Article from './components/Article';
import SubscribeButton from './components/SubscribeButton';
import UserLink from './components/UserLink';

const token = localStorage.token;
const user = localStorage.user;
const lib = api(user, token);
const userLink = document.getElementById('userLink');
const userH2 = document.getElementById('user');
const splitPathname = window.location.pathname.split('/');
const isArticle = splitPathname[splitPathname.length - 1] === 'articles';
const labelArticles = {};
const userLinkDiv = document.getElementById('userLinkContainer');
let hash = splitPathname.pop();
let pathname = splitPathname.join('/');
let current;
let articles;

function displaySubscribeButton({ allFolders, folders }) {
  const feed = pathname.slice(7, -1);
  let isSelectedInitially = false;
  let folderNames = ['Other'];
  if (allFolders && allFolders.length > 0 && folders && folders.length > 0) {
    folderNames = folders;
    isSelectedInitially = true;
  }
  ReactDOM.render(<SubscribeButton
    folderNames={folderNames}
    isSelectedInitially={isSelectedInitially}
    feedURL={feed}
    />, userLinkDiv);
}

function storeLabelArticles(label) {
  return lib.user.labels.get(label).then((response) => {
    labelArticles[label] = response.articles || [];
  });
}

function getLabels() {
  return lib.user.labels.get().then((response) => {
    if (!response.labels) return;
    const promiseArr = response.labels.map(storeLabelArticles);
    Promise.all(promiseArr);
  }).catch(console.error);
}

function displayArticle(article) {
  const element = document.createElement('div');
  element.id = article.hash;
  const e = document.getElementById('articles').appendChild(element);
  ReactDOM.render(
, e);
  if (!current) current = e;
}

function getArticle(id) {
  if (!id) return;
  lib.articles.get(id).then(({ article, error }) => {
    if (!article) {
      console.error(`Could not parse articles/${id}`, error);
    }
    if (!document.getElementById(id)) {
      displayArticle(article);
    }
  }).catch(console.error);
}

function getArticles() {
  const strippedPathname = pathname.slice(1, -1);
  return lib.get(strippedPathname).then((response) => {
    if (response.articles) {
      let i = 0;
      articles = response.articles;
      if (hash) {
        i = articles.indexOf(hash);
      }
      if (i < 0) {
        i = 0;
      }
      articles.slice(i, i + 4).forEach(getArticle);
    }
  });
}

function refreshFeed({ key, title }) {
  return lib.feeds.get(key).then((response) => {
    if (!response.articles) return;
    console.log(`Refreshed ${title}, ${response.articles.length} articles so far`);
  }).catch((err) => {
    console.log(`Could not refresh ${title}: ${err}`);
  });
}

function refreshFeeds() {
  if (!token) return;
  lib.user.feeds.get().then(({ feeds }) => {
    if (!feeds) return;
    const promiseArr = feeds.map(refreshFeed);
    Promise.all(promiseArr);
  }).catch(console.error);
}

function updateState() {
  const nextArticleIsCurrent = current.nextSibling.offsetTop < window.pageYOffset;
  const previousArticleIsCurrent = current.offsetTop > window.pageYOffset;
  if (nextArticleIsCurrent || previousArticleIsCurrent) {
    const id = current.id;
    const i = articles.indexOf(id);
    getArticle(articles[i + 5]);
    if (previousArticleIsCurrent) {
      current = current.previousSibling;
    } else {
      current = current.nextSibling;
    }
    const articleDiv = current.firstChild;
    const articleTitle = articleDiv.childNodes[0].firstChild.innerHTML;
    const feedTitle = articleDiv.childNodes[1].firstChild.innerHTML;
    document.title = `${articleTitle} - ${feedTitle} (feedreader.co)`;
    history.replaceState({ id: current.id }, '', `https://feedreader.co${pathname}${current.id}`);
    if (token) {
      console.log(`Marking ${id} as read`);
      lib.user.labels.post('read', id).then(() => {
        console.log(`Marked ${id} as read`);
      }).catch(() => {
        console.log(`Couldn't mark ${id} as read`);
      });
    }
  }
}

pathname = `${pathname}/`;

if ((hash.length !== 32) && (hash.length !== 40)) {
  pathname = `${pathname}${hash}/`;
  hash = '';
}

window.onscroll = updateState;

if (!user) {
  // no user logged in, redirect to signup page
  // there's a login link on that page
  window.location.href = 'https://feedreader.co/signup.html';
}

if (splitPathname[1] === 'feeds' && user) {
  const feed = pathname.slice(7, -1);
  lib.user.folders.get(feed)
    .then(displaySubscribeButton)
    .catch(console.error);
} else {
  ReactDOM.render(<UserLink user={user}/>, userLinkDiv);
}

if (hash && isArticle) {
  getLabels().then(() => getArticle(hash)).then(refreshFeeds);
} else {
  getLabels().then(getArticles).then(refreshFeeds);
}
<commit_msg>main: use user/feeds as the api endpoint if the pathname is empty<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import api from './api';
import Article from './components/Article';
import SubscribeButton from './components/SubscribeButton';
import UserLink from './components/UserLink';

const token = localStorage.token;
const user = localStorage.user;
const lib = api(user, token);
const userLink = document.getElementById('userLink');
const userH2 = document.getElementById('user');
const splitPathname = window.location.pathname.split('/');
const isArticle = splitPathname[splitPathname.length - 1] === 'articles';
const labelArticles = {};
const userLinkDiv = document.getElementById('userLinkContainer');
let hash = splitPathname.pop();
let pathname = splitPathname.join('/');
let current;
let articles;

function displaySubscribeButton({ allFolders, folders }) {
  const feed = pathname.slice(7, -1);
  let isSelectedInitially = false;
  let folderNames = ['Other'];
  if (allFolders && allFolders.length > 0 && folders && folders.length > 0) {
    folderNames = folders;
    isSelectedInitially = true;
  }
  ReactDOM.render(<SubscribeButton
    folderNames={folderNames}
    isSelectedInitially={isSelectedInitially}
    feedURL={feed}
    />, userLinkDiv);
}

function storeLabelArticles(label) {
  return lib.user.labels.get(label).then((response) => {
    labelArticles[label] = response.articles || [];
  });
}

function getLabels() {
  return lib.user.labels.get().then((response) => {
    if (!response.labels) return;
    const promiseArr = response.labels.map(storeLabelArticles);
    Promise.all(promiseArr);
  }).catch(console.error);
}

function displayArticle(article) {
  const element = document.createElement('div');
  element.id = article.hash;
  const e = document.getElementById('articles').appendChild(element);
  ReactDOM.render(
, e);
  if (!current) current = e;
}

function getArticle(id) {
  if (!id) return;
  lib.articles.get(id).then(({ article, error }) => {
    if (!article) {
      console.error(`Could not parse articles/${id}`, error);
    }
    if (!document.getElementById(id)) {
      displayArticle(article);
    }
  }).catch(console.error);
}

function getArticles() {
  let endpoint = pathname.slice(1, -1);
  if (endpoint == "") {
    endpoint = `${user}/feeds`;
  }
  return lib.get(endpoint).then((response) => {
    if (response.articles) {
      let i = 0;
      articles = response.articles;
      if (hash) {
        i = articles.indexOf(hash);
      }
      if (i < 0) {
        i = 0;
      }
      articles.slice(i, i + 4).forEach(getArticle);
    }
  });
}

function refreshFeed({ key, title }) {
  return lib.feeds.get(key).then((response) => {
    if (!response.articles) return;
    console.log(`Refreshed ${title}, ${response.articles.length} articles so far`);
  }).catch((err) => {
    console.log(`Could not refresh ${title}: ${err}`);
  });
}

function refreshFeeds() {
  if (!token) return;
  lib.user.feeds.get().then(({ feeds }) => {
    if (!feeds) return;
    const promiseArr = feeds.map(refreshFeed);
    Promise.all(promiseArr);
  }).catch(console.error);
}

function updateState() {
  const nextArticleIsCurrent = current.nextSibling.offsetTop < window.pageYOffset;
  const previousArticleIsCurrent = current.offsetTop > window.pageYOffset;
  if (nextArticleIsCurrent || previousArticleIsCurrent) {
    const id = current.id;
    const i = articles.indexOf(id);
    getArticle(articles[i + 5]);
    if (previousArticleIsCurrent) {
      current = current.previousSibling;
    } else {
      current = current.nextSibling;
    }
    const articleDiv = current.firstChild;
    const articleTitle = articleDiv.childNodes[0].firstChild.innerHTML;
    const feedTitle = articleDiv.childNodes[1].firstChild.innerHTML;
    document.title = `${articleTitle} - ${feedTitle} (feedreader.co)`;
    history.replaceState({ id: current.id }, '', `https://feedreader.co${pathname}${current.id}`);
    if (token) {
      console.log(`Marking ${id} as read`);
      lib.user.labels.post('read', id).then(() => {
        console.log(`Marked ${id} as read`);
      }).catch(() => {
        console.log(`Couldn't mark ${id} as read`);
      });
    }
  }
}

pathname = `${pathname}/`;

if ((hash.length !== 32) && (hash.length !== 40)) {
  pathname = `${pathname}${hash}/`;
  hash = '';
}

window.onscroll = updateState;

if (!user) {
  // no user logged in, redirect to signup page
  // there's a login link on that page
  window.location.href = 'https://feedreader.co/signup.html';
}

if (splitPathname[1] === 'feeds' && user) {
  const feed = pathname.slice(7, -1);
  lib.user.folders.get(feed)
    .then(displaySubscribeButton)
    .catch(console.error);
} else {
  ReactDOM.render(<UserLink user={user}/>, userLinkDiv);
}

if (hash && isArticle) {
  getLabels().then(() => getArticle(hash)).then(refreshFeeds);
} else {
  getLabels().then(getArticles).then(refreshFeeds);
}
<|endoftext|>


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

var dnsCache = {};
var callbacks = {};
var TIMEOUT = 5000;
var CACHE_TIME = 30000;

function lookupDNS(hostname, callback) {
  var list = callbacks[hostname];
  if (list) {
    if (callback) {
      list.push(callback);
    }
    return;
  }
  callbacks[hostname] = list = [];
  if (callback) {
    list.push(callback);
  }
  var done;
  function execCallback(err, ip) {
    if (!err) {
      dnsCache[hostname] = {
        ip: ip,
        hostname: hostname,
        time: Date.now()
      };
    }
    if (done) {
      return;
    }
    done = true;
    callbacks[hostname] = null;
    list.forEach(function(callback) {
      callback(err, ip);
    });
  }

  var timer = setTimeout(function() {
    execCallback(new Error('Timeout'));
  }, TIMEOUT);

  try {
    dns.lookup(hostname, function (err, ip, type) {
      clearTimeout(timer);
      if (err) {
        execCallback(err);
      } else {
        execCallback(null, ip || getDefaultIp(type));
      }
    });
  } catch(err) {//如果断网，可能直接抛异常，https代理没有用到error-handler
    execCallback(err);
  }
}

function getDefaultIp(type) {
  return !type || type == 4 ? '127.0.0.1' : '0:0:0:0:0:0:0:1';
}

module.exports = function lookup(hostname, callback, allowDnsCache) {
  var host = allowDnsCache ? dnsCache[hostname] : null;
  if (host) {
    callback(null, host.ip);
    if (Date.now() - host.time > CACHE_TIME) {
      lookupDNS(host.hostname);
    }
    return host.ip;
  }
  lookupDNS(hostname, function(err, ip) {
    err ? lookupDNS(hostname, callback) : callback(err, ip);
  });
};
<commit_msg>refactor: DNS cache time<commit_after>var dns = require('dns');

var dnsCache = {};
var callbacks = {};
var TIMEOUT = 5000;
var MAX_CACHE_TIME = 600000;
var CACHE_TIME = 30000;

function lookupDNS(hostname, callback) {
  var list = callbacks[hostname];
  if (list) {
    if (callback) {
      list.push(callback);
    }
    return;
  }
  callbacks[hostname] = list = [];
  if (callback) {
    list.push(callback);
  }
  var done;
  function execCallback(err, ip) {
    if (!err) {
      dnsCache[hostname] = {
        ip: ip,
        hostname: hostname,
        time: Date.now()
      };
    }
    if (done) {
      return;
    }
    done = true;
    var host = dnsCache[hostname];
    callbacks[hostname] = null;
    list.forEach(function(callback) {
      callback(err, host && host.ip);
    });
  }

  var timer = setTimeout(function() {
    execCallback(new Error('Timeout'));
  }, TIMEOUT);

  try {
    dns.lookup(hostname, function (err, ip, type) {
      clearTimeout(timer);
      if (err) {
        execCallback(err);
      } else {
        execCallback(null, ip || getDefaultIp(type));
      }
    });
  } catch(err) {//如果断网，可能直接抛异常，https代理没有用到error-handler
    execCallback(err);
  }
}

function getDefaultIp(type) {
  return !type || type == 4 ? '127.0.0.1' : '0:0:0:0:0:0:0:1';
}

module.exports = function lookup(hostname, callback, allowDnsCache) {
  var host = allowDnsCache ? dnsCache[hostname] : null;
  var cacheTime;
  if (host) {
    cacheTime = Date.now() - host.time;
  }
  if (host && cacheTime < MAX_CACHE_TIME) {
    callback(null, host.ip);
    if (cacheTime > CACHE_TIME) {
      lookupDNS(host.hostname);
    }
    return host.ip;
  }
  lookupDNS(hostname, function(err, ip) {
    err ? lookupDNS(hostname, callback) : callback(err, ip);
  });
};
<|endoftext|>


<commit_before>'use strict';

var events = require('events');

var persistence = exports;
persistence.SchemaInstance = require('./schema_instance');
persistence.schemas = {};

persistence.validator = null;
persistence.engine = null;

/**
 * Sets the validator.
 */
persistence.setValidator = function(validator) {
  persistence.validator = validator;
};

/**
 * Gets the validator.
 */
persistence.getValidator = function() {
  return persistence.validator;
};

/**
 * Sets the storage engine.resource
 */
persistence.setEngine = function(engine) {
  persistence.engine = engine;
};

/**
 * Gets the storage engine.
 */
persistence.getEngine = function() {
  return persistence.engine;
}

/**
 * Defines a new factory schema for creating instances of schemas.
 *
 * @param name
 *            string
 * @param schema
 *            JSON schema object
 * @returns factory function for creating new instances
 */
persistence.define = function(name, schema) {

  function Factory(attrs) {
    var self = this;
    persistence.SchemaInstance.call(this, attrs, schema);

    // verify methods
    for ( var m in Factory) {
      if (typeof Factory[m] != 'undefined' && Factory[m].type === 'method') {
        if (typeof this[m] != 'undefined')
          throw new Error(m + ' is a reserverd word on the schema instance');
      }
      this[m] = Factory[m];
      this[m].type = "method";
      this[m].required = false;
    }

    // define properties from schema
    Object.keys(this._properties).forEach(function(k) {
      resourceful.defineProperty(self, k, Factory.schema.properties[k]);
    });

    return instance;
  }

  // define the properties that each schema must have

  // set name
  Factory.name = name;

  // set schema
  Factory.schema = schema;

  // prototype inheritance
  Factory.__proto__ = persistence.SchemaInstance;
  Factory.prototype.__proto__ = persistence.SchemaInstance.prototype

  // define some hooks
  Factory.hooks = {
    before : {},
    after : {}
  };

  // set before and after hooks
  [ 'get', 'save', 'update', 'create', 'destroy' ].forEach(function(m) {
    Factory.hooks.before[m] = [];
    Factory.hooks.after[m] = [];
  });

  Factory.emitter = new events.EventEmitter();

  // register hooks with event emitter
  Object.keys(events.EventEmitter.prototype).forEach(function(k) {
    Factory[k] = function() {
      return Factory.emitter[k].apply(Factory.emitter, arguments);
    };
  });

  // emit 'init' event
  Factory.init();

  // Add this schema to the set of resources, persistence knows about
  persistence.register(name, Factory);

  return Factory;
};

/**
 * Registers a schema.
 */
persistence.register = function(name, schema) {
  return this.schemas[name] = schema;
};

/**
 * Unregisters a schema.
 */
persistence.unregister = function(name) {
  delete this.schemas[name];
};

/**
 * TODO: Try to get what this function does.
 */
persistence.instantiate = function(obj) {
  var instance, Factory, id;

  Factory = persistence.resources[this.name];

  id = obj[this.key];

  if (id && this.engine.cache.has(id)) {
    obj = this.engine.cache.get(id);
  }

  if (Factory) {
    // Don't instantiate an already instantiated object
    if (obj instanceof Factory) {
      return obj;
    } else {
      instance = new Factory(obj);
      instance.isNewRecord = false;
      return instance;
    }
  } else {
    throw new Error("unrecognised resource '" + obj.name + "'");
  }
};
<commit_msg>Use JS getters and setters<commit_after>'use strict';

var events = require('events');

var persistence = exports;
persistence.SchemaInstance = require('./schema_instance');
persistence.schemas = {};

persistence._validator = null;
persistence._engine = null;

persistence.__defineSetter__('validator', function(validator) {
  return this._validator = validator;
});

persistence.__defineGetter__('validator', function() {
  return this._validator;
});

persistence.__defineSetter__('engine', function(engine) {
  return persistence.engine = engine;
});

persistence.__defineGetter__('engine', function() {
  return persistence.engine;
});

/**
 * Defines a new factory schema for creating instances of schemas.
 *
 * @param name
 *            string
 * @param schema
 *            JSON schema object
 * @returns factory function for creating new instances
 */
persistence.define = function(name, schema) {

  function Factory(attrs) {
    var self = this;
    persistence.SchemaInstance.call(this, attrs, schema);

    // verify methods
    for ( var m in Factory) {
      if (typeof Factory[m] != 'undefined' && Factory[m].type === 'method') {
        if (typeof this[m] != 'undefined')
          throw new Error(m + ' is a reserverd word on the schema instance');
      }
      this[m] = Factory[m];
      this[m].type = "method";
      this[m].required = false;
    }

    // define properties from schema
    Object.keys(this._properties).forEach(function(k) {
      resourceful.defineProperty(self, k, Factory.schema.properties[k]);
    });

    return instance;
  }

  // define the properties that each schema must have

  // set name
  Factory.name = name;

  // set schema
  Factory.schema = schema;

  // prototype inheritance
  Factory.__proto__ = persistence.SchemaInstance;
  Factory.prototype.__proto__ = persistence.SchemaInstance.prototype

  // define some hooks
  Factory.hooks = {
    before : {},
    after : {}
  };

  // set before and after hooks
  [ 'get', 'save', 'update', 'create', 'destroy' ].forEach(function(m) {
    Factory.hooks.before[m] = [];
    Factory.hooks.after[m] = [];
  });

  Factory.emitter = new events.EventEmitter();

  // register hooks with event emitter
  Object.keys(events.EventEmitter.prototype).forEach(function(k) {
    Factory[k] = function() {
      return Factory.emitter[k].apply(Factory.emitter, arguments);
    };
  });

  // emit 'init' event
  Factory.init();

  // Add this schema to the set of resources, persistence knows about
  persistence.register(name, Factory);

  return Factory;
};

/**
 * Registers a schema.
 */
persistence.register = function(name, schema) {
  return this.schemas[name] = schema;
};

/**
 * Unregisters a schema.
 */
persistence.unregister = function(name) {
  delete this.schemas[name];
};

/**
 * TODO: needed? run by runBeforeHooks
 */
persistence.instantiate = function(obj) {
  var instance, Factory, id;

  Factory = persistence.resources[this.name];

  id = obj[this.key];

  if (id && this.engine.cache.has(id)) {
    obj = this.engine.cache.get(id);
  }

  if (Factory) {
    // Don't instantiate an already instantiated object
    if (obj instanceof Factory) {
      return obj;
    } else {
      instance = new Factory(obj);
      instance.isNewRecord = false;
      return instance;
    }
  } else {
    throw new Error("unrecognised resource '" + obj.name + "'");
  }
};
<|endoftext|>