<commit_before>/* Intro */
import PropTypes from 'prop-types';
import React from 'react';
import { Col, Row } from 'react-bootstrap';
import styled from 'styled-components';

import collab from 'img/art/collaborate.png';
import speedometer from 'img/art/accelerate.png';
import Gallery from 'containers/Gallery';
import palette from 'img/art/palette.png';
import pkg from 'img/art/package.png';

const Styler = styled.div`
  margin-top: 2em;

  .intro-row:not(:nth-child(2)) {
    margin-top: 5em;
  }

  .intro-row h1 {
    font-size: 3em;
  }

  .intro-row p {
    font-size: 1.1em;
  }

  .intro-row img {
    display: block;
    margin: 0 auto;
    margin-top: 3em;
    max-width: 400px;
    width: 90%;
  }

  img.fade {
    filter: grayscale(50%);
  }
`;

const Terminal = styled.div`
  background-color: rgb(32, 32, 32);
  color: #ddd;
  font-size: 1.2em;
  margin: 1em 1em 1em 0;
  padding: 1em;
  width: auto;

  span {
    display: block;
  }
`;

function Intro() {
  return (

  );
}

Intro.propTypes = {

};

const ClipCol = styled(Col)`
  overflow: hidden;
`;

// eslint-disable-next-line object-curly-newline
function IntroRow({ detail, src, srcFade, textRight, title, typing }) {
  const text = (
    <Col key="text" xs={12} sm={7}>

{ title }

      { detail }
      {
        typing ?
          <Terminal className="fixed">
            { typing }
          </Terminal> : null
      }
    </Col>
  );

  const picture = (
    <ClipCol key="picture" xs={12} sm={5}>

    </ClipCol>
  );

  return (
    <Row className="intro-row">
      { textRight ? [picture, text] : [text, picture] }
    </Row>
  );
}

IntroRow.propTypes = {
  detail: PropTypes.node.isRequired,
  src: PropTypes.string.isRequired,
  srcFade: PropTypes.bool,
  textRight: PropTypes.bool,
  title: PropTypes.node.isRequired,
  typing: PropTypes.node,
};

export default Intro;
<commit_msg>fix badly escaped chars<commit_after>/* Intro */
import PropTypes from 'prop-types';
import React from 'react';
import { Col, Row } from 'react-bootstrap';
import styled from 'styled-components';

import collab from 'img/art/collaborate.png';
import speedometer from 'img/art/accelerate.png';
import Gallery from 'containers/Gallery';
import palette from 'img/art/palette.png';
import pkg from 'img/art/package.png';

const Styler = styled.div`
  margin-top: 2em;

  .intro-row:not(:nth-child(2)) {
    margin-top: 5em;
  }

  .intro-row h1 {
    font-size: 3em;
  }

  .intro-row p {
    font-size: 1.1em;
  }

  .intro-row img {
    display: block;
    margin: 0 auto;
    margin-top: 3em;
    max-width: 400px;
    width: 90%;
  }

  img.fade {
    filter: grayscale(50%);
  }
`;

const Terminal = styled.div`
  background-color: rgb(32, 32, 32);
  color: #ddd;
  font-size: 1.2em;
  margin: 1em 1em 1em 0;
  padding: 1em;
  width: auto;

  span {
    display: block;
  }
`;

function Intro() {
  return (

  );
}

Intro.propTypes = {

};

const ClipCol = styled(Col)`
  overflow: hidden;
`;

// eslint-disable-next-line object-curly-newline
function IntroRow({ detail, src, srcFade, textRight, title, typing }) {
  const text = (
    <Col key="text" xs={12} sm={7}>

{ title }

      { detail }
      {
        typing ?
          <Terminal className="fixed">
            { typing }
          </Terminal> : null
      }
    </Col>
  );

  const picture = (
    <ClipCol key="picture" xs={12} sm={5}>

    </ClipCol>
  );

  return (
    <Row className="intro-row">
      { textRight ? [picture, text] : [text, picture] }
    </Row>
  );
}

IntroRow.propTypes = {
  detail: PropTypes.node.isRequired,
  src: PropTypes.string.isRequired,
  srcFade: PropTypes.bool,
  textRight: PropTypes.bool,
  title: PropTypes.node.isRequired,
  typing: PropTypes.node,
};

export default Intro;
<|endoftext|>


<commit_before>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // choose either `'stable'` for receiving highly polished,
    // or `'canary'` for less polished but more frequent updates
    updateChannel: 'stable',

    // default font size in pixels for all tabs
    fontSize: 14,

    // font family with optional fallbacks
    fontFamily: 'Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // default font weight: 'normal' or 'bold'
    fontWeight: 'normal',

    // font weight for bold characters: 'normal' or 'bold'
    fontWeightBold: 'bold',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // terminal text color under BLOCK cursor
    cursorAccentColor: '#000',

    // `'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █
    cursorShape: 'BEAM',

    // set to `true` (without backticks and without quotes) for blinking cursor
    cursorBlink: true,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    // opacity is only supported on macOS
    backgroundColor: '#000',

    // terminal selection color
    selectionColor: 'rgba(248,28,229,0.3)',

    // border color (window, tabs)
    borderColor: '#333',

    // custom CSS to embed in the main window
    css: '',

    // custom CSS to embed in the terminal window
    termCSS: '',

    // if you're using a Linux setup which show native menus, set to false
    // default: `true` on Linux, `true` on Windows, ignored on macOS
    showHamburgerMenu: '',

    // set to `false` (without backticks and without quotes) if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` (without backticks and without quotes) on Windows and Linux, ignored on macOS
    showWindowControls: '',

    // custom padding (CSS format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#C51E14',
      green: '#1DC121',
      yellow: '#C7C329',
      blue: '#0A2FC4',
      magenta: '#C839C5',
      cyan: '#20C5C6',
      white: '#C7C7C7',
      lightBlack: '#686868',
      lightRed: '#FD6F6B',
      lightGreen: '#67F86F',
      lightYellow: '#FFFA72',
      lightBlue: '#6A76FB',
      lightMagenta: '#FD7CFC',
      lightCyan: '#68FDFE',
      lightWhite: '#FFFFFF',
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // PowerShell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: '',

    // for setting shell arguments (i.e. for using interactive shellArgs: `['-i']`)
    // by default `['--login']` will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to `false` for no bell
    bell: 'SOUND',

    // if `true` (without backticks and without quotes), selected text will automatically be copied to the clipboard
    copyOnSelect: false,

    // if `true` (without backticks and without quotes), hyper will be set as the default protocol client for SSH
    defaultSSHApp: true,

    // if `true` (without backticks and without quotes), on right click selected text will be copied or pasted if no
    // selection is present (`true` by default on Windows and disables the context menu feature)
    // quickEdit: true,

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: ["hypercwd", "hyper-night-owl"],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  },
};
<commit_msg>hyper: add hyper-night-owl plugin<commit_after>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // choose either `'stable'` for receiving highly polished,
    // or `'canary'` for less polished but more frequent updates
    updateChannel: 'stable',

    // default font size in pixels for all tabs
    fontSize: 14,

    // font family with optional fallbacks
    fontFamily: 'Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // default font weight: 'normal' or 'bold'
    fontWeight: 'normal',

    // font weight for bold characters: 'normal' or 'bold'
    fontWeightBold: 'bold',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // terminal text color under BLOCK cursor
    cursorAccentColor: '#000',

    // `'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █
    cursorShape: 'BEAM',

    // set to `true` (without backticks and without quotes) for blinking cursor
    cursorBlink: true,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    // opacity is only supported on macOS
    backgroundColor: '#000',

    // terminal selection color
    selectionColor: 'rgba(248,28,229,0.3)',

    // border color (window, tabs)
    borderColor: '#333',

    // custom CSS to embed in the main window
    css: '',

    // custom CSS to embed in the terminal window
    termCSS: '',

    // if you're using a Linux setup which show native menus, set to false
    // default: `true` on Linux, `true` on Windows, ignored on macOS
    showHamburgerMenu: '',

    // set to `false` (without backticks and without quotes) if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` (without backticks and without quotes) on Windows and Linux, ignored on macOS
    showWindowControls: '',

    // custom padding (CSS format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#C51E14',
      green: '#1DC121',
      yellow: '#C7C329',
      blue: '#0A2FC4',
      magenta: '#C839C5',
      cyan: '#20C5C6',
      white: '#C7C7C7',
      lightBlack: '#686868',
      lightRed: '#FD6F6B',
      lightGreen: '#67F86F',
      lightYellow: '#FFFA72',
      lightBlue: '#6A76FB',
      lightMagenta: '#FD7CFC',
      lightCyan: '#68FDFE',
      lightWhite: '#FFFFFF',
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // PowerShell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: '',

    // for setting shell arguments (i.e. for using interactive shellArgs: `['-i']`)
    // by default `['--login']` will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to `false` for no bell
    bell: 'SOUND',

    // if `true` (without backticks and without quotes), selected text will automatically be copied to the clipboard
    copyOnSelect: false,

    // if `true` (without backticks and without quotes), hyper will be set as the default protocol client for SSH
    defaultSSHApp: true,

    // if `true` (without backticks and without quotes), on right click selected text will be copied or pasted if no
    // selection is present (`true` by default on Windows and disables the context menu feature)
    // quickEdit: true,

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: ["hyper-night-owl"],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  },
};
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var ch = require('child_process');

app.get('/postreceive', function(req, res){

    console.log(req);

    var child = ch.exec('git submodule -q foreach git pull -q origin master', [], function(err, stdout, stderr) {
        console.log(stdout, stderr);

        var child2 = ch.exec('pm2 restart all', [], function(err, stdout, stderr) {
            console.log(stdout, stderr);
            res.send('Triggered code update. Thanks!');
        });
    });
});

app.listen(1337, function(){
    console.log('Deployment Server Started');
});<commit_msg>Adding base route.<commit_after>var express = require('express');
var app = express();
var ch = require('child_process');

app.get('/', function(req, res){
    res.send('You have reached the deploy server.');
});

app.get('/postreceive', function(req, res){

    console.log(req);

    var child = ch.exec('git submodule -q foreach git pull -q origin master', [], function(err, stdout, stderr) {
        console.log(stdout, stderr);

        var child2 = ch.exec('pm2 restart all', [], function(err, stdout, stderr) {
            console.log(stdout, stderr);
            res.send('Triggered code update. Thanks!');
        });
    });
});

app.listen(1337, function(){
    console.log('Deployment Server Started');
});<|endoftext|>


<commit_before>import d3 from "d3";

class Editor{
  constructor(slide) {
    this.slide = slide;
    this.regions = this.slide.select("regions");

    this.x = d3.scale.linear();
    this.y = d3.scale.linear();

    this.initUI();
    this.initBehavior();

    this.update();

    this.slide.on("update", ()=> { this.update(); });
  }

  destroy() {
    this.$ui.remove();
  }

  initUI(){
    this.$ui = d3.select("body")
      .append("div")
      .classed({"nbpresent-editor": 1});

    this.$bg = this.$ui.append("div")
      .classed({"slide-bg": 1});

    this.$svg = this.$bg.append("svg");
  }

  initBehavior(){
    let that = this,
      {x, y} = this;

    let dragX, dragY;

    this.regionDrag = d3.behavior.drag()
      .on("dragstart", function(d){
        let $region = d3.select(this)
          .classed({dragging: 1});
        dragX = d.value.x;
        dragY = d.value.y;
      })
      .on("drag", function(d){
        dragX += x.invert(d3.event.dx);
        dragY += y.invert(d3.event.dy);
        let $region = d3.select(this)
          .attr({
            transform: (d) => `translate(${[x(dragX), y(dragY)]})`
          });
      })
      .on("dragend", function(d){
        let $region = d3.select(this)
          .classed({dragging: 0});

        that.regions.merge(d.key, {
          x: dragX,
          y: dragY,
        });
      });
  }

  padding(){
    return 20;
  }

  aspectRatio(){
    // TODO: put in data
    return 16 / 9;
  }

  update(){
    let uibb = this.$ui.node().getBoundingClientRect(),
      width = uibb.width - (2 * this.padding()),
      height = width / this.aspectRatio();

    if(height > uibb.height + 2 * this.padding()){
      height = uibb.height - (2 * this.padding());
      width = height * this.aspectRatio();
    }

    this.x.range([0, width]);
    this.y.range([0, height]);

    this.$bg.style({
      left: `${(uibb.width - width) / 2}px`,
      top: `${(uibb.height - height) / 2}px`,
      width: `${width}px`,
      height: `${height}px`
    });

    this.$svg.attr({width, height});

    let regions = d3.entries(this.regions.get());

    console.table(regions.map(({value}) => value));

    let $region = this.$svg.selectAll(".region")
      .data(regions, (d) => d.key);

    $region.exit().remove();

    $region.enter()
      .append("g")
      .classed({"region": 1})
      .call(function($region){
        $region.append("rect")
          .classed({"region-bg": 1});
      })
      .call(this.regionDrag);

    let {x, y} = this;

    $region.attr({
        transform: (d) => `translate(${[x(d.value.x), y(d.value.y)]})`
      })
      .select(".region-bg")
      .attr({
        width: (d) => x(d.value.width),
        height: (d) => y(d.value.height)
      });
  }
}

export {Editor};
<commit_msg>handles<commit_after>import d3 from "d3";

let directions = [
  "nw",
  "n",
  "ne",
  "e",
  "se",
  "s",
  "sw",
  "w"
];

class Editor{
  constructor(slide) {
    this.slide = slide;
    this.regions = this.slide.select("regions");

    this.x = d3.scale.linear();
    this.y = d3.scale.linear();

    this.initUI();
    this.initBehavior();

    this.update();

    this.slide.on("update", ()=> { this.update(); });
  }

  destroy() {
    this.$ui.remove();
  }

  initUI(){
    this.$ui = d3.select("body")
      .append("div")
      .classed({"nbpresent-editor": 1});

    this.$bg = this.$ui.append("div")
      .classed({"slide-bg": 1});

    this.$svg = this.$bg.append("svg");
  }

  initBehavior(){
    let that = this,
      {x, y} = this;

    let dragX, dragY, dragWidth, dragHeight;

    this.regionDrag = d3.behavior.drag()
      .origin((d) => d)
      .on("dragstart", function(d){
        let $region = d3.select(this.parentNode)
          .classed({dragging: 1});
        dragX = d.value.x;
        dragY = d.value.y;
      })
      .on("drag", function(d){
        dragX += x.invert(d3.event.dx);
        dragY += y.invert(d3.event.dy);
        let $region = d3.select(this.parentNode)
          .attr({
            transform: (d) => `translate(${[x(dragX), y(dragY)]})`
          });
      })
      .on("dragend", function(d){
        let $region = d3.select(this.parentNode)
          .classed({dragging: 0});

        that.regions.merge(d.key, {
          x: dragX,
          y: dragY,
        });
      });

    this.handleDrag = d3.behavior.drag()
      .origin((d) => d)
      .on("dragstart", function(d){
        let $handle = d3.select(this)
          .classed({dragging: 1});
        dragX = d.region.value.x;
        dragY = d.region.value.y;
        dragWidth = d.region.value.width;
        dragHeight = d.region.value.height;
      })
      .on("drag", function(d){
        let $handle = d3.select(this),
          $region = d3.select(this.parentNode);

        let dx = x.invert(d3.event.dx),
          dy = y.invert(d3.event.dy);

        if(/n/.test(d.dir)){ dragY += dy; dragHeight -= dy; }
        if(/e/.test(d.dir)){ dragWidth += dx; }
        if(/s/.test(d.dir)){ dragHeight += dy; }
        if(/w/.test(d.dir)){ dragX += dx; dragWidth -= dx; }

        $region
          .attr({
            transform: (d) => `translate(${[x(dragX), y(dragY)]})`
          })
          .select(".region-bg")
          .attr({
            width: x(dragWidth),
            height: y(dragHeight),
          });

        $region
          .selectAll(".handle")
          .attr({
            cx: (d) => {
              return x(
                /w/.test(d.dir) ? 0 :
                /e/.test(d.dir) ? dragWidth :
                dragWidth / 2
              )
            },
            cy: (d) => y(
              /n/.test(d.dir) ? 0 :
              /s/.test(d.dir) ? dragHeight :
              dragHeight / 2
            )
          })

      })
      .on("dragend", function(d){
        let $handle = d3.select(this)
          .classed({dragging: 0});

        that.regions.merge(d.region.key, {
          x: dragX,
          y: dragY,
          width: dragWidth,
          height: dragHeight
        });
      });

  }

  padding(){
    return 20;
  }

  aspectRatio(){
    // TODO: put in data
    return 16 / 9;
  }

  update(){
    let uibb = this.$ui.node().getBoundingClientRect(),
      width = uibb.width - (2 * this.padding()),
      height = width / this.aspectRatio();

    if(height > uibb.height + 2 * this.padding()){
      height = uibb.height - (2 * this.padding());
      width = height * this.aspectRatio();
    }

    this.x.range([0, width]);
    this.y.range([0, height]);
    let {x, y} = this;

    this.$bg.style({
      left: `${(uibb.width - width) / 2}px`,
      top: `${(uibb.height - height) / 2}px`,
      width: `${width}px`,
      height: `${height}px`
    });

    this.$svg.attr({width, height});

    let regions = d3.entries(this.regions.get());

    //console.table(regions.map(({value}) => value));

    let $region = this.$svg.selectAll(".region")
      .data(regions, (d) => d.key);

    $region.exit().remove();

    let regionData = (region) => {
      return directions.map((dir) => {
        return {region, dir};
      })
    };

    $region.enter()
      .append("g")
      .classed({"region": 1})
      .call(($region) => {
        $region.append("rect")
          .classed({"region-bg": 1})
          .call(this.regionDrag);

        let $handle = $region.selectAll(".handle")
          .data(regionData);

        $handle.enter()
          .append("circle")
          .classed({handle: 1})
          .attr({
            r: 5
          })
          .call(this.handleDrag);
      });

    $region.attr({
        transform: (d) => `translate(${[x(d.value.x), y(d.value.y)]})`
      })
      .select(".region-bg")
      .attr({
        width: (d) => x(d.value.width),
        height: (d) => y(d.value.height)
      });

    $region.selectAll(".handle")
      .data(regionData)
      .attr({
        cx: (d) => {
          return x(
            /w/.test(d.dir) ? 0 :
            /e/.test(d.dir) ? d.region.value.width :
            d.region.value.width / 2
          )
        },
        cy: (d) => y(
          /n/.test(d.dir) ? 0 :
          /s/.test(d.dir) ? d.region.value.height :
          d.region.value.height / 2
        )
      })
  }
}

export {Editor};
<|endoftext|>


<commit_before><commit_msg>* Check all checkboxes by default * Toggle nested checkboxes<commit_after><|endoftext|>


<commit_before>// @flow

import type {MapType} from '../../../maps/type';
import type {GameDataType, UnitActionMoveType, UnitActionsMapType, UnitActionType} from './unit/unit';
import {Unit} from './unit/unit';

function getUnitListByPlayerId(gameData: GameDataType, activeUserId: string): Array<Unit> {
    return gameData.unitList.filter((unit: Unit): boolean => unit.getUserId() === activeUserId);
}

function getMoveActionList(unit: Unit, actionMap: UnitActionsMapType): Array<UnitActionMoveType> {
    const moveActionList = [];

    actionMap.forEach((actionListList: Array<Array<UnitActionType>>) => {
        actionListList.forEach((actionList: Array<UnitActionType>) => {
            actionList.forEach((action: UnitActionType) => {
                if (action.type !== 'move') {
                    return;
                }

                moveActionList.push(action);
            });
        });
    });

    return moveActionList;
}

function getActionMapAfterMove(
    unit: Unit,
    actionMove: UnitActionMoveType,
    gameData: GameDataType
): UnitActionsMapType | null {
    const beforeUnitAttr = unit.getAttr();
    const moveUnitAttr = unit.getAttr();

    moveUnitAttr.x = actionMove.to.x;
    moveUnitAttr.y = actionMove.to.y;

    unit.setAttr(moveUnitAttr);
    unit.setDidMove(true);

    const actionMap = unit.getActions(gameData);

    unit.setAttr(beforeUnitAttr);

    return actionMap;
}

function getUnitActionMapList(unit: Unit, gameData: GameDataType): Array<UnitActionsMapType> | null {
    // 1 - get unit action list // +
    // 2 - filter MOVE action only // +
    // 3 - get action list for every move position
    // 4 - get action list for current position, without move
    // 5 - rate every unit action

    const actionMap = unit.getActions(gameData);

    if (actionMap === null) {
        return null;
    }

    const actionMapList = [actionMap];

    getMoveActionList(unit, actionMap).forEach((actionMove: UnitActionMoveType) => {
        const actionMapAfterMove = getActionMapAfterMove(unit, actionMove, gameData);

        if (actionMapAfterMove === null) {
            return;
        }

        actionMapList.push(actionMapAfterMove);
    });

    return actionMapList;
}

export function getBotTurnData(map: MapType, gameData: GameDataType): mixed | null {
    console.log('getBotTurnData map', map);

    // get unit
    const unitList = getUnitListByPlayerId(gameData, map.activeUserId);

    unitList.forEach((unit: Unit) => {
        // get action uit list
        const unitActionList = getUnitActionMapList(unit, gameData);

        console.log(unitActionList);
    });

    console.log('getBotTurnData unitList', unitList);

    return null;
}
<commit_msg>update<commit_after>// @flow

import type {MapType, MapUserType} from '../../../maps/type';
import type {GameDataType, UnitActionMoveType, UnitActionsMapType, UnitActionType} from './unit/unit';
import {Unit} from './unit/unit';
import type {UserType} from '../../auth/reducer';
import type {TeamIdType} from '../../../maps/map-guide';

function getUnitListByPlayerId(gameData: GameDataType, activeUserId: string): Array<Unit> {
    return gameData.unitList.filter((unit: Unit): boolean => unit.getUserId() === activeUserId);
}

function getEnemyUnitListByPlayerId(gameData: GameDataType, activeUserId: string): Array<Unit> {
    const playerData =
        gameData.userList.find((userData: MapUserType): boolean => userData.userId === activeUserId) || null;

    if (playerData === null) {
        console.error('can not find user by id', activeUserId);
        return [];
    }

    const {teamId} = playerData;

    const enemyPlayerDataList = gameData.userList.filter(
        (userData: MapUserType): boolean => userData.teamId !== teamId
    );

    const enemyPlayerIdList = enemyPlayerDataList.map((userData: MapUserType): string => userData.userId);

    return gameData.unitList.filter((unit: Unit): boolean => enemyPlayerIdList.includes(unit.getUserId()));
}

function getMoveActionList(unit: Unit, actionMap: UnitActionsMapType): Array<UnitActionMoveType> {
    const moveActionList = [];

    actionMap.forEach((actionListList: Array<Array<UnitActionType>>) => {
        actionListList.forEach((actionList: Array<UnitActionType>) => {
            actionList.forEach((action: UnitActionType) => {
                if (action.type !== 'move') {
                    return;
                }

                moveActionList.push(action);
            });
        });
    });

    return moveActionList;
}

function getActionMapAfterMove(
    unit: Unit,
    actionMove: UnitActionMoveType,
    gameData: GameDataType
): UnitActionsMapType | null {
    const beforeUnitAttr = unit.getAttr();
    const moveUnitAttr = unit.getAttr();

    moveUnitAttr.x = actionMove.to.x;
    moveUnitAttr.y = actionMove.to.y;

    unit.setAttr(moveUnitAttr);
    unit.setDidMove(true);

    const actionMap = unit.getActions(gameData);

    unit.setAttr(beforeUnitAttr);

    return actionMap;
}

function getUnitActionMapList(unit: Unit, gameData: GameDataType): Array<UnitActionsMapType> | null {
    // 1 - get unit action list // +
    // 2 - filter MOVE action only // +
    // 3 - get action list for every move position
    // 4 - get action list for current position, without move
    // 5 - rate every unit action

    const actionMap = unit.getActions(gameData);

    if (actionMap === null) {
        return null;
    }

    const actionMapList = [actionMap];

    getMoveActionList(unit, actionMap).forEach((actionMove: UnitActionMoveType) => {
        const actionMapAfterMove = getActionMapAfterMove(unit, actionMove, gameData);

        if (actionMapAfterMove === null) {
            return;
        }

        actionMapList.push(actionMapAfterMove);
    });

    return actionMapList;
}

export function getBotTurnData(map: MapType, gameData: GameDataType): mixed | null {
    console.log('getBotTurnData map', map);

    // get unit
    const unitList = getUnitListByPlayerId(gameData, map.activeUserId);

    console.log('getBotTurnData unitList', unitList);

    const enemyUnitList = getEnemyUnitListByPlayerId(gameData, map.activeUserId);

    console.log('getBotTurnData enemyUnitList', enemyUnitList);

    unitList.forEach((unit: Unit) => {
        // get action uit list
        const unitActionList = getUnitActionMapList(unit, gameData);

        // console.log(unitActionList);
    });

    return null;
}
<|endoftext|>


<commit_before>import Phaser from 'phaser'
import Weapon from './Weapon'
import { getRandomInt } from '../utils'

export default class extends Weapon  {

    constructor (game, isEnemy) {
        super({ game: game, name: "Beam", isEnemy: isEnemy });
        this.game = game;
        this.isEnemy = isEnemy;
        this.fireRate = 25;
    }

    fire(source) {
        if (this.game.time.time < this.nextFire) { return; }

        let y = source.position.y;
        let x = (this.isEnemy) ? source.position.x + source.width - 25: source.position.x + source.width + 25;
        let angle = (this.isEnemy) ? -180 : 0;

        this.getFirstExists(false).fire(x, y, angle, this.bulletSpeed, 0, 0);

        this.nextFire = this.game.time.time + this.fireRate;

        if (!this.isEnemy) {
            this.game.sound.play('BeamShotSound', 1, false);
        }
    }

}

<commit_msg>Play beam sound less loudly.<commit_after>import Phaser from 'phaser'
import Weapon from './Weapon'
import { getRandomInt } from '../utils'

export default class extends Weapon  {

    constructor (game, isEnemy) {
        super({ game: game, name: "Beam", isEnemy: isEnemy });
        this.game = game;
        this.isEnemy = isEnemy;
        this.fireRate = 25;
    }

    fire(source) {
        if (this.game.time.time < this.nextFire) { return; }

        let y = source.position.y;
        let x = (this.isEnemy) ? source.position.x + source.width - 25: source.position.x + source.width + 25;
        let angle = (this.isEnemy) ? -180 : 0;

        this.getFirstExists(false).fire(x, y, angle, this.bulletSpeed, 0, 0);

        this.nextFire = this.game.time.time + this.fireRate;

        if (!this.isEnemy) {
            this.game.sound.play('BeamShotSound', 0.8, false);
        }
    }

}

<|endoftext|>


<commit_before><commit_msg>image grid view: subselection of images in a group is now allowed<commit_after><|endoftext|>


<commit_before>"use strict";
const Cli = require("matrix-appservice-bridge").Cli;
const log = require("./lib/logging").get("CLI");
const main = require("./lib/main");
const path = require("path");

const REG_PATH = "appservice-registration-irc.yaml";
new Cli({
    registrationPath: REG_PATH,
    enableRegistration: true,
    enableLocalpart: true,
    port: -1, // Set this here so we know if the port is a default
    bridgeConfig: {
        affectsRegistration: true,
        schema: path.join(__dirname, "config.schema.yml"),
        defaults: {
            homeserver: {
                dropMatrixMessagesAfterSecs: 0,
                enablePresence: true
            },
            ircService: {
                ident: {
                    enabled: false,
                    port: 113
                },
                logging: {
                    level: "debug",
                    toConsole: true
                },
                statsd: {},
                debugApi: {},
                provisioning: {
                    enabled: false,
                    requestTimeoutSeconds: 60 * 5
                }
            }
        }
    },
    generateRegistration: function(reg, callback) {
        main.generateRegistration(reg, this.getConfig()).done(function(completeRegistration) {
            callback(completeRegistration);
        });
    },
    run: function(port, config, reg) {
        if (port === -1) {
            port = null;
        }
        main.runBridge(port, config, reg).catch(function(err) {
            log.error("Failed to run bridge.");
            throw err;
        });
    }
}).run();
<commit_msg>.done is no longer a thing, use async/await<commit_after>"use strict";
const Cli = require("matrix-appservice-bridge").Cli;
const log = require("./lib/logging").get("CLI");
const main = require("./lib/main");
const path = require("path");

const REG_PATH = "appservice-registration-irc.yaml";
new Cli({
    registrationPath: REG_PATH,
    enableRegistration: true,
    enableLocalpart: true,
    port: -1, // Set this here so we know if the port is a default
    bridgeConfig: {
        affectsRegistration: true,
        schema: path.join(__dirname, "config.schema.yml"),
        defaults: {
            homeserver: {
                dropMatrixMessagesAfterSecs: 0,
                enablePresence: true
            },
            ircService: {
                ident: {
                    enabled: false,
                    port: 113
                },
                logging: {
                    level: "debug",
                    toConsole: true
                },
                statsd: {},
                debugApi: {},
                provisioning: {
                    enabled: false,
                    requestTimeoutSeconds: 60 * 5
                }
            }
        }
    },
    generateRegistration: async function(reg, callback) {
        try {
            const completeReg = await main.generateRegistration(reg, this.getConfig());
            callback(completeReg);
        }
        catch (ex) {
            log.error("Failed to generate registration:", ex);
            process.exit(1);
        }
    },
    run: function(port, config, reg) {
        if (port === -1) {
            port = null;
        }
        main.runBridge(port, config, reg).catch(function(err) {
            log.error("Failed to run bridge.");
            throw err;
        });
    }
}).run();
<|endoftext|>


<commit_before>'use strict';

/**
 * Imports.
 */
const http = require('http');
const Koa = require('koa');
const auth = require('koa-basic-auth');
const bodyParser = require('koa-bodyparser');
const Router = require('koa-router');
const uuidV4 = require('uuid/v4');

const config = require('../../config');
const Initializer = require('../lib/Initializer');
const ApiWebController = require('./controllers/ApiWebController');
const ToolsWebController = require('./controllers/ToolsWebController');
const WebHooksWebController = require('./controllers/WebHooksWebController');

/**
 * Initializations.
 */
// Chdir to project root to ensure that relative paths work.
process.chdir(__dirname);

// Web server
const blinkWeb = new Koa();

// Setup web middleware.
blinkWeb.use(bodyParser());

// Set context id.
blinkWeb.use(async (ctx, next) => {
  ctx.id = ctx.id || uuidV4();
  await next();
  ctx.set('X-Request-Id', ctx.id);
});

// Setup web server env from local config.
blinkWeb.env = config.app.env;

// Authentication
// Custom 401 handling
blinkWeb.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    if (err.status === 401) {
      ctx.status = 401;
      ctx.set('WWW-Authenticate', 'Basic');
      // Doctor Who Easter Egg
      // Copyright info: http://tardis.wikia.com/wiki/File:Angel_bares_fangs.jpg
      ctx.set('Content-type', 'text/html');
      ctx.body = 'Don\'t blink!
';
    } else {
      throw err;
    }
  }
});
blinkWeb.use(auth({ name: config.app.auth.name, pass: config.app.auth.password }));

// Setup dependencies.
const router = new Router();
config.router = router;
config.initializer = new Initializer(config);

config.initializer.getExchange();
config.initializer.getFetchQ();
config.initializer.getCustomerIoWebhookQ();

/**
 * Initialize all web controllers.
 */
const apiWebController = new ApiWebController(config);
const toolsWebController = new ToolsWebController(config);
const webHooksWebController = new WebHooksWebController(config);

/**
 * Routing.
 */
router.get('/', apiWebController.welcome);
router.get('api.v1', '/api/v1', apiWebController.v1);
router.get('api.index', '/api', apiWebController.index);
router.get('api.v1', '/api/v1', apiWebController.v1);
router.get('api.v1.tools', '/api/v1/tools', toolsWebController.index);
router.post('api.v1.tools.fetch', '/api/v1/tools/fetch', toolsWebController.fetch);
router.get('api.v1.webhooks', '/api/v1/webhooks', webHooksWebController.index);
router.post('api.v1.webhooks.customerio', '/api/v1/webhooks/customerio', webHooksWebController.customerio);

blinkWeb
  .use(router.routes())
  .use(router.allowedMethods());

/**
 * Create server.
 */
const server = http.createServer(blinkWeb.callback());
server.listen(config.web.bind_port, config.web.bind_address, () => {
  const address = server.address();
  // Make sure random port setting gets overriden with actual resolved port.
  config.web.bind_port = address.port;
  config.logger.info(
    `Blink is listening on http://${config.web.hostname}:${config.web.bind_port} env:${config.app.env}`
  );
});

module.exports = blinkWeb;
<commit_msg>Remove old blinkWeb.js<commit_after><|endoftext|>


<commit_before><commit_msg>Increment running time total before scheduling triggers<commit_after><|endoftext|>


<commit_before>command: 'curl -s "http://legacy.cafebonappetit.com/api/2/menus?cafe=261"',
refreshFrequency: 300000,

render: function(output) {
  return [
      '<link rel="stylesheet" href="BonApp-Widget/styles/bonAppStyle.css">',
      '<link rel="stylesheet" href="BonApp-widget/styles/jquery/jquery-ui.css">',
      '',

      '
',
        //'
Could not update
',
        '

',
        '
',
          '

',
          '
',
            '
',
              '<input type="text" class="queryBox" id="search" placeholder="Search...">',
            '
',
          '
',
          '
',
            '',
          '
',
        '
',
        '
',
          '

',
          '

',
          '
',
            '<select class="myDiet">',
              '<option value="-1">All</option>',
              '<option value="6">Farm to Fork</option>',
              '<option value="18">Humane</option>',
              '<option value="7">In-Balance</option>',
              '<option value="9">Made Without Gluten</option>',
              '<option value="57">Contains Nuts</option>',
              '<option value="3">Seafood Watch</option>',
              '<option value="1">Vegetarian</option>',
              '<option value="4">Vegan</option>',
            '</select>',
          '
',
          '

',
          '

',
        '
',
      '
'
    ].join('')
  },

  update: function(output, domEl) {
    var theMenu = null

    var dietSelection = domEl.querySelector('.myDiet')

    var parseCafe = function(json) {
      var id = Object.keys(json['days'][0]['cafes'])[0]
      var theTitle = json['days'][0]['cafes'][id]['name']

      return theTitle
    }

    var parseDate = function(x) {
      var y = x.substr(0, 4)
      var m = x.substr(5, 2)
      var d = x.substr(8, 2)

      var postedDate = new Date(y, m - 1, d).toString()
      postedDate = postedDate.substr(0, 10)

      return postedDate
    }

    var widgetSelect = 'Find Your Café'
    var jstringObj   = JSON.parse(output)
    var theDate      = parseDate(jstringObj.days[0].date)
    var title        = parseCafe(jstringObj)

    var createOutputString = function(okItems) {
      return okItems.join('
')
    }

    var parseMenu = function(menu, diet) {
      var preferredDiet = parseInt(diet)
      var okItems = []
      var prevStation = ''
      var item = ''
      var desc = ''

      for (var prop in menu) {
        if (menu.hasOwnProperty(prop)) {
          if (menu[prop].cor_icon.hasOwnProperty(preferredDiet) || preferredDiet === -1) {
            if (menu[prop].station !== prevStation) {
              item = '
' + cleanUpStationLabel(menu[prop].station + '
')
              item += '⚬ ' + capitalizeStr(menu[prop].label, 0, 1)
              if(menu[prop].description != '') {
                  desc = menu[prop].description.replace(/
/g, '
 ⚬ ')
                  item += "
" + '⚬ ' + desc
              }
              prevStation = menu[prop].station
            }
            else {
                item = '⚬ ' + capitalizeStr(menu[prop].label, 0, 1)
              if(menu[prop].description != '') {
                  desc = menu[prop].description.replace(/
/g, '
 ⚬ ')
                  item += "
" + '⚬ ' + desc
              }
                prevStation = menu[prop].station
            }
            okItems.push(item)
          }
        }
      }
      if (okItems.length === 0) {
        okItems.push('0 menu items found...')
      }

      return okItems
    }

    var lastUpdated = function() {
      var time = new Date
      var hours = time.getHours()
      var minutes = time.getMinutes()
      var timeOfDay = ''

      if (hours > 12) {
        timeOfDay = 'pm'
        hours -= 12
      }
      else if (hours == 12) {
        timeOfDay = 'pm'
      }
      else if (hours === 0) {
        timeOfDay = 'am'
        hours = 12
      }
      else {
        timeOfDay = 'am'
      }

      return function() { return 'Updated at ' + pad(hours) + ':' + pad(minutes) + timeOfDay}
    }

    var pad = function(number) {
      return (number < 10 ? '0' : '') + number
    }

    var capitalizeStr = function(theStr, upperCaseLetter, removeLetter) {
      var newCapitalStr = theStr[upperCaseLetter].toUpperCase() + theStr.slice(removeLetter)
      return newCapitalStr
    }

    var sortByProperty = function(property) {
      //'use strict'
      return function(a, b) {
        var sortStatus = 0
        if (a[property]  b[property]) {
          sortStatus = 1
        }

        return sortStatus
      }
    }

    const updateTheData = (cafeId) => {
      const cmd = `curl -s http://legacy.cafebonappetit.com/api/2/menus?cafe=${cafeId}`
      return this.run(cmd, (err, output) => {
        makeItAllHappen(output)
        return changeTheView()
      })
    }

    var initSearch = function() {
      return jQuery.get('BonApp-Widget/scripts/data.json', function(data) {
        return $('#search').autocomplete({
          source: data.sort(sortByProperty('label')),
          minLength: 2,

          select: function(event, ui) {
            $("#spinner").show()
            $('#search').val(ui.item.label)

            updateTheData(ui.item.id)

            return false
          },

          open: function() {
            return $('.ui-autocomplete:visible').css({
              top: '+=0',
              left: '-=0'
            })
          }

        }).autocomplete('instance')._renderItem = function(ul, item) {
          return $('
').append('
' +
                                  '' + item.label + '' +
                                  '' + item.desc + '' + '
')
                          .appendTo(ul)
        }
      })
    }

    var cleanUpStationLabel = function(theStation) {
      var cleanString = theStation.replace('@', '')
      var capitalizedStr = capitalizeStr(cleanString, 8, 9)
      capitalizedStr = '' + capitalizedStr + ''

      return capitalizedStr
    }

    var updateView = function(theDate, widgetSelect, title, outputString) {
      var err
      var theLastUpdate = lastUpdated

      try {
        $(domEl).find(widgetSelectTitle).html(widgetSelect)
      }
      catch (_error) {
        err = _error
        console.log('Error: "' + err.message + '" on line ' + err.line)
      }
      try {
       $(domEl).find(widgetTitle).html(title)
      }
      catch (_error) {
        err = _error
        console.log('Error: "' + err.message + '" on line ' + err.line)
      }
      try {
        $(domEl).find(date).html(theDate)
      }
      catch (_error) {
        err = _error
        console.log('Error: "' + err.message + '" on line ' + err.line)
      }
      try {
        $(domEl).find(footerBA).html(theLastUpdate)
      }
      catch (_error) {
        err = _error
        console.log('Error: "' + err.message + '" on line ' + err.line)
      }
      try {
        return $(domEl).find(food).html(outputString)
      }
      catch (_error) {
        err = _error
        console.log('Error: "' + err.message + '" on line ' + err.line)
      }
    }

    var initFromLocalStorage = function() {
      var theValue

      if (localStorage.getItem('BonAppSettings') !== null) {
        savedDiet = localStorage.getItem('BonAppSettings')
        var theValue = JSON.parse(savedDiet).diet
        document.querySelector('.myDiet').value = theValue
      }
      else {
        return -1
      }

      return theValue
    }

    var switchNum = 0

    var changeTheView = function() {

      if (switchNum % 2 == 0) {
        $('#cafeSelection').show()
        $('#main').hide()
        $("#spinner").hide()
        $('#topRightIcon').css('background-image', 'url(BonApp-Widget/img/arrow.png)')
        $('#bonApp').css('height', '200px')
        $('.queryBox').focus()

        initSearch()
      }
      else {
        $('#cafeSelection').hide()
        $('#main').show()
        $('#topRightIcon').css('background-image', 'url(BonApp-Widget/img/search.png)')
        $('#bonApp').css('height', 'auto')
      }

      return switchNum++
    }

    document.getElementById('topRightIcon').addEventListener('click', function() {
      return changeTheView()
    })

   var makeItAllHappen = function(output) {
      var savedDiet    = initFromLocalStorage()
      var jstringObj   = JSON.parse(output)
      var title        = parseCafe(jstringObj)
      var theDate      = parseDate(jstringObj.days[0].date)
      var theMenu      = jstringObj.items
      var friendly     = parseMenu(theMenu, savedDiet)
      var outputString = createOutputString(friendly)
      var widgetSelect = 'Find Your Café'

      dietSelection.onchange = function() {
        return saveSettings(dietSelection.value)
      }

      var saveSettings = function(diet) {
        var friendly, userSettings

        userSettings = {
          diet: diet
        }

        localStorage.setItem('BonAppSettings', JSON.stringify(userSettings))
        friendly = parseMenu(theMenu, diet)
        outputString = createOutputString(friendly)

        return updateView(theDate, widgetSelect, title, outputString)
    }

      return updateView(theDate, widgetSelect, title, outputString)
    }

    makeItAllHappen(output)
  }
<commit_msg>Move group of try/catch to same block<commit_after>command: 'curl -s "http://legacy.cafebonappetit.com/api/2/menus?cafe=261"',
refreshFrequency: 300000,

render: function(output) {
  return [
      '<link rel="stylesheet" href="BonApp-Widget/styles/bonAppStyle.css">',
      '<link rel="stylesheet" href="BonApp-widget/styles/jquery/jquery-ui.css">',
      '',

      '
',
        //'
Could not update
',
        '

',
        '
',
          '

',
          '
',
            '
',
              '<input type="text" class="queryBox" id="search" placeholder="Search...">',
            '
',
          '
',
          '
',
            '',
          '
',
        '
',
        '
',
          '

',
          '

',
          '
',
            '<select class="myDiet">',
              '<option value="-1">All</option>',
              '<option value="6">Farm to Fork</option>',
              '<option value="18">Humane</option>',
              '<option value="7">In-Balance</option>',
              '<option value="9">Made Without Gluten</option>',
              '<option value="57">Contains Nuts</option>',
              '<option value="3">Seafood Watch</option>',
              '<option value="1">Vegetarian</option>',
              '<option value="4">Vegan</option>',
            '</select>',
          '
',
          '

',
          '

',
        '
',
      '
'
    ].join('')
  },

  update: function(output, domEl) {
    var theMenu = null

    var dietSelection = domEl.querySelector('.myDiet')

    var parseCafe = function(json) {
      var id = Object.keys(json['days'][0]['cafes'])[0]
      var theTitle = json['days'][0]['cafes'][id]['name']

      return theTitle
    }

    var parseDate = function(x) {
      var y = x.substr(0, 4)
      var m = x.substr(5, 2)
      var d = x.substr(8, 2)

      var postedDate = new Date(y, m - 1, d).toString()
      postedDate = postedDate.substr(0, 10)

      return postedDate
    }

    var widgetSelect = 'Find Your Café'
    var jstringObj   = JSON.parse(output)
    var theDate      = parseDate(jstringObj.days[0].date)
    var title        = parseCafe(jstringObj)

    var createOutputString = function(okItems) {
      return okItems.join('
')
    }

    var parseMenu = function(menu, diet) {
      var preferredDiet = parseInt(diet)
      var okItems = []
      var prevStation = ''
      var item = ''
      var desc = ''

      for (var prop in menu) {
        if (menu.hasOwnProperty(prop)) {
          if (menu[prop].cor_icon.hasOwnProperty(preferredDiet) || preferredDiet === -1) {
            if (menu[prop].station !== prevStation) {
              item = '
' + cleanUpStationLabel(menu[prop].station + '
')
              item += '⚬ ' + capitalizeStr(menu[prop].label, 0, 1)
              if(menu[prop].description != '') {
                  desc = menu[prop].description.replace(/
/g, '
 ⚬ ')
                  item += "
" + '⚬ ' + desc
              }
              prevStation = menu[prop].station
            }
            else {
                item = '⚬ ' + capitalizeStr(menu[prop].label, 0, 1)
              if(menu[prop].description != '') {
                  desc = menu[prop].description.replace(/
/g, '
 ⚬ ')
                  item += "
" + '⚬ ' + desc
              }
                prevStation = menu[prop].station
            }
            okItems.push(item)
          }
        }
      }
      if (okItems.length === 0) {
        okItems.push('0 menu items found...')
      }

      return okItems
    }

    var lastUpdated = function() {
      var time = new Date
      var hours = time.getHours()
      var minutes = time.getMinutes()
      var timeOfDay = ''

      if (hours > 12) {
        timeOfDay = 'pm'
        hours -= 12
      }
      else if (hours == 12) {
        timeOfDay = 'pm'
      }
      else if (hours === 0) {
        timeOfDay = 'am'
        hours = 12
      }
      else {
        timeOfDay = 'am'
      }

      return function() { return 'Updated at ' + pad(hours) + ':' + pad(minutes) + timeOfDay}
    }

    var pad = function(number) {
      return (number < 10 ? '0' : '') + number
    }

    var capitalizeStr = function(theStr, upperCaseLetter, removeLetter) {
      var newCapitalStr = theStr[upperCaseLetter].toUpperCase() + theStr.slice(removeLetter)
      return newCapitalStr
    }

    var sortByProperty = function(property) {
      //'use strict'
      return function(a, b) {
        var sortStatus = 0
        if (a[property]  b[property]) {
          sortStatus = 1
        }

        return sortStatus
      }
    }

    const updateTheData = (cafeId) => {
      const cmd = `curl -s http://legacy.cafebonappetit.com/api/2/menus?cafe=${cafeId}`
      return this.run(cmd, (err, output) => {
        makeItAllHappen(output)
        return changeTheView()
      })
    }

    var initSearch = function() {
      return jQuery.get('BonApp-Widget/scripts/data.json', function(data) {
        return $('#search').autocomplete({
          source: data.sort(sortByProperty('label')),
          minLength: 2,

          select: function(event, ui) {
            $("#spinner").show()
            $('#search').val(ui.item.label)

            updateTheData(ui.item.id)

            return false
          },

          open: function() {
            return $('.ui-autocomplete:visible').css({
              top: '+=0',
              left: '-=0'
            })
          }

        }).autocomplete('instance')._renderItem = function(ul, item) {
          return $('
').append('
' +
                                  '' + item.label + '' +
                                  '' + item.desc + '' + '
')
                          .appendTo(ul)
        }
      })
    }

    var cleanUpStationLabel = function(theStation) {
      var cleanString = theStation.replace('@', '')
      var capitalizedStr = capitalizeStr(cleanString, 8, 9)
      capitalizedStr = '' + capitalizedStr + ''

      return capitalizedStr
    }

    var updateView = function(theDate, widgetSelect, title, outputString) {
      var err
      var theLastUpdate = lastUpdated

      try {
        $(domEl).find(widgetSelectTitle).html(widgetSelect)
        $(domEl).find(widgetTitle).html(title)
        $(domEl).find(date).html(theDate)
        $(domEl).find(footerBA).html(theLastUpdate)
        return $(domEl).find(food).html(outputString)
      }
      catch (_error) {
        err = _error
        console.log('Error: "' + err.message + '" on line ' + err.line)
      }
    }

    var initFromLocalStorage = function() {
      var theValue

      if (localStorage.getItem('BonAppSettings') !== null) {
        savedDiet = localStorage.getItem('BonAppSettings')
        var theValue = JSON.parse(savedDiet).diet
        document.querySelector('.myDiet').value = theValue
      }
      else {
        return -1
      }

      return theValue
    }

    var switchNum = 0

    var changeTheView = function() {

      if (switchNum % 2 == 0) {
        $('#cafeSelection').show()
        $('#main').hide()
        $("#spinner").hide()
        $('#topRightIcon').css('background-image', 'url(BonApp-Widget/img/arrow.png)')
        $('#bonApp').css('height', '200px')
        $('.queryBox').focus()

        initSearch()
      }
      else {
        $('#cafeSelection').hide()
        $('#main').show()
        $('#topRightIcon').css('background-image', 'url(BonApp-Widget/img/search.png)')
        $('#bonApp').css('height', 'auto')
      }

      return switchNum++
    }

    document.getElementById('topRightIcon').addEventListener('click', function() {
      return changeTheView()
    })

   var makeItAllHappen = function(output) {
      var savedDiet    = initFromLocalStorage()
      var jstringObj   = JSON.parse(output)
      var title        = parseCafe(jstringObj)
      var theDate      = parseDate(jstringObj.days[0].date)
      var theMenu      = jstringObj.items
      var friendly     = parseMenu(theMenu, savedDiet)
      var outputString = createOutputString(friendly)
      var widgetSelect = 'Find Your Café'

      dietSelection.onchange = function() {
        return saveSettings(dietSelection.value)
      }

      var saveSettings = function(diet) {
        var friendly, userSettings

        userSettings = {
          diet: diet
        }

        localStorage.setItem('BonAppSettings', JSON.stringify(userSettings))
        friendly = parseMenu(theMenu, diet)
        outputString = createOutputString(friendly)

        return updateView(theDate, widgetSelect, title, outputString)
    }

      return updateView(theDate, widgetSelect, title, outputString)
    }

    makeItAllHappen(output)
  }
<|endoftext|>


<commit_before>//attaches event listeners and handles passing messages

$(document).ready(function() {
    /**** automatically try to decrypt DOM whenever it changes ****************************************************/
    $(document).on('DOMNodeInserted', function(e) {
        decryptFakeblocks($(e.target));
    });

});

/****** stuff for finding fakeblocks and parsing them *****************************************************************/

//get immediate parents of a fakeblock
function getDivsContainingFakeBlock($container) {

    return $container.find('div').add($container).filter(
        ':contains("' + FAKEBLOCK_OPEN_TAG + '")' +
        ':contains("' + FAKEBLOCK_CLOSE_TAG + '")'
        ).filter(function(i, elm) {
            return $(elm).find(':contains("' + FAKEBLOCK_OPEN_TAG + '")').length == 0 &&
                $(elm).find(':contains("' + FAKEBLOCK_CLOSE_TAG + '")').length == 0 &&
                !$(elm).hasClass(FAKEBLOCK_TEXTAREA_CLASS);
    });
}

// returns array of match objects,
// match_object[0] = whole match
// match_object[1] = json
// returns empty array if there were no matches
function getFakeBlocksFromText(text) {
    var to_return = [];
    var myRe = new RegExp(FAKEBLOCK_OPEN_TAG.split('|').join('\\|') +
        "(.*)" +
        FAKEBLOCK_CLOSE_TAG.split('|').join('\\|'),
        "g"
    );
    var result = myRe.exec(text);
    while (result != null) {
        to_return.push(result);
        result = myRe.exec(text);
    }
    return to_return;
}

// get all fakeblock objects from whole page
function getFakeblockObjectsFromContainer($container) {
    var ps_containing_fblocks = getDivsContainingFakeBlock($container);
    if (ps_containing_fblocks.length == 0) {
        return null;
    }
    var all_fakeblocks = [];
    ps_containing_fblocks.each(function() {
        var div = $(this);
        var match_objects = getFakeBlocksFromText(div.text());
        $.each(match_objects, function() {
            try {
                var match_object = $(this);
                var whole_match = match_object[0];
                var byte_str = match_object[1];
                var unparsed_json = decodeByteString(byte_str);
                var parsed_json = JSON.parse(unparsed_json);
                var fakeblock_obj = {
                    'whole_match': whole_match,
                    'unparsed_json': unparsed_json,
                    'parsed_json': parsed_json
                };
                all_fakeblocks.push(fakeblock_obj);
            } catch (ex) {
                console.log(ex);
            }
        });
    });
    return {
        'all_fakeblocks': all_fakeblocks,
        'ps_containing_fakeblocks': ps_containing_fblocks
    };
}

// decrypt and replace all faceblocks for a user
function decryptFakeblocks($container) {
    var returned_dict = getFakeblockObjectsFromContainer($container);
    if (returned_dict === null) {
        return;
    }
    var fakeblocks = returned_dict['all_fakeblocks'];
    var ps_containing_fakeblocks = returned_dict['ps_containing_fakeblocks'];
    $.each(fakeblocks, function() {
        var fakeblock = $(this)[0];
        var to_replace = fakeblock['whole_match'];
        var unparsed_json = fakeblock['unparsed_json'];
        var parsed_json = fakeblock['parsed_json'];
        // send to back to decrypt and replace to_replace with decrypted_text
        replaceFakeblockWithDecryptedText(ps_containing_fakeblocks, to_replace, parsed_json);
    });
}

// backend decrypts fakeblock unparsed_json into decrypted_text
function replaceFakeblockWithDecryptedText(ps_containing_fakeblocks, to_replace, json) {
    sendMessage({
        "action": "decrypt",
        "json": json
    }, function(response) {
        var decrypted_text = $.parseJSON(response).res;
        if (decrypted_text != null) {
            $.each(ps_containing_fakeblocks, function(i, e) {
                var all_html = $(this).text();
                var new_html = all_html.replace(to_replace, decrypted_text);
                $(this).html(new_html);
                // if the newly decrypted text was in an unencrypted area,
                // make sure encrypted area is updated
                var $unencryptedArea = $(this).closest('.parseltongue-unencrypted');
                if ($unencryptedArea.length > 0) {
                    encryptHandler($unencryptedArea);
                }
            });
        }
    });
}<commit_msg>adding an initial decrypt fakeblocks call<commit_after>//attaches event listeners and handles passing messages

$(document).ready(function() {
    setTimeout(function() {
        decryptFakeblocks($('body'));
    }, 1000);

    /**** automatically try to decrypt DOM whenever it changes ****************************************************/
    $(document).on('DOMNodeInserted', function(e) {
        decryptFakeblocks($(e.target));
    });

});

/****** stuff for finding fakeblocks and parsing them *****************************************************************/

//get immediate parents of a fakeblock
function getDivsContainingFakeBlock($container) {

    return $container.find('div').add($container).filter(
        ':contains("' + FAKEBLOCK_OPEN_TAG + '")' +
        ':contains("' + FAKEBLOCK_CLOSE_TAG + '")'
        ).filter(function(i, elm) {
            return $(elm).find(':contains("' + FAKEBLOCK_OPEN_TAG + '")').length == 0 &&
                $(elm).find(':contains("' + FAKEBLOCK_CLOSE_TAG + '")').length == 0 &&
                !$(elm).hasClass(FAKEBLOCK_TEXTAREA_CLASS);
    });
}

// returns array of match objects,
// match_object[0] = whole match
// match_object[1] = json
// returns empty array if there were no matches
function getFakeBlocksFromText(text) {
    var to_return = [];
    var myRe = new RegExp(FAKEBLOCK_OPEN_TAG.split('|').join('\\|') +
        "(.*)" +
        FAKEBLOCK_CLOSE_TAG.split('|').join('\\|'),
        "g"
    );
    var result = myRe.exec(text);
    while (result != null) {
        to_return.push(result);
        result = myRe.exec(text);
    }
    return to_return;
}

// get all fakeblock objects from whole page
function getFakeblockObjectsFromContainer($container) {
    var ps_containing_fblocks = getDivsContainingFakeBlock($container);
    if (ps_containing_fblocks.length == 0) {
        return null;
    }
    var all_fakeblocks = [];
    ps_containing_fblocks.each(function() {
        var div = $(this);
        var match_objects = getFakeBlocksFromText(div.text());
        $.each(match_objects, function() {
            try {
                var match_object = $(this);
                var whole_match = match_object[0];
                var byte_str = match_object[1];
                var unparsed_json = decodeByteString(byte_str);
                var parsed_json = JSON.parse(unparsed_json);
                var fakeblock_obj = {
                    'whole_match': whole_match,
                    'unparsed_json': unparsed_json,
                    'parsed_json': parsed_json
                };
                all_fakeblocks.push(fakeblock_obj);
            } catch (ex) {
                console.log(ex);
            }
        });
    });
    return {
        'all_fakeblocks': all_fakeblocks,
        'ps_containing_fakeblocks': ps_containing_fblocks
    };
}

// decrypt and replace all faceblocks for a user
function decryptFakeblocks($container) {
    var returned_dict = getFakeblockObjectsFromContainer($container);
    if (returned_dict === null) {
        return;
    }
    var fakeblocks = returned_dict['all_fakeblocks'];
    var ps_containing_fakeblocks = returned_dict['ps_containing_fakeblocks'];
    $.each(fakeblocks, function() {
        var fakeblock = $(this)[0];
        var to_replace = fakeblock['whole_match'];
        var unparsed_json = fakeblock['unparsed_json'];
        var parsed_json = fakeblock['parsed_json'];
        // send to back to decrypt and replace to_replace with decrypted_text
        replaceFakeblockWithDecryptedText(ps_containing_fakeblocks, to_replace, parsed_json);
    });
}

// backend decrypts fakeblock unparsed_json into decrypted_text
function replaceFakeblockWithDecryptedText(ps_containing_fakeblocks, to_replace, json) {
    sendMessage({
        "action": "decrypt",
        "json": json
    }, function(response) {
        var decrypted_text = $.parseJSON(response).res;
        if (decrypted_text != null) {
            $.each(ps_containing_fakeblocks, function(i, e) {
                var all_html = $(this).text();
                var new_html = all_html.replace(to_replace, decrypted_text);
                $(this).html(new_html);
                // if the newly decrypted text was in an unencrypted area,
                // make sure encrypted area is updated
                var $unencryptedArea = $(this).closest('.parseltongue-unencrypted');
                if ($unencryptedArea.length > 0) {
                    encryptHandler($unencryptedArea);
                }
            });
        }
    });
}<|endoftext|>


<commit_before>module.exports = function (grunt) {
    return {
        main: {
            options: {
                add    : (grunt.option('cleanup') ? false : true),
                base   : 'dist',
                branch : 'gh-pages',
                message: global.release_target ? 'Release to ' + global.release_target : 'Auto-generated commit',
            },
            src: global.branch ? [global.branch_prefix + global.branch + '/**'] : ['**', '!' + (global.branch_prefix || 'br_') + '*/**']
        },
        trigger_tests: {
            options: {
                add    : true,
                base   : 'dist',
                branch : 'master',
                repo   : 'git@github.com:binary-com/binary-static-ci.git',
                message: 'Trigger tests',
            },
            src: grunt.cli.tasks[0] === 'release' && global.release_target === 'staging' ? 'version' : '',
        },
    }
};
<commit_msg>Remove unnecessary condition<commit_after>module.exports = function (grunt) {
    return {
        main: {
            options: {
                add    : (grunt.option('cleanup') ? false : true),
                base   : 'dist',
                branch : 'gh-pages',
                message: global.release_target ? 'Release to ' + global.release_target : 'Auto-generated commit',
            },
            src: global.branch ? [global.branch_prefix + global.branch + '/**'] : ['**', '!' + (global.branch_prefix || 'br_') + '*/**']
        },
        trigger_tests: {
            options: {
                add    : true,
                base   : 'dist',
                branch : 'master',
                repo   : 'git@github.com:binary-com/binary-static-ci.git',
                message: 'Trigger tests',
            },
            src: global.release_target === 'staging' ? 'version' : '',
        },
    }
};
<|endoftext|>


<commit_before>var routes= function (app) {
	var mongoose = require('mongoose');
	var Post = mongoose.model('Post');
	var Comment = mongoose.model('Comment');
	var moment =require('moment');
	var Category=mongoose.model('Category');
	var PostCategory=mongoose.model('PostCategory');
	var FriendlySite=mongoose.model('FriendlySite');
	var urlify = require('urlify').create({
	  addEToUmlauts:true,
	  szToSs:true,
	  spaces:"-",
	  nonPrintable:"-",
	  trim:true
	});

	////Error nesnesini null tanımlıyoruz
	app.locals.error=null;

	function generate_xml_sitemap(res) {
    // this is the source of the URLs on your site, in this case we use a simple array, actually it could come from the database
    var urls = ['about.html', 'javascript.html', 'css.html', 'html5.html'];
    // the root of your website - the protocol and the domain name with a trailing slash
    var root_path = 'http://www.fuattatar.com/';
    // XML sitemap generation starts here
    var postpriority = 0.5;
    var categorypriority = 0.3;
    var freq = 'weekly';
    var xml = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
    Post.find({}).sort({createddate: -1}).exec(function(err, docs){
    	Category.find({}).sort({createddate: -1}).exec(function(err, categories){
    		for (var i = 0; i < docs.length; i++) {
				console.log(docs[i].seotitle);
				xml += '<url>';
		        xml += '<loc>'+ root_path +'post/'+ docs[i].seotitle + '</loc>';
		        xml += '<changefreq>'+ freq +'</changefreq>';
		        xml += '<priority>'+ postpriority +'</priority>';
		        xml += '</url>';
    		};

			for (var i = 0; i < categories.length; i++) {

				xml += '<url>';
		        xml += '<loc>'+ root_path +'Kategori/'+ categories[i].seoname + '</loc>';
		        xml += '<changefreq>'+ freq +'</changefreq>';
		        xml += '<priority>'+ categorypriority +'</priority>';
		        xml += '</url>';
    		};
		    xml += '</urlset>';
		    res.header('Content-Type', 'text/xml');
			res.send(xml);
    	});

	});
	}

	app.get('/sitemap.xml', function(req, res) {
    	generate_xml_sitemap(res); // get the dynamically generated XML sitemap

	})
	app.get('/',function(req, res){

		Post.find({}).sort({createddate: -1}).exec(function(err, docs){
			if(! docs.length) {
				console.log('Gönderi bulunamadı');
			}
			console.log(docs);

			Category.find({}).sort({createddate: -1}).exec(function(err, categories){
				FriendlySite.find({}).sort({createddate:-1}).exec(function(err,sites){
					return res.render(__dirname+"/views/index",{
						title: 'Fuat Tatar Software Developer',
						stylesheet: 'blog',
						posts:docs,
						urlify:urlify,
						categories:categories,
						description:'Hobisi ve mesleği Yazılım olan Software Developer',
						sites:sites
					});
				});
			});
		});
	});

	app.get('/Iletisim',function(req,res){

		return res.render(__dirname + "/views/contact",{
			title: 'İletişim',
			stylesheet: 'contact',
			description: 'Fuat Tatar ile iletişime geçin'
		});
	});

	app.get('/Kategori/:seoname',function(req,res){

		Category.findOne({seoname:req.params.seoname},function(err, category){
			if(err) return next(err);
			console.log('kategori id:'+category._id);
			PostCategory.find({categoryid:category._id+''},function(err,postcategories){
				if(err) return next(err);
				console.log('post kategorileri:'+postcategories);
				var ids = [];
				postcategories.forEach(function(postcategory){
					ids.push(postcategory.postid);
				});
				 console.log('idlerrrr:'+ids);
				Post.find({_id:{ $in : ids }},function(err,posts){
				console.log('postlarrrr'+posts);
				if(err) return next(err);
					return res.render(__dirname + "/views/categorydetail",{
						title: req.params.seoname+' kategorisinde bulunan yazılar',
						stylesheet: 'categorydetail',
						urlify:urlify,
						posts:posts,
						description:category.name+' kategorisinde bulunan yazılar',
						keywords: category.name+' kategorisinde bulunan yazılar'
					});
				});
			});
		});
	});

	app.get('/Hakkimda',function(req,res){

		return res.render(__dirname + "/views/about",{
			title: 'Hakkımda',
			stylesheet: 'about',
			description: 'Fuat Tatar hakkında',
			keywords:'Fuat Tatar Hakkımda,Hakkımda,Fuat Tatar'
		});
	});

	app.get('/Post/:title',function(req,res){
		Post.findOne({seotitle:req.params.title},function(err, post){
			if(err) return next(err);
				Comment.find({postid:post._id,status:1},function(err, comments){
				if(err) {
					console.log("yorum bulunamadı");
					return next(err);
				}
					PostCategory.find({postid:post._id},function(err, postcategories){
						if(err) return next(err);

						return res.render(__dirname+"/views/postdetail",{
							title: post.title,
							stylesheet: 'postdetail',
							post:post,
							keywords:post.keywords,
							comments:comments,
							postcategories:postcategories,
							moment:moment,
							description:post.title
						});
					});
				});
			});
	});

	app.post('/Post/Comment',function(req, res){
		 new Comment({
        email:req.body.comment.email,
        website:req.body.comment.website,
        content:req.body.comment.content,
        postid:req.body.comment.postid,
        createddate:new Date(),
        status:0
      }).save(function (err, docs){
        if(err) {res.json({success: false});}else{ res.json({success: true}); }
        console.log('Gönderi oluşturuldu');
      });
	});

	app.post('/Iletisim',function(req,res){
		console.log('contactttttt');
		var nodemailer= require("nodemailer");
		var smtpTransport = nodemailer.createTransport("SMTP",{
		    service: "Hotmail",
		    auth: {
		        user: "ftdeveloperacc@outlook.com",
		        pass: "PsmSalamanda"
		    }
		});

		var mailOptions = {
		    from: req.body.email, // sender address
		    to: "fuat.tatar@hotmail.com", // list of receivers
		    subject: req.body.name, // Subject line
		    text: req.body.text // plaintext body
		}
		smtpTransport.sendMail(mailOptions, function(error, response){
		    if(error){
		        console.log(error);
		        return res.render(__dirname + "/views/contact",{
					title: 'İletişim',
					stylesheet: 'contact',
					error:'Bir hata oldu. Kısa sürede halledeceğim.'

				});

		    }else{
		        console.log("Message sent: " + response.message);
				        return res.render(__dirname + "/views/contact",{
					title: 'İletişim',
					stylesheet: 'contact',
					error: 'Mesajınız başarılı bir şekilde gönderilmiştir. En kısa sürede cevap vermeye çalışacağım'
				});

		    }
		});
	});
};

module.exports = routes;<commit_msg>Posts ordered by _id<commit_after>var routes= function (app) {
	var mongoose = require('mongoose');
	var Post = mongoose.model('Post');
	var Comment = mongoose.model('Comment');
	var moment =require('moment');
	var Category=mongoose.model('Category');
	var PostCategory=mongoose.model('PostCategory');
	var FriendlySite=mongoose.model('FriendlySite');
	var urlify = require('urlify').create({
	  addEToUmlauts:true,
	  szToSs:true,
	  spaces:"-",
	  nonPrintable:"-",
	  trim:true
	});

	////Error nesnesini null tanımlıyoruz
	app.locals.error=null;

	function generate_xml_sitemap(res) {
    // this is the source of the URLs on your site, in this case we use a simple array, actually it could come from the database
    var urls = ['about.html', 'javascript.html', 'css.html', 'html5.html'];
    // the root of your website - the protocol and the domain name with a trailing slash
    var root_path = 'http://www.fuattatar.com/';
    // XML sitemap generation starts here
    var postpriority = 0.5;
    var categorypriority = 0.3;
    var freq = 'weekly';
    var xml = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
    Post.find({}).sort({createddate: -1}).exec(function(err, docs){
    	Category.find({}).sort({createddate: -1}).exec(function(err, categories){
    		for (var i = 0; i < docs.length; i++) {
				console.log(docs[i].seotitle);
				xml += '<url>';
		        xml += '<loc>'+ root_path +'post/'+ docs[i].seotitle + '</loc>';
		        xml += '<changefreq>'+ freq +'</changefreq>';
		        xml += '<priority>'+ postpriority +'</priority>';
		        xml += '</url>';
    		};

			for (var i = 0; i < categories.length; i++) {

				xml += '<url>';
		        xml += '<loc>'+ root_path +'Kategori/'+ categories[i].seoname + '</loc>';
		        xml += '<changefreq>'+ freq +'</changefreq>';
		        xml += '<priority>'+ categorypriority +'</priority>';
		        xml += '</url>';
    		};
		    xml += '</urlset>';
		    res.header('Content-Type', 'text/xml');
			res.send(xml);
    	});

	});
	}

	app.get('/sitemap.xml', function(req, res) {
    	generate_xml_sitemap(res); // get the dynamically generated XML sitemap

	})
	app.get('/',function(req, res){

		Post.find({}).sort({_id: -1}).exec(function(err, docs){
			if(! docs.length) {
				console.log('Gönderi bulunamadı');
			}
			console.log(docs);

			Category.find({}).sort({_id: -1}).exec(function(err, categories){
				FriendlySite.find({}).sort({_id:-1}).exec(function(err,sites){
					return res.render(__dirname+"/views/index",{
						title: 'Fuat Tatar Software Developer',
						stylesheet: 'blog',
						posts:docs,
						urlify:urlify,
						categories:categories,
						description:'Hobisi ve mesleği Yazılım olan Software Developer',
						sites:sites
					});
				});
			});
		});
	});

	app.get('/Iletisim',function(req,res){

		return res.render(__dirname + "/views/contact",{
			title: 'İletişim',
			stylesheet: 'contact',
			description: 'Fuat Tatar ile iletişime geçin'
		});
	});

	app.get('/Kategori/:seoname',function(req,res){

		Category.findOne({seoname:req.params.seoname},function(err, category){
			if(err) return next(err);
			console.log('kategori id:'+category._id);
			PostCategory.find({categoryid:category._id+''},function(err,postcategories){
				if(err) return next(err);
				console.log('post kategorileri:'+postcategories);
				var ids = [];
				postcategories.forEach(function(postcategory){
					ids.push(postcategory.postid);
				});
				 console.log('idlerrrr:'+ids);
				Post.find({_id:{ $in : ids }},function(err,posts){
				console.log('postlarrrr'+posts);
				if(err) return next(err);
					return res.render(__dirname + "/views/categorydetail",{
						title: req.params.seoname+' kategorisinde bulunan yazılar',
						stylesheet: 'categorydetail',
						urlify:urlify,
						posts:posts,
						description:category.name+' kategorisinde bulunan yazılar',
						keywords: category.name+' kategorisinde bulunan yazılar'
					});
				});
			});
		});
	});

	app.get('/Hakkimda',function(req,res){

		return res.render(__dirname + "/views/about",{
			title: 'Hakkımda',
			stylesheet: 'about',
			description: 'Fuat Tatar hakkında',
			keywords:'Fuat Tatar Hakkımda,Hakkımda,Fuat Tatar'
		});
	});

	app.get('/Post/:title',function(req,res){
		Post.findOne({seotitle:req.params.title},function(err, post){
			if(err) return next(err);
				Comment.find({postid:post._id,status:1},function(err, comments){
				if(err) {
					console.log("yorum bulunamadı");
					return next(err);
				}
					PostCategory.find({postid:post._id},function(err, postcategories){
						if(err) return next(err);

						return res.render(__dirname+"/views/postdetail",{
							title: post.title,
							stylesheet: 'postdetail',
							post:post,
							keywords:post.keywords,
							comments:comments,
							postcategories:postcategories,
							moment:moment,
							description:post.title
						});
					});
				});
			});
	});

	app.post('/Post/Comment',function(req, res){
		 new Comment({
        email:req.body.comment.email,
        website:req.body.comment.website,
        content:req.body.comment.content,
        postid:req.body.comment.postid,
        createddate:new Date(),
        status:0
      }).save(function (err, docs){
        if(err) {res.json({success: false});}else{ res.json({success: true}); }
        console.log('Gönderi oluşturuldu');
      });
	});

	app.post('/Iletisim',function(req,res){
		console.log('contactttttt');
		var nodemailer= require("nodemailer");
		var smtpTransport = nodemailer.createTransport("SMTP",{
		    service: "Hotmail",
		    auth: {
		        user: "ftdeveloperacc@outlook.com",
		        pass: "PsmSalamanda"
		    }
		});

		var mailOptions = {
		    from: req.body.email, // sender address
		    to: "fuat.tatar@hotmail.com", // list of receivers
		    subject: req.body.name, // Subject line
		    text: req.body.text // plaintext body
		}
		smtpTransport.sendMail(mailOptions, function(error, response){
		    if(error){
		        console.log(error);
		        return res.render(__dirname + "/views/contact",{
					title: 'İletişim',
					stylesheet: 'contact',
					error:'Bir hata oldu. Kısa sürede halledeceğim.'

				});

		    }else{
		        console.log("Message sent: " + response.message);
				        return res.render(__dirname + "/views/contact",{
					title: 'İletişim',
					stylesheet: 'contact',
					error: 'Mesajınız başarılı bir şekilde gönderilmiştir. En kısa sürede cevap vermeye çalışacağım'
				});

		    }
		});
	});
};

module.exports = routes;<|endoftext|>


<commit_before>var kafka = require('kafka-node'),
    Promise = require('promise'),
    args = require('yargs').argv,

    clientId = args.clientId || 'kafka-mirror';

var fromClient = new kafka.Client(args.from_zk_connect, clientId);

var consumer = new kafka.HighLevelConsumer(
    fromClient, [{
        topic: args.from_topic
    }], {
    //consumer group id
    groupId: clientId,
    // Auto commit config
    autoCommit: true,
    autoCommitIntervalMs: 5000,
    // The max wait time is the maximum amount of time in milliseconds to block waiting if insufficient data is available at the time the request is issued, default 100ms
    fetchMaxWaitMs: 100,
    // This is the minimum number of bytes of messages that must be available to give a response, default 1 byte
    fetchMinBytes: 1,
    // The maximum bytes to include in the message set for this partition. This helps bound the size of the response.
    fetchMaxBytes: 1024 * 10,
    // If set true, consumer will fetch message from the given offset in the payloads
    fromOffset: false,
    // If set to 'buffer', values will be returned as raw buffer objects.
    encoding: 'utf8'
});

var exit = function () {
    consumer.close(true, function () {
        process.exit();
    });
}

var queue = [],
    stop = false,
    publish = function () {
        var items = queue.slice(0);
        queue = queue.slice(items.length);

        if (!stop && items.length == 0) return setTimeout(publish, 100);

        process.stdout.write(items.join(','));

        if (queue.length == 0) consumer.commit(function () {});

        if (!stop || queue.length > 0) setTimeout(publish, 100);

    };

consumer.on('message', function (m) {
    queue.push(m.value);
});

consumer.on('error', function (e) {
    console.error("Error receiving messages from source: " + e);
    exit();
});

consumer.on('offsetOutOfRange', function (e) {
    console.error("Error receiving messages from source: " + e);
    exit();
});

process.on('SIGINT', function () {
    console.log("Shutting down...");
    exit();
});<commit_msg>set up a high-level producer to publish messages when flushing<commit_after>var kafka = require('kafka-node'),
    Promise = require('promise'),
    args = require('yargs').argv,

    clientId = args.clientId || 'kafka-mirror';

var fromClient = new kafka.Client(args.from_zk_connect, clientId),
    toClient = new kafka.Client(args.to_zk_connect, clientId);

var consumer = new kafka.HighLevelConsumer(
    fromClient, [{
        topic: args.from_topic
    }], {
    //consumer group id
    groupId: clientId,
    // Auto commit config
    autoCommit: false,
    autoCommitIntervalMs: 5000,
    // The max wait time is the maximum amount of time in milliseconds to block waiting if insufficient data is available at the time the request is issued, default 100ms
    fetchMaxWaitMs: 100,
    // This is the minimum number of bytes of messages that must be available to give a response, default 1 byte
    fetchMinBytes: 1,
    // The maximum bytes to include in the message set for this partition. This helps bound the size of the response.
    fetchMaxBytes: 1024 * 10,
    // If set true, consumer will fetch message from the given offset in the payloads
    fromOffset: false,
    // If set to 'buffer', values will be returned as raw buffer objects.
    encoding: 'utf8'
});

var producer = new kafka.HighLevelProducer(toClient, { requireAcks: 1, ackTimeoutMs: 100 });

var exit = function () {
    consumer.close(true, function () {
        var waitToExit = function () {
            if (queue.length == 0) {
                return producer.close(function () {
                    process.exit();
                });
            }
            setTimeout(waitToExit, 100);
        };
        waitToExit();
    });
};

var queue = [],
    stop = false,
    publishTimeout,
    publish = function () {
        var items = queue.slice(0);
        queue = queue.slice(items.length);

        if (!stop && items.length == 0) return setTimeout(publish, 100);

        process.stdout.write(items.join(','));
        producer.send(
            [{
                topic: args.to_topic,
                messages: items,
                attributes: 2
            }],
            function (e) {
                if (e) {
                    console.error("Error sending message to destination: " + e);
                    exit();
                }

                if (queue.length == 0) consumer.commit(function () {});

                process.stdout.write('.');

                if (!stop || queue.length > 0) setTimeout(publish, 100);
            });

    };

producer.on('ready', function () {
    producer.createTopics([args.to_topic], false, function () {});
    setTimeout(publish, 100);
});

consumer.on('message', function (m) {
    queue.push(m.value);
});

consumer.on('error', function (e) {
    console.error("Error receiving messages from source: " + e);
    exit();
});

consumer.on('offsetOutOfRange', function (e) {
    console.error("Error receiving messages from source: " + e);
    exit();
});

process.on('SIGINT', function () {
    console.log("Shutting down...");
    exit();
});<|endoftext|>


<commit_before>/* jslint es5: true */

var config = require('./config/config.js');
config.load();

var express = require('express');
var http = require('http');
var https = require('https');
var fs = require('fs');
var multer = require('multer');
var path = require('path');

var rotator = require('file-stream-rotator');

var mongoose = require('mongoose');

var configPath = config.configPath;
var apiSettings = config.api;
var mongoConfig = config.mongo;
var appSettings = config.app;

// Load MongoDB object modeling tool
mongoose.connection.close();
// Load MongoDB models
require('./model/user.js');
require('./model/form.js');
require('./model/traveler.js');
require('./model/binder.js');

//Connect to mongo database
var mongoAddress = 'mongodb://';
mongoAddress += mongoConfig.server_address || 'localhost';
mongoAddress += ':' + (mongoConfig.server_port || '27017');
mongoAddress += '/' + (mongoConfig.traveler_db || 'traveler');

var mongoOptions = {
  native_parser: true,
  poolSize: 5,
  connectTimeoutMS: 30000,
  keepAlive: 1,
};

// Set authentication options if specified
if (mongoConfig.username !== undefined) {
  mongoOptions.user = mongoConfig.username;
  mongoOptions.pass = mongoConfig.password;
}
if (mongoConfig.auth) {
  mongoOptions.auth = config.mongo.auth;
}

mongoose.connect(mongoAddress, mongoOptions);
mongoose.connection.on('connected', function() {
  console.log('Mongoose default connection opened.');
});

mongoose.connection.on('error', function(err) {
  console.log('Mongoose default connection error: ' + err);
});

mongoose.connection.on('disconnected', function() {
  console.log('Mongoose default connection disconnected');
});

// LDAP client
var adClient = require('./lib/ldap-client').client;
adClient.on('connect', function() {
  console.log('ldap client connected');
});
adClient.on('timeout', function(message) {
  console.error(message);
});
adClient.on('error', function(error) {
  console.error(error);
});

// CAS client
var auth = require('./lib/auth');

// api and web app
var api = express();
var app = express();

/* Configure Web Application */
app.locals.orgName = appSettings.org_name;

app.enable('strict routing');
if (app.get('env') === 'production') {
  var access_logfile = rotator.getStream({
    filename: path.resolve(appSettings.log_dir, 'access.log'),
    frequency: 'daily',
  });
}

app.configure(function() {
  app.set('port', process.env.PORT || appSettings.app_port);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  if (app.get('env') === 'production') {
    app.use(
      express.logger({
        stream: access_logfile,
      })
    );
  }

  app.use(express.compress());
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.favicon(__dirname + '/public/favicon.ico'));
  if (app.get('env') === 'development') {
    app.use(express.logger('dev'));
  }

  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(
    express.session({
      secret: appSettings.cookie_sec || 'traveler_secret',
      cookie: {
        maxAge: appSettings.cookie_life || 28800000,
      },
    })
  );
  app.use(
    multer({
      dest: config.uploadPath,
      limits: {
        files: 1,
        fileSize: (config.app.upload_size || 10) * 1024 * 1024,
      },
    })
  );
  app.use(express.json());
  app.use(express.urlencoded());
  app.use(auth.proxied);
  app.use(auth.sessionLocals);
  app.use(app.router);
});

app.configure('development', function() {
  app.use(express.errorHandler());
});
var routes = require('./routes');

require('./routes/main')(app);
require('./routes/form')(app);
require('./routes/traveler')(app);
require('./routes/binder')(app);
require('./routes/report')(app);
require('./routes/admin')(app);
require('./routes/user')(app);
require('./routes/profile')(app);
require('./routes/device')(app);
require('./routes/ldaplogin')(app);
require('./routes/doc')(app);

app.get('/api', function(req, res) {
  res.render('api', {
    prefix: req.proxied ? req.proxied_prefix : '',
  });
});

// app.get('/', auth.ensureAuthenticated, routes.main);
app.get('/login', auth.ensureAuthenticated, function(req, res) {
  if (req.session.userid) {
    return res.redirect(req.proxied ? auth.proxied_service : '/');
  }

  // something wrong
  res.send(400, 'please enable cookie in your browser');
});

app.get('/logout', routes.logout);
app.get('/apis', function(req, res) {
  res.redirect('https://' + req.host + ':' + api.get('port') + req.originalUrl);
});

// Start application using settings
var appPort = appSettings.app_port;
var server;
if (appSettings.ssl_key !== undefined) {
  var appCredentials = {
    key: fs.readFileSync('./' + configPath + '/' + appSettings.ssl_key),
    cert: fs.readFileSync('./' + configPath + '/' + appSettings.ssl_cert),
  };
  server = https.createServer(appCredentials, app).listen(appPort, function() {
    console.log('Express server listening on ssl port ' + appPort);
  });
} else {
  server = http.createServer(app).listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
  });
}

/* Configure REST API */
var apiPort = apiSettings.app_port;
api.enable('strict routing');
api.configure(function() {
  api.set('port', process.env.APIPORT || apiPort);
  api.use(express.logger('dev'));

  // api.use(express.logger({stream: access_logfile}));
  api.use(express.json());
  api.use(express.urlencoded());
  api.use(auth.basicAuth);
  api.use(express.compress());
  api.use(api.router);
});

require('./routes/api')(api);

//Start Api using settings
var apiserver;
if (apiSettings.ssl_key !== undefined) {
  var apiCredentials = {
    key: fs.readFileSync('./' + configPath + '/' + apiSettings.ssl_key),
    cert: fs.readFileSync('./' + configPath + '/' + apiSettings.ssl_cert),
  };

  apiserver = https
    .createServer(apiCredentials, api)
    .listen(api.get('port'), function() {
      console.log('API server listening on ssl port ' + api.get('port'));
    });
} else {
  apiserver = http.createServer(api).listen(api.get('port'), function() {
    console.log('API server listening on port ' + api.get('port'));
  });
}

// When the node.js application is closed.
function cleanup() {
  server._connections = 0;
  apiserver._connections = 0;
  mongoose.connection.close();
  adClient.unbind(function() {
    console.log('ldap client stops.');
  });

  server.close(function() {
    apiserver.close(function() {
      console.log('web and api servers close.');

      // Close db connections, other chores, etc.
      process.exit();
    });
  });

  setTimeout(function() {
    console.error('Could not close connections in time, forcing shut down');
    process.exit(1);
  }, 30 * 1000);
}

process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
<commit_msg>use logger<commit_after>/* jslint es5: true */

var config = require('./config/config.js');
config.load();

var express = require('express');
var http = require('http');
var https = require('https');
var fs = require('fs');
var multer = require('multer');
var path = require('path');

const logger = require('./lib/loggers').get(process.env.NODE_ENV);

var rotator = require('file-stream-rotator');

var mongoose = require('mongoose');

var configPath = config.configPath;
var apiSettings = config.api;
var mongoConfig = config.mongo;
var appSettings = config.app;

// Load MongoDB object modeling tool
mongoose.connection.close();
// Load MongoDB models
require('./model/user.js');
require('./model/form.js');
require('./model/traveler.js');
require('./model/binder.js');
require('./model/history.js');

//Connect to mongo database
var mongoAddress = 'mongodb://';
mongoAddress += mongoConfig.server_address || 'localhost';
mongoAddress += ':' + (mongoConfig.server_port || '27017');
mongoAddress += '/' + (mongoConfig.traveler_db || 'traveler');

var mongoOptions = {
  native_parser: true,
  poolSize: 5,
  connectTimeoutMS: 30000,
  keepAlive: 1,
};

// Set authentication options if specified
if (mongoConfig.username !== undefined) {
  mongoOptions.user = mongoConfig.username;
  mongoOptions.pass = mongoConfig.password;
}
if (mongoConfig.auth) {
  mongoOptions.auth = config.mongo.auth;
}

mongoose.connect(mongoAddress, mongoOptions);
mongoose.connection.on('connected', function() {
  logger.info('Mongoose default connection opened.');
});

mongoose.connection.on('error', function(err) {
  logger.info('Mongoose default connection error: ' + err);
});

mongoose.connection.on('disconnected', function() {
  logger.info('Mongoose default connection disconnected');
});

// LDAP client
var adClient = require('./lib/ldap-client').client;
adClient.on('connect', function() {
  logger.info('ldap client connected');
});
adClient.on('timeout', function(message) {
  logger.error(message);
});
adClient.on('error', function(error) {
  logger.error(error);
});

// CAS client
var auth = require('./lib/auth');

// api and web app
var api = express();
var app = express();

/* Configure Web Application */
app.locals.orgName = appSettings.org_name;

app.enable('strict routing');
if (app.get('env') === 'production') {
  var access_logfile = rotator.getStream({
    filename: path.resolve(appSettings.log_dir, 'access.log'),
    frequency: 'daily',
  });
}

app.configure(function() {
  app.set('port', process.env.PORT || appSettings.app_port);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  if (app.get('env') === 'production') {
    app.use(
      express.logger({
        stream: access_logfile,
      })
    );
  }

  app.set('logger', logger);

  app.use(express.compress());
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.favicon(__dirname + '/public/favicon.ico'));
  if (app.get('env') === 'development') {
    app.use(express.logger('dev'));
  }

  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(
    express.session({
      secret: appSettings.cookie_sec || 'traveler_secret',
      cookie: {
        maxAge: appSettings.cookie_life || 28800000,
      },
    })
  );
  app.use(
    multer({
      dest: config.uploadPath,
      limits: {
        files: 1,
        fileSize: (config.app.upload_size || 10) * 1024 * 1024,
      },
    })
  );
  app.use(express.json());
  app.use(express.urlencoded());
  app.use(auth.proxied);
  app.use(auth.sessionLocals);
  app.use(app.router);
});

app.configure('development', function() {
  app.use(express.errorHandler());
});
var routes = require('./routes');

require('./routes/main')(app);
require('./routes/form')(app);
require('./routes/form-management')(app);
require('./routes/traveler')(app);
require('./routes/binder')(app);
require('./routes/report')(app);
require('./routes/admin')(app);
require('./routes/user')(app);
require('./routes/profile')(app);
require('./routes/device')(app);
require('./routes/ldaplogin')(app);
require('./routes/doc')(app);

app.get('/api', function(req, res) {
  res.render('api', {
    prefix: req.proxied ? req.proxied_prefix : '',
  });
});

// app.get('/', auth.ensureAuthenticated, routes.main);
app.get('/login', auth.ensureAuthenticated, function(req, res) {
  if (req.session.userid) {
    return res.redirect(req.proxied ? auth.proxied_service : '/');
  }

  // something wrong
  res.send(400, 'please enable cookie in your browser');
});

app.get('/logout', routes.logout);
app.get('/apis', function(req, res) {
  res.redirect('https://' + req.host + ':' + api.get('port') + req.originalUrl);
});

// Start application using settings
var appPort = appSettings.app_port;
var server;
if (appSettings.ssl_key !== undefined) {
  var appCredentials = {
    key: fs.readFileSync('./' + configPath + '/' + appSettings.ssl_key),
    cert: fs.readFileSync('./' + configPath + '/' + appSettings.ssl_cert),
  };
  server = https.createServer(appCredentials, app).listen(appPort, function() {
    logger.info('Express server listening on ssl port ' + appPort);
  });
} else {
  server = http.createServer(app).listen(app.get('port'), function() {
    logger.info('Express server listening on port ' + app.get('port'));
  });
}

/* Configure REST API */
var apiPort = apiSettings.app_port;
api.enable('strict routing');
api.configure(function() {
  api.set('port', process.env.APIPORT || apiPort);
  api.use(express.logger('dev'));

  // api.use(express.logger({stream: access_logfile}));
  api.use(express.json());
  api.use(express.urlencoded());
  api.use(auth.basicAuth);
  api.use(express.compress());
  api.use(api.router);
});

require('./routes/api')(api);

//Start Api using settings
var apiserver;
if (apiSettings.ssl_key !== undefined) {
  var apiCredentials = {
    key: fs.readFileSync('./' + configPath + '/' + apiSettings.ssl_key),
    cert: fs.readFileSync('./' + configPath + '/' + apiSettings.ssl_cert),
  };

  apiserver = https
    .createServer(apiCredentials, api)
    .listen(api.get('port'), function() {
      logger.info('API server listening on ssl port ' + api.get('port'));
    });
} else {
  apiserver = http.createServer(api).listen(api.get('port'), function() {
    logger.info('API server listening on port ' + api.get('port'));
  });
}

// When the node.js application is closed.
function cleanup() {
  server._connections = 0;
  apiserver._connections = 0;
  mongoose.connection.close();
  adClient.unbind(function() {
    logger.info('ldap client stops.');
  });

  server.close(function() {
    apiserver.close(function() {
      logger.info('web and api servers close.');

      // Close db connections, other chores, etc.
      process.exit();
    });
  });

  setTimeout(function() {
    logger.error('Could not close connections in time, forcing shut down');
    process.exit(1);
  }, 30 * 1000);
}

process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
<|endoftext|>