<commit_before>'use strict';

import React, {
    Component
} from 'react';

import {
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    Keyboard,
    Platform,
} from 'react-native';

type State = {
    keyboardUp: boolean,
}

class Tabs extends Component {
    state: State = {};

    onSelect(el){
        if (el.props.onSelect) {
            el.props.onSelect(el);
        } else if (this.props.onSelect) {
            this.props.onSelect(el);
        }
    }

    componentWillMount(){
        if (Platform.OS==='android') {
            Keyboard.addListener('keyboardDidShow', this.keyboardWillShow);
            Keyboard.addListener('keyboardDidHide', this.keyboardWillHide);
        }
    }

    keyboardWillShow = (e) => {
        this.setState({ keyboardUp: true });
    };

    keyboardWillHide = (e) => {
        this.setState({ keyboardUp: false });
    };

    render(){
        const self = this;
        let selected = this.props.selected
        if (!selected){
            React.Children.forEach(this.props.children.filter(c=>c), el=>{
                if (!selected || el.props.initial){
                    selected = el.props.name || el.key;
                }
            });
        }
        return (
            <View style={[styles.tabbarView, this.props.style, this.state.keyboardUp && styles.hidden]}>
                {React.Children.map(this.props.children.filter(c=>c),(el)=>
                    <TouchableOpacity key={el.props.name+"touch"}
                       testID={el.props.testID}
                       style={[styles.iconView, this.props.iconStyle, (el.props.name || el.key) == selected ? this.props.selectedIconStyle || el.props.selectedIconStyle || {} : {} ]}
                       onPress={()=>!self.props.locked && self.onSelect(el)}
                       onLongPress={()=>self.onSelect(el)}
                       activeOpacity={el.props.pressOpacity}>
                         {selected == (el.props.name || el.key) ? React.cloneElement(el, {selected: true, style: [el.props.style, this.props.selectedStyle, el.props.selectedStyle]}) : el}
                    </TouchableOpacity>
                )}
            </View>
        );
    }
}
var styles = StyleSheet.create({
    tabbarView: {
        position:'absolute',
        bottom:0,
        right:0,
        left:0,
        height:50,
        opacity:1,
        backgroundColor:'transparent',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
    iconView: {
        flex: 1,
        height: 50,
        justifyContent: 'center',
        alignItems: 'center',
    },
    hidden: {
        height: 0,
    },
});

module.exports = Tabs;
<commit_msg>Fix. setState() can only update a mounted component<commit_after>'use strict';

import React, {
    Component
} from 'react';

import {
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    Keyboard,
    Platform,
} from 'react-native';

type State = {
    keyboardUp: boolean,
}

class Tabs extends Component {
    state: State = {};

    onSelect(el){
        if (el.props.onSelect) {
            el.props.onSelect(el);
        } else if (this.props.onSelect) {
            this.props.onSelect(el);
        }
    }

    componentWillMount(){
        if (Platform.OS==='android') {
            this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this.keyboardWillShow);
            this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardWillHide);
        }
    }

    componentWillUnmount(){
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove();
    }

    keyboardWillShow = (e) => {
        this.setState({ keyboardUp: true });
    };

    keyboardWillHide = (e) => {
        this.setState({ keyboardUp: false });
    };

    render(){
        const self = this;
        let selected = this.props.selected
        if (!selected){
            React.Children.forEach(this.props.children.filter(c=>c), el=>{
                if (!selected || el.props.initial){
                    selected = el.props.name || el.key;
                }
            });
        }
        return (
            <View style={[styles.tabbarView, this.props.style, this.state.keyboardUp && styles.hidden]}>
                {React.Children.map(this.props.children.filter(c=>c),(el)=>
                    <TouchableOpacity key={el.props.name+"touch"}
                       testID={el.props.testID}
                       style={[styles.iconView, this.props.iconStyle, (el.props.name || el.key) == selected ? this.props.selectedIconStyle || el.props.selectedIconStyle || {} : {} ]}
                       onPress={()=>!self.props.locked && self.onSelect(el)}
                       onLongPress={()=>self.onSelect(el)}
                       activeOpacity={el.props.pressOpacity}>
                         {selected == (el.props.name || el.key) ? React.cloneElement(el, {selected: true, style: [el.props.style, this.props.selectedStyle, el.props.selectedStyle]}) : el}
                    </TouchableOpacity>
                )}
            </View>
        );
    }
}
var styles = StyleSheet.create({
    tabbarView: {
        position:'absolute',
        bottom:0,
        right:0,
        left:0,
        height:50,
        opacity:1,
        backgroundColor:'transparent',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
    iconView: {
        flex: 1,
        height: 50,
        justifyContent: 'center',
        alignItems: 'center',
    },
    hidden: {
        height: 0,
    },
});

module.exports = Tabs;
<|endoftext|>


<commit_before>var internals = {};
var fs = require("fs");
var moment = require("moment");
var Papa = require("papaparse");
var lodash = require("lodash");

String.prototype.splice = function(idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return true;
}

function returnCol(row, map, format){
	var parsed_row = {};
	for(var item in map){
		var value = row.substring(map[item].start-1, (map[item].start + map[item].width - 1)).trim();
		if(value){
			switch(map[item].type){
				case "date":
					if(map[item].inputformat){
						parsed_row[map[item].name] = moment(value, map[item].inputformat).format(map[item].outputformat);
					}
					else{
						parsed_row[map[item].name] = moment(value).format(map[item].outputformat);
					}
					break;
				case "float":
					var percision = 2;
					if(map[item].percision){
						percision = map[item].percision;
					}
					var symbol = "";
					if(map[item].symbol && format === "csv"){
						symbol = map[item].symbol;
					}
					parsed_row[map[item].name] = symbol + parseFloat(value.splice(map[item].width - percision, 0, ".")).toFixed(percision);
					break;
				case "int":
					parsed_row[map[item].name] = parseInt(value);
					break;
				case "bool":
					parsed_row[map[item].name] = false;
					if(value === map[item].tVal){
						parsed_row[map[item].name] = true;
					}
					break;
				case "string":
					parsed_row[map[item].name] = value;
					break;
				default:
					parsed_row[map[item].name] = value;
			}
		}
		else{
			parsed_row[map[item].name] = null;
		}
	}
	return parsed_row;
}

internals.parse = function(specs, input){
	try {
		if(typeof(specs) !== "object")  throw "specs is not an array";
		if(isEmpty(specs)) throw "specs is empty";
		if(isEmpty(specs.map)) throw "specs maps is empty";
		if(isEmpty(specs.options)) throw "specs options is empty";
		if(input === "") throw "input is empty";
		var array_output = [];
		var object_output = {};
		var split_input = input.replace(/\r\n/g,'\n').split("\n");
		if(split_input.indexOf("") !== -1){
			split_input.splice(split_input.indexOf(""), 1);
		}
		for(var i in split_input){
			if(split_input[i].length === specs.options.fullwidth && !specs.options.levels){
				if(specs.options.skiplines !== null){
					if(specs.options.skiplines.indexOf(parseInt(i) + 1) === -1){
						var row = returnCol(split_input[i], specs.map, specs.options.format);
						array_output.push(row)
					}
				}
				else{
					var row = returnCol(split_input[i], specs.map, specs.options.format);
					array_output.push(row)
				}
			}
			else if(specs.options.levels){
				var level = lodash.find(specs.options.levels, function(v, k){
					if(i >= v.start && i <= v.end){
						return true;
					}
				});
				var level_map = lodash.filter(specs.map, {
					level: lodash.findKey(specs.options.levels, function(v, k){
						if(i >= v.start && i <= v.end){
							return true;
						}
					})
				});
				if(split_input[i].length === level.fullwidth){
					if(!object_output.hasOwnProperty(level.nickname)){
						object_output[level.nickname] = [];
					}
					if(specs.options.skiplines !== null){
						if(specs.options.skiplines.indexOf(parseInt(i) + 1) === -1){
							var row = returnCol(split_input[i], level_map, specs.options.format);
							object_output[level.nickname].push(row);
						}
					}
					else{
						var row = returnCol(split_input[i], level_map, specs.options.format);
						object_output[level.nickname].push(row);
					}
				}
				else{
					throw "Row #" + (parseInt(i) + 1) + " does not match fullwidth";
				}
			}
			else{
				throw "Row #" + (parseInt(i) + 1) + " does not match fullwidth";
			}
		}
		switch(specs.options.format){
			case "csv":
				if(array_output.length === 0){
					throw "Multi-Level Maps Cannot Convert to CSV";
				}
				else{
					return Papa.unparse(array_output.length > 0 ? array_output : object_output, {
						newline: "\n"
					});
				}
				break;
			default:
				return array_output.length > 0 ? array_output : object_output;
		}
	}
	catch(err){
		console.log(err);
	}
};

internals.unparse = function(specs, input, levels){
	var output = [];
	try {
		if(typeof(specs) !== "object")  throw "specs is not an array";
		if(isEmpty(specs)) throw "specs is empty";
		if(input === "") throw "input is empty";
		var counter = 0;
		if(levels){
			var rowCount = 0;
			lodash.forEach(levels, function(l){
				var input_by_level = input[l];
				rowCount = rowCount + input_by_level.length;
			});
			lodash.forEach(levels, function(l){
				var input_by_level = input[l];
				var specs_by_level = lodash.filter(specs, {
					level: l
				});
				lodash.forEach(input_by_level, function(inp){
					lodash.forEach(specs_by_level, function(spec){
						var value = String(inp[spec.name]);
						var valueLength = value.length;
						if(spec.width - value.length > 0){
							for(var i = 1; i <= spec.width - valueLength; i++){
								var symbol = spec.padding_symbol ? spec.padding_symbol : " ";
								if(symbol.length > 1) throw "padding_symbol can not have length > 1";
								switch(spec.padding_position){
									case "start":
										value = symbol + value;
										break;
									case "end":
										value = value + symbol;
										break;
									default:
										value = symbol + value;
										break;
								}
							}
							output = output + value;
						}
					});
					counter = counter + 1;
					if(rowCount !== counter){
						output = output + "\n"
					}
				});

			});
			return output;
		}
		else{
			for(var row in input){
				for(var spec in specs){
					var value = String(input[row][specs[spec].name]);
					var valueLength = value.length;
					if(specs[spec].width - value.length > 0){
						for(var i = 1; i <= specs[spec].width - valueLength; i++){
							var symbol = specs[spec].padding_symbol ? specs[spec].padding_symbol : " ";
							if(symbol.length > 1) throw "padding_symbol can not have length > 1";
							switch(specs[spec].padding_position){
								case "start":
									value = symbol + value;
									break;
								case "end":
									value = value + symbol;
									break;
								default:
									value = symbol + value;
									break;
							}
						}
					}
					output = output + value;
				}
				counter = counter + 1;
				if(input.length !== counter){
					output = output + "\n"
				}
			}
			return output;
		}
	}
	catch(err){
		console.log(err);
	}
};

module.exports = internals;<commit_msg>Fixes #12<commit_after>var internals = {};
var fs = require("fs");
var moment = require("moment");
var Papa = require("papaparse");
var lodash = require("lodash");

String.prototype.splice = function(idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return true;
}

function returnCol(row, map, format){
	var parsed_row = {};
	for(var item in map){
		var value = row.substring(map[item].start-1, (map[item].start + map[item].width - 1)).trim();
		if(value){
			switch(map[item].type){
				case "date":
					if(map[item].inputformat){
						if(moment(value, map[item].inputformat).isValid()){
							parsed_row[map[item].name] = moment(value, map[item].inputformat).format(map[item].outputformat);
						}
						else{
							parsed_row[map[item].name] = null;
						}
					}
					else{
						if(moment(value).isValid()){
							parsed_row[map[item].name] = moment(value).format(map[item].outputformat);
						}
						else{
							parsed_row[map[item].name] = null;
						}
					}
					break;
				case "float":
					var percision = 2;
					if(map[item].percision){
						percision = map[item].percision;
					}
					var symbol = "";
					if(map[item].symbol && format === "csv"){
						symbol = map[item].symbol;
					}
					parsed_row[map[item].name] = symbol + parseFloat(value.splice(map[item].width - percision, 0, ".")).toFixed(percision);
					break;
				case "int":
					parsed_row[map[item].name] = parseInt(value);
					break;
				case "bool":
					parsed_row[map[item].name] = false;
					if(value === map[item].tVal){
						parsed_row[map[item].name] = true;
					}
					break;
				case "string":
					parsed_row[map[item].name] = value;
					break;
				default:
					parsed_row[map[item].name] = value;
			}
		}
		else{
			parsed_row[map[item].name] = null;
		}
	}
	return parsed_row;
}

internals.parse = function(specs, input){
	try {
		if(typeof(specs) !== "object")  throw "specs is not an array";
		if(isEmpty(specs)) throw "specs is empty";
		if(isEmpty(specs.map)) throw "specs maps is empty";
		if(isEmpty(specs.options)) throw "specs options is empty";
		if(input === "") throw "input is empty";
		var array_output = [];
		var object_output = {};
		var split_input = input.replace(/\r\n/g,'\n').split("\n");
		if(split_input.indexOf("") !== -1){
			split_input.splice(split_input.indexOf(""), 1);
		}
		for(var i in split_input){
			if(split_input[i].length === specs.options.fullwidth && !specs.options.levels){
				if(specs.options.skiplines !== null){
					if(specs.options.skiplines.indexOf(parseInt(i) + 1) === -1){
						var row = returnCol(split_input[i], specs.map, specs.options.format);
						array_output.push(row)
					}
				}
				else{
					var row = returnCol(split_input[i], specs.map, specs.options.format);
					array_output.push(row)
				}
			}
			else if(specs.options.levels){
				var level = lodash.find(specs.options.levels, function(v, k){
					if(i >= v.start && i <= v.end){
						return true;
					}
				});
				var level_map = lodash.filter(specs.map, {
					level: lodash.findKey(specs.options.levels, function(v, k){
						if(i >= v.start && i <= v.end){
							return true;
						}
					})
				});
				if(split_input[i].length === level.fullwidth){
					if(!object_output.hasOwnProperty(level.nickname)){
						object_output[level.nickname] = [];
					}
					if(specs.options.skiplines !== null){
						if(specs.options.skiplines.indexOf(parseInt(i) + 1) === -1){
							var row = returnCol(split_input[i], level_map, specs.options.format);
							object_output[level.nickname].push(row);
						}
					}
					else{
						var row = returnCol(split_input[i], level_map, specs.options.format);
						object_output[level.nickname].push(row);
					}
				}
				else{
					throw "Row #" + (parseInt(i) + 1) + " does not match fullwidth";
				}
			}
			else{
				throw "Row #" + (parseInt(i) + 1) + " does not match fullwidth";
			}
		}
		switch(specs.options.format){
			case "csv":
				if(array_output.length === 0){
					throw "Multi-Level Maps Cannot Convert to CSV";
				}
				else{
					return Papa.unparse(array_output.length > 0 ? array_output : object_output, {
						newline: "\n"
					});
				}
				break;
			default:
				return array_output.length > 0 ? array_output : object_output;
		}
	}
	catch(err){
		console.log(err);
	}
};

internals.unparse = function(specs, input, levels){
	var output = [];
	try {
		if(typeof(specs) !== "object")  throw "specs is not an array";
		if(isEmpty(specs)) throw "specs is empty";
		if(input === "") throw "input is empty";
		var counter = 0;
		if(levels){
			var rowCount = 0;
			lodash.forEach(levels, function(l){
				var input_by_level = input[l];
				rowCount = rowCount + input_by_level.length;
			});
			lodash.forEach(levels, function(l){
				var input_by_level = input[l];
				var specs_by_level = lodash.filter(specs, {
					level: l
				});
				lodash.forEach(input_by_level, function(inp){
					lodash.forEach(specs_by_level, function(spec){
						var value = String(inp[spec.name]);
						var valueLength = value.length;
						if(spec.width - value.length > 0){
							for(var i = 1; i <= spec.width - valueLength; i++){
								var symbol = spec.padding_symbol ? spec.padding_symbol : " ";
								if(symbol.length > 1) throw "padding_symbol can not have length > 1";
								switch(spec.padding_position){
									case "start":
										value = symbol + value;
										break;
									case "end":
										value = value + symbol;
										break;
									default:
										value = symbol + value;
										break;
								}
							}
							output = output + value;
						}
					});
					counter = counter + 1;
					if(rowCount !== counter){
						output = output + "\n"
					}
				});

			});
			return output;
		}
		else{
			for(var row in input){
				for(var spec in specs){
					var value = String(input[row][specs[spec].name]);
					var valueLength = value.length;
					if(specs[spec].width - value.length > 0){
						for(var i = 1; i <= specs[spec].width - valueLength; i++){
							var symbol = specs[spec].padding_symbol ? specs[spec].padding_symbol : " ";
							if(symbol.length > 1) throw "padding_symbol can not have length > 1";
							switch(specs[spec].padding_position){
								case "start":
									value = symbol + value;
									break;
								case "end":
									value = value + symbol;
									break;
								default:
									value = symbol + value;
									break;
							}
						}
					}
					output = output + value;
				}
				counter = counter + 1;
				if(input.length !== counter){
					output = output + "\n"
				}
			}
			return output;
		}
	}
	catch(err){
		console.log(err);
	}
};

module.exports = internals;<|endoftext|>


<commit_before>import {TextBuffer, Range, Point} from 'atom';

const LAYER_NAMES = ['unchanged', 'addition', 'deletion', 'nonewline', 'hunk', 'patch'];

export default class PatchBuffer {
  constructor() {
    this.buffer = new TextBuffer();
    this.layers = LAYER_NAMES.reduce((map, layerName) => {
      map[layerName] = this.buffer.addMarkerLayer();
      return map;
    }, {});
  }

  getBuffer() {
    return this.buffer;
  }

  getInsertionPoint() {
    return this.buffer.getEndPosition();
  }

  getLayer(layerName) {
    return this.layers[layerName];
  }

  findMarkers(layerName, ...args) {
    return this.layers[layerName].findMarkers(...args);
  }

  markPosition(layerName, ...args) {
    return this.layers[layerName].markPosition(...args);
  }

  markRange(layerName, ...args) {
    return this.layers[layerName].markRange(...args);
  }

  clearAllLayers() {
    for (const layerName of LAYER_NAMES) {
      this.layers[layerName].clear();
    }
  }

  createInserterAt(insertionPoint) {
    return new Inserter(this, Point.fromObject(insertionPoint));
  }

  createInserterAtEnd() {
    return this.createInserterAt(this.getInsertionPoint());
  }

  extractPatchBuffer(rangeLike) {
    const range = Range.fromObject(rangeLike);
    const baseOffset = range.start.negate();
    const movedMarkersByLayer = LAYER_NAMES.reduce((map, layerName) => {
      map[layerName] = this.layers[layerName].findMarkers({containedInRange: range});
      return map;
    }, {});
    const markerMap = new Map();

    const subBuffer = new PatchBuffer();
    subBuffer.getBuffer().setText(this.buffer.getTextInRange(range));

    for (const layerName of LAYER_NAMES) {
      for (const oldMarker of movedMarkersByLayer[layerName]) {
        const startOffset = oldMarker.getRange().start.row === range.start.row ? baseOffset : [baseOffset.row, 0];
        const endOffset = oldMarker.getRange().end.row === range.start.row ? baseOffset : [baseOffset.row, 0];
        const newMarker = subBuffer.markRange(
          layerName,
          oldMarker.getRange().translate(startOffset, endOffset),
          oldMarker.getProperties(),
        );
        markerMap.set(oldMarker, newMarker);
        oldMarker.destroy();
      }
    }

    this.buffer.setTextInRange(range, '');
    return {patchBuffer: subBuffer, markerMap};
  }
}

class Inserter {
  constructor(patchBuffer, insertionPoint) {
    this.patchBuffer = patchBuffer;
    this.startPoint = insertionPoint.copy();
    this.insertionPoint = insertionPoint;
    this.markerBlueprints = [];

    this.markersBefore = new Set();
    this.markersAfter = new Set();
  }

  keepBefore(markers) {
    for (const marker of markers) {
      if (marker.getRange().end.isEqual(this.startPoint)) {
        this.markersBefore.add(marker);
      }
    }
  }

  keepAfter(markers) {
    for (const marker of markers) {
      if (marker.getRange().end.isEqual(this.startPoint)) {
        this.markersAfter.add(marker);
      }
    }
  }

  markWhile(layerName, block, markerOpts) {
    const start = this.insertionPoint.copy();
    block();
    const end = this.insertionPoint.copy();
    this.markerBlueprints.push({layerName, range: new Range(start, end), markerOpts});
    return this;
  }

  insert(text) {
    const insertedRange = this.patchBuffer.getBuffer().insert(this.insertionPoint, text);
    this.insertionPoint = insertedRange.end;
    return this;
  }

  insertMarked(text, layerName, markerOpts) {
    return this.markWhile(layerName, () => this.insert(text), markerOpts);
  }

  insertPatchBuffer(subPatchBuffer, opts) {
    const baseOffset = this.insertionPoint.copy();
    this.insert(subPatchBuffer.getBuffer().getText());

    const subMarkerMap = new Map();
    for (const layerName of LAYER_NAMES) {
      for (const oldMarker of subPatchBuffer.findMarkers(layerName, {})) {
        const startOffset = oldMarker.getRange().start.row === 0 ? baseOffset : [baseOffset.row, 0];
        const endOffset = oldMarker.getRange().end.row === 0 ? baseOffset : [baseOffset.row, 0];

        const range = oldMarker.getRange().translate(startOffset, endOffset);
        const markerOpts = {
          ...oldMarker.getProperties(),
          callback: newMarker => { subMarkerMap.set(oldMarker, newMarker); },
        };
        this.markerBlueprints.push({layerName, range, markerOpts});
      }
    }

    if (opts.callback) {
      opts.callback(subMarkerMap);
    }

    return this;
  }

  apply() {
    for (const {layerName, range, markerOpts} of this.markerBlueprints) {
      const callback = markerOpts.callback;
      delete markerOpts.callback;

      const marker = this.patchBuffer.markRange(layerName, range, markerOpts);
      if (callback) {
        callback(marker);
      }
    }

    for (const beforeMarker of this.markersBefore) {
      if (!beforeMarker.isReversed()) {
        beforeMarker.setHeadPosition(this.startPoint);
      } else {
        beforeMarker.setTailPosition(this.startPoint);
      }
    }

    for (const afterMarker of this.markersAfter) {
      if (!afterMarker.isReversed()) {
        afterMarker.setTailPosition(this.insertionPoint);
      } else {
        afterMarker.setHeadPosition(this.insertionPoint);
      }
    }
  }
}
<commit_msg>PatchBuffer::inspect() to debug marker placement<commit_after>import {TextBuffer, Range, Point} from 'atom';
import {inspect} from 'util';

const LAYER_NAMES = ['unchanged', 'addition', 'deletion', 'nonewline', 'hunk', 'patch'];

export default class PatchBuffer {
  constructor() {
    this.buffer = new TextBuffer();
    this.layers = LAYER_NAMES.reduce((map, layerName) => {
      map[layerName] = this.buffer.addMarkerLayer();
      return map;
    }, {});
  }

  getBuffer() {
    return this.buffer;
  }

  getInsertionPoint() {
    return this.buffer.getEndPosition();
  }

  getLayer(layerName) {
    return this.layers[layerName];
  }

  findMarkers(layerName, ...args) {
    return this.layers[layerName].findMarkers(...args);
  }

  markPosition(layerName, ...args) {
    return this.layers[layerName].markPosition(...args);
  }

  markRange(layerName, ...args) {
    return this.layers[layerName].markRange(...args);
  }

  clearAllLayers() {
    for (const layerName of LAYER_NAMES) {
      this.layers[layerName].clear();
    }
  }

  createInserterAt(insertionPoint) {
    return new Inserter(this, Point.fromObject(insertionPoint));
  }

  createInserterAtEnd() {
    return this.createInserterAt(this.getInsertionPoint());
  }

  extractPatchBuffer(rangeLike) {
    const range = Range.fromObject(rangeLike);
    const baseOffset = range.start.negate();
    const movedMarkersByLayer = LAYER_NAMES.reduce((map, layerName) => {
      map[layerName] = this.layers[layerName].findMarkers({containedInRange: range});
      return map;
    }, {});
    const markerMap = new Map();

    const subBuffer = new PatchBuffer();
    subBuffer.getBuffer().setText(this.buffer.getTextInRange(range));

    for (const layerName of LAYER_NAMES) {
      for (const oldMarker of movedMarkersByLayer[layerName]) {
        const startOffset = oldMarker.getRange().start.row === range.start.row ? baseOffset : [baseOffset.row, 0];
        const endOffset = oldMarker.getRange().end.row === range.start.row ? baseOffset : [baseOffset.row, 0];
        const newMarker = subBuffer.markRange(
          layerName,
          oldMarker.getRange().translate(startOffset, endOffset),
          oldMarker.getProperties(),
        );
        markerMap.set(oldMarker, newMarker);
        oldMarker.destroy();
      }
    }

    this.buffer.setTextInRange(range, '');
    return {patchBuffer: subBuffer, markerMap};
  }

  inspect() {
    let inspectString = '';

    const increasingMarkers = [];
    for (const layerName of LAYER_NAMES) {
      for (const marker of this.findMarkers(layerName, {})) {
        increasingMarkers.push({layerName, point: marker.getRange().start, start: true, id: marker.id});
        increasingMarkers.push({layerName, point: marker.getRange().end, end: true, id: marker.id});
      }
    }
    increasingMarkers.sort((a, b) => {
      const cmp = a.point.compare(b.point);
      if (cmp !== 0) {
        return cmp;
      } else if (a.start && b.start) {
        return 0;
      } else if (a.start && !b.start) {
        return -1;
      } else if (!a.start && b.start) {
        return 1;
      } else {
        return 0;
      }
    });

    let inspectPoint = Point.fromObject([0, 0]);
    for (const marker of increasingMarkers) {
      if (!marker.point.isEqual(inspectPoint)) {
        inspectString += inspect(this.buffer.getTextInRange([inspectPoint, marker.point])) + '\n';
      }

      if (marker.start) {
        inspectString += `  start ${marker.layerName}@${marker.id}\n`;
      } else if (marker.end) {
        inspectString += `  end ${marker.layerName}@${marker.id}\n`;
      }

      inspectPoint = marker.point;
    }

    return inspectString;
  }
}

class Inserter {
  constructor(patchBuffer, insertionPoint) {
    this.patchBuffer = patchBuffer;
    this.startPoint = insertionPoint.copy();
    this.insertionPoint = insertionPoint;
    this.markerBlueprints = [];

    this.markersBefore = new Set();
    this.markersAfter = new Set();
  }

  keepBefore(markers) {
    for (const marker of markers) {
      if (marker.getRange().end.isEqual(this.startPoint)) {
        this.markersBefore.add(marker);
      }
    }
  }

  keepAfter(markers) {
    for (const marker of markers) {
      if (marker.getRange().end.isEqual(this.startPoint)) {
        this.markersAfter.add(marker);
      }
    }
  }

  markWhile(layerName, block, markerOpts) {
    const start = this.insertionPoint.copy();
    block();
    const end = this.insertionPoint.copy();
    this.markerBlueprints.push({layerName, range: new Range(start, end), markerOpts});
    return this;
  }

  insert(text) {
    const insertedRange = this.patchBuffer.getBuffer().insert(this.insertionPoint, text);
    this.insertionPoint = insertedRange.end;
    return this;
  }

  insertMarked(text, layerName, markerOpts) {
    return this.markWhile(layerName, () => this.insert(text), markerOpts);
  }

  insertPatchBuffer(subPatchBuffer, opts) {
    const baseOffset = this.insertionPoint.copy();
    this.insert(subPatchBuffer.getBuffer().getText());

    const subMarkerMap = new Map();
    for (const layerName of LAYER_NAMES) {
      for (const oldMarker of subPatchBuffer.findMarkers(layerName, {})) {
        const startOffset = oldMarker.getRange().start.row === 0 ? baseOffset : [baseOffset.row, 0];
        const endOffset = oldMarker.getRange().end.row === 0 ? baseOffset : [baseOffset.row, 0];

        const range = oldMarker.getRange().translate(startOffset, endOffset);
        const markerOpts = {
          ...oldMarker.getProperties(),
          callback: newMarker => { subMarkerMap.set(oldMarker, newMarker); },
        };
        this.markerBlueprints.push({layerName, range, markerOpts});
      }
    }

    if (opts.callback) {
      opts.callback(subMarkerMap);
    }

    return this;
  }

  apply() {
    for (const {layerName, range, markerOpts} of this.markerBlueprints) {
      const callback = markerOpts.callback;
      delete markerOpts.callback;

      const marker = this.patchBuffer.markRange(layerName, range, markerOpts);
      if (callback) {
        callback(marker);
      }
    }

    for (const beforeMarker of this.markersBefore) {
      if (!beforeMarker.isReversed()) {
        beforeMarker.setHeadPosition(this.startPoint);
      } else {
        beforeMarker.setTailPosition(this.startPoint);
      }
    }

    for (const afterMarker of this.markersAfter) {
      if (!afterMarker.isReversed()) {
        afterMarker.setTailPosition(this.insertionPoint);
      } else {
        afterMarker.setHeadPosition(this.insertionPoint);
      }
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Implement package exports<commit_after>'use strict';

var model_factory = require('./src/model-factory');
var Repository = require('./src/repository');

module.exports = {
    model_factory: model_factory,
    Repository: Repository
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Sprymix Inc.
 * All rights reserved.
 *
 * See LICENSE for details.
 */

// %import metamagic.utils.lang.javascript.types
// %import metamagic.caos.frontends.javascript.base

sx.types.register('pgjson.', function(format, data, metadata, ctx) {
    "use strict";

    var format_string = format[0], format_version = format[1];
    var FREEFORM_RECORD_ID = '6e51108d-7440-47f7-8c65-dc4d43fd90d2';
    var supported_formats = ['pgjson.caos.selector', 'pgjson.caos.queryselector',
                             'pgjson.caos.entity', 'pgjson.caos'];
    var hop = {}.constructor.prototype.hasOwnProperty;
    var session = (ctx ? ctx.session : null) || sx.caos.$current_session;

    var _throw = function(msg) {
        throw new sx.Error('malformed "' + format_string + '" data: ' + msg);
    }

    var is_concept = function(cls) {
        return cls.$sx_prototype.__class__ === sx.caos.ProtoConcept;
    };

    var merge_into_session = function(session, cls, data, virtuals_map) {
        var result = session.get(data['metamagic.caos.builtins.id']);

        if (result) {
            result.update(data, virtuals_map);
        } else {
            session.withSession(function() {
                result = new cls(data, virtuals_map);
            });
        }

        return result;
    };

    var merge_entity = function(session, data, rec_info) {
        var clsname = data['$sxclsname$'];
        data['$sxclsname$'] = null;
        var cls = sx.caos.schema.get(clsname);

        // Filter out pointers that do not belong to this class.
        // This happens when we receive a combined record for multiple classes.
        var keys = sx.keys(data), kl = keys.length;

        var result;

        for (var i = 0; i < kl; i++) {
            var key = keys[i];
            if (!sx.contains(key, '<') && !cls['$ptr$' + key]) {
                delete data[key];
            }
        }

        if (session != null && is_concept(cls)) {
            result = merge_into_session(session, cls, data,
                                        rec_info.virtuals_map);
        } else {
            result = new cls(data, rec_info.virtuals_map);
        }

        return result;
    };

    if (sx.contains(supported_formats, format_string)) {
        if (format_version != 1) {
            throw new sx.Error('unsupported "' + format_string + '" version: ' + format_version);
        }
    } else {
        _throw('unsupported format: "' + format_string + '"');
    }

    if (!sx.is_array(data)) {
        _throw('not an array');
    }

    var result = [];
    var record_info = {};

    if (metadata) {
        for (var i = 0; i < metadata.record_info.length; i++) {
            var ri = metadata.record_info[i];
            record_info[ri.id] = ri;
        }
    }

    var _decode_record_tree = function(tree, connecting_attribute) {
        var tl = tree.length;

        var toplevel = [];
        var updates = {};
        var ca = connecting_attribute;
        var attrname = ca.name + ca.direction + ca.target;
        var target;

        var total_order = {};

        var items = {};

        for (var i = 0; i < tl; i++) {
            var item = _decode_record(tree[i]);
            var item_id = item[ca.name].id;
            items[item_id] = item;
            total_order[item_id] = i;
        }

        for (var id in items) {
            if (!items.hasOwnProperty(id)) {
                continue;
            }

            var item = items[id];

            var entity = item[ca.name];

            if (entity == null) {
                continue;
            }

            var target_id = item['__target__'];

            if (target_id == null) {
                continue;
            }

            var target = items[target_id];

            if (!target) {
                // The items below us have been cut off by recursion depth limit
                continue;
            }

            var titem = [total_order[target_id], target[ca.name]];

            if (item['__depth__'] == 0) {
                sx.array.insort_left(toplevel, titem);
            } else {
                if (!updates.hasOwnProperty(entity.id)) {
                    updates[entity.id] = [titem];
                } else {
                    sx.array.insort_left(updates[entity.id], titem);
                }
            }
        }

        for (var src_id in updates) {
            if (hop.call(updates, src_id)) {
                var src = items[src_id][ca.name];
                if (!src) {
                    _throw('unexpected error in recursion tree unpack: source is empty');
                }

                var src_updates = updates[src_id];
                var entities = [];

                for (var i = 0; i < src_updates.length; i++) {
                    entities.push(src_updates[i][1]);
                }

                var u = {};
                u[attrname] = entities;

                src.update(u);
            }
        }

        var toplevel_entities = [];

        for (var i = 0; i < toplevel.length; i++) {
            toplevel_entities.push(toplevel[i][1]);
        }

        return toplevel_entities;
    };

    var _decode_sequence = function(seq) {
        var i, len, v, result = [];

        for (i = 0, len = seq.length; i < len; i++) {
            v = seq[i];

            if (v && hop.call(v, 'f1')) {
                v = _decode_record(v);
            }

            if (v != null) {
                result.push(v);
            }
        }

        return result;
    }

    var _decode_record = function(record) {
        var result = {};
        var rec_id = record.f1;
        var rec_info = record_info[rec_id];
        var k, v, reclen, i, item_val, item_key, _rec;

        if (rec_id == FREEFORM_RECORD_ID) {
            result = [];

            reclen = sx.len(record);
            for (i = 1; i < reclen; i++) {
                k = 'f' + (i + 1).toString();
                item_val = record[k];

                if (item_val && hop.call(item_val, 'f1')) {
                    item_val = _decode_record(item_val);
                } else if (sx.is_array(item_val)) {
                    item_val = _decode_sequence(item_val);
                }

                result.push(item_val);
            }
        } else if (!rec_info) {
            if (format_string == 'pgjson.caos') {
                // Raw SQL result
                result = record;
            } else {
                for (k in record) {
                    if (!hop.call(record, k)) {
                        continue;
                    }
                    v = record[k];

                    item_key = v.f1;

                    if (!item_key) {
                        _throw('missing record item name');
                    }

                    item_val = v.f2;

                    if (item_val && hop.call(item_val, 'f1')) {
                        item_val = _decode_record(item_val);
                    } else if (sx.is_array(item_val)) {
                        item_val = _decode_sequence(item_val);
                    }

                    result[item_key] = item_val;
                }
            }
        } else {
            if (rec_info.recursive_link) {
                _rec = {};

                reclen = sx.len(record);
                for (i = 1; i < reclen; i++) {
                    k = 'f' + (i + 1).toString();
                    item_key = rec_info.attribute_map[i - 1];

                    item_val = record[k];

                    _rec[item_key] = item_val;
                }

                if (_rec['data']) {
                    return _decode_record_tree(_rec['data'], rec_info.recursive_link);
                }
            }

            reclen = sx.len(record);
            for (i = 1; i < reclen; i++) {
                k = 'f' + (i + 1).toString();
                item_key = rec_info.attribute_map[i - 1];

                if (!item_key) {
                    _throw('missing record item name');
                }

                item_val = record[k];

                if (item_val && hop.call(item_val, 'f1')) {
                    item_val = _decode_record(item_val);
                } else if (sx.is_array(item_val)) {
                    item_val = _decode_sequence(item_val);
                }

                if (sx.is_object(item_key)) {
                    // key is a PointerVector
                    if (item_key.direction == '<') {
                        result[item_key.name + item_key.direction + item_key.target] = item_val;
                    } else {
                        result[item_key.name] = item_val;
                    }
                } else {
                    result[item_key] = item_val;
                }
            }
        }

        if (result['$sxclsid$']) {
            result['$sxclsid$'] = null;
        }

        if (result['$sxclsname$']) {
            result = merge_entity(session, result, rec_info);
        } else if (result.hasOwnProperty('t')) {
            result = new sx.caos.xvalue(result['t'], result['p']);
        }

        return result;
    };

    if (format_string == 'pgjson.caos.selector' || format_string == 'pgjson.caos.entity') {
        for (var i = 0; i < data.length; i++) {
            var row = sx.json.parse(data[i]);
            var item = _decode_record(row);

            if (sx.len(item) != 1) {
                _throw('top-level element must contain exactly one attribute');
            }

            result.push(sx.first(item));
        }
    } else {
        for (var i = 0; i < data.length; i++) {
            var row = sx.json.parse(data[i]);
            var item = _decode_record(row);

            result.push(item);
        }
    }

    if (format_string == 'pgjson.caos.entity') {
        var rlen = sx.len(result);

        if (rlen > 1) {
            _throw('caos.entity selector did not yield exactly one element');
        } else if (rlen == 0) {
            result = null;
        } else {
            result = result[0];
        }
    }

    return result;
});
<commit_msg>caos.frontends.js: Batch session notifications when unpacking tres<commit_after>/*
 * Copyright (c) 2012 Sprymix Inc.
 * All rights reserved.
 *
 * See LICENSE for details.
 */

// %import metamagic.utils.lang.javascript.types
// %import metamagic.caos.frontends.javascript.base

sx.types.register('pgjson.', function(format, data, metadata, ctx) {
    "use strict";

    var format_string = format[0], format_version = format[1];
    var FREEFORM_RECORD_ID = '6e51108d-7440-47f7-8c65-dc4d43fd90d2';
    var supported_formats = ['pgjson.caos.selector', 'pgjson.caos.queryselector',
                             'pgjson.caos.entity', 'pgjson.caos'];
    var hop = {}.constructor.prototype.hasOwnProperty;
    var session = (ctx ? ctx.session : null) || sx.caos.$current_session;

    var _throw = function(msg) {
        throw new sx.Error('malformed "' + format_string + '" data: ' + msg);
    }

    var is_concept = function(cls) {
        return cls.$sx_prototype.__class__ === sx.caos.ProtoConcept;
    };

    var merge_into_session = function(session, cls, data, virtuals_map) {
        var result = session.get(data['metamagic.caos.builtins.id']);

        if (result) {
            result.update(data, virtuals_map);
        } else {
            session.withSession(function() {
                result = new cls(data, virtuals_map);
            });
        }

        return result;
    };

    var merge_entity = function(session, data, rec_info) {
        var clsname = data['$sxclsname$'];
        data['$sxclsname$'] = null;
        var cls = sx.caos.schema.get(clsname);

        // Filter out pointers that do not belong to this class.
        // This happens when we receive a combined record for multiple classes.
        var keys = sx.keys(data), kl = keys.length;

        var result;

        for (var i = 0; i < kl; i++) {
            var key = keys[i];
            if (!sx.contains(key, '<') && !cls['$ptr$' + key]) {
                delete data[key];
            }
        }

        if (session != null && is_concept(cls)) {
            result = merge_into_session(session, cls, data,
                                        rec_info.virtuals_map);
        } else {
            result = new cls(data, rec_info.virtuals_map);
        }

        return result;
    };

    if (sx.contains(supported_formats, format_string)) {
        if (format_version != 1) {
            throw new sx.Error('unsupported "' + format_string + '" version: ' + format_version);
        }
    } else {
        _throw('unsupported format: "' + format_string + '"');
    }

    if (!sx.is_array(data)) {
        _throw('not an array');
    }

    var result = [];
    var record_info = {};

    if (metadata) {
        for (var i = 0; i < metadata.record_info.length; i++) {
            var ri = metadata.record_info[i];
            record_info[ri.id] = ri;
        }
    }

    var _decode_record_tree = function(tree, connecting_attribute) {
        var tl = tree.length;

        var toplevel = [];
        var updates = {};
        var ca = connecting_attribute;
        var attrname = ca.name + ca.direction + ca.target;
        var target;

        var total_order = {};

        var items = {};

        for (var i = 0; i < tl; i++) {
            var item = _decode_record(tree[i]);
            var item_id = item[ca.name].id;
            items[item_id] = item;
            total_order[item_id] = i;
        }

        for (var id in items) {
            if (!items.hasOwnProperty(id)) {
                continue;
            }

            var item = items[id];

            var entity = item[ca.name];

            if (entity == null) {
                continue;
            }

            var target_id = item['__target__'];

            if (target_id == null) {
                continue;
            }

            var target = items[target_id];

            if (!target) {
                // The items below us have been cut off by recursion depth limit
                continue;
            }

            var titem = [total_order[target_id], target[ca.name]];

            if (item['__depth__'] == 0) {
                sx.array.insort_left(toplevel, titem);
            } else {
                if (!updates.hasOwnProperty(entity.id)) {
                    updates[entity.id] = [titem];
                } else {
                    sx.array.insort_left(updates[entity.id], titem);
                }
            }
        }

        for (var src_id in updates) {
            if (hop.call(updates, src_id)) {
                var src = items[src_id][ca.name];
                if (!src) {
                    _throw('unexpected error in recursion tree unpack: source is empty');
                }

                var src_updates = updates[src_id];
                var entities = [];

                for (var i = 0; i < src_updates.length; i++) {
                    entities.push(src_updates[i][1]);
                }

                var u = {};
                u[attrname] = entities;

                src.update(u);
            }
        }

        var toplevel_entities = [];

        for (var i = 0; i < toplevel.length; i++) {
            toplevel_entities.push(toplevel[i][1]);
        }

        return toplevel_entities;
    };

    var _decode_sequence = function(seq) {
        var i, len, v, result = [];

        for (i = 0, len = seq.length; i < len; i++) {
            v = seq[i];

            if (v && hop.call(v, 'f1')) {
                v = _decode_record(v);
            }

            if (v != null) {
                result.push(v);
            }
        }

        return result;
    }

    var _decode_record = function(record) {
        var result = {};
        var rec_id = record.f1;
        var rec_info = record_info[rec_id];
        var k, v, reclen, i, item_val, item_key, _rec;

        if (rec_id == FREEFORM_RECORD_ID) {
            result = [];

            reclen = sx.len(record);
            for (i = 1; i < reclen; i++) {
                k = 'f' + (i + 1).toString();
                item_val = record[k];

                if (item_val && hop.call(item_val, 'f1')) {
                    item_val = _decode_record(item_val);
                } else if (sx.is_array(item_val)) {
                    item_val = _decode_sequence(item_val);
                }

                result.push(item_val);
            }
        } else if (!rec_info) {
            if (format_string == 'pgjson.caos') {
                // Raw SQL result
                result = record;
            } else {
                for (k in record) {
                    if (!hop.call(record, k)) {
                        continue;
                    }
                    v = record[k];

                    item_key = v.f1;

                    if (!item_key) {
                        _throw('missing record item name');
                    }

                    item_val = v.f2;

                    if (item_val && hop.call(item_val, 'f1')) {
                        item_val = _decode_record(item_val);
                    } else if (sx.is_array(item_val)) {
                        item_val = _decode_sequence(item_val);
                    }

                    result[item_key] = item_val;
                }
            }
        } else {
            if (rec_info.recursive_link) {
                _rec = {};

                reclen = sx.len(record);
                for (i = 1; i < reclen; i++) {
                    k = 'f' + (i + 1).toString();
                    item_key = rec_info.attribute_map[i - 1];

                    item_val = record[k];

                    _rec[item_key] = item_val;
                }

                if (_rec['data']) {
                    return _decode_record_tree(_rec['data'], rec_info.recursive_link);
                }
            }

            reclen = sx.len(record);
            for (i = 1; i < reclen; i++) {
                k = 'f' + (i + 1).toString();
                item_key = rec_info.attribute_map[i - 1];

                if (!item_key) {
                    _throw('missing record item name');
                }

                item_val = record[k];

                if (item_val && hop.call(item_val, 'f1')) {
                    item_val = _decode_record(item_val);
                } else if (sx.is_array(item_val)) {
                    item_val = _decode_sequence(item_val);
                }

                if (sx.is_object(item_key)) {
                    // key is a PointerVector
                    if (item_key.direction == '<') {
                        result[item_key.name + item_key.direction + item_key.target] = item_val;
                    } else {
                        result[item_key.name] = item_val;
                    }
                } else {
                    result[item_key] = item_val;
                }
            }
        }

        if (result['$sxclsid$']) {
            result['$sxclsid$'] = null;
        }

        if (result['$sxclsname$']) {
            result = merge_entity(session, result, rec_info);
        } else if (result.hasOwnProperty('t')) {
            result = new sx.caos.xvalue(result['t'], result['p']);
        }

        return result;
    };

    var _decode = function() {
        if (format_string == 'pgjson.caos.selector'
                    || format_string == 'pgjson.caos.entity') {
            for (var i = 0; i < data.length; i++) {
                var row = sx.json.parse(data[i]);
                var item = _decode_record(row);

                if (sx.len(item) != 1) {
                    _throw('top-level element must contain exactly one attribute');
                }

                result.push(sx.first(item));
            }
        } else {
            for (var i = 0; i < data.length; i++) {
                var row = sx.json.parse(data[i]);
                var item = _decode_record(row);

                result.push(item);
            }
        }

        if (format_string == 'pgjson.caos.entity') {
            var rlen = sx.len(result);

            if (rlen > 1) {
                _throw('caos.entity selector did not yield exactly one element');
            } else if (rlen == 0) {
                result = null;
            } else {
                result = result[0];
            }
        }
    }

    session.withBatch(_decode)

    return result;
});
<|endoftext|>


<commit_before>'use strict';
// Reference: https://projectpokemon.org/wiki/Pokemon_X/Y_3DS_Structure
function stripNullChars (str) {
  return str.replace(/\0.*/, '');
}

function parseMap (data, map) {
  const parsedData = [];
  for (let i = 0; i < map.length; i++, data = Math.floor(data / 2)) {
    if (map[i] && data % 2) {
      parsedData.push(map[i]);
    }
  }
  return parsedData;
}

function checksumIsValid (buf) {
  let sum = 0;
  for (let i = 8; i < 232; i += 2) {
    sum += buf.readUInt16LE(i);
  }
  return (sum & 0xffff) === buf.readUInt16LE(0x06);
}

function getDateFromInt (dateStorage) {
  if (!dateStorage) {
    return null;
  }
  return Date.UTC((dateStorage & 0xff) + 2000, (dateStorage >>> 8 & 0xff) - 1, (dateStorage >>> 16 & 0xff));
}

exports.parseBuffer = buf => {
  if (buf.readUInt16LE(0x04) || !checksumIsValid(buf) || [232, 260].indexOf(buf.length) === -1 || buf.readUInt8(0x58) || buf.readUInt8(0x90) || buf.readUInt8(0xc8)) {
    throw new TypeError('The provided buffer is not valid pk6 data');
  }
  const data = {};
  data.encryptionConstant = buf.readUInt32LE(0x00);
  data.dexNo = buf.readUInt16LE(0x08);
  data.heldItemId = buf.readUInt16LE(0x0a);
  data.tid = buf.readUInt16LE(0x0c);
  data.sid = buf.readUInt16LE(0x0e);
  data.exp = buf.readUInt32LE(0x10);
  data.abilityId = buf.readUInt8(0x14);
  data.abilityNum = buf.readUInt8(0x15);
  data.superTrainingHitsRemaining = buf.readUInt8(0x16);
  data.superTrainingBag = buf.readUInt8(0x17);
  data.pid = buf.readUInt32LE(0x18);
  data.natureId = buf.readUInt8(0x1c);

  const genderByte = buf.readUInt8(0x1d);
  data.isFatefulEncounter = !!(genderByte & 0x01);
  const isFemale = genderByte & 0x02;
  const isGenderless = genderByte & 0x04;
  data.gender = isFemale ? 'F' : isGenderless ? '' : 'M';
  data.formId = genderByte >>> 3;

  data.evHp = buf.readUInt8(0x1e);
  data.evAtk = buf.readUInt8(0x1f);
  data.evDef = buf.readUInt8(0x20);
  data.evSpe = buf.readUInt8(0x21);
  data.evSpAtk = buf.readUInt8(0x22);
  data.evSpDef = buf.readUInt8(0x23);

  data.contestStatCool = buf.readUInt8(0x24);
  data.contestStatBeauty = buf.readUInt8(0x25);
  data.contestStatCute = buf.readUInt8(0x26);
  data.contestStatSmart = buf.readUInt8(0x27);
  data.contestStatTough = buf.readUInt8(0x28);
  data.contestStatSheen = buf.readUInt8(0x29);

  const markingByte = buf.readUInt8(0x2a);
  data.hasCircleMarking = !!(markingByte & 0x01);
  data.hasTriangleMarking = !!(markingByte & 0x02);
  data.hasSquareMarking = !!(markingByte & 0x04);
  data.hasHeartMarking = !!(markingByte & 0x08);
  data.hasStarMarking = !!(markingByte & 0x10);
  data.hasDiamondMarking = !!(markingByte & 0x20);

  const pokerusByte = buf.readUInt8(0x2b);
  data.pokerusDuration = pokerusByte & 16;
  data.pokerusStrain = pokerusByte >>> 4;

  data.medalData = buf.readUInt32LE(0x2c);
  data.ribbonData = buf.readUIntLE(0x30, 6);
  data.distributionSuperTrainingFlags = buf.readUInt8(0x3a); // Not sure what these are
  data.nickname = stripNullChars(buf.toString('utf16le', 0x40, 0x58));

  data.move1Id = buf.readUInt16LE(0x5a);
  data.move2Id = buf.readUInt16LE(0x5c);
  data.move3Id = buf.readUInt16LE(0x5e);
  data.move4Id = buf.readUInt16LE(0x60);
  data.move1Pp = buf.readUInt8(0x62);
  data.move2Pp = buf.readUInt8(0x63);
  data.move3Pp = buf.readUInt8(0x64);
  data.move4Pp = buf.readUInt8(0x65);
  data.move1Ppu = buf.readUInt8(0x66);
  data.move2Ppu = buf.readUInt8(0x67);
  data.move3Ppu = buf.readUInt8(0x68);
  data.move4Ppu = buf.readUInt8(0x69);
  data.eggMove1Id = buf.readUInt16LE(0x6a);
  data.eggMove2Id = buf.readUInt16LE(0x6c);
  data.eggMove3Id = buf.readUInt16LE(0x6e);
  data.eggMove4Id = buf.readUInt16LE(0x70);

  data.canDoSecretSuperTraining = !!(buf.readUInt8(0x72));

  const ivBytes = buf.readUInt32LE(0x74);
  data.ivHp = ivBytes & 0x1f;
  data.ivAtk = ivBytes >>> 5 & 0x1f;
  data.ivDef = ivBytes >>> 10 & 0x1f;
  data.ivSpe = ivBytes >>> 15 & 0x1f;
  data.ivSpAtk = ivBytes >>> 20 & 0x1f;
  data.ivSpDef = ivBytes >>> 25 & 0x1f;
  data.isEgg = (ivBytes >>> 30) % 2 !== 0;
  data.isNicknamed = (ivBytes >>> 31) % 2 !== 0;

  data.notOt = stripNullChars(buf.toString('utf16le', 0x78, 0x90));
  data.notOtGender = buf.readUInt8(0x92) ? 'F' : 'M';

  data.currentHandlerIsOt = !buf.readUInt8(0x93);

  data.geoLocation1 = buf.readUInt16LE(0x94); // TODO: Figure out how to parse these
  data.geoLocation2 = buf.readUInt16LE(0x96);
  data.geoLocation3 = buf.readUInt16LE(0x98);
  data.geoLocation4 = buf.readUInt16LE(0x9a);
  data.geoLocation5 = buf.readUInt16LE(0x9c);

  data.notOtFriendship = buf.readUInt8(0xa2);
  data.notOtAffection = buf.readUInt8(0xa3);
  data.notOtMemoryIntensity = buf.readUInt8(0xa4); // TODO: Parse
  data.notOtMemoryLine = buf.readUInt8(0xa5);
  data.notOtMemoryFeeling = buf.readUInt8(0xa6);
  data.notOtMemoryTextVar = buf.readUInt16LE(0xa8);

  data.fullness = buf.readUInt8(0xae);
  data.enjoyment = buf.readUInt8(0xaf);

  data.ot = stripNullChars(buf.toString('utf16le', 0xb0, 0xc8));
  data.otFriendship = buf.readUInt8(0xca);
  data.otAffection = buf.readUInt8(0xcb);
  data.otMemoryIntensity = buf.readUInt8(0xcc); // TODO: Parse
  data.otMemoryLine = buf.readUInt8(0xcd);
  data.otMemoryTextVar = buf.readUInt16LE(0xce);
  data.otMemoryFeeling = buf.readUInt8(0xd0);

  data.eggDate = getDateFromInt(buf.readUIntLE(0xd1, 3));
  data.metDate = getDateFromInt(buf.readUIntLE(0xd4, 3));

  data.eggLocationId = buf.readUInt16LE(0xd8);
  data.metLocationId = buf.readUInt32LE(0xda);
  data.ballId = buf.readUInt8(0xdc);

  const encounterLevelByte = buf.readUInt8(0xdd);
  data.levelMet = encounterLevelByte & 0x7f;
  data.otGender = encounterLevelByte >>> 7 ? 'F' : 'M';

  data.encounterTypeId = buf.readUInt8(0xde);
  data.otGameId = buf.readUInt8(0xdf);
  data.countryId = buf.readUInt8(0xe0); // TODO: Parse
  data.regionId = buf.readUInt8(0xe1); // TODO: Parse
  data.consoleRegion = ['J', 'U', 'E', '?', 'C', 'K', 'T'][buf.readUInt8(0xe2)];
  data.language = [null, 'JPN', 'ENG', 'FRE', 'ITA', 'GER', '???', 'SPA', 'KOR'][buf.readUInt8(0xe3)];
  data._rawPk6 = buf.toString('base64');

  return data;
};

const langMap = {ENG: 'en', SPA: 'es', FRE: 'fr', GER: 'de', ITA: 'it', JPN: 'ja', KOR: 'ko'};
exports.assignReadableNames = (data, language) => {
  const findName = specificData => specificData && specificData.names.find(data => data.language === langMap[language]).name;
  language = language || 'ENG';
  if (!langMap.hasOwnProperty(language)) {
    throw new TypeError(`Invalid language '${language}'`);
  }
  data.speciesName = findName(exports.getPokemonData(data.dexNo));
  data.heldItemName = findName(exports.getItemData(data.heldItemId));
  data.abilityName = findName(exports.getAbilityData(data.abilityId));
  data.natureName = findName(exports.getNatureData(data.natureId));
  data.move1Name = findName(exports.getMoveData(data.move1Id));
  data.move2Name = findName(exports.getMoveData(data.move2Id));
  data.move3Name = findName(exports.getMoveData(data.move3Id));
  data.move4Name = findName(exports.getMoveData(data.move4Id));
  data.eggMove1Name = findName(exports.getMoveData(data.eggMove1Id));
  data.eggMove2Name = findName(exports.getMoveData(data.eggMove2Id));
  data.eggMove3Name = findName(exports.getMoveData(data.eggMove3Id));
  data.eggMove4Name = findName(exports.getMoveData(data.eggMove4Id));
  data.medals = exports.getMedalData(data.medalData);
  data.ribbons = exports.getRibbonData(data.ribbonData);
  data.eggLocationName = exports.getLocationData(data.eggLocationId);
  data.metLocationName = exports.getLocationData(data.metLocationId);
  data.encounterTypeName = exports.getEncounterTypeData(data.encounterTypeId);
  data.otGameName = exports.getGameData(data.otGameId);
  return data;
};

exports.parseFile = path => {
  return exports.parseBuffer(require('fs').readFileSync(path));
};

exports.getPokemonData = dexNo => {
  try {
    return require(`./pokemon_data/${dexNo}.json`);
  } catch (e) {
    throw new TypeError(`Invalid dex number: ${dexNo}`);
  }
};

exports.getItemData = itemId => {
  if (itemId === 0) {
    return null;
  }
  try {
    return require(`./item_data_gen6/${itemId}.json`);
  } catch (e) {
    throw new TypeError(`Invalid item ID: ${itemId}`);
  }
};

exports.getMoveData = moveId => {
  if (moveId === 0) {
    return null;
  }
  try {
    return require(`./move_data/${moveId}.json`);
  } catch (e) {
    throw new TypeError(`Invalid move ID: ${moveId}`);
  }
};

exports.getAbilityData = abilityId => {
  if (abilityId === 0) {
    return null;
  }
  try {
    return require(`./ability_data/${abilityId}.json`);
  } catch (e) {
    throw new TypeError(`Invalid ability ID: ${abilityId}`);
  }
};

exports.getNatureData = natureId => {
  if (natureId === 0) {
    return null;
  }
  try {
    return require(`./nature_data/${natureId}.json`);
  } catch (e) {
    throw new TypeError(`Invalid nature ID: ${natureId}`);
  }
};

exports.getLocationData = locationId => require('./location_data_gen6')[locationId & 0xffff] || null;

exports.getRibbonData = ribbonData => {
  return parseMap(ribbonData, require('./ribbonsByOrder'));
};

exports.getMedalData = medalData => {
  return parseMap(medalData, require('./medalsByOrder'));
};

exports.getEncounterTypeData = encounterTypeId => {
  return [
    'Pal Park/Egg/Event',
    null,
    'Tall Grass',
    null,
    'Sinjoh Ruins Event',
    'Cave/Hall of Origin',
    null,
    'Surfing/Fishing',
    null,
    'Building',
    'Great Marsh/Safari Zone',
    null,
    'Starter/Gift/Fossil'
  ][encounterTypeId];
};

exports.getGameData = gameId => require('./games.json')[gameId];
<commit_msg>Fix a bug where too many bytes were getting read for metLocationId<commit_after>'use strict';
// Reference: https://projectpokemon.org/wiki/Pokemon_X/Y_3DS_Structure
function stripNullChars (str) {
  return str.replace(/\0.*/, '');
}

function parseMap (data, map) {
  const parsedData = [];
  for (let i = 0; i < map.length; i++, data = Math.floor(data / 2)) {
    if (map[i] && data % 2) {
      parsedData.push(map[i]);
    }
  }
  return parsedData;
}

function checksumIsValid (buf) {
  let sum = 0;
  for (let i = 8; i < 232; i += 2) {
    sum += buf.readUInt16LE(i);
  }
  return (sum & 0xffff) === buf.readUInt16LE(0x06);
}

function getDateFromInt (dateStorage) {
  if (!dateStorage) {
    return null;
  }
  return Date.UTC((dateStorage & 0xff) + 2000, (dateStorage >>> 8 & 0xff) - 1, (dateStorage >>> 16 & 0xff));
}

exports.parseBuffer = buf => {
  if (buf.readUInt16LE(0x04) || !checksumIsValid(buf) || [232, 260].indexOf(buf.length) === -1 || buf.readUInt8(0x58) || buf.readUInt8(0x90) || buf.readUInt8(0xc8)) {
    throw new TypeError('The provided buffer is not valid pk6 data');
  }
  const data = {};
  data.encryptionConstant = buf.readUInt32LE(0x00);
  data.dexNo = buf.readUInt16LE(0x08);
  data.heldItemId = buf.readUInt16LE(0x0a);
  data.tid = buf.readUInt16LE(0x0c);
  data.sid = buf.readUInt16LE(0x0e);
  data.exp = buf.readUInt32LE(0x10);
  data.abilityId = buf.readUInt8(0x14);
  data.abilityNum = buf.readUInt8(0x15);
  data.superTrainingHitsRemaining = buf.readUInt8(0x16);
  data.superTrainingBag = buf.readUInt8(0x17);
  data.pid = buf.readUInt32LE(0x18);
  data.natureId = buf.readUInt8(0x1c);

  const genderByte = buf.readUInt8(0x1d);
  data.isFatefulEncounter = !!(genderByte & 0x01);
  const isFemale = genderByte & 0x02;
  const isGenderless = genderByte & 0x04;
  data.gender = isFemale ? 'F' : isGenderless ? '' : 'M';
  data.formId = genderByte >>> 3;

  data.evHp = buf.readUInt8(0x1e);
  data.evAtk = buf.readUInt8(0x1f);
  data.evDef = buf.readUInt8(0x20);
  data.evSpe = buf.readUInt8(0x21);
  data.evSpAtk = buf.readUInt8(0x22);
  data.evSpDef = buf.readUInt8(0x23);

  data.contestStatCool = buf.readUInt8(0x24);
  data.contestStatBeauty = buf.readUInt8(0x25);
  data.contestStatCute = buf.readUInt8(0x26);
  data.contestStatSmart = buf.readUInt8(0x27);
  data.contestStatTough = buf.readUInt8(0x28);
  data.contestStatSheen = buf.readUInt8(0x29);

  const markingByte = buf.readUInt8(0x2a);
  data.hasCircleMarking = !!(markingByte & 0x01);
  data.hasTriangleMarking = !!(markingByte & 0x02);
  data.hasSquareMarking = !!(markingByte & 0x04);
  data.hasHeartMarking = !!(markingByte & 0x08);
  data.hasStarMarking = !!(markingByte & 0x10);
  data.hasDiamondMarking = !!(markingByte & 0x20);

  const pokerusByte = buf.readUInt8(0x2b);
  data.pokerusDuration = pokerusByte & 16;
  data.pokerusStrain = pokerusByte >>> 4;

  data.medalData = buf.readUInt32LE(0x2c);
  data.ribbonData = buf.readUIntLE(0x30, 6);
  data.distributionSuperTrainingFlags = buf.readUInt8(0x3a); // Not sure what these are
  data.nickname = stripNullChars(buf.toString('utf16le', 0x40, 0x58));

  data.move1Id = buf.readUInt16LE(0x5a);
  data.move2Id = buf.readUInt16LE(0x5c);
  data.move3Id = buf.readUInt16LE(0x5e);
  data.move4Id = buf.readUInt16LE(0x60);
  data.move1Pp = buf.readUInt8(0x62);
  data.move2Pp = buf.readUInt8(0x63);
  data.move3Pp = buf.readUInt8(0x64);
  data.move4Pp = buf.readUInt8(0x65);
  data.move1Ppu = buf.readUInt8(0x66);
  data.move2Ppu = buf.readUInt8(0x67);
  data.move3Ppu = buf.readUInt8(0x68);
  data.move4Ppu = buf.readUInt8(0x69);
  data.eggMove1Id = buf.readUInt16LE(0x6a);
  data.eggMove2Id = buf.readUInt16LE(0x6c);
  data.eggMove3Id = buf.readUInt16LE(0x6e);
  data.eggMove4Id = buf.readUInt16LE(0x70);

  data.canDoSecretSuperTraining = !!(buf.readUInt8(0x72));

  const ivBytes = buf.readUInt32LE(0x74);
  data.ivHp = ivBytes & 0x1f;
  data.ivAtk = ivBytes >>> 5 & 0x1f;
  data.ivDef = ivBytes >>> 10 & 0x1f;
  data.ivSpe = ivBytes >>> 15 & 0x1f;
  data.ivSpAtk = ivBytes >>> 20 & 0x1f;
  data.ivSpDef = ivBytes >>> 25 & 0x1f;
  data.isEgg = (ivBytes >>> 30) % 2 !== 0;
  data.isNicknamed = (ivBytes >>> 31) % 2 !== 0;

  data.notOt = stripNullChars(buf.toString('utf16le', 0x78, 0x90));
  data.notOtGender = buf.readUInt8(0x92) ? 'F' : 'M';

  data.currentHandlerIsOt = !buf.readUInt8(0x93);

  data.geoLocation1 = buf.readUInt16LE(0x94); // TODO: Figure out how to parse these
  data.geoLocation2 = buf.readUInt16LE(0x96);
  data.geoLocation3 = buf.readUInt16LE(0x98);
  data.geoLocation4 = buf.readUInt16LE(0x9a);
  data.geoLocation5 = buf.readUInt16LE(0x9c);

  data.notOtFriendship = buf.readUInt8(0xa2);
  data.notOtAffection = buf.readUInt8(0xa3);
  data.notOtMemoryIntensity = buf.readUInt8(0xa4); // TODO: Parse
  data.notOtMemoryLine = buf.readUInt8(0xa5);
  data.notOtMemoryFeeling = buf.readUInt8(0xa6);
  data.notOtMemoryTextVar = buf.readUInt16LE(0xa8);

  data.fullness = buf.readUInt8(0xae);
  data.enjoyment = buf.readUInt8(0xaf);

  data.ot = stripNullChars(buf.toString('utf16le', 0xb0, 0xc8));
  data.otFriendship = buf.readUInt8(0xca);
  data.otAffection = buf.readUInt8(0xcb);
  data.otMemoryIntensity = buf.readUInt8(0xcc); // TODO: Parse
  data.otMemoryLine = buf.readUInt8(0xcd);
  data.otMemoryTextVar = buf.readUInt16LE(0xce);
  data.otMemoryFeeling = buf.readUInt8(0xd0);

  data.eggDate = getDateFromInt(buf.readUIntLE(0xd1, 3));
  data.metDate = getDateFromInt(buf.readUIntLE(0xd4, 3));

  data.eggLocationId = buf.readUInt16LE(0xd8);
  data.metLocationId = buf.readUInt16LE(0xda);
  data.ballId = buf.readUInt8(0xdc);

  const encounterLevelByte = buf.readUInt8(0xdd);
  data.levelMet = encounterLevelByte & 0x7f;
  data.otGender = encounterLevelByte >>> 7 ? 'F' : 'M';

  data.encounterTypeId = buf.readUInt8(0xde);
  data.otGameId = buf.readUInt8(0xdf);
  data.countryId = buf.readUInt8(0xe0); // TODO: Parse
  data.regionId = buf.readUInt8(0xe1); // TODO: Parse
  data.consoleRegion = ['J', 'U', 'E', '?', 'C', 'K', 'T'][buf.readUInt8(0xe2)];
  data.language = [null, 'JPN', 'ENG', 'FRE', 'ITA', 'GER', '???', 'SPA', 'KOR'][buf.readUInt8(0xe3)];
  data._rawPk6 = buf.toString('base64');

  return data;
};

const langMap = {ENG: 'en', SPA: 'es', FRE: 'fr', GER: 'de', ITA: 'it', JPN: 'ja', KOR: 'ko'};
exports.assignReadableNames = (data, language) => {
  const findName = specificData => specificData && specificData.names.find(data => data.language === langMap[language]).name;
  language = language || 'ENG';
  if (!langMap.hasOwnProperty(language)) {
    throw new TypeError(`Invalid language '${language}'`);
  }
  data.speciesName = findName(exports.getPokemonData(data.dexNo));
  data.heldItemName = findName(exports.getItemData(data.heldItemId));
  data.abilityName = findName(exports.getAbilityData(data.abilityId));
  data.natureName = findName(exports.getNatureData(data.natureId));
  data.move1Name = findName(exports.getMoveData(data.move1Id));
  data.move2Name = findName(exports.getMoveData(data.move2Id));
  data.move3Name = findName(exports.getMoveData(data.move3Id));
  data.move4Name = findName(exports.getMoveData(data.move4Id));
  data.eggMove1Name = findName(exports.getMoveData(data.eggMove1Id));
  data.eggMove2Name = findName(exports.getMoveData(data.eggMove2Id));
  data.eggMove3Name = findName(exports.getMoveData(data.eggMove3Id));
  data.eggMove4Name = findName(exports.getMoveData(data.eggMove4Id));
  data.medals = exports.getMedalData(data.medalData);
  data.ribbons = exports.getRibbonData(data.ribbonData);
  data.eggLocationName = exports.getLocationData(data.eggLocationId);
  data.metLocationName = exports.getLocationData(data.metLocationId);
  data.encounterTypeName = exports.getEncounterTypeData(data.encounterTypeId);
  data.otGameName = exports.getGameData(data.otGameId);
  return data;
};

exports.parseFile = path => {
  return exports.parseBuffer(require('fs').readFileSync(path));
};

exports.getPokemonData = dexNo => {
  try {
    return require(`./pokemon_data/${dexNo}.json`);
  } catch (e) {
    throw new TypeError(`Invalid dex number: ${dexNo}`);
  }
};

exports.getItemData = itemId => {
  if (itemId === 0) {
    return null;
  }
  try {
    return require(`./item_data_gen6/${itemId}.json`);
  } catch (e) {
    throw new TypeError(`Invalid item ID: ${itemId}`);
  }
};

exports.getMoveData = moveId => {
  if (moveId === 0) {
    return null;
  }
  try {
    return require(`./move_data/${moveId}.json`);
  } catch (e) {
    throw new TypeError(`Invalid move ID: ${moveId}`);
  }
};

exports.getAbilityData = abilityId => {
  if (abilityId === 0) {
    return null;
  }
  try {
    return require(`./ability_data/${abilityId}.json`);
  } catch (e) {
    throw new TypeError(`Invalid ability ID: ${abilityId}`);
  }
};

exports.getNatureData = natureId => {
  if (natureId === 0) {
    return null;
  }
  try {
    return require(`./nature_data/${natureId}.json`);
  } catch (e) {
    throw new TypeError(`Invalid nature ID: ${natureId}`);
  }
};

exports.getLocationData = locationId => require('./location_data_gen6')[locationId] || null;

exports.getRibbonData = ribbonData => {
  return parseMap(ribbonData, require('./ribbonsByOrder'));
};

exports.getMedalData = medalData => {
  return parseMap(medalData, require('./medalsByOrder'));
};

exports.getEncounterTypeData = encounterTypeId => {
  return [
    'Pal Park/Egg/Event',
    null,
    'Tall Grass',
    null,
    'Sinjoh Ruins Event',
    'Cave/Hall of Origin',
    null,
    'Surfing/Fishing',
    null,
    'Building',
    'Great Marsh/Safari Zone',
    null,
    'Starter/Gift/Fossil'
  ][encounterTypeId];
};

exports.getGameData = gameId => require('./games.json')[gameId];
<|endoftext|>


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

const path = require('path')
const fs = require('fs')
const program = require('commander')
const gulp = require('gulp')
const pkginfo = require('pkginfo')(module, 'version')
function init() {
  gutil.log(gutil.colors.red(`hugulp v${module.exports.version}`))

  const hugulpRc = path.join(process.cwd(), '.hugulprc')

  if (fs.existsSync(hugulpRc)) {
    gutil.log(
      gutil.colors.yellow('.hugulprc already exists (initialization skipped)')
    )
    return
  }

  const config = {
    version: 1,
    pipeline: ['images', 'styles', 'scripts', 'fingerprint', 'html'],
    path: {
      styles: 'styles',
      images: 'images',
      scripts: 'scripts'
    },
    watch: {
      source: 'assets',
      target: 'static'
    },
    build: {
      source: 'public',
      target: 'public'
    },
    autoprefixer: {
      browsers: ['last 2 versions']
    },
    cleancss: {
      advanced: false
    },
    htmlmin: {
      collapsedWhitespace: true,
      removeEmptyElements: true
    }
  }

  fs.writeFileSync(hugulpRc, JSON.stringify(config, null, '  '))

  gutil.log(
    gutil.colors.green(
      'hugulp has been initialized (.hugulprc was created with default values)'
    )
  )
}

function build() {
  require(path.join(fs.realpathSync(__dirname), 'gulp', 'build'))
  gulp.start('build')
}

function watch() {
  require(path.join(fs.realpathSync(__dirname), 'gulp', 'watch'))
  gulp.start('watch')
}

function version() {
  console.log('hugulp v' + module.exports.version)
}

function minifyhtml() {
  gulp.start('minifyhtml:minifyhtml')
}

program
  .command('build')
  .description('optimize site (for publishing purposes)')
  .action(build)

program
  .command('watch')
  .description('watch for changes to styles and/or javascript')
  .action(watch)

program
  .command('version')
  .option('-v, --version', 'Display version')
  .description('display version information')
  .action(version)

program
  .command('minifyhtml')
  .description('minify your created html')
  .action(minifyhtml)

program.parse(process.argv)
<commit_msg>Clean up & add logging<commit_after>#!/usr/bin/env node

const path = require('path')
const fs = require('fs')
const program = require('commander')
const gulp = require('gulp')
const pkginfo = require('pkginfo')(module, 'version')
const gutil = require('gulp-util')

function init() {
  gutil.log(gutil.colors.red(`hugulp v${module.exports.version}`))

  const hugulpRc = path.join(process.cwd(), '.hugulprc')

  if (fs.existsSync(hugulpRc)) {
    gutil.log(
      gutil.colors.yellow('.hugulprc already exists (initialization skipped)')
    )
    return
  }

  const config = {
    version: 1,
    pipeline: ['images', 'styles', 'scripts', 'fingerprint', 'html'],
    path: {
      styles: 'styles',
      images: 'images',
      scripts: 'scripts'
    },
    watch: {
      source: 'assets',
      target: 'static'
    },
    build: {
      source: 'public',
      target: 'public'
    },
    autoprefixer: {
      browsers: ['last 2 versions']
    },
    cleancss: {
      advanced: false
    },
    htmlmin: {
      collapsedWhitespace: true,
      removeEmptyElements: true
    }
  }

  fs.writeFileSync(hugulpRc, JSON.stringify(config, null, '  '))

  gutil.log(
    gutil.colors.green(
      'hugulp has been initialized (.hugulprc was created with default values)'
    )
  )
}

function build() {
  gutil.log(gutil.colors.red(`hugulp v${module.exports.version}`))

  require(path.join(fs.realpathSync(__dirname), 'gulp', 'build'))
  gulp.start('build')
}

function watch() {
  gutil.log(gutil.colors.red(`hugulp v${module.exports.version}`))

  require(path.join(fs.realpathSync(__dirname), 'gulp', 'watch'))
  gulp.start('watch')
}

function version() {
  console.log('hugulp v' + module.exports.version)
}

program
  .command('init')
  .description('create default .hugulprc')
  .action(init)

program
  .command('version')
  .description('display version information')
  .action(version)

program
  .command('build')
  .description('optimize site (for publishing purposes)')
  .action(build)

program
  .command('watch')
  .description('watch for changes to styles and/or javascript')
  .action(watch)

program.parse(process.argv)
<|endoftext|>


<commit_before>function up(data, upNode){
  if (upNode && upNode.element)
    data.input.set(upNode.element);
}

module.exports = require('api').define('template', {
  setSourceFragment: function(){
    return basis.resource.buildCloak(__dirname + '/../js-source/index.js').fetch().set;
  },
  setDataFlowValue: function(data){
    return function(id){
      var setDataFlowValue = data.output.value.setDataFlowValue;
      if (typeof setDataFlowValue == 'function')
        setDataFlowValue(id);
    };
  },
  select: function(data){
    return function(id){
      var selectNodeById = data.output.value.selectNodeById;
      if (typeof selectNodeById == 'function')
        selectNodeById(id);
    };
  },
  upParent: function(data, inspectBasis){
    var inspectBasisGroupingNode = inspectBasis.require('basis.dom.wrapper').GroupingNode;

    return function(){
      var object = data.output.value.object;
      if (object && object.parentNode)
      {
        var upNode = object.parentNode;

        if (upNode instanceof inspectBasisGroupingNode)
          upNode = upNode.owner;

        up(data, upNode);
      }
    };
  },
  upOwner: function(data){
    return function(){
      var object = data.output.value.object;
      if (object && object.owner)
        up(data, object.owner);
    };
  },
  upGroup: function(data){
    return function(){
      var object = data.output.value.object;
      if (object && object.groupNode)
        up(data,object.groupNode);
    };
  },
  dropTarget: function(data){
    return function(){
      data.input.set();
    };
  },
  logInfo: function(data, inspectBasis){
    var inspectBasisTemplate = inspectBasis.require('basis.template');

    return function(){
      var object = data.output.value.object;
      var debugInfo = null;
      var values = null;

      if (data.input.value)
      {
        var info = inspectBasisTemplate.resolveTemplateInfoByNode(data.input.value);
        var objectBinding = object ? object.binding : {};

        debugInfo = info.debug || null;

        if (debugInfo)
          values = debugInfo.values || null;

        if (values)
          values = basis.object.slice(values, basis.object.keys(objectBinding));
      }

      global.$basisjsInfo = {
        object: object,
        template: {
          debugInfo: debugInfo,
          declaration: data.output.value.decl || '<no info>',
          values: values
        }
      };
      console.log(global.$basisjsInfo);
    };
  }
});
<commit_msg>devpanel: fix issue with nested grouping<commit_after>function up(data, upNode){
  if (upNode && upNode.element)
    data.input.set(upNode.element);
}

module.exports = require('api').define('template', {
  setSourceFragment: function(){
    return basis.resource.buildCloak(__dirname + '/../js-source/index.js').fetch().set;
  },
  setDataFlowValue: function(data){
    return function(id){
      var setDataFlowValue = data.output.value.setDataFlowValue;
      if (typeof setDataFlowValue == 'function')
        setDataFlowValue(id);
    };
  },
  select: function(data){
    return function(id){
      var selectNodeById = data.output.value.selectNodeById;
      if (typeof selectNodeById == 'function')
        selectNodeById(id);
    };
  },
  upParent: function(data, inspectBasis){
    var inspectBasisGroupingNode = inspectBasis.require('basis.dom.wrapper').GroupingNode;

    return function(){
      var object = data.output.value.object;

      if (object && object.parentNode)
      {
        var upNode = object.parentNode;

        while (upNode && upNode instanceof inspectBasisGroupingNode)
          upNode = upNode.owner;

        up(data, upNode);
      }
    };
  },
  upOwner: function(data){
    return function(){
      var object = data.output.value.object;
      if (object && object.owner)
        up(data, object.owner);
    };
  },
  upGroup: function(data){
    return function(){
      var object = data.output.value.object;
      if (object && object.groupNode)
        up(data,object.groupNode);
    };
  },
  dropTarget: function(data){
    return function(){
      data.input.set();
    };
  },
  logInfo: function(data, inspectBasis){
    var inspectBasisTemplate = inspectBasis.require('basis.template');

    return function(){
      var object = data.output.value.object;
      var debugInfo = null;
      var values = null;

      if (data.input.value)
      {
        var info = inspectBasisTemplate.resolveTemplateInfoByNode(data.input.value);
        var objectBinding = object ? object.binding : {};

        debugInfo = info.debug || null;

        if (debugInfo)
          values = debugInfo.values || null;

        if (values)
          values = basis.object.slice(values, basis.object.keys(objectBinding));
      }

      global.$basisjsInfo = {
        object: object,
        template: {
          debugInfo: debugInfo,
          declaration: data.output.value.decl || '<no info>',
          values: values
        }
      };
      console.log(global.$basisjsInfo);
    };
  }
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var auth = require('./server/authentication');

var bodyParser = require('body-parser');

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(bodyParser.json());

//app.use('/', function(request, response) {
//	// Use response.sendfile, as it streams instead of reading the file into memory.
//	response.sendfile(__dirname + '/public/index.html');
//});
app.post('/api/login',auth.login);
app.post("/api/userRegister",auth.register);
//app.post("/api/savedata", eligibility_core.add);
/*
 * app.get('/', function(request, response) { response.render('pages/index');
 * });
 */
app.post('/api/login',auth.login);
//app.use('/', function(request, response) {
//	// Use response.sendfile, as it streams instead of reading the file into memory.
//	response.sendfile(__dirname + '/public/index.html');
//});

app.listen(app.get('port'), function() {
	console.log('Node app is running on port', app.get('port'));
});
<commit_msg>Vimal:Login Changes<commit_after>var express = require('express');
var app = express();
var auth = require('./server/authentication');

var bodyParser = require('body-parser');

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(bodyParser.json());

//app.use('/', function(request, response) {
//	// Use response.sendfile, as it streams instead of reading the file into memory.
//	response.sendfile(__dirname + '/public/index.html');
//});
app.post('/api/login',auth.login);
app.post("/api/userRegister",auth.register);
//app.post("/api/savedata", eligibility_core.add);
/*
 * app.get('/', function(request, response) { response.render('pages/index');
 * });
 */
//app.post('/api/login',auth.login);
//app.use('/', function(request, response) {
//	// Use response.sendfile, as it streams instead of reading the file into memory.
//	response.sendfile(__dirname + '/public/index.html');
//});

app.listen(app.get('port'), function() {
	console.log('Node app is running on port', app.get('port'));
});
<|endoftext|>