<commit_before>import fs from "fs";
import {DeliciousHtmlExporter as Exporter} from "./lib";
import program from "commander";
import pck from "./../package.json";

program.version(pck.version)
       .option('-u --username [username]', 'Your del.icio.us username')
       .option('-e --endpoint [endpoint]', 'The endpoint of the API', 'https://del.icio.us')
       .option('-w --write-html [dir]', 'Each loaded HTML page will be saved in the directory')
       .option('-r --read-html [dir]', 'Instead of loading the pages from the API, it reads them from the directory')
       .option('-o --output-file [file]', 'Result file', 'result.json')
       .parse(process.argv);

if (program.readHtml && program.writeHtml && program.readHtml === program.writeHtml) {
  console.error('You cannot read and write the same data...');
  program.help();
}

if (program.username) {

  const exporter = new Exporter({
    username: program.username,
    baseEndpoint: program.endpoint,
    readHtmlFromDirectory: program.readHtml,
    writeHtmlToDirectory: program.writeHtml,
  });

  exporter.fetch()
          .then((result) => {
            console.log(`Finished, found ${result.items.length} items`);
            fs.writeFile(program.outputFile, JSON.stringify(result));
            console.log(`Result file: ${program.outputFile}`);
          }, (err) => {
            console.error('FAILED: ' + JSON.stringify(err));
          });
}<commit_msg>Add missing bin header<commit_after>#! /usr/bin/env node

import fs from "fs";
import {DeliciousHtmlExporter as Exporter} from "./lib";
import program from "commander";
import pck from "./../package.json";

program.version(pck.version)
       .option('-u --username [username]', 'Your del.icio.us username')
       .option('-e --endpoint [endpoint]', 'The endpoint of the API', 'https://del.icio.us')
       .option('-w --write-html [dir]', 'Each loaded HTML page will be saved in the directory')
       .option('-r --read-html [dir]', 'Instead of loading the pages from the API, it reads them from the directory')
       .option('-o --output-file [file]', 'Result file', 'result.json')
       .parse(process.argv);

if (program.readHtml && program.writeHtml && program.readHtml === program.writeHtml) {
  console.error('You cannot read and write the same data...');
  program.help();
}

if (program.username) {

  const exporter = new Exporter({
    username: program.username,
    baseEndpoint: program.endpoint,
    readHtmlFromDirectory: program.readHtml,
    writeHtmlToDirectory: program.writeHtml,
  });

  exporter.fetch()
          .then((result) => {
            console.log(`Finished, found ${result.items.length} items`);
            fs.writeFile(program.outputFile, JSON.stringify(result));
            console.log(`Result file: ${program.outputFile}`);
          }, (err) => {
            console.error('FAILED: ' + JSON.stringify(err));
          });
}<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Dimensions, Modal, DeviceEventEmitter, TouchableWithoutFeedback } from 'react-native';
import PropTypes from 'prop-types';
import { View, initializeRegistryWithDefinitions } from 'react-native-animatable';
import * as ANIMATION_DEFINITIONS from './animations';

import styles from './index.style.js';

// Override default animations
initializeRegistryWithDefinitions(ANIMATION_DEFINITIONS);

export class ReactNativeModal extends Component {
  static propTypes = {
    animationIn: PropTypes.string,
    animationInTiming: PropTypes.number,
    animationOut: PropTypes.string,
    animationOutTiming: PropTypes.number,
    backdropColor: PropTypes.string,
    backdropOpacity: PropTypes.number,
    backdropTransitionInTiming: PropTypes.number,
    backdropTransitionOutTiming: PropTypes.number,
    children: PropTypes.node.isRequired,
    isVisible: PropTypes.bool.isRequired,
    onModalShow: PropTypes.func,
    onModalHide: PropTypes.func,
    hideOnBack: PropTypes.bool,
    hideOnBackdrop: PropTypes.bool,
    onBackButtonPress: PropTypes.func,
    onBackdropPress: PropTypes.func,
    style: PropTypes.any,
  };

  static defaultProps = {
    animationIn: 'slideInUp',
    animationInTiming: 300,
    animationOut: 'slideOutDown',
    animationOutTiming: 300,
    backdropColor: 'black',
    backdropOpacity: 0.70,
    backdropTransitionInTiming: 300,
    backdropTransitionOutTiming: 300,
    onModalShow: () => null,
    onModalHide: () => null,
    isVisible: false,
    hideOnBack: true,
    hideOnBackdrop: true,
    onBackdropPress: () => null,
    onBackButtonPress: () => null,
  };

  // We use an internal state for keeping track of the modal visibility: this allows us to keep
  // the modal visibile during the exit animation, even if the user has already change the
  // isVisible prop to false.
  // We also store in the state the device width and height so that we can update the modal on
  // device rotation.
  state = {
    isVisible: false,
    deviceWidth: Dimensions.get('window').width,
    deviceHeight: Dimensions.get('window').height,
  };

  componentWillReceiveProps(nextProps) {
    if (!this.state.isVisible && nextProps.isVisible) {
      this.setState({ isVisible: true });
    }
  }

  componentWillMount() {
    if (this.props.isVisible) {
      this.setState({ isVisible: true });
    }
  }

  componentDidMount() {
    if (this.state.isVisible) {
      this._open();
    }
    DeviceEventEmitter.addListener('didUpdateDimensions', this._handleDimensionsUpdate);
  }

  componentDidUpdate(prevProps, prevState) {
    // On modal open request, we slide the view up and fade in the backdrop
    if (this.state.isVisible && !prevState.isVisible) {
      this._open();
      // On modal close request, we slide the view down and fade out the backdrop
    } else if (!this.props.isVisible && prevProps.isVisible) {
      this._close();
    }
  }

  _handleDimensionsUpdate = dimensionsUpdate => {
    // Here we update the device dimensions in the state if the layout changed (triggering a render)
    const deviceWidth = Dimensions.get('window').width;
    const deviceHeight = Dimensions.get('window').height;
    if (deviceWidth !== this.state.deviceWidth || deviceHeight !== this.state.deviceHeight) {
      this.setState({ deviceWidth, deviceHeight });
    }
  };

  _open = () => {
    this.backdropRef.transitionTo(
      { opacity: this.props.backdropOpacity },
      this.props.backdropTransitionInTiming,
    );
    this.contentRef[this.props.animationIn](this.props.animationInTiming).then(() => {
      this.props.onModalShow();
    });
  };

  _close = async () => {
    this.backdropRef.transitionTo({ opacity: 0 }, this.props.backdropTransitionOutTiming);
    this.contentRef[this.props.animationOut](this.props.animationOutTiming).then(() => {
      this.setState({ isVisible: false });
      this.props.onModalHide();
    });
  };

  _closeOnBack = () => {
    if (this.props.hideOnBack) {
      this._close();
    }

    this.props.onBackButtonPress();
  };

  _closeOnBackdrop = () => {
    if (this.props.hideOnBackdrop) {
      this._close()
    }
    this.props.onBackdropPress()
  }

  render() {
    const {
      animationIn,
      animationInTiming,
      animationOut,
      animationOutTiming,
      backdropColor,
      backdropOpacity,
      backdropTransitionInTiming,
      backdropTransitionOutTiming,
      children,
      isVisible,
      onModalShow,
      onModalHide,
      style,
      ...otherProps
    } = this.props;
    const { deviceWidth, deviceHeight } = this.state;
    return (
      <Modal
        transparent={true}
        animationType={'none'}
        visible={this.state.isVisible}
        onRequestClose={this._closeOnBack}
        {...otherProps}
      >
        <TouchableWithoutFeedback onPress={this._closeOnBackdrop}>
          <View
            ref={ref => (this.backdropRef = ref)}
            style={[
              styles.backdrop,
              {
                backgroundColor: backdropColor,
                width: deviceWidth,
                height: deviceHeight,
              },
            ]}
          />
        </TouchableWithoutFeedback>
        <View
          ref={ref => (this.contentRef = ref)}
          style={[{ margin: deviceWidth * 0.05 }, styles.content, style]}
          pointerEvents="box-none"
          {...otherProps}

        >
          {children}
        </View>
      </Modal>
    );
  }
}

export default ReactNativeModal;
<commit_msg>Fix to much enter<commit_after>import React, { Component } from 'react';
import { Dimensions, Modal, DeviceEventEmitter, TouchableWithoutFeedback } from 'react-native';
import PropTypes from 'prop-types';
import { View, initializeRegistryWithDefinitions } from 'react-native-animatable';
import * as ANIMATION_DEFINITIONS from './animations';

import styles from './index.style.js';

// Override default animations
initializeRegistryWithDefinitions(ANIMATION_DEFINITIONS);

export class ReactNativeModal extends Component {
  static propTypes = {
    animationIn: PropTypes.string,
    animationInTiming: PropTypes.number,
    animationOut: PropTypes.string,
    animationOutTiming: PropTypes.number,
    backdropColor: PropTypes.string,
    backdropOpacity: PropTypes.number,
    backdropTransitionInTiming: PropTypes.number,
    backdropTransitionOutTiming: PropTypes.number,
    children: PropTypes.node.isRequired,
    isVisible: PropTypes.bool.isRequired,
    onModalShow: PropTypes.func,
    onModalHide: PropTypes.func,
    hideOnBack: PropTypes.bool,
    hideOnBackdrop: PropTypes.bool,
    onBackButtonPress: PropTypes.func,
    onBackdropPress: PropTypes.func,
    style: PropTypes.any,
  };

  static defaultProps = {
    animationIn: 'slideInUp',
    animationInTiming: 300,
    animationOut: 'slideOutDown',
    animationOutTiming: 300,
    backdropColor: 'black',
    backdropOpacity: 0.70,
    backdropTransitionInTiming: 300,
    backdropTransitionOutTiming: 300,
    onModalShow: () => null,
    onModalHide: () => null,
    isVisible: false,
    hideOnBack: true,
    hideOnBackdrop: true,
    onBackdropPress: () => null,
    onBackButtonPress: () => null,
  };

  // We use an internal state for keeping track of the modal visibility: this allows us to keep
  // the modal visibile during the exit animation, even if the user has already change the
  // isVisible prop to false.
  // We also store in the state the device width and height so that we can update the modal on
  // device rotation.
  state = {
    isVisible: false,
    deviceWidth: Dimensions.get('window').width,
    deviceHeight: Dimensions.get('window').height,
  };

  componentWillReceiveProps(nextProps) {
    if (!this.state.isVisible && nextProps.isVisible) {
      this.setState({ isVisible: true });
    }
  }

  componentWillMount() {
    if (this.props.isVisible) {
      this.setState({ isVisible: true });
    }
  }

  componentDidMount() {
    if (this.state.isVisible) {
      this._open();
    }
    DeviceEventEmitter.addListener('didUpdateDimensions', this._handleDimensionsUpdate);
  }

  componentDidUpdate(prevProps, prevState) {
    // On modal open request, we slide the view up and fade in the backdrop
    if (this.state.isVisible && !prevState.isVisible) {
      this._open();
      // On modal close request, we slide the view down and fade out the backdrop
    } else if (!this.props.isVisible && prevProps.isVisible) {
      this._close();
    }
  }

  _handleDimensionsUpdate = dimensionsUpdate => {
    // Here we update the device dimensions in the state if the layout changed (triggering a render)
    const deviceWidth = Dimensions.get('window').width;
    const deviceHeight = Dimensions.get('window').height;
    if (deviceWidth !== this.state.deviceWidth || deviceHeight !== this.state.deviceHeight) {
      this.setState({ deviceWidth, deviceHeight });
    }
  };

  _open = () => {
    this.backdropRef.transitionTo(
      { opacity: this.props.backdropOpacity },
      this.props.backdropTransitionInTiming,
    );
    this.contentRef[this.props.animationIn](this.props.animationInTiming).then(() => {
      this.props.onModalShow();
    });
  };

  _close = async () => {
    this.backdropRef.transitionTo({ opacity: 0 }, this.props.backdropTransitionOutTiming);
    this.contentRef[this.props.animationOut](this.props.animationOutTiming).then(() => {
      this.setState({ isVisible: false });
      this.props.onModalHide();
    });
  };

  _closeOnBack = () => {
    if (this.props.hideOnBack) {
      this._close();
    }

    this.props.onBackButtonPress();
  };

  _closeOnBackdrop = () => {
    if (this.props.hideOnBackdrop) {
      this._close()
    }
    this.props.onBackdropPress()
  }

  render() {
    const {
      animationIn,
      animationInTiming,
      animationOut,
      animationOutTiming,
      backdropColor,
      backdropOpacity,
      backdropTransitionInTiming,
      backdropTransitionOutTiming,
      children,
      isVisible,
      onModalShow,
      onModalHide,
      style,
      ...otherProps
    } = this.props;
    const { deviceWidth, deviceHeight } = this.state;
    return (
      <Modal
        transparent={true}
        animationType={'none'}
        visible={this.state.isVisible}
        onRequestClose={this._closeOnBack}
        {...otherProps}
      >
        <TouchableWithoutFeedback onPress={this._closeOnBackdrop}>
          <View
            ref={ref => (this.backdropRef = ref)}
            style={[
              styles.backdrop,
              {
                backgroundColor: backdropColor,
                width: deviceWidth,
                height: deviceHeight,
              },
            ]}
          />
        </TouchableWithoutFeedback>
        <View
          ref={ref => (this.contentRef = ref)}
          style={[{ margin: deviceWidth * 0.05 }, styles.content, style]}
          pointerEvents="box-none"
          {...otherProps}
        >
          {children}
        </View>
      </Modal>
    );
  }
}

export default ReactNativeModal;
<|endoftext|>


<commit_before>
/*
 just an example of configuration useful to redirect all the request on the same endpoint */

$.jStorage.set('profile', {
    // parametri di connessione agli endpoint
    'connection' : {
        'http://fiteagle,http://localhost,http://federation.av.tu-berlin.de,file:///opt,http://demo.fiteagle.org/resource,http://open-multinet.info' : {
            description : {
                en : 'FITeagle Database'
            },
            useForInverseSameAs : true,
            endpoint : '/openrdf-sesame/repositories/fiteagle',
            endpointType : 'sesame',
            examples : [{
                label : 'MotorGarage-1',
                uri : 'http://localhost/resource/MotorGarage-1'
            }]
        },
    },
    arrows : {
        'http://www.w3.org/2002/07/owl#sameAs' : 'isSameAs',
        'http://purl.org/dc/terms/isPartOf' : 'isPartOf',
        'http://purl.org/dc/elements/1.1/type' : 'isType',
        'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' : 'isType'
    },
    uriSubstitutor : [{
        findStr : 'mpii.de/yago/resource/',
        replaceStr : 'yago-knowledge.org/resource/'
    }],

    // configurazione standard per la rappresentazione di un documento
    // utilizzata nel caso manchi una specifica configurazione per la classe
    'default' : {
        sparql : {
            allClasses : 'SELECT DISTINCT ?object WHERE {[] a ?object}',
            findSubject : 'SELECT DISTINCT ?subject WHERE { {?subject a <{CLASS}>;<http://purl.org/dc/elements/1.1/title> ?object. FILTER(regex(str(?object),\'{VALUE}\',\'i\'))} UNION {?subject a <{CLASS}>;<http://www.w3.org/2000/01/rdf-schema#label> ?object. FILTER(regex(str(?object),\'{VALUE}\',\'i\'))} UNION {?subject a <{CLASS}>;<http://www.w3.org/2004/02/skos/core#prefLabel> ?object. FILTER(regex(str(?object),\'{VALUE}\',\'i\'))} }  LIMIT 1  ',
            documentUri : 'SELECT DISTINCT * WHERE {<{URI}> ?property ?object} ORDER BY ?property',
            document : 'SELECT DISTINCT * WHERE {<{URI}> ?property ?object}',
            bnode : 'SELECT DISTINCT *  WHERE {<{URI}> ?property ?object}',
            inverse : 'SELECT DISTINCT * WHERE {?object ?property <{URI}>.} LIMIT 100',
            inverseSameAs : 'SELECT DISTINCT * WHERE {{?object <http://www.w3.org/2002/07/owl#sameAs> <{URI}> } UNION { ?object <http://www.w3.org/2004/02/skos/core#exactMatch> <{URI}>}}'
        },
        endpoint : 'http://labs.regesta.com/resourceProxy/',
        document : {
            className : 'standard',
            titleProperties : ['http://dati.senato.it/osr/titolo', 'http://www.w3.org/2004/02/skos/core#notation', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#value', 'http://www.geonames.org/ontology#name', 'http://purl.org/dc/elements/1.1/title', 'http://purl.org/dc/terms/title', 'http://www.w3.org/2000/01/rdf-schema#label', 'http://www.w3.org/2004/02/skos/core#prefLabel', 'http://logd.tw.rpi.edu/source/visualizing-org/dataset/2010-global-agenda-council-interlinkage-survey/vocab/enhancement/1/how_councils_interlink', 'http://rdf.freebase.com/ns/type.object.name', 'http://spcdata.digitpa.gov.it/nome_cognome', 'http://xmlns.com/foaf/0.1/firstName', 'http://xmlns.com/foaf/0.1/lastName', 'http://xmlns.com/foaf/0.1/surname', 'http://xmlns.com/foaf/0.1/name', 'http://purl.org/dc/terms/description', 'http://www.geonames.org/ontology/officialName']
        }, // http://www.w3.org/2000/01/rdf-schema#label
        images : {
            properties : ['http://www.w3.org/2006/vcard/ns#photo', 'http://xmlns.com/foaf/0.1/depiction', 'http://dbpedia.org/ontology/thumbnail', 'http://dbpedia.org/property/logo', 'http://linkedgeodata.org/ontology/schemaIcon']
        },
        maps : {
            longs : ['http://www.w3.org/2003/01/geo/wgs84_pos#long'],
            lats : ['http://www.w3.org/2003/01/geo/wgs84_pos#lat'],
            points : ['http://www.georss.org/georss/point']
        },
        weblinks : {
            properties : ['http://www.w3.org/ns/dcat#accessURL', 'http://xmlns.com/foaf/0.1/mbox', 'http://rdfs.org/sioc/ns#links_to', 'http://it.dbpedia.org/property/url', 'http://data.nytimes.com/elements/search_api_query', 'http://www.w3.org/2000/01/rdf-schema#isDefinedBy', 'http://xmlns.com/foaf/0.1/page', 'http://xmlns.com/foaf/0.1/homepage', 'http://purl.org/dc/terms/isReferencedBy', 'http://purl.org/dc/elements/1.1/relation', 'http://dbpedia.org/ontology/wikiPageExternalLink', 'http://data.nytimes.com/elements/topicPage']
        }
    },

    'http://www.w3.org/2002/07/owl#Class' : {
        document : {
            className : 'Class'/*,
             titleProperties : ['http://purl.org/dc/elements/1.1/title', 'http://www.w3.org/2000/01/rdf-schema#label']*/
        }
    },
    'http://www.w3.org/2002/07/owl#ObjectProperty' : {
        document : {
            className : 'ObjectProperty'
        }
    },
    'http://www.w3.org/2002/07/owl#Restriction' : {
        document : {
            className : 'DatatypeProperty'
        }
    },
    'http://www.w3.org/2002/07/owl#DatatypeProperty' : {
        document : {
            className : 'DatatypeProperty'
        }
    },
    'http://www.w3.org/2002/07/owl#Property' : {
        document : {
            className : 'Property'
        }
    },
    'http://www.w3.org/ns/locn#Address' : {
        document : {
            titleProperties : ['http://www.w3.org/ns/locn#fullAddress']
        }
    }

});
if (!document.lodliveVars) {
    document.lodliveVars = {};
}

$.jStorage.set('boxTemplate', '

');
$.jStorage.set('relationsLimit', 25);
$.jStorage.set('doStats', $.jStorage.get('doStats', true));
$.jStorage.set('doInverse', $.jStorage.get('doAutoExpand', true));
$.jStorage.set('doAutoExpand', $.jStorage.get('doAutoExpand', true));
$.jStorage.set('doAutoSameas', $.jStorage.get('doAutoSameas', true));
$.jStorage.set('doCollectImages', $.jStorage.get('doCollectImages', true));
$.jStorage.set('doDrawMap', $.jStorage.get('doDrawMap', true));
$.jStorage.set('showInfoConsole', $.jStorage.get('showInfoConsole', true));

$.jStorage.set('endpoints', {
    all : 'output=json&format=application/json&timeout=0',
    arcSparql : 'output=json&jsonp=lodlive',
    sesame : 'Accept=application/sparql-results%2Bjson'
});
<commit_msg>use localhost as default<commit_after>
/*
 just an example of configuration useful to redirect all the request on the same endpoint */

$.jStorage.set('profile', {
    // parametri di connessione agli endpoint
    'connection' : {
        'http://fiteagle,http://localhost,http://federation.av.tu-berlin.de,file:///opt,http://demo.fiteagle.org/resource,http://open-multinet.info,urn:' : {
            description : {
                en : 'FITeagle Database'
            },
            useForInverseSameAs : true,
            endpoint : '/openrdf-sesame/repositories/fiteagle',
            endpointType : 'sesame',
            examples : [{
                label : 'MotorGarage-1',
                uri : 'http://localhost/resource/MotorGarage-1'
            }]
        },
    },
    arrows : {
        'http://www.w3.org/2002/07/owl#sameAs' : 'isSameAs',
        'http://purl.org/dc/terms/isPartOf' : 'isPartOf',
        'http://purl.org/dc/elements/1.1/type' : 'isType',
        'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' : 'isType'
    },
    uriSubstitutor : [{
        findStr : 'mpii.de/yago/resource/',
        replaceStr : 'yago-knowledge.org/resource/'
    }],

    // configurazione standard per la rappresentazione di un documento
    // utilizzata nel caso manchi una specifica configurazione per la classe
    'default' : {
        sparql : {
            allClasses : 'SELECT DISTINCT ?object WHERE {[] a ?object}',
            findSubject : 'SELECT DISTINCT ?subject WHERE { {?subject a <{CLASS}>;<http://purl.org/dc/elements/1.1/title> ?object. FILTER(regex(str(?object),\'{VALUE}\',\'i\'))} UNION {?subject a <{CLASS}>;<http://www.w3.org/2000/01/rdf-schema#label> ?object. FILTER(regex(str(?object),\'{VALUE}\',\'i\'))} UNION {?subject a <{CLASS}>;<http://www.w3.org/2004/02/skos/core#prefLabel> ?object. FILTER(regex(str(?object),\'{VALUE}\',\'i\'))} }  LIMIT 1  ',
            documentUri : 'SELECT DISTINCT * WHERE {<{URI}> ?property ?object} ORDER BY ?property',
            document : 'SELECT DISTINCT * WHERE {<{URI}> ?property ?object}',
            bnode : 'SELECT DISTINCT *  WHERE {<{URI}> ?property ?object}',
            inverse : 'SELECT DISTINCT * WHERE {?object ?property <{URI}>.} LIMIT 100',
            inverseSameAs : 'SELECT DISTINCT * WHERE {{?object <http://www.w3.org/2002/07/owl#sameAs> <{URI}> } UNION { ?object <http://www.w3.org/2004/02/skos/core#exactMatch> <{URI}>}}'
        },
        //endpoint : 'http://labs.regesta.com/resourceProxy/',
        endpoint : '/openrdf-sesame/repositories/fiteagle',
        document : {
            className : 'standard',
            titleProperties : ['http://dati.senato.it/osr/titolo', 'http://www.w3.org/2004/02/skos/core#notation', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#value', 'http://www.geonames.org/ontology#name', 'http://purl.org/dc/elements/1.1/title', 'http://purl.org/dc/terms/title', 'http://www.w3.org/2000/01/rdf-schema#label', 'http://www.w3.org/2004/02/skos/core#prefLabel', 'http://logd.tw.rpi.edu/source/visualizing-org/dataset/2010-global-agenda-council-interlinkage-survey/vocab/enhancement/1/how_councils_interlink', 'http://rdf.freebase.com/ns/type.object.name', 'http://spcdata.digitpa.gov.it/nome_cognome', 'http://xmlns.com/foaf/0.1/firstName', 'http://xmlns.com/foaf/0.1/lastName', 'http://xmlns.com/foaf/0.1/surname', 'http://xmlns.com/foaf/0.1/name', 'http://purl.org/dc/terms/description', 'http://www.geonames.org/ontology/officialName']
        }, // http://www.w3.org/2000/01/rdf-schema#label
        images : {
            properties : ['http://www.w3.org/2006/vcard/ns#photo', 'http://xmlns.com/foaf/0.1/depiction', 'http://dbpedia.org/ontology/thumbnail', 'http://dbpedia.org/property/logo', 'http://linkedgeodata.org/ontology/schemaIcon']
        },
        maps : {
            longs : ['http://www.w3.org/2003/01/geo/wgs84_pos#long'],
            lats : ['http://www.w3.org/2003/01/geo/wgs84_pos#lat'],
            points : ['http://www.georss.org/georss/point']
        },
        weblinks : {
            properties : ['http://www.w3.org/ns/dcat#accessURL', 'http://xmlns.com/foaf/0.1/mbox', 'http://rdfs.org/sioc/ns#links_to', 'http://it.dbpedia.org/property/url', 'http://data.nytimes.com/elements/search_api_query', 'http://www.w3.org/2000/01/rdf-schema#isDefinedBy', 'http://xmlns.com/foaf/0.1/page', 'http://xmlns.com/foaf/0.1/homepage', 'http://purl.org/dc/terms/isReferencedBy', 'http://purl.org/dc/elements/1.1/relation', 'http://dbpedia.org/ontology/wikiPageExternalLink', 'http://data.nytimes.com/elements/topicPage']
        }
    },

    'http://www.w3.org/2002/07/owl#Class' : {
        document : {
            className : 'Class'/*,
             titleProperties : ['http://purl.org/dc/elements/1.1/title', 'http://www.w3.org/2000/01/rdf-schema#label']*/
        }
    },
    'http://www.w3.org/2002/07/owl#ObjectProperty' : {
        document : {
            className : 'ObjectProperty'
        }
    },
    'http://www.w3.org/2002/07/owl#Restriction' : {
        document : {
            className : 'DatatypeProperty'
        }
    },
    'http://www.w3.org/2002/07/owl#DatatypeProperty' : {
        document : {
            className : 'DatatypeProperty'
        }
    },
    'http://www.w3.org/2002/07/owl#Property' : {
        document : {
            className : 'Property'
        }
    },
    'http://www.w3.org/ns/locn#Address' : {
        document : {
            titleProperties : ['http://www.w3.org/ns/locn#fullAddress']
        }
    }

});
if (!document.lodliveVars) {
    document.lodliveVars = {};
}

$.jStorage.set('boxTemplate', '

');
$.jStorage.set('relationsLimit', 25);
$.jStorage.set('doStats', $.jStorage.get('doStats', true));
$.jStorage.set('doInverse', $.jStorage.get('doAutoExpand', true));
$.jStorage.set('doAutoExpand', $.jStorage.get('doAutoExpand', true));
$.jStorage.set('doAutoSameas', $.jStorage.get('doAutoSameas', true));
$.jStorage.set('doCollectImages', $.jStorage.get('doCollectImages', true));
$.jStorage.set('doDrawMap', $.jStorage.get('doDrawMap', true));
$.jStorage.set('showInfoConsole', $.jStorage.get('showInfoConsole', true));

$.jStorage.set('endpoints', {
    all : 'output=json&format=application/json&timeout=0',
    arcSparql : 'output=json&jsonp=lodlive',
    sesame : 'Accept=application/sparql-results%2Bjson'
});
<|endoftext|>


<commit_before>/*jslint node : true, nomen: true, plusplus: true, vars: true, eqeq: true,*/
"use strict";

var restify = require('restify');

var DEFAULT_PLUGINS = {
    queryParser: {},
    bodyParser : { mapParams: false },
    gzipResponse : {}
};

function registerPlugins(server, plugins) {
    Object.keys(DEFAULT_PLUGINS).forEach(function (name) {
        if (!plugins[name]) {
            plugins[name] = DEFAULT_PLUGINS[name];
        }
    });
    Object.keys(plugins || {}).forEach(function (name) {
        if (restify[name]) {
            server.use(restify[name](plugins[name]));
        }
    });
}

module.exports = function startup(options, imports, register) {

    var config = {
        name: options.name ||  'restify-server',
        version: options.name || '0.0.1'
    };

    var server = restify.createServer(config);

    server.use(restify.acceptParser(server.acceptable));

    registerPlugins(server, options.plugins || {});

    server.listen(options.port, options.host || "0.0.0.0", function (err) {
        if (err) {
            return register(err);
        }
        //console.log("HTTP server listening on http://%s%s/", options.host || "localhost", port === 80 ? "" : ":" + port);
        register(null, {
            // When a plugin is unloaded, it's onDestruct function will be called if there is one.
            onDestruct: function (callback) {
                server.close(callback);
            },
            rest: server
        });
    });

};
<commit_msg>fix #3 : listen on unix socket<commit_after>/*jslint node : true, nomen: true, plusplus: true, vars: true, eqeq: true,*/
"use strict";

var restify = require('restify');

var DEFAULT_PLUGINS = {
    queryParser: {},
    bodyParser : { mapParams: false },
    gzipResponse : {}
};

function registerPlugins(server, plugins) {
    Object.keys(DEFAULT_PLUGINS).forEach(function (name) {
        if (!plugins[name]) {
            plugins[name] = DEFAULT_PLUGINS[name];
        }
    });
    Object.keys(plugins || {}).forEach(function (name) {
        if (restify[name]) {
            server.use(restify[name](plugins[name]));
        }
    });
}

module.exports = function startup(options, imports, register) {

    var config = {
        name: options.name ||  'restify-server',
        version: options.version || '0.0.1'
    };

    var server = restify.createServer(config);
    server.use(restify.acceptParser(server.acceptable));

    registerPlugins(server, options.plugins || {});

    function listenCb(err) {
        if (err) {
            return register(err);
        }
        register(null, {
            onDestruct: function (callback) {
                server.close(callback);
            },
            rest: server
        });
    }

    if (options.socket) {
        server.listen(options.socket, listenCb);
        return;
    }

    server.listen(options.port, options.host || "0.0.0.0", listenCb);
};
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*global window,jQuery*/
(function (window, $, undefined) {

    var TemplateManager,RenderEngine,SingleValueView,TableValueView,SlideShow;

    function error(msg){
        if(window.console){
            console.error(msg);
        }
    }

    TableValueView = function(){

    };

    TableValueView.prototype.transformModel = function(model,item){
        var idx,entry;

        if(!model || !model.current || !model.current.data){
            return {table:[]};
        }

        for(idx in model.current.data.table){
            entry = model.current.data.table[idx];
            entry.status = entry.value == 0 ? 'ok' : 'fail';
        }

        return model.current.data;
    };

    SingleValueView = function(views){
        this.views = views;
        this.defaultStatusThreshold = 1;
        this.relations = {
            gt : function(a,b){return a > b},
            lt : function(a,b){return a < b}
        };
        this.defaultRelation = 'lt';
    };

    SingleValueView.prototype.transformModel = function(model,item){

        // fallback
        if (!model || !model.current || !model.current.data || !model.current.data.value) {
            return {
                current : '?',
                previous: '?',
                status :  'ok',
                diff : '?',
                diffStatus : 'ok',
                since : '?',
                unit : '?'
            }
        }

        var current  = model.current.data.value;
        var previous = null;
        var diff = null;

        if(model.previous){
            previous = model.previous.data.value;
            diff =  current - previous;
            if(diff>0){
                diff = '+' + diff;
            }
        }

        return {
            current : current,
            previous: previous,
            status :  this.calcStatus(current,item),
            diff : diff,
            diffStatus : this.calcDiffStatus(diff,item),
            since : this.calcSince(model),
            unit : this.calcUnit(item)
        }
    };

    SingleValueView.prototype.calcUnit = function(item){
        if(item.conf){
            if(item.conf.unit){
                return item.conf.unit
            }
        }
        return null;
    };

    SingleValueView.prototype.calcSince = function(model){
        var creation = model.current.creation;
        var now = new Date().getTime();
        var diff = now - creation;
        var secs = this.intDiv(diff,1000);
        if(secs < 60){
            return "a few seconds ago.";
        }
        var minutes = this.intDiv(secs,60);
        if(minutes < 5){
            return "a few minutes ago.";
        }
        if(minutes < 120) {
            return "about " + minutes + " minutes ago.";
        }
        var hours = this.intDiv(minutes,60);
        if(hours < 48) {
            return "about " + hours + " hours ago.";
        }
        var days = this.intDiv(hours,24);
        return "about " + days + " days ago.";
    };

    SingleValueView.prototype.intDiv = function(a,b){
        return Math.floor( a / b );
    };

    SingleValueView.prototype.calcStatus = function(val,item){
        var statusThreshold = item.statusThreshold || this.defaultStatusThreshold;
        var statusRelation  = item.statusRelation;
        if(this.relation(statusRelation,val,statusThreshold)){
            return 'ok';
        }
        else {
            return 'fail';
        }
    };

    SingleValueView.prototype.calcDiffStatus = function(val,item){
        var diffStatusRelation = item.statusRelation;
        if(this.relation(diffStatusRelation,val,0)){
            return 'ok';
        }
        else {
            return 'fail';
        }
    };

    SingleValueView.prototype.relation = function(name,a,b){
        var rel;
        if(name){
            rel = this.relations[name];
        }
        if(!rel){
            if(name){
                error("relation does not exist: " + name);
            }
            rel = this.relations[this.defaultRelation];
        }
        return rel(a,b);
    };

    /**
     * The TemplateManager is responsible to extract the Mustache template code from the hosting DOM tree.
     *
     * The template has to be embedded in a script tag and there in HTML comments:
     *
     *
     */
	TemplateManager = function () {};

    /**
     * Extracts the template from the DOM Tree.
     *
     * @param container the id of the DOM script Element, which contains the tempalte code.
     */
	TemplateManager.prototype.getTemplate = function (container) {
	    var text = $('#template-' + container).html();
	    if (text === undefined || text === null) {
	        return null;
	    }

	    text = this.trimLines(text);
	    text = this.removeComments(text);

	    return text;
	};

    TemplateManager.prototype.getTemplates = function(containers) {
        var result = {}, container, template,idx;
        for(idx in containers){
            container = containers[idx];
            template = this.getTemplate(container);
            if(template != null){
                result[container] = template;
            }
        }
        return result;
    };

    /**
     * The Template Code is embedded in HTML Comments. Hence we have to remove them.
     *
     * @param str
     */
	TemplateManager.prototype.removeComments = function (str) {
	    return str.replace('', '');
	};

    /**
     * Since we create a lot of HTML, it is a good idea to avoid any non required data. Whitespace
     * as such could be removed without harm, hence we do that for the sake of performance.
     *
     * @param str
     */
	TemplateManager.prototype.trimLines = function (str) {
		var lines, i;

	    lines = str.split('\n');

	    for (i = 0; i < lines.length; i = i +  1) {
	        lines[i] = $.trim(lines[i]);
	    }

	    return lines.join('\n');
	};

    RenderEngine = function(opts){
        opts = opts || {};

        this.defaultViewName = opts.defaultView || 'single-value';
        this.entries = {};

        var items = opts.items || [];
        for(var idx in items){
            var item = items[idx];
            var itemConf = item.conf || {};

            var viewName = itemConf.view || this.defaultViewName;
            var view = opts.views[viewName];
            this.entries[item.name] = {
                item : item,
                view : view,
                viewName : viewName
            }
        }

        this.baseUrl = opts.baseUrl;

        this.templates = opts.templates || {};
    };

    RenderEngine.prototype.renderItem = function(name,dest,callback){
        var entry = this.entries[name];
        if(!entry){
            error('Cannot render item "' + name + '", because it does not consist.');
            return;
        }

        var view = entry.view;
        var item = entry.item;

        var template = this.templates[entry.viewName];
        if(!template){
            error('no template found for "' + view+"'.");
            return;
        }

        $.ajax({
            url : this.baseUrl + "/" + item.name,
            success:function(data){
                var model = view.transformModel(data,item);
                var html = $.mustache(template,model);
                $(dest).html(html);
                if(callback){
                    callback();
                }
            }
        });

    };

    var slideShowAnimation = {
        slide : {
            initNewSlide : function(elem) {
                var e = $(elem);
                var height = e.height();
                e.offset({left:0,top:height});
            },
            newSlideAnimation : function(elem) {
                var width = $(elem).width();
                return {top:-width};
            },
            currentSlideAnimation : function(elem) {
                return {top:0};
            }
        },
        fade : {
            initNewSlide : function(elem) {
                var e = $(elem);
                e.offset({opacity:1});
            },
            newSlideAnimation : function(elem) {
                return {opacity:0};
            },
            currentSlideAnimation : function(elem) {
                return {opacity:1};
            }
        }
    };

    SlideShow = function(opts){
        this.renderEngine = opts.renderEngine;
        this.items = opts.items;
        this.container = $(opts.container);
        this.delay = (opts.delay || 5) * 1000;
        this.fxDuration = opts.fxDuration || 600;
        this.currItemId = 0;
        this.slideShowAnimation = slideShowAnimation[ opts.animation || 'slide' ];
    };

    SlideShow.prototype.start = function(){
        this.replace();
        this.animateNext();
    };

    SlideShow.prototype.animateNext = function(){
        var self = this;
        this.timer = setTimeout(function(){
            self.start();
        },this.delay);
    };

    SlideShow.prototype.replace = function(){
        var item = this.nextItem();
        this.replaceTitle(item);
        this.replaceView(item);
    };

    SlideShow.prototype.replaceTitle = function(item){
        var duration = this.fxDuration/2;
        $('#title')
                .fadeOut(duration)
                .queue(function(next){
                    $(this).html(item.title)
                    next();
                })
                .fadeIn(duration);
    };

    SlideShow.prototype.replaceView = function(item){
        var self = this;
        var elem = $('

').appendTo(this.container);
        var width = $(this.container).width();
        var height = $(this.container).height();
        var fxDuration = this.fxDuration;
        $(elem)
            .width(width)
            .height(height);
        this.initNewSlide(elem);
        this.renderEngine.renderItem(item.name,elem,function(){
            var views = $('.view',this.container);
            var currentAnimation = self.currentSlideAnimation(elem);
            var newAnimation = self.newSlideAnimation(elem);
            $(elem).animate( currentAnimation,{duration: fxDuration} );
            if(views.length > 1){
                $(views[0]).animate(newAnimation,fxDuration,function(){$(this).remove()});
            }
        });
    };

    SlideShow.prototype.initNewSlide = function(elem){
        return this.slideShowAnimation.initNewSlide(elem);
    };

    SlideShow.prototype.newSlideAnimation = function(elem){
        return this.slideShowAnimation.newSlideAnimation(elem);
    };

    SlideShow.prototype.currentSlideAnimation = function(elem){
        return this.slideShowAnimation.currentSlideAnimation(elem);
    };

    SlideShow.prototype.nextItem = function(){
        return this.items[this.nextItemId()];
    };

    SlideShow.prototype.nextItemId = function(){
        var curr = this.currItemId;
        this.currItemId = (curr + 1) % this.items.length;
        return curr;
    };

	window.infowall = {};
	window.infowall.TemplateManager = TemplateManager;
    window.infowall.RenderEngine = RenderEngine;
    window.infowall.SingleValueView = SingleValueView;
    window.infowall.TableValueView = TableValueView;
    window.infowall.SlideShow = SlideShow;

}(window, jQuery));<commit_msg>- added fade animation - fixed animation framework<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*global window,jQuery*/
(function (window, $, undefined) {

    var TemplateManager,RenderEngine,SingleValueView,TableValueView,SlideShow;

    function error(msg){
        if(window.console){
            console.error(msg);
        }
    }

    TableValueView = function(){

    };

    TableValueView.prototype.transformModel = function(model,item){
        var idx,entry;

        if(!model || !model.current || !model.current.data){
            return {table:[]};
        }

        for(idx in model.current.data.table){
            entry = model.current.data.table[idx];
            entry.status = entry.value == 0 ? 'ok' : 'fail';
        }

        return model.current.data;
    };

    SingleValueView = function(views){
        this.views = views;
        this.defaultStatusThreshold = 1;
        this.relations = {
            gt : function(a,b){return a > b},
            lt : function(a,b){return a < b}
        };
        this.defaultRelation = 'lt';
    };

    SingleValueView.prototype.transformModel = function(model,item){

        // fallback
        if (!model || !model.current || !model.current.data || !model.current.data.value) {
            return {
                current : '?',
                previous: '?',
                status :  'ok',
                diff : '?',
                diffStatus : 'ok',
                since : '?',
                unit : '?'
            }
        }

        var current  = model.current.data.value;
        var previous = null;
        var diff = null;

        if(model.previous){
            previous = model.previous.data.value;
            diff =  current - previous;
            if(diff>0){
                diff = '+' + diff;
            }
        }

        return {
            current : current,
            previous: previous,
            status :  this.calcStatus(current,item),
            diff : diff,
            diffStatus : this.calcDiffStatus(diff,item),
            since : this.calcSince(model),
            unit : this.calcUnit(item)
        }
    };

    SingleValueView.prototype.calcUnit = function(item){
        if(item.conf){
            if(item.conf.unit){
                return item.conf.unit
            }
        }
        return null;
    };

    SingleValueView.prototype.calcSince = function(model){
        var creation = model.current.creation;
        var now = new Date().getTime();
        var diff = now - creation;
        var secs = this.intDiv(diff,1000);
        if(secs < 60){
            return "a few seconds ago.";
        }
        var minutes = this.intDiv(secs,60);
        if(minutes < 5){
            return "a few minutes ago.";
        }
        if(minutes < 120) {
            return "about " + minutes + " minutes ago.";
        }
        var hours = this.intDiv(minutes,60);
        if(hours < 48) {
            return "about " + hours + " hours ago.";
        }
        var days = this.intDiv(hours,24);
        return "about " + days + " days ago.";
    };

    SingleValueView.prototype.intDiv = function(a,b){
        return Math.floor( a / b );
    };

    SingleValueView.prototype.calcStatus = function(val,item){
        var statusThreshold = item.statusThreshold || this.defaultStatusThreshold;
        var statusRelation  = item.statusRelation;
        if(this.relation(statusRelation,val,statusThreshold)){
            return 'ok';
        }
        else {
            return 'fail';
        }
    };

    SingleValueView.prototype.calcDiffStatus = function(val,item){
        var diffStatusRelation = item.statusRelation;
        if(this.relation(diffStatusRelation,val,0)){
            return 'ok';
        }
        else {
            return 'fail';
        }
    };

    SingleValueView.prototype.relation = function(name,a,b){
        var rel;
        if(name){
            rel = this.relations[name];
        }
        if(!rel){
            if(name){
                error("relation does not exist: " + name);
            }
            rel = this.relations[this.defaultRelation];
        }
        return rel(a,b);
    };

    /**
     * The TemplateManager is responsible to extract the Mustache template code from the hosting DOM tree.
     *
     * The template has to be embedded in a script tag and there in HTML comments:
     *
     *
     */
	TemplateManager = function () {};

    /**
     * Extracts the template from the DOM Tree.
     *
     * @param container the id of the DOM script Element, which contains the tempalte code.
     */
	TemplateManager.prototype.getTemplate = function (container) {
	    var text = $('#template-' + container).html();
	    if (text === undefined || text === null) {
	        return null;
	    }

	    text = this.trimLines(text);
	    text = this.removeComments(text);

	    return text;
	};

    TemplateManager.prototype.getTemplates = function(containers) {
        var result = {}, container, template,idx;
        for(idx in containers){
            container = containers[idx];
            template = this.getTemplate(container);
            if(template != null){
                result[container] = template;
            }
        }
        return result;
    };

    /**
     * The Template Code is embedded in HTML Comments. Hence we have to remove them.
     *
     * @param str
     */
	TemplateManager.prototype.removeComments = function (str) {
	    return str.replace('', '');
	};

    /**
     * Since we create a lot of HTML, it is a good idea to avoid any non required data. Whitespace
     * as such could be removed without harm, hence we do that for the sake of performance.
     *
     * @param str
     */
	TemplateManager.prototype.trimLines = function (str) {
		var lines, i;

	    lines = str.split('\n');

	    for (i = 0; i < lines.length; i = i +  1) {
	        lines[i] = $.trim(lines[i]);
	    }

	    return lines.join('\n');
	};

    RenderEngine = function(opts){
        opts = opts || {};

        this.defaultViewName = opts.defaultView || 'single-value';
        this.entries = {};

        var items = opts.items || [];
        for(var idx in items){
            var item = items[idx];
            var itemConf = item.conf || {};

            var viewName = itemConf.view || this.defaultViewName;
            var view = opts.views[viewName];
            this.entries[item.name] = {
                item : item,
                view : view,
                viewName : viewName
            }
        }

        this.baseUrl = opts.baseUrl;

        this.templates = opts.templates || {};
    };

    RenderEngine.prototype.renderItem = function(name,dest,callback){
        var entry = this.entries[name];
        if(!entry){
            error('Cannot render item "' + name + '", because it does not consist.');
            return;
        }

        var view = entry.view;
        var item = entry.item;

        var template = this.templates[entry.viewName];
        if(!template){
            error('no template found for "' + view+"'.");
            return;
        }

        $.ajax({
            url : this.baseUrl + "/" + item.name,
            success:function(data){
                var model = view.transformModel(data,item);
                var html = $.mustache(template,model);
                $(dest).html(html);
                if(callback){
                    callback();
                }
            }
        });

    };

    var slideShowAnimation = {
        slide : {
            initNewSlide : function(elem) {
                var e = $(elem);
                var height = e.height();
                e.offset({left:0,top:height});
            },
            newSlideAnimation : function(elem) {
                return {top:0};
            },
            currentSlideAnimation : function(elem) {
                var width = $(elem).width();
                return {top:-width};
            },
            serializeAnimation : false
        },
        fade : {
            initNewSlide : function(elem) {
                var e = $(elem);
                e.css({opacity:0});
            },
            newSlideAnimation : function(elem) {
                return {opacity:1};
            },
            currentSlideAnimation : function(elem) {
                return {opacity:0};
            },
            serializeAnimation:true
        }
    };

    SlideShow = function(opts){
        this.renderEngine = opts.renderEngine;
        this.items = opts.items;
        this.container = $(opts.container);
        this.delay = (opts.delay || 5) * 1000;
        this.fxDuration = opts.fxDuration || 600;
        this.currItemId = 0;
        this.slideShowAnimation = slideShowAnimation[ opts.animation || 'slide' ];
    };

    SlideShow.prototype.start = function(){
        this.replace();
        this.animateNext();
    };

    SlideShow.prototype.animateNext = function(){
        var self = this;
        this.timer = setTimeout(function(){
            self.start();
        },this.delay);
    };

    SlideShow.prototype.replace = function(){
        var item = this.nextItem();
        this.replaceTitle(item);
        this.replaceView(item);
    };

    SlideShow.prototype.replaceTitle = function(item){
        var duration = this.fxDuration/2;
        $('#title')
                .fadeOut(duration)
                .queue(function(next){
                    $(this).html(item.title)
                    next();
                })
                .fadeIn(duration);
    };

    SlideShow.prototype.replaceView = function(item){
        var self = this;
        var elem = $('

').appendTo(this.container);
        var width = $(this.container).width();
        var height = $(this.container).height();
        var fxDuration = this.fxDuration;
        $(elem)
            .width(width)
            .height(height);
        this.initNewSlide(elem);
        this.renderEngine.renderItem(item.name,elem,function(){
            var views = $('.view',this.container);
            var currentAnimation = self.currentSlideAnimation(elem);
            var newAnimation = self.newSlideAnimation(elem);
            var serializeAnimation = self.slideShowAnimation.serializeAnimation;

            var delay = serializeAnimation ? fxDuration  : 0;
            // animate current
            if(views.length > 1){
                $(views[0]).animate( currentAnimation,fxDuration,function(){$(this).remove()});
            }
            // animate new
            $(elem).delay(delay).animate( newAnimation ,{duration: fxDuration} );
        });
    };

    SlideShow.prototype.initNewSlide = function(elem){
        return this.slideShowAnimation.initNewSlide(elem);
    };

    SlideShow.prototype.newSlideAnimation = function(elem){
        return this.slideShowAnimation.newSlideAnimation(elem);
    };

    SlideShow.prototype.currentSlideAnimation = function(elem){
        return this.slideShowAnimation.currentSlideAnimation(elem);
    };

    SlideShow.prototype.nextItem = function(){
        return this.items[this.nextItemId()];
    };

    SlideShow.prototype.nextItemId = function(){
        var curr = this.currItemId;
        this.currItemId = (curr + 1) % this.items.length;
        return curr;
    };

	window.infowall = {};
	window.infowall.TemplateManager = TemplateManager;
    window.infowall.RenderEngine = RenderEngine;
    window.infowall.SingleValueView = SingleValueView;
    window.infowall.TableValueView = TableValueView;
    window.infowall.SlideShow = SlideShow;

}(window, jQuery));<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var numeral = require('numeral');
var slack = require('slack-notify')(process.env.SLACK_HOOK_URL);

var imdb = require('node-movie');
var RottenTomatoes = require('./rottentomatoes.js');
var rt = new RottenTomatoes(process.env.RT_API_KEY);

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', function (req, res) {
  var q = req.body.text;
  // Search RottenTomatoes
  rt.search(q, function(rtData) {
    if (!rtData) {
      res.status(404).send('Movie not found');
      return;
    }

    // Search IMDb
    var imdbCallback = function(err, imdbData) {
      if (err || !imdbData) {
        res.status(404).send('Movie not found');
        return;
      }

      // Build Slack response
      var fields = [{
        title: 'Rotten Tomatoes Rating',
        value: (rtData.ratings.critics_score ? rtData.ratings.critics_score + '%' : '_No rating_'),
        short: true
      }, {
        title: 'IMDb Rating',
        value: (imdbData.imdbRating ? imdbData.imdbRating + ' (' + numeral(imdbData.imdbVotes).format('0,0') + ' votes)' : '_No rating_'),
        short: true
      }];
      if (imdbData.Year || rtData.year) {
        fields.push({
          title: 'Year',
          value: (imdbData.Year ? imdbData.Year : rtData.year),
          short: true
        });
      }
      if (imdbData.Runtime || rtData.runtime) {
        fields.push({
          title: 'Runtime',
          value: (imdbData.Runtime ? imdbData.Runtime : rtData.runtime + ' min'),
          short: true
        });
      }

      // Send to Slack
      slack.send({
        username: 'moviebot',
        icon_emoji: ':movie_camera:',
        channel: req.body.channel_id,
        text: '_' + req.body.command + ' ' + req.body.text + '_',
        attachments: [{
          title: rtData.title,
          title_link: rtData.links.alternate,
          color: '#FDEE00',
          image_url: (rtData.posters ? rtData.posters.original : null),
          fields: fields
        }]
      });

      res.send();
    };

    var imdbId = (rtData.alternate_ids ? rtData.alternate_ids.imdb : null);
    if (imdbId) {
      imdb.getByID('tt' + imdbId, imdbCallback);
    } else {
      imdb(q, imdbCallback);
    }
  });
});

var port = process.env.PORT || 3000;
var server = app.listen(port, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('App listening at http://%s:%s', host, port);
});<commit_msg>Links<commit_after>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var numeral = require('numeral');
var slack = require('slack-notify')(process.env.SLACK_HOOK_URL);

var imdb = require('node-movie');
var RottenTomatoes = require('./rottentomatoes.js');
var rt = new RottenTomatoes(process.env.RT_API_KEY);

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', function (req, res) {
  var q = req.body.text;
  // Search RottenTomatoes
  rt.search(q, function(rtData) {
    if (!rtData) {
      res.status(404).send('Movie not found');
      return;
    }

    // Search IMDb
    var imdbCallback = function(err, imdbData) {
      if (err || !imdbData) {
        res.status(404).send('Movie not found');
        return;
      }

      // Build Slack response
      var fields = [{
        title: 'Rotten Tomatoes Rating',
        value: '<' + rtData.links.alternate + '|' + (rtData.ratings.critics_score ? rtData.ratings.critics_score + '%' : '_No rating_') + '>',
        short: true
      }, {
        title: 'IMDb Rating',
        value: '<http://www.imdb.com/title/' + imdbData.imdbID + '|' + (imdbData.imdbRating !== 'N/A' ? imdbData.imdbRating + ' (' + numeral(imdbData.imdbVotes).format('0,0') + ' votes)' : '_No rating_') + '>',
        short: true
      }];
      if (imdbData.Year || rtData.year) {
        fields.push({
          title: 'Year',
          value: (imdbData.Year ? imdbData.Year : rtData.year),
          short: true
        });
      }
      if (imdbData.Runtime !== 'N/A' || rtData.runtime) {
        fields.push({
          title: 'Runtime',
          value: (imdbData.Runtime !== 'N/A' ? imdbData.Runtime : rtData.runtime + ' min'),
          short: true
        });
      }

      // Send to Slack
      slack.send({
        username: 'moviebot',
        icon_emoji: ':movie_camera:',
        channel: req.body.channel_id,
        text: '_' + req.body.command + ' ' + req.body.text + '_',
        attachments: [{
          title: rtData.title,
          title_link: rtData.links.alternate,
          color: '#FDEE00',
          image_url: (rtData.posters ? rtData.posters.original : null),
          fields: fields
        }]
      });

      res.send();
    };

    var imdbId = (rtData.alternate_ids ? rtData.alternate_ids.imdb : null);
    if (imdbId) {
      imdb.getByID('tt' + imdbId, imdbCallback);
    } else {
      imdb(q, imdbCallback);
    }
  });
});

var port = process.env.PORT || 3000;
var server = app.listen(port, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('App listening at http://%s:%s', host, port);
});<|endoftext|>


<commit_before>import {fromDOM, fromText, toDOM, Pos, slice} from "./model"

import * as keys from "./keys"
import * as dom from "./dom"
import commands from "./commands"
import {interpretTextInput} from "./interpret"

let stopSeq = null
const handlers = {}

function dispatchKey(pm, name, e) {
  let seq = pm.state.keySeq
  if (seq) {
    if (keys.isModifierKey(name)) return true
    clearTimeout(stopSeq)
    stopSeq = setTimeout(function() {
      if (pm.state.keySeq == seq)
        pm.state.keySeq = null;
    }, 50)
    name = seq + " " + name
  }
  let result = keys.lookupKey(name, pm.options.keymap, bound => {
    if (typeof bound == "string") {
      bound = commands[bound]
      if (!bound) return false
    }
    return bound(pm) !== false
  }, pm)

  if (result == "multi")
    pm.state.keySeq = name

  if (result == "handled" || result == "multi")
    e.preventDefault()

  if (seq && !result && /\'$/.test(name)) {
    e.preventDefault()
    return true
  }
  return !!result
}

handlers.keydown = (pm, e) => {
  let name = keys.keyName(e)
  if (name) dispatchKey(pm, name, e)
}

function inputText(pm, range, text) {
  if (range.empty && !text) return false
  pm.apply({name: "replace", pos: range.from, end: range.end, text: text})
  if (range.empty) interpretTextInput(pm, pm.selection.head)
}

handlers.keypress = (pm, e) => {
  if (e.ctrlKey && !e.altKey || dom.mac && e.metaKey) return
  let ch = String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode)
  if (dispatchKey(pm, "'" + ch + "'", e)) return
  inputText(pm, pm.selection, ch)
  e.preventDefault()
}

handlers.compositionstart = (pm, e) => {
  let data = e.data
  pm.state.composing = {sel: pm.selection,
                        data: data,
                        startData: data}
  pm.state.composeActive++
  // FIXME set selection around existing data if applicable
}

handlers.compositionupdate = (pm, e) => {
  pm.state.composing.data = e.data;
}

handlers.compositionend = (pm, e) => {
  let info = pm.state.composing
  if (!info) return
  pm.state.composing = null
  if (e.data != info.startData && !/\u200b/.test(e.data))
    info.data = e.data
  applyComposition(pm, info)
  // Disable input events for a short time more
  setTimeout((() => pm.state.composeActive--), 50)
}

function applyComposition(pm, info) {
  inputText(pm, info.sel, info.data)
}

handlers.input = (pm) => {
  if (pm.state.composeActive) return
  console.log("INPUT EVENT!");
  // FIXME poll DOM for changes
}

let lastCopied = null

// FIXME also copy/paste text

handlers.copy = handlers.cut = (pm, e) => {
  let sel = pm.selection
  if (sel.empty) return
  let elt = document.createElement("div")
  let fragment = slice.between(pm.doc, sel.from, sel.to)
  elt.appendChild(toDOM(fragment, {document: document}))
  lastCopied = {doc: pm.doc, from: sel.from, to: sel.to, html: elt.innerHTML}

  if (e.clipboardData) {
    e.preventDefault()
    e.clipboardData.clearData()
    e.clipboardData.setData("text/html", lastCopied.html)
//    e.clipboardData.setData("text/plain", lastCopied.text);
    if (e.type == "cut" && !sel.empty)
      pm.apply({name: "replace", pos: sel.from, end: sel.to})
  }
}

handlers.paste = (pm, e) => {
  if (!e.clipboardData) return
  let sel = pm.selection
  let html = e.clipboardData.getData("text/html")
  let text = e.clipboardData.getData("text/plain")
  if (html || text) {
    e.preventDefault()
    let doc, from, to
    if (lastCopied && (lastCopied.html == html || lastCopied.text == text)) {
      ({doc, from, to}) = lastCopied
    } else if (html) {
      let elt = document.createElement("div")
      elt.innerHTML = html
      doc = fromDOM(elt)
    } else {
      doc = fromText(text)
    }
    pm.apply({name: "replace", pos: sel.from, end: sel.to,
              source: doc, from: from || Pos.start(doc), to: to || Pos.end(doc)})
  }
}

exports.registerHandlers = function(pm) {
  for (let event in handlers) {
    let handler = handlers[event]
    pm.content.addEventListener(event, (e) => handler(pm, e))
  }
}
<commit_msg>Wire in toText to also put text on clipboard when copying<commit_after>import {fromDOM, fromText, toDOM, toText, Pos, slice} from "./model"

import * as keys from "./keys"
import * as dom from "./dom"
import commands from "./commands"
import {interpretTextInput} from "./interpret"

let stopSeq = null
const handlers = {}

function dispatchKey(pm, name, e) {
  let seq = pm.state.keySeq
  if (seq) {
    if (keys.isModifierKey(name)) return true
    clearTimeout(stopSeq)
    stopSeq = setTimeout(function() {
      if (pm.state.keySeq == seq)
        pm.state.keySeq = null;
    }, 50)
    name = seq + " " + name
  }
  let result = keys.lookupKey(name, pm.options.keymap, bound => {
    if (typeof bound == "string") {
      bound = commands[bound]
      if (!bound) return false
    }
    return bound(pm) !== false
  }, pm)

  if (result == "multi")
    pm.state.keySeq = name

  if (result == "handled" || result == "multi")
    e.preventDefault()

  if (seq && !result && /\'$/.test(name)) {
    e.preventDefault()
    return true
  }
  return !!result
}

handlers.keydown = (pm, e) => {
  let name = keys.keyName(e)
  if (name) dispatchKey(pm, name, e)
}

function inputText(pm, range, text) {
  if (range.empty && !text) return false
  pm.apply({name: "replace", pos: range.from, end: range.end, text: text})
  if (range.empty) interpretTextInput(pm, pm.selection.head)
}

handlers.keypress = (pm, e) => {
  if (e.ctrlKey && !e.altKey || dom.mac && e.metaKey) return
  let ch = String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode)
  if (dispatchKey(pm, "'" + ch + "'", e)) return
  inputText(pm, pm.selection, ch)
  e.preventDefault()
}

handlers.compositionstart = (pm, e) => {
  let data = e.data
  pm.state.composing = {sel: pm.selection,
                        data: data,
                        startData: data}
  pm.state.composeActive++
  // FIXME set selection around existing data if applicable
}

handlers.compositionupdate = (pm, e) => {
  pm.state.composing.data = e.data;
}

handlers.compositionend = (pm, e) => {
  let info = pm.state.composing
  if (!info) return
  pm.state.composing = null
  if (e.data != info.startData && !/\u200b/.test(e.data))
    info.data = e.data
  applyComposition(pm, info)
  // Disable input events for a short time more
  setTimeout((() => pm.state.composeActive--), 50)
}

function applyComposition(pm, info) {
  inputText(pm, info.sel, info.data)
}

handlers.input = (pm) => {
  if (pm.state.composeActive) return
  console.log("INPUT EVENT!");
  // FIXME poll DOM for changes
}

let lastCopied = null

handlers.copy = handlers.cut = (pm, e) => {
  let sel = pm.selection
  if (sel.empty) return
  let elt = document.createElement("div")
  let fragment = slice.between(pm.doc, sel.from, sel.to)
  elt.appendChild(toDOM(fragment, {document: document}))
  lastCopied = {doc: pm.doc, from: sel.from, to: sel.to,
                html: elt.innerHTML, text: toText(fragment)}

  if (e.clipboardData) {
    e.preventDefault()
    e.clipboardData.clearData()
    e.clipboardData.setData("text/html", lastCopied.html)
    e.clipboardData.setData("text/plain", lastCopied.text);
    if (e.type == "cut" && !sel.empty)
      pm.apply({name: "replace", pos: sel.from, end: sel.to})
  }
}

handlers.paste = (pm, e) => {
  if (!e.clipboardData) return
  let sel = pm.selection
  let html = e.clipboardData.getData("text/html")
  let text = e.clipboardData.getData("text/plain")
  if (html || text) {
    e.preventDefault()
    let doc, from, to
    if (lastCopied && (lastCopied.html == html || lastCopied.text == text)) {
      ({doc, from, to}) = lastCopied
    } else if (html) {
      let elt = document.createElement("div")
      elt.innerHTML = html
      doc = fromDOM(elt)
    } else {
      doc = fromText(text)
    }
    pm.apply({name: "replace", pos: sel.from, end: sel.to,
              source: doc, from: from || Pos.start(doc), to: to || Pos.end(doc)})
  }
}

exports.registerHandlers = function(pm) {
  for (let event in handlers) {
    let handler = handlers[event]
    pm.content.addEventListener(event, (e) => handler(pm, e))
  }
}
<|endoftext|>


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

// nS - No Space
// lC - Lowercase

import cheerio from 'cheerio';
import colors from 'colors';
import fs from 'fs';
import mv from 'mv';
import name from 'project-name';
import pathExists from 'path-exists';
import program from 'commander';
import replace from 'replace';
import shell from 'shelljs';
import {foldersAndFiles} from './config/foldersAndFiles';
import {filesToModifyContent} from './config/filesToModifyContent';
import {bundleIdentifiers} from './config/bundleIdentifiers';

const projectName = name();
const replaceOptions = {
  recursive: true,
  silent: true
};

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
      if (err) { reject(err); }
      resolve(data);
    });
  });
}

function replaceContent(regex, replacement, paths) {
  replace({
    regex,
    replacement,
    paths,
    ...replaceOptions
  });

  for (const path of paths) {
    console.log(`${path} ${colors.green('MODIFIED')}`);
  }
}

readFile('./android/app/src/main/res/values/strings.xml')
  .then(data => {
    const $ = cheerio.load(data);
    const currentAppName = $('string[name=app_name]').text();
    const nS_CurrentAppName = currentAppName.replace(/\s/g, '');
    const lC_Ns_CurrentAppName = nS_CurrentAppName.toLowerCase();

    program
      .version('2.1.0')
      .arguments('<newName>')
      .option('-b, --bundleID [value]', 'Set custom bundle identifier eg. "com.junedomingo.travelapp"')
      .action((newName) => {
        const nS_NewName = newName.replace(/\s/g, '');
        const pattern = /^([0-9]|[a-z])+([0-9a-z\s]+)$/i;
        const lC_Ns_NewAppName = nS_NewName.toLowerCase();
        const bundleID = program.bundleID ? program.bundleID.toLowerCase() : null;
        let newBundlePath;

        if (bundleID) {
          newBundlePath = bundleID.replace(/\./g, '/');
          const id = bundleID.split('.');
          if (id.length < 2) return console.log('Invalid Bundle Identifier. Add something like "com.travelapp" or "com.junedomingo.travelapp"');
        }

        if (!pattern.test(newName)) {
          return console.log(`"${newName}" is not a valid name for a project. Please use a valid identifier name (alphanumeric and space).`);
        }

        if (newName === currentAppName
          || newName === nS_CurrentAppName
          || newName === lC_Ns_CurrentAppName) {
          return console.log(`Please try a different name.`);
        }

        // Clean builds on both platform
        shell.rm('-rf', [
          './ios/build/*',
          './android/.gradle/*',
          './android/app/build/*',
          './android/build/*'
        ]);

        foldersAndFiles(currentAppName, newName)
          .forEach((element, index) => {
            const dest = element.replace(new RegExp(nS_CurrentAppName, 'gi'), nS_NewName);
            pathExists(element)
              .then(exists => {
                setTimeout(() => {
                  if (exists) {
                    mv(element, dest, err => {
                      if (err) return console.log('Error in renaming folder.', err);
                      console.log(`${dest} ${colors.green('RENAMED')}`);
                    });
                  } else {
                    // Rename children files and folders
                    mv(element, dest, err => {
                      if (err) return;
                      console.log(`${dest} ${colors.green('RENAMED')}`);
                    });
                  }
                }, 600*index);
              });
          });

        setTimeout(() => {
          filesToModifyContent(currentAppName, newName, projectName).map(file => {
            file.paths.map((path, index) => {
              const newPaths = [];
              pathExists(path)
                .then(exists => {
                  if (exists) {
                    newPaths.push(path);
                    setTimeout(() => {
                      replaceContent(file.regex, file.replacement, newPaths);
                    }, 500*index);
                  }
                });
            });
          });
        }, 8000);

        setTimeout(() => {
          readFile('./android/app/src/main/AndroidManifest.xml')
            .then(data => {
              const $ = cheerio.load(data);
              const currentBundleID = $('manifest').attr('package');
              const newBundleID = program.bundleID ? bundleID : `com.${lC_Ns_NewAppName}`;
              const javaFileBase = './android/app/src/main/java';
              const newJavaPath = `${javaFileBase}/${newBundleID.replace(/\./g, '/')}`;
              const currentJavaPath = `${javaFileBase}/${currentBundleID.replace(/\./g, '/')}`;

              const javaFiles = [
                `MainActivity.java`,
                `MainApplication.java`
              ];

              if (bundleID) {
                newBundlePath = newJavaPath;

                for (const file of javaFiles) {
                  mv(`${currentJavaPath}/${file}`, `${newBundlePath}/${file}`, {mkdirp: true}, err => {
                    if (err) return console.log('Error in moving java files.', err);
                    console.log(`${newBundlePath} ${colors.green('BUNDLE INDENTIFIER CHANGED')}`);
                  });
                }
              } else {
                newBundlePath = newBundleID.replace(/\./g, '/').toLowerCase();
                newBundlePath = `${javaFileBase}/${newBundlePath}`;

                for (const file of javaFiles) {
                  mv(`${currentJavaPath}/${file}`, `${newBundlePath}/${file}`, {mkdirp: true}, err => {
                    if (err) return console.log('Error in moving java files.', err);
                    console.log(`${newBundlePath} ${colors.green('BUNDLE INDENTIFIER CHANGED')}`);
                  });
                }
              }

              setTimeout(function () {
                bundleIdentifiers(currentAppName, newName, projectName, currentBundleID, newBundleID, newBundlePath).map(file => {
                  file.paths.map((path, index) => {
                    const newPaths = [];
                    pathExists(path)
                    .then(exists => {
                      if (exists) {
                        newPaths.push(path);
                        setTimeout(() => {
                          replaceContent(file.regex, file.replacement, newPaths);
                        }, 500*index);
                      }
                    });
                  });
                });
              }, 2000);
            })
        }, 10000);

      }).parse(process.argv);
    if (!process.argv.slice(2).length) program.outputHelp();
  })
  .catch(err => {
    if (err.code === 'ENOENT') return console.log('Directory should be created using "react-native init"');
    return console.log('Something went wrong: ', err);
  });
<commit_msg>Clean-up<commit_after>#!/usr/bin/env node

// nS - No Space
// lC - Lowercase

import cheerio from 'cheerio';
import colors from 'colors';
import fs from 'fs';
import mv from 'mv';
import name from 'project-name';
import pathExists from 'path-exists';
import program from 'commander';
import replace from 'replace';
import shell from 'shelljs';
import {foldersAndFiles} from './config/foldersAndFiles';
import {filesToModifyContent} from './config/filesToModifyContent';
import {bundleIdentifiers} from './config/bundleIdentifiers';

const projectName = name();
const replaceOptions = {
  recursive: true,
  silent: true
};

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
      if (err) { reject(err); }
      resolve(data);
    });
  });
}

function replaceContent(regex, replacement, paths) {
  replace({
    regex,
    replacement,
    paths,
    ...replaceOptions
  });

  for (const path of paths) {
    console.log(`${path} ${colors.green('MODIFIED')}`);
  }
}

function moveJavaFiles(javaFiles, currentJavaPath, newBundlePath) {
  for (const file of javaFiles) {
    mv(`${currentJavaPath}/${file}`, `${newBundlePath}/${file}`, {mkdirp: true}, err => {
      if (err) return console.log('Error in moving java files.', err);
      console.log(`${newBundlePath} ${colors.green('BUNDLE INDENTIFIER CHANGED')}`);
    });
  }
}

readFile('./android/app/src/main/res/values/strings.xml')
  .then(data => {
    const $ = cheerio.load(data);
    const currentAppName = $('string[name=app_name]').text();
    const nS_CurrentAppName = currentAppName.replace(/\s/g, '');
    const lC_Ns_CurrentAppName = nS_CurrentAppName.toLowerCase();

    program
      .version('2.1.0')
      .arguments('<newName>')
      .option('-b, --bundleID [value]', 'Set custom bundle identifier eg. "com.junedomingo.travelapp"')
      .action((newName) => {
        const nS_NewName = newName.replace(/\s/g, '');
        const pattern = /^([0-9]|[a-z])+([0-9a-z\s]+)$/i;
        const lC_Ns_NewAppName = nS_NewName.toLowerCase();
        const bundleID = program.bundleID ? program.bundleID.toLowerCase() : null;
        let newBundlePath;

        if (bundleID) {
          newBundlePath = bundleID.replace(/\./g, '/');
          const id = bundleID.split('.');
          if (id.length < 2) return console.log('Invalid Bundle Identifier. Add something like "com.travelapp" or "com.junedomingo.travelapp"');
        }

        if (!pattern.test(newName)) {
          return console.log(`"${newName}" is not a valid name for a project. Please use a valid identifier name (alphanumeric and space).`);
        }

        if (newName === currentAppName
          || newName === nS_CurrentAppName
          || newName === lC_Ns_CurrentAppName) {
          return console.log(`Please try a different name.`);
        }

        // Clean builds on both platform
        shell.rm('-rf', [
          './ios/build/*',
          './android/.gradle/*',
          './android/app/build/*',
          './android/build/*'
        ]);

        foldersAndFiles(currentAppName, newName)
          .forEach((element, index) => {
            const dest = element.replace(new RegExp(nS_CurrentAppName, 'gi'), nS_NewName);
            pathExists(element)
              .then(exists => {
                setTimeout(() => {
                  if (exists) {
                    mv(element, dest, err => {
                      if (err) return console.log('Error in renaming folder.', err);
                      console.log(`${dest} ${colors.green('RENAMED')}`);
                    });
                  } else {
                    // Rename children files and folders
                    mv(element, dest, err => {
                      if (err) return;
                      console.log(`${dest} ${colors.green('RENAMED')}`);
                    });
                  }
                }, 600*index);
              });
          });

        setTimeout(() => {
          filesToModifyContent(currentAppName, newName, projectName).map(file => {
            file.paths.map((path, index) => {
              const newPaths = [];
              pathExists(path)
                .then(exists => {
                  if (exists) {
                    newPaths.push(path);
                    setTimeout(() => {
                      replaceContent(file.regex, file.replacement, newPaths);
                    }, 500*index);
                  }
                });
            });
          });
        }, 8000);

        setTimeout(() => {
          readFile('./android/app/src/main/AndroidManifest.xml')
            .then(data => {
              const $ = cheerio.load(data);
              const currentBundleID = $('manifest').attr('package');
              const newBundleID = program.bundleID ? bundleID : `com.${lC_Ns_NewAppName}`;
              const javaFileBase = './android/app/src/main/java';
              const newJavaPath = `${javaFileBase}/${newBundleID.replace(/\./g, '/')}`;
              const currentJavaPath = `${javaFileBase}/${currentBundleID.replace(/\./g, '/')}`;

              const javaFiles = [
                `MainActivity.java`,
                `MainApplication.java`
              ];

              if (bundleID) {
                newBundlePath = newJavaPath;
                moveJavaFiles(javaFiles, currentJavaPath, newBundlePath);
              } else {
                newBundlePath = newBundleID.replace(/\./g, '/').toLowerCase();
                newBundlePath = `${javaFileBase}/${newBundlePath}`;
                moveJavaFiles(javaFiles, currentJavaPath, newBundlePath);
              }

              setTimeout(function () {
                bundleIdentifiers(currentAppName, newName, projectName, currentBundleID, newBundleID, newBundlePath).map(file => {
                  file.paths.map((path, index) => {
                    const newPaths = [];
                    pathExists(path)
                    .then(exists => {
                      if (exists) {
                        newPaths.push(path);
                        setTimeout(() => {
                          replaceContent(file.regex, file.replacement, newPaths);
                        }, 500*index);
                      }
                    });
                  });
                });
              }, 2000);
            })
        }, 10000);

      }).parse(process.argv);
    if (!process.argv.slice(2).length) program.outputHelp();
  })
  .catch(err => {
    if (err.code === 'ENOENT') return console.log('Directory should be created using "react-native init"');
    return console.log('Something went wrong: ', err);
  });
<|endoftext|>