<commit_before>/* eslint-disable import/prefer-default-export */
/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import { SearchBar } from 'react-native-ui-components';

import { UIDatabase } from '../database';
import Settings from '../settings/MobileAppSettings';

import { MODAL_KEYS, getAllPrograms } from '../utilities';
import { usePageReducer } from '../hooks';
import { getItemLayout, recordKeyExtractor } from './dataTableUtilities';

import { PageButton, DataTablePageView } from '../widgets';
import { BottomConfirmModal, DataTablePageModal } from '../widgets/modals';
import { DataTable, DataTableHeaderRow, DataTableRow } from '../widgets/DataTable';

import { buttonStrings, modalStrings } from '../localization';
import globalStyles, { SUSSOL_ORANGE, newDataTableStyles, newPageStyles } from '../globalStyles';

import {
  gotoStocktakeManagePage,
  createStocktake,
  gotoStocktakeEditPage,
} from '../navigation/actions';

export const StocktakesPage = ({ routeName, currentUser, dispatch: reduxDispatch }) => {
  const [state, dispatch, instantDebouncedDispatch, debouncedDispatch] = usePageReducer(routeName, {
    backingData: UIDatabase.objects('Stocktake'),
    data: UIDatabase.objects('Stocktake')
      .sorted('createdDate', false)
      .slice(),
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['name'],
    sortBy: 'createdDate',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    currentUser,
    reduxDispatch,
    usingPrograms: getAllPrograms(Settings, UIDatabase).length > 0,
  });

  const {
    data,
    dataState,
    sortBy,
    isAscending,
    modalKey,
    hasSelection,
    usingPrograms,
    keyExtractor,
    columns,
    PageActions,
  } = state;

  const { PROGRAM_STOCKTAKE } = MODAL_KEYS;

  const getAction = useCallback((colKey, propName) => {
    switch (colKey) {
      case 'remove':
        if (propName === 'onCheckAction') return PageActions.selectRow;
        return PageActions.deselectRow;
      default:
        return null;
    }
  });

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = keyExtractor(item);
      const { row, alternateRow } = newDataTableStyles;

      return (
        <DataTableRow
          rowData={data[index]}
          rowState={dataState.get(rowKey)}
          rowKey={rowKey}
          style={index % 2 === 0 ? alternateRow : row}
          columns={columns}
          dispatch={dispatch}
          getAction={getAction}
          onPress={() => reduxDispatch(gotoStocktakeEditPage(item))}
        />
      );
    },
    [data, dataState]
  );

  const newStocktake = () => {
    if (usingPrograms) return dispatch(PageActions.openModal(PROGRAM_STOCKTAKE));
    return reduxDispatch(gotoStocktakeManagePage({ stocktakeName: '' }));
  };

  const renderButtons = () => {
    const { verticalContainer, topButton } = globalStyles;
    return (
      <View style={verticalContainer}>
        <PageButton
          style={topButton}
          text={buttonStrings.new_stocktake}
          onPress={() => newStocktake()}
        />
      </View>
    );
  };

  const getModalOnSelect = () => {
    switch (modalKey) {
      case PROGRAM_STOCKTAKE:
        return ({ stocktakeName, program }) => {
          reduxDispatch(createStocktake({ program, stocktakeName, currentUser }));
          dispatch(PageActions.closeModal());
        };
      default:
        return null;
    }
  };

  const renderHeader = () => (
    <DataTableHeaderRow
      columns={columns}
      dispatch={instantDebouncedDispatch}
      sortAction={PageActions.sortData}
      isAscending={isAscending}
      sortBy={sortBy}
    />
  );

  const {
    newPageTopSectionContainer,
    newPageTopLeftSectionContainer,
    newPageTopRightSectionContainer,
    searchBar,
  } = newPageStyles;
  return (
    <DataTablePageView>
      <View style={newPageTopSectionContainer}>
        <View style={newPageTopLeftSectionContainer}>
          <SearchBar
            onChange={value => debouncedDispatch(PageActions.filterData(value))}
            style={searchBar}
            color={SUSSOL_ORANGE}
            placeholder=""
          />
        </View>
        <View style={newPageTopRightSectionContainer}>{renderButtons()}</View>
      </View>
      <DataTable
        data={data}
        extraData={dataState}
        renderRow={renderRow}
        renderHeader={renderHeader}
        keyExtractor={keyExtractor}
        getItemLayout={getItemLayout}
      />
      <BottomConfirmModal
        isOpen={hasSelection}
        questionText={modalStrings.remove_these_items}
        onCancel={() => dispatch(PageActions.deselectAll())}
        onConfirm={() => dispatch(PageActions.deleteStocktakes())}
        confirmText={modalStrings.remove}
      />
      <DataTablePageModal
        fullScreen={false}
        isOpen={!!modalKey}
        modalKey={modalKey}
        onClose={() => dispatch(PageActions.closeModal())}
        onSelect={getModalOnSelect()}
        dispatch={dispatch}
      />
    </DataTablePageView>
  );
};

StocktakesPage.propTypes = {
  routeName: PropTypes.string.isRequired,
  dispatch: PropTypes.func.isRequired,
  currentUser: PropTypes.object.isRequired,
};
<commit_msg>Add use of internal SearchBar component over external package<commit_after>/* eslint-disable import/prefer-default-export */
/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';

import { UIDatabase } from '../database';
import Settings from '../settings/MobileAppSettings';

import { MODAL_KEYS, getAllPrograms } from '../utilities';
import { usePageReducer } from '../hooks';
import { getItemLayout, recordKeyExtractor } from './dataTableUtilities';

import { PageButton, DataTablePageView, SearchBar } from '../widgets';
import { BottomConfirmModal, DataTablePageModal } from '../widgets/modals';
import { DataTable, DataTableHeaderRow, DataTableRow } from '../widgets/DataTable';

import { buttonStrings, modalStrings } from '../localization';
import globalStyles, { SUSSOL_ORANGE, newDataTableStyles, newPageStyles } from '../globalStyles';

import {
  gotoStocktakeManagePage,
  createStocktake,
  gotoStocktakeEditPage,
} from '../navigation/actions';

export const StocktakesPage = ({ routeName, currentUser, dispatch: reduxDispatch }) => {
  const [state, dispatch, instantDebouncedDispatch, debouncedDispatch] = usePageReducer(routeName, {
    backingData: UIDatabase.objects('Stocktake'),
    data: UIDatabase.objects('Stocktake')
      .sorted('createdDate', false)
      .slice(),
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['name'],
    sortBy: 'createdDate',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    currentUser,
    reduxDispatch,
    usingPrograms: getAllPrograms(Settings, UIDatabase).length > 0,
  });

  const {
    data,
    dataState,
    sortBy,
    isAscending,
    searchTerm,
    modalKey,
    hasSelection,
    usingPrograms,
    keyExtractor,
    columns,
    PageActions,
  } = state;

  const { PROGRAM_STOCKTAKE } = MODAL_KEYS;

  const getAction = useCallback((colKey, propName) => {
    switch (colKey) {
      case 'remove':
        if (propName === 'onCheckAction') return PageActions.selectRow;
        return PageActions.deselectRow;
      default:
        return null;
    }
  });

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = keyExtractor(item);
      const { row, alternateRow } = newDataTableStyles;

      return (
        <DataTableRow
          rowData={data[index]}
          rowState={dataState.get(rowKey)}
          rowKey={rowKey}
          style={index % 2 === 0 ? alternateRow : row}
          columns={columns}
          dispatch={dispatch}
          getAction={getAction}
          onPress={() => reduxDispatch(gotoStocktakeEditPage(item))}
        />
      );
    },
    [data, dataState]
  );

  const newStocktake = () => {
    if (usingPrograms) return dispatch(PageActions.openModal(PROGRAM_STOCKTAKE));
    return reduxDispatch(gotoStocktakeManagePage({ stocktakeName: '' }));
  };

  const renderButtons = () => {
    const { verticalContainer, topButton } = globalStyles;
    return (
      <View style={verticalContainer}>
        <PageButton
          style={topButton}
          text={buttonStrings.new_stocktake}
          onPress={() => newStocktake()}
        />
      </View>
    );
  };

  const getModalOnSelect = () => {
    switch (modalKey) {
      case PROGRAM_STOCKTAKE:
        return ({ stocktakeName, program }) => {
          reduxDispatch(createStocktake({ program, stocktakeName, currentUser }));
          dispatch(PageActions.closeModal());
        };
      default:
        return null;
    }
  };

  const renderHeader = () => (
    <DataTableHeaderRow
      columns={columns}
      dispatch={instantDebouncedDispatch}
      sortAction={PageActions.sortData}
      isAscending={isAscending}
      sortBy={sortBy}
    />
  );

  const {
    newPageTopSectionContainer,
    newPageTopLeftSectionContainer,
    newPageTopRightSectionContainer,
    searchBar,
  } = newPageStyles;
  return (
    <DataTablePageView>
      <View style={newPageTopSectionContainer}>
        <View style={newPageTopLeftSectionContainer}>
          <SearchBar
            onChangeText={value => debouncedDispatch(PageActions.filterData(value))}
            style={searchBar}
            color={SUSSOL_ORANGE}
            placeholder=""
            value={searchTerm}
          />
        </View>
        <View style={newPageTopRightSectionContainer}>{renderButtons()}</View>
      </View>
      <DataTable
        data={data}
        extraData={dataState}
        renderRow={renderRow}
        renderHeader={renderHeader}
        keyExtractor={keyExtractor}
        getItemLayout={getItemLayout}
      />
      <BottomConfirmModal
        isOpen={hasSelection}
        questionText={modalStrings.remove_these_items}
        onCancel={() => dispatch(PageActions.deselectAll())}
        onConfirm={() => dispatch(PageActions.deleteStocktakes())}
        confirmText={modalStrings.remove}
      />
      <DataTablePageModal
        fullScreen={false}
        isOpen={!!modalKey}
        modalKey={modalKey}
        onClose={() => dispatch(PageActions.closeModal())}
        onSelect={getModalOnSelect()}
        dispatch={dispatch}
      />
    </DataTablePageView>
  );
};

StocktakesPage.propTypes = {
  routeName: PropTypes.string.isRequired,
  dispatch: PropTypes.func.isRequired,
  currentUser: PropTypes.object.isRequired,
};
<|endoftext|>


<commit_before>/**
 * maryamyriameliamurphies.js
 *
 * @name eq.js
 * @author Steven J. Syrek
 * @file Eq type class.
 * @license ISC
 */

 /** @module maryamyriameliamurphies.js/source/eq */

////////////////////////////////////////////////////////////////////////////////////////////////////
// Eq

/**
 * The `Eq` type class defines equality and inequality. Instances of `Eq` must define an `isEq` method.
 * @const {Function} - Returns `true` if an object is an instance of `Eq` and `false` otherwise.
 */
const Eq = defines(`isEq`);

/**
 * Compare two objects for equality. Both objects must be instances of the `Eq` type class (i.e. they
 * both define an `isEq` static method) and must also be the same data type (or the same primitive type).
 * Haskell> (==) :: a -> a -> Bool
 * @param {*} a - Any object.
 * @param {*} b - Any object.
 * @returns {boolean} - a === b
 * @example
 * let lst1 = list(1,2,3);
 * let lst2 = list(4,5,6);
 * isEq(lst1, lst2);        // => false
 * isEq(lst1, list(1,2,3)); // => true
 * isEq(0, 1);              // => false
 * isEq(0, 0);              // => true
 */
function isEq(a, b) {
  const isEqP = (a, b) => {
    if (typeCheck(a, b)) { return Eq(a) ? dataType(a).isEq(a, b) : a === b; }
    return error.typeMismatch(a, b, isEq);
  }
  return partial(isEqP, a, b);
}

/**
 * Compare two objects for inequality. Both objects must be instances of the `Eq` type class (i.e. they
 * both define an `isEq` static method) and must be also be the same data type (or the same primitive type).
 * Haskell> (/=) :: a -> a -> Bool
 * @param {*} a - Any object.
 * @param {*} b - Any object.
 * @returns {boolean} - a !== b
 * @example
 * let lst1 = list(1,2,3);
 * let lst2 = list(4,5,6);
 * isNotEq(lst1, lst2);        // => true
 * isNotEq(lst1, list(1,2,3)); // => false
 * isNotEq(0, 1);              // => true
 * isNotEq(0, 0);              // => false
 */
function isNotEq(a, b) {
  const isNotEqP = (a, b) => !isEq(a, b);
  return partial(isNotEqP, a, b);
}
<commit_msg>Add export keyword to eq.js functions<commit_after>/**
 * maryamyriameliamurphies.js
 *
 * @name eq.js
 * @author Steven J. Syrek
 * @file Eq type class.
 * @license ISC
 */

 /** @module maryamyriameliamurphies.js/source/eq */

////////////////////////////////////////////////////////////////////////////////////////////////////
// Eq

/**
 * The `Eq` type class defines equality and inequality. Instances of `Eq` must define an `isEq` method.
 * @const {Function} - Returns `true` if an object is an instance of `Eq` and `false` otherwise.
 */
const Eq = defines(`isEq`);

/**
 * Compare two objects for equality. Both objects must be instances of the `Eq` type class (i.e. they
 * both define an `isEq` static method) and must also be the same data type (or the same primitive type).
 * Haskell> (==) :: a -> a -> Bool
 * @param {*} a - Any object.
 * @param {*} b - Any object.
 * @returns {boolean} - a === b
 * @example
 * let lst1 = list(1,2,3);
 * let lst2 = list(4,5,6);
 * isEq(lst1, lst2);        // => false
 * isEq(lst1, list(1,2,3)); // => true
 * isEq(0, 1);              // => false
 * isEq(0, 0);              // => true
 */
export function isEq(a, b) {
  const isEqP = (a, b) => {
    if (typeCheck(a, b)) { return Eq(a) ? dataType(a).isEq(a, b) : a === b; }
    return error.typeMismatch(a, b, isEq);
  }
  return partial(isEqP, a, b);
}

/**
 * Compare two objects for inequality. Both objects must be instances of the `Eq` type class (i.e. they
 * both define an `isEq` static method) and must be also be the same data type (or the same primitive type).
 * Haskell> (/=) :: a -> a -> Bool
 * @param {*} a - Any object.
 * @param {*} b - Any object.
 * @returns {boolean} - a !== b
 * @example
 * let lst1 = list(1,2,3);
 * let lst2 = list(4,5,6);
 * isNotEq(lst1, lst2);        // => true
 * isNotEq(lst1, list(1,2,3)); // => false
 * isNotEq(0, 1);              // => true
 * isNotEq(0, 0);              // => false
 */
export function isNotEq(a, b) {
  const isNotEqP = (a, b) => !isEq(a, b);
  return partial(isNotEqP, a, b);
}
<|endoftext|>


<commit_before>(function(a){a.isScrollToFixed=function(b){return a(b).data("ScrollToFixed")!==undefined};a.ScrollToFixed=function(d,h){var k=this;k.$el=a(d);k.el=d;k.$el.data("ScrollToFixed",k);var c=false;var F=k.$el;var G;var D;var p;var C=0;var q=0;var i=-1;var e=-1;var t=null;var y;var f;function u(){F.trigger("preUnfixed.ScrollToFixed");j();F.trigger("unfixed.ScrollToFixed");e=-1;C=F.offset().top;q=F.offset().left;if(k.options.offsets){q+=(F.offset().left-F.position().left)}if(i==-1){i=q}G=F.css("position");c=true;if(k.options.bottom!=-1){F.trigger("preFixed.ScrollToFixed");w();F.trigger("fixed.ScrollToFixed")}}function m(){var H=k.options.limit;if(!H){return 0}if(typeof(H)==="function"){return H.apply(F)}return H}function o(){return G==="fixed"}function x(){return G==="absolute"}function g(){return !(o()||x())}function w(){if(!o()){t.css({display:F.css("display"),width:F.outerWidth(true),height:F.outerHeight(true),"float":F.css("float")});F.css({width:F.width(),position:"fixed",top:k.options.bottom==-1?s():"",bottom:k.options.bottom==-1?"":k.options.bottom,"margin-left":"0px"});F.addClass("scroll-to-fixed-fixed");if(k.options.className){F.addClass(k.options.className)}G="fixed"}}function b(){var I=m();var H=q;if(k.options.removeOffsets){H=0;I=I-C}F.css({width:F.width(),position:"absolute",top:I,left:H,"margin-left":"0px",bottom:""});G="absolute"}function j(){if(!g()){e=-1;t.css("display","none");F.css({width:"",position:D,left:"",top:p.top,"margin-left":""});F.removeClass("scroll-to-fixed-fixed");if(k.options.className){F.removeClass(k.options.className)}G=null}}function v(H){if(H!=e){F.css("left",q-H);e=H}}function s(){var H=k.options.marginTop;if(!H){return 0}if(typeof(H)==="function"){return H.apply(F)}return H}function z(){if(!a.isScrollToFixed(F)){return}var J=c;if(!c){u()}var H=a(window).scrollLeft();var K=a(window).scrollTop();var I=m();if(k.options.minWidth&&a(window).width()<k.options.minWidth){if(!g()||!J){n();F.trigger("preUnfixed.ScrollToFixed");j();F.trigger("unfixed.ScrollToFixed")}}else{if(k.options.bottom==-1){if(I>0&&K>=I-s()){if(!x()||!J){n();F.trigger("preAbsolute.ScrollToFixed");b();F.trigger("unfixed.ScrollToFixed")}}else{if(K>=C-s()){if(!o()||!J){n();F.trigger("preFixed.ScrollToFixed");w();e=-1;F.trigger("fixed.ScrollToFixed")}v(H)}else{if(!g()||!J){n();F.trigger("preUnfixed.ScrollToFixed");j();F.trigger("unfixed.ScrollToFixed")}}}}else{if(I>0){if(K+a(window).height()-F.outerHeight(true)>=I-(s()||-l())){if(o()){n();F.trigger("preUnfixed.ScrollToFixed");if(D==="absolute"){b()}else{j()}F.trigger("unfixed.ScrollToFixed")}}else{if(!o()){n();F.trigger("preFixed.ScrollToFixed");w()}v(H);F.trigger("fixed.ScrollToFixed")}}else{v(H)}}}}function l(){if(!k.options.bottom){return 0}return k.options.bottom}function n(){var H=F.css("position");if(H=="absolute"){F.trigger("postAbsolute.ScrollToFixed")}else{if(H=="fixed"){F.trigger("postFixed.ScrollToFixed")}else{F.trigger("postUnfixed.ScrollToFixed")}}}var B=function(H){if(F.is(":visible")){c=false;z()}};var E=function(H){z()};var A=function(){var I=document.body;if(document.createElement&&I&&I.appendChild&&I.removeChild){var K=document.createElement("div");if(!K.getBoundingClientRect){return null}K.innerHTML="x";K.style.cssText="position:fixed;top:100px;";I.appendChild(K);var L=I.style.height,M=I.scrollTop;I.style.height="3000px";I.scrollTop=500;var H=K.getBoundingClientRect().top;I.style.height=L;var J=(H===100);I.removeChild(K);I.scrollTop=M;return J}return null};var r=function(H){H=H||window.event;if(H.preventDefault){H.preventDefault()}H.returnValue=false};k.init=function(){k.options=a.extend({},a.ScrollToFixed.defaultOptions,h);k.$el.css("z-index",k.options.zIndex);t=a("<div />");G=F.css("position");D=F.css("position");p=a.extend({},F.offset());if(g()){k.$el.after(t)}a(window).bind("resize.ScrollToFixed",B);a(window).bind("scroll.ScrollToFixed",E);if(k.options.preFixed){F.bind("preFixed.ScrollToFixed",k.options.preFixed)}if(k.options.postFixed){F.bind("postFixed.ScrollToFixed",k.options.postFixed)}if(k.options.preUnfixed){F.bind("preUnfixed.ScrollToFixed",k.options.preUnfixed)}if(k.options.postUnfixed){F.bind("postUnfixed.ScrollToFixed",k.options.postUnfixed)}if(k.options.preAbsolute){F.bind("preAbsolute.ScrollToFixed",k.options.preAbsolute)}if(k.options.postAbsolute){F.bind("postAbsolute.ScrollToFixed",k.options.postAbsolute)}if(k.options.fixed){F.bind("fixed.ScrollToFixed",k.options.fixed)}if(k.options.unfixed){F.bind("unfixed.ScrollToFixed",k.options.unfixed)}if(k.options.spacerClass){t.addClass(k.options.spacerClass)}F.bind("resize.ScrollToFixed",function(){t.height(F.height())});F.bind("scroll.ScrollToFixed",function(){F.trigger("preUnfixed.ScrollToFixed");j();F.trigger("unfixed.ScrollToFixed");z()});F.bind("detach.ScrollToFixed",function(H){r(H);F.trigger("preUnfixed.ScrollToFixed");j();F.trigger("unfixed.ScrollToFixed");a(window).unbind("resize.ScrollToFixed",B);a(window).unbind("scroll.ScrollToFixed",E);F.unbind(".ScrollToFixed");k.$el.removeData("ScrollToFixed")});B()};k.init()};a.ScrollToFixed.defaultOptions={marginTop:0,limit:0,bottom:-1,zIndex:1000};a.fn.scrollToFixed=function(b){return this.each(function(){(new a.ScrollToFixed(this,b))})}})(jQuery);<commit_msg>See #80: Minified the plugin.<commit_after>(function(a){a.isScrollToFixed=function(b){return a(b).data("ScrollToFixed")!==undefined};a.ScrollToFixed=function(d,h){var k=this;k.$el=a(d);k.el=d;k.$el.data("ScrollToFixed",k);var c=false;var F=k.$el;var G;var D;var p;var C=0;var q=0;var i=-1;var e=-1;var t=null;var y;var f;function u(){F.trigger("preUnfixed.ScrollToFixed");j();F.trigger("unfixed.ScrollToFixed");e=-1;C=F.offset().top;q=F.offset().left;if(k.options.offsets){q+=(F.offset().left-F.position().left)}if(i==-1){i=q}G=F.css("position");c=true;if(k.options.bottom!=-1){F.trigger("preFixed.ScrollToFixed");w();F.trigger("fixed.ScrollToFixed")}}function m(){var H=k.options.limit;if(!H){return 0}if(typeof(H)==="function"){return H.apply(F)}return H}function o(){return G==="fixed"}function x(){return G==="absolute"}function g(){return !(o()||x())}function w(){if(!o()){t.css({display:F.css("display"),width:F.outerWidth(true),height:F.outerHeight(true),"float":F.css("float")});cssOptions={position:"fixed",top:k.options.bottom==-1?s():"",bottom:k.options.bottom==-1?"":k.options.bottom,"margin-left":"0px"};if(!k.options.dontSetWidth){cssOptions.width=F.width()}F.css(cssOptions);F.addClass("scroll-to-fixed-fixed");if(k.options.className){F.addClass(k.options.className)}G="fixed"}}function b(){var I=m();var H=q;if(k.options.removeOffsets){H=0;I=I-C}cssOptions={position:"absolute",top:I,left:H,"margin-left":"0px",bottom:""};if(!k.options.dontSetWidth){cssOptions.width=F.width()}F.css(cssOptions);G="absolute"}function j(){if(!g()){e=-1;t.css("display","none");F.css({width:"",position:D,left:"",top:p.top,"margin-left":""});F.removeClass("scroll-to-fixed-fixed");if(k.options.className){F.removeClass(k.options.className)}G=null}}function v(H){if(H!=e){F.css("left",q-H);e=H}}function s(){var H=k.options.marginTop;if(!H){return 0}if(typeof(H)==="function"){return H.apply(F)}return H}function z(){if(!a.isScrollToFixed(F)){return}var J=c;if(!c){u()}var H=a(window).scrollLeft();var K=a(window).scrollTop();var I=m();if(k.options.minWidth&&a(window).width()<k.options.minWidth){if(!g()||!J){n();F.trigger("preUnfixed.ScrollToFixed");j();F.trigger("unfixed.ScrollToFixed")}}else{if(k.options.bottom==-1){if(I>0&&K>=I-s()){if(!x()||!J){n();F.trigger("preAbsolute.ScrollToFixed");b();F.trigger("unfixed.ScrollToFixed")}}else{if(K>=C-s()){if(!o()||!J){n();F.trigger("preFixed.ScrollToFixed");w();e=-1;F.trigger("fixed.ScrollToFixed")}v(H)}else{if(!g()||!J){n();F.trigger("preUnfixed.ScrollToFixed");j();F.trigger("unfixed.ScrollToFixed")}}}}else{if(I>0){if(K+a(window).height()-F.outerHeight(true)>=I-(s()||-l())){if(o()){n();F.trigger("preUnfixed.ScrollToFixed");if(D==="absolute"){b()}else{j()}F.trigger("unfixed.ScrollToFixed")}}else{if(!o()){n();F.trigger("preFixed.ScrollToFixed");w()}v(H);F.trigger("fixed.ScrollToFixed")}}else{v(H)}}}}function l(){if(!k.options.bottom){return 0}return k.options.bottom}function n(){var H=F.css("position");if(H=="absolute"){F.trigger("postAbsolute.ScrollToFixed")}else{if(H=="fixed"){F.trigger("postFixed.ScrollToFixed")}else{F.trigger("postUnfixed.ScrollToFixed")}}}var B=function(H){if(F.is(":visible")){c=false;z()}};var E=function(H){z()};var A=function(){var I=document.body;if(document.createElement&&I&&I.appendChild&&I.removeChild){var K=document.createElement("div");if(!K.getBoundingClientRect){return null}K.innerHTML="x";K.style.cssText="position:fixed;top:100px;";I.appendChild(K);var L=I.style.height,M=I.scrollTop;I.style.height="3000px";I.scrollTop=500;var H=K.getBoundingClientRect().top;I.style.height=L;var J=(H===100);I.removeChild(K);I.scrollTop=M;return J}return null};var r=function(H){H=H||window.event;if(H.preventDefault){H.preventDefault()}H.returnValue=false};k.init=function(){k.options=a.extend({},a.ScrollToFixed.defaultOptions,h);k.$el.css("z-index",k.options.zIndex);t=a("<div />");G=F.css("position");D=F.css("position");p=a.extend({},F.offset());if(g()){k.$el.after(t)}a(window).bind("resize.ScrollToFixed",B);a(window).bind("scroll.ScrollToFixed",E);if(k.options.preFixed){F.bind("preFixed.ScrollToFixed",k.options.preFixed)}if(k.options.postFixed){F.bind("postFixed.ScrollToFixed",k.options.postFixed)}if(k.options.preUnfixed){F.bind("preUnfixed.ScrollToFixed",k.options.preUnfixed)}if(k.options.postUnfixed){F.bind("postUnfixed.ScrollToFixed",k.options.postUnfixed)}if(k.options.preAbsolute){F.bind("preAbsolute.ScrollToFixed",k.options.preAbsolute)}if(k.options.postAbsolute){F.bind("postAbsolute.ScrollToFixed",k.options.postAbsolute)}if(k.options.fixed){F.bind("fixed.ScrollToFixed",k.options.fixed)}if(k.options.unfixed){F.bind("unfixed.ScrollToFixed",k.options.unfixed)}if(k.options.spacerClass){t.addClass(k.options.spacerClass)}F.bind("resize.ScrollToFixed",function(){t.height(F.height())});F.bind("scroll.ScrollToFixed",function(){F.trigger("preUnfixed.ScrollToFixed");j();F.trigger("unfixed.ScrollToFixed");z()});F.bind("detach.ScrollToFixed",function(H){r(H);F.trigger("preUnfixed.ScrollToFixed");j();F.trigger("unfixed.ScrollToFixed");a(window).unbind("resize.ScrollToFixed",B);a(window).unbind("scroll.ScrollToFixed",E);F.unbind(".ScrollToFixed");k.$el.removeData("ScrollToFixed")});B()};k.init()};a.ScrollToFixed.defaultOptions={marginTop:0,limit:0,bottom:-1,zIndex:1000};a.fn.scrollToFixed=function(b){return this.each(function(){(new a.ScrollToFixed(this,b))})}})(jQuery);<|endoftext|>


<commit_before>var FtreesController = function($scope, $state, $stateParams, $location, ftrees, notification) {
	var self = this;

	this.individuals = [];
	this.search_params = {};
	this.query = '';
	this.advanced_search = false;

	this.search_modifiers = {
		first_name: 	'',
		last_name: 		'',
		birth_place: 	'',
		marriage_place: '',
		death_place: 	''
	};
	this.fudge_factors = {
		birth_year: 	0,
		marriage_year: 	0,
		death_year: 	0
	};

	this.$state = $state;
	this.$stateParams = $stateParams;
	this.$scope = $scope;
	this.$location = $location;
	this.ftrees = ftrees;
	this.notification = notification;

	Object.defineProperty($scope, '$stateParams', {
		get: function() {
			return $stateParams;
		}
	});

	//search
	var BreakException= {};
	var parameters = [];
	try {
		Object.keys($stateParams).forEach(function(key) {
			if ($stateParams[key]) {

				// read state params & update bound objects to update view accordingly
				for (var param in $stateParams) {
					if ( $stateParams[param] !== undefined ) {
						parameters.push($stateParams[param]);

						// handle search modifiers & fudge factors in query string
						if ( $stateParams[param].indexOf('~') !== -1 ) {
							var parts = $stateParams[param].split('~');
							self.search_params[param] = parts[0];
							self.fudge_factors[param] = parts[1];
						}
						else if ( $stateParams[param].indexOf(';') !== -1 ) {
							var parts = $stateParams[param].split(';');
							self.search_params[param] = parts[0];
							self.search_modifiers[param] = parts[1];
						}
						else {
							self.search_params[param] = $stateParams[param];
						}
					}
					self.query = parameters.join(' + ');
				};

				self.search($stateParams);
				throw BreakException;
			}
		});
	}
	catch(e) {
		 if (e !== BreakException) throw e;
	}
};

FtreesController.prototype = {
	search: function(search_params) {
		var self = this;

		this.notification.put({
			en:'Searching family trees...',
			he: 'מחפש בעצי משפחה...'
		});

		this.ftrees.search(search_params).
			then(function(individuals) {
				self.individuals = individuals;

				if (self.results_per_page > individuals.length) {
					if (individuals.length === 0) {
						self.results_per_page = 15;
					}
					else {
						self.results_per_page = (individuals.length - individuals.length % 5) || 5;
					}
				}

				self.notification.put({
					en: 'Family Trees Search has finished successfully.',
					he: 'חיפוש בעצי משפחה הסתיים בהצלחה.'
				});

			}, function() {
				self.notification.put({
					en: 'Family Trees Search has failed.',
					he: 'חיפוש בעצי משפחה נכשל.'
				});
			});
	},

	fetch_more: function() {
		var self = this;
		var search_params = angular.copy(this.search_params);
		search_params.start = self.individuals.items.length;
		var individuals = self.individuals;
		this.ftrees.search(search_params).
			then(function (r){
				self.individuals.items = individuals.items.concat(r.items);
			});
    },

	update: function() {
		var self = this;
		var search_params = angular.copy(this.search_params);

		for (var param in search_params) {
			if (search_params[param] === '') {
				delete search_params[param];
			}
		}

		if (search_params.ind_index) {
			delete(search_params.ind_index);
		}

		// insert search modifiers & fudge_factors into query string
		for (var modifier in this.search_modifiers) {
			var modifier_string = this.search_modifiers[modifier];
			if (search_params[modifier] !== undefined && modifier_string !== '') {
				search_params[modifier] += ';' + modifier_string;
			}
		}
		for (var factor in this.fudge_factors) {
			var fudge_val = this.fudge_factors[factor];
			if (search_params[factor] !== undefined && fudge_val !== 0) {
				search_params[factor] += '~' + fudge_val;
			}
		}

		// avoid conflict with parameter from state ftree-view.ftree-item
		search_params.tree_number = search_params.filters_tree_number;
		delete search_params.filters_tree_number;

		for (var param in this.search_params) {
			this.$location.search(param, search_params[param]);
		}
	},

 	clear_filters: function() {
 		for (var modifier in this.search_modifiers) {
 			this.search_params[modifier] = '';
 		}
 	},

	get_href: function (individual) {
		// TODO: support languages
		return this.$state.href('person-view', {tree_number: individual.GTN,
							   			   node_id: individual.II});
	},

	read_about_center: function (collection_name) {
        this.$state.go('about_center', {collection: collection_name});
    }
};

angular.module('main').controller('FtreesController', ['$scope', '$state', '$stateParams', '$location', 'ftrees', 'notification', FtreesController]);
<commit_msg>fixing clear filters<commit_after>var FtreesController = function($scope, $state, $stateParams, $location, ftrees, notification) {
	var self = this;

	this.individuals = [];
	this.search_params = {};
	this.query = '';
	this.advanced_search = false;

	this.search_modifiers = {
		first_name: 	'',
		last_name: 		'',
		birth_place: 	'',
		marriage_place: '',
		death_place: 	''
	};
	this.fudge_factors = {
		birth_year: 	0,
		marriage_year: 	0,
		death_year: 	0
	};

	this.$state = $state;
	this.$stateParams = $stateParams;
	this.$scope = $scope;
	this.$location = $location;
	this.ftrees = ftrees;
	this.notification = notification;

	Object.defineProperty($scope, '$stateParams', {
		get: function() {
			return $stateParams;
		}
	});

	//search
	var BreakException= {};
	var parameters = [];
	try {
		Object.keys($stateParams).forEach(function(key) {
			if ($stateParams[key]) {

				// read state params & update bound objects to update view accordingly
				for (var param in $stateParams) {
					if ( $stateParams[param] !== undefined ) {
						parameters.push($stateParams[param]);

						// handle search modifiers & fudge factors in query string
						if ( $stateParams[param].indexOf('~') !== -1 ) {
							var parts = $stateParams[param].split('~');
							self.search_params[param] = parts[0];
							self.fudge_factors[param] = parts[1];
						}
						else if ( $stateParams[param].indexOf(';') !== -1 ) {
							var parts = $stateParams[param].split(';');
							self.search_params[param] = parts[0];
							self.search_modifiers[param] = parts[1];
						}
						else {
							self.search_params[param] = $stateParams[param];
						}
					}
					self.query = parameters.join(' + ');
				};

				self.search($stateParams);
				throw BreakException;
			}
		});
	}
	catch(e) {
		 if (e !== BreakException) throw e;
	}
};

FtreesController.prototype = {
	search: function(search_params) {
		var self = this;

		this.notification.put({
			en:'Searching family trees...',
			he: 'מחפש בעצי משפחה...'
		});

		this.ftrees.search(search_params).
			then(function(individuals) {
				self.individuals = individuals;

				if (self.results_per_page > individuals.length) {
					if (individuals.length === 0) {
						self.results_per_page = 15;
					}
					else {
						self.results_per_page = (individuals.length - individuals.length % 5) || 5;
					}
				}

				self.notification.put({
					en: 'Family Trees Search has finished successfully.',
					he: 'חיפוש בעצי משפחה הסתיים בהצלחה.'
				});

			}, function() {
				self.notification.put({
					en: 'Family Trees Search has failed.',
					he: 'חיפוש בעצי משפחה נכשל.'
				});
			});
	},

	fetch_more: function() {
		var self = this;
		var search_params = angular.copy(this.search_params);
		search_params.start = self.individuals.items.length;
		var individuals = self.individuals;
		this.ftrees.search(search_params).
			then(function (r){
				self.individuals.items = individuals.items.concat(r.items);
			});
    },

	update: function() {
		var self = this;
		var search_params = angular.copy(this.search_params);

		for (var param in search_params) {
			if (search_params[param] === '') {
				delete search_params[param];
			}
		}

		if (search_params.ind_index) {
			delete(search_params.ind_index);
		}

		// insert search modifiers & fudge_factors into query string
		for (var modifier in this.search_modifiers) {
			var modifier_string = this.search_modifiers[modifier];
			if (search_params[modifier] !== undefined && modifier_string !== '') {
				search_params[modifier] += ';' + modifier_string;
			}
		}
		for (var factor in this.fudge_factors) {
			var fudge_val = this.fudge_factors[factor];
			if (search_params[factor] !== undefined && fudge_val !== 0) {
				search_params[factor] += '~' + fudge_val;
			}
		}

		// avoid conflict with parameter from state ftree-view.ftree-item
		search_params.tree_number = search_params.filters_tree_number;
		delete search_params.filters_tree_number;

		for (var param in this.search_params) {
			this.$location.search(param, search_params[param]);
		}
	},

 	clear_filters: function() {
 		for (var parameter in this.search_params) {
 			this.search_params[parameter] = '';
 		}
 	},

	get_href: function (individual) {
		// TODO: support languages
		return this.$state.href('person-view', {tree_number: individual.GTN,
							   			   node_id: individual.II});
	},

	read_about_center: function (collection_name) {
        this.$state.go('about_center', {collection: collection_name});
    }
};

angular.module('main').controller('FtreesController', ['$scope', '$state', '$stateParams', '$location', 'ftrees', 'notification', FtreesController]);
<|endoftext|>


<commit_before>import { createHmac } from 'crypto';

export default async function handleWebhook(req, res) {
  // verify the webhook signature request against the
  // unmodified, unparsed body
  const body = await getRawBody(req);
  if (!body) {
    res.status(400).send('Bad request (no body)');
    return;
  }

  const jsonBody = JSON.parse(body);

  console.log({ jsonBody });

  const slug = jsonBody.fields.slug;

  console.log({ slug });

  // secret
  const secret = process.env.NEXT_PUBLIC_REVALIDATION;

  if (req.query.secret === secret) {
    // issue opened or edited
    // comment created or edited
    console.log('[Next.js] Revalidating /');
    await res.revalidate('/');
    if (slug) {
      console.log(`[Next.js] Revalidating /${slug}`);
      await res.revalidate(`/${slug}`);
    }

    return res.status(200).send('Success!');
  } else {
    return res.status(403).send('Forbidden');
  }
}

function getRawBody(req) {
  return new Promise((resolve, reject) => {
    let bodyChunks = [];
    req.on('end', () => {
      const rawBody = Buffer.concat(bodyChunks).toString('utf8');
      resolve(rawBody);
    });
    req.on('data', (chunk) => bodyChunks.push(chunk));
  });
}

export const config = {
  api: {
    bodyParser: false,
  },
};
<commit_msg>fix: api revalidation test<commit_after>import { createHmac } from 'crypto';

export default async function handleWebhook(req, res) {
  // verify the webhook signature request against the
  // unmodified, unparsed body
  const body = await getRawBody(req);
  if (!body) {
    res.status(400).send('Bad request (no body)');
    return;
  }

  const jsonBody = JSON.parse(body);

  console.log(jsonBody);

  const slug = jsonBody.fields.slug['en-US'];

  console.log(slug);

  // secret
  const secret = process.env.NEXT_PUBLIC_REVALIDATION;

  if (req.query.secret === secret) {
    // issue opened or edited
    // comment created or edited
    console.log('[Next.js] Revalidating /');
    await res.revalidate('/');
    if (slug) {
      console.log(`[Next.js] Revalidating /${slug}`);
      await res.revalidate(`/${slug}`);
    }

    return res.status(200).send('Success!');
  } else {
    return res.status(403).send('Forbidden');
  }
}

function getRawBody(req) {
  return new Promise((resolve, reject) => {
    let bodyChunks = [];
    req.on('end', () => {
      const rawBody = Buffer.concat(bodyChunks).toString('utf8');
      resolve(rawBody);
    });
    req.on('data', (chunk) => bodyChunks.push(chunk));
  });
}

export const config = {
  api: {
    bodyParser: false,
  },
};
<|endoftext|>


<commit_before>"use strict";

var Web3 = require('web3');
var web3;

// @see https://gist.github.com/frozeman/fbc7465d0b0e6c1c4c23
if (typeof web3 !== 'undefined') {
  var defaultAccount = web3.eth.defaultAccount;
  web3 = new Web3(web3.currentProvider);
  web3.eth.defaultAccount = defaultAccount;
}
else {
  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
  web3.eth.defaultAccount = web3.eth.accounts[0];
}

var blobStoreAbi = require('./blobstore.abi.json');
var blobStoreContract = web3.eth.contract(blobStoreAbi);
var blobStoreAddress = '0x8a69A63fcA907939e5C7d92A260D8875C8700383';
var blobStore = blobStoreContract.at(blobStoreAddress);

module.exports.contract = blobStore;

// solc version: 0.4.2+commit.af6afb04.Linux.g++

function sendTransaction(tx, callback) {
  web3.eth.estimateGas(tx, 'pending', function(error, gas) {
    if (error) { callback(error); return; }
    tx.gas = gas;
    // Broadcast the transaction.
    web3.eth.sendTransaction(tx, function(error, result) {
      if (error) { callback(error); return; }
      callback(null, result);
    });
  });
}

module.exports.create = function(contents, flags, callback) {
  // Combine the flags into 4 bytes.
  var flagsBinary = 0;
  if (flags.updatable) {
    flagsBinary |= 0x01;
  }
  if (flags.enforceRevisions) {
    flagsBinary |= 0x02;
  }
  if (flags.retractable) {
    flagsBinary |= 0x04;
  }
  if (flags.transferable) {
    flagsBinary |= 0x08;
  }
  if (flags.anonymous) {
    flagsBinary |= 0x10;
  }
  var flagsBuf = new Buffer(4);
  flagsBuf.writeUInt8(flagsBinary, 3);

  // Keep hashing until we find a unique blobId.
  var nonce = web3.sha3(contents.toString('hex'), {encoding: 'hex'});
  var flagsNonce = "0x" + flagsBuf.toString('hex') + nonce.substr(2, 56);
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.createWithNonce.getData(flagsNonce, '0x' + contents.toString('hex'))
  }
  var blobId = web3.eth.call(tx, 'pending');
  while (blobId == "0x") {
    nonce = web3.sha3(nonce);
    flagsNonce = "0x" + flagsBuf.toString('hex') + nonce.substr(2, 56);
    // Create transaction object.
    tx = {
      to: blobStoreAddress,
      data: blobStore.createWithNonce.getData(flagsNonce, '0x' + contents.toString('hex'))
    }
    blobId = web3.eth.call(tx, 'pending');
  }
  sendTransaction(tx, callback);
  // Remove the padding from blobId.
  return blobId.substr(0, 42);
}

module.exports.createNewRevision = function(blobId, blob, callback) {
  // Create the transaction.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.createNewRevision.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Send it.
  sendTransaction(tx, callback);
}

module.exports.updateLatestRevision = function(blobId, blob, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.updateLatestRevision.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.retractLatestRevision = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.retractLatestRevision.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.restart = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.restart.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.retract = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.retract.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.transferEnable = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.transferEnable.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.transferDisable = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.transferDisable.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.transfer = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.transfer.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.disown = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.disown.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.setNotUpdatable = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.setNotUpdatable.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.setEnforceRevisions = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.setEnforceRevisions.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.setNotRetractable = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.setNotRetractable.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.setNotTransferable = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.setNotTransferable.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.getContractId = module.exports.contract.getContractId;
module.exports.getExists = module.exports.contract.getExists;
module.exports.getInfo = module.exports.contract.getInfo;
module.exports.getFlags = module.exports.contract.getFlags;
module.exports.getUpdatable = module.exports.contract.getUpdatable;
module.exports.getEnforceRevisions = module.exports.contract.getEnforceRevisions;
module.exports.getRetractable = module.exports.contract.getRetractable;
module.exports.getTransferable = module.exports.contract.getTransferable;
module.exports.getOwner = module.exports.contract.getOwner;
module.exports.getRevisionCount = module.exports.contract.getRevisionCount;
module.exports.getRevisionBlockNumber = module.exports.contract.getRevisionBlockNumber;
module.exports.getAllRevisionBlockNumbers = module.exports.contract.getAllRevisionBlockNumbers;

module.exports.getContents = function(blobId, revisionId, callback) {
  // Get the block number.
  blobStore.getRevisionBlockNumber(blobId, revisionId, 'pending', function(error, blockNumber) {
    if (error) { callback(error); return; }
    if (blockNumber == 0) {
      callback("Error: blob revision not found.");
      return;
    }
    var fromBlock, toBlock;
    if (web3.eth.blockNumber - blockNumber < 20) {
      fromBlock = web3.eth.blockNumber - 20;
      toBlock = 'pending';
    }
    else {
      fromBlock = toBlock = blockNumber;
    }
    var revisionIdBuf = new Buffer(32);
    revisionIdBuf.fill(0);
    revisionIdBuf.writeUInt32BE(revisionId, 28);
    // Search the logs.
    web3.eth.filter({fromBlock: fromBlock, toBlock: toBlock, address: blobStoreAddress, topics: ["0xfd5eeef8919c5473de9558a49bf3a5b19bcf59ec0d36e420586d7c3bbaf17d01", blobId + "000000000000000000000000", "0x" + revisionIdBuf.toString('hex')]}).get(function(error, result) {
      if (error) { callback(error); return; }
      for (var i = 0; i < result.length; i++) {
        var length = parseInt(result[i].data.substr(66, 64), 16);
        callback(null, new Buffer(result[i].data.substr(130, length * 2), 'hex'));
      }
    });
  });
}
<commit_msg>Fix contract address.<commit_after>"use strict";

var Web3 = require('web3');
var web3;

// @see https://gist.github.com/frozeman/fbc7465d0b0e6c1c4c23
if (typeof web3 !== 'undefined') {
  var defaultAccount = web3.eth.defaultAccount;
  web3 = new Web3(web3.currentProvider);
  web3.eth.defaultAccount = defaultAccount;
}
else {
  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
  web3.eth.defaultAccount = web3.eth.accounts[0];
}

var blobStoreAbi = require('./blobstore.abi.json');
var blobStoreContract = web3.eth.contract(blobStoreAbi);
var blobStoreAddress = '0xe70e90fdD2B9d3e27BDd56ef249EE1D408F40BE2';
var blobStore = blobStoreContract.at(blobStoreAddress);

module.exports.contract = blobStore;

function sendTransaction(tx, callback) {
  web3.eth.estimateGas(tx, 'pending', function(error, gas) {
    if (error) { callback(error); return; }
    tx.gas = gas;
    // Broadcast the transaction.
    web3.eth.sendTransaction(tx, function(error, result) {
      if (error) { callback(error); return; }
      callback(null, result);
    });
  });
}

module.exports.create = function(contents, flags, callback) {
  // Combine the flags into 4 bytes.
  var flagsBinary = 0;
  if (flags.updatable) {
    flagsBinary |= 0x01;
  }
  if (flags.enforceRevisions) {
    flagsBinary |= 0x02;
  }
  if (flags.retractable) {
    flagsBinary |= 0x04;
  }
  if (flags.transferable) {
    flagsBinary |= 0x08;
  }
  if (flags.anonymous) {
    flagsBinary |= 0x10;
  }
  var flagsBuf = new Buffer(4);
  flagsBuf.writeUInt8(flagsBinary, 3);

  // Keep hashing until we find a unique blobId.
  var nonce = web3.sha3(contents.toString('hex'), {encoding: 'hex'});
  var flagsNonce = "0x" + flagsBuf.toString('hex') + nonce.substr(2, 56);
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.createWithNonce.getData(flagsNonce, '0x' + contents.toString('hex'))
  }
  var blobId = web3.eth.call(tx, 'pending');
  while (blobId == "0x") {
    nonce = web3.sha3(nonce);
    flagsNonce = "0x" + flagsBuf.toString('hex') + nonce.substr(2, 56);
    // Create transaction object.
    tx = {
      to: blobStoreAddress,
      data: blobStore.createWithNonce.getData(flagsNonce, '0x' + contents.toString('hex'))
    }
    blobId = web3.eth.call(tx, 'pending');
  }
  sendTransaction(tx, callback);
  // Remove the padding from blobId.
  return blobId.substr(0, 42);
}

module.exports.createNewRevision = function(blobId, blob, callback) {
  // Create the transaction.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.createNewRevision.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Send it.
  sendTransaction(tx, callback);
}

module.exports.updateLatestRevision = function(blobId, blob, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.updateLatestRevision.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.retractLatestRevision = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.retractLatestRevision.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.restart = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.restart.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.retract = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.retract.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.transferEnable = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.transferEnable.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.transferDisable = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.transferDisable.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.transfer = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.transfer.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.disown = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.disown.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.setNotUpdatable = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.setNotUpdatable.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.setEnforceRevisions = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.setEnforceRevisions.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.setNotRetractable = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.setNotRetractable.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.setNotTransferable = function(blobId, callback) {
  // Create transaction object.
  var tx = {
    to: blobStoreAddress,
    data: blobStore.setNotTransferable.getData(blobId, '0x' + contents.toString('hex'))
  }
  // Create the transaction.
  sendTransaction(tx, callback);
}

module.exports.getContractId = module.exports.contract.getContractId;
module.exports.getExists = module.exports.contract.getExists;
module.exports.getInfo = module.exports.contract.getInfo;
module.exports.getFlags = module.exports.contract.getFlags;
module.exports.getUpdatable = module.exports.contract.getUpdatable;
module.exports.getEnforceRevisions = module.exports.contract.getEnforceRevisions;
module.exports.getRetractable = module.exports.contract.getRetractable;
module.exports.getTransferable = module.exports.contract.getTransferable;
module.exports.getOwner = module.exports.contract.getOwner;
module.exports.getRevisionCount = module.exports.contract.getRevisionCount;
module.exports.getRevisionBlockNumber = module.exports.contract.getRevisionBlockNumber;
module.exports.getAllRevisionBlockNumbers = module.exports.contract.getAllRevisionBlockNumbers;

module.exports.getContents = function(blobId, revisionId, callback) {
  // Get the block number.
  blobStore.getRevisionBlockNumber(blobId, revisionId, 'pending', function(error, blockNumber) {
    if (error) { callback(error); return; }
    if (blockNumber == 0) {
      callback("Error: blob revision not found.");
      return;
    }
    var fromBlock, toBlock;
    if (web3.eth.blockNumber - blockNumber < 20) {
      fromBlock = web3.eth.blockNumber - 20;
      toBlock = 'pending';
    }
    else {
      fromBlock = toBlock = blockNumber;
    }
    var revisionIdBuf = new Buffer(32);
    revisionIdBuf.fill(0);
    revisionIdBuf.writeUInt32BE(revisionId, 28);
    // Search the logs.
    web3.eth.filter({fromBlock: fromBlock, toBlock: toBlock, address: blobStoreAddress, topics: ["0xfd5eeef8919c5473de9558a49bf3a5b19bcf59ec0d36e420586d7c3bbaf17d01", blobId + "000000000000000000000000", "0x" + revisionIdBuf.toString('hex')]}).get(function(error, result) {
      if (error) { callback(error); return; }
      for (var i = 0; i < result.length; i++) {
        var length = parseInt(result[i].data.substr(66, 64), 16);
        callback(null, new Buffer(result[i].data.substr(130, length * 2), 'hex'));
      }
    });
  });
}
<|endoftext|>


<commit_before>calculator = {

	"+" : {eval: function(x,y){return (x+y);}},
	"-" : {eval: function(x,y){return (x-y);}},
	"*" : {eval: function(x,y){return (x*y);}},
	"/" : {eval: function(x,y){return (x/y);}},
};

function getUserInput() {
	var operand1 = parseInt(document.getElementById("operand1").value);
	var operand2 = parseInt(document.getElementById("operand2").value);
	var operator = document.getElementById("operator").value;
	userinput = {"operand1": operand1, "operand2": operand2, "operator": operator};
	return userinput;
}

function calculate(userinput) {
	operator = userinput["operator"];
	result = calculator[operator].eval(userinput["operand1"], userinput["operand2"]);
    return result;
}<commit_msg>removes the calculator dictionary to use the inbuilt eval function in JS<commit_after>
function getUserInput() {
	var operand1 = parseInt(document.getElementById("operand1").value);
	var operand2 = parseInt(document.getElementById("operand2").value);
	var operator = document.getElementById("operator").value;
	userinput = {"operand1": operand1, "operand2": operand2, "operator": operator};
	return userinput;
}

function calculate(userinput) {
	result = eval(userinput["operand1"]+ " " + userinput["operator"] + " " + userinput["operand2"]);
    return result;
}<|endoftext|>


<commit_before>const labs = require('../../../../../../services/labs');
const membersService = require('../../../../../../services/members');
const MEMBER_TAG = '#members';
const PERMIT_CONTENT = false;
const BLOCK_CONTENT = true;

// Checks if request should hide memnbers only content
function hideMembersOnlyContent(attrs, frame) {
    const membersEnabled = labs.isSet('members');
    if (!membersEnabled) {
        return PERMIT_CONTENT;
    }

    const postHasMemberTag = attrs.tags && attrs.tags.find((tag) => {
        return (tag.name === MEMBER_TAG);
    });
    const requestFromMember = frame.original.context.member;
    if (!postHasMemberTag) {
        return PERMIT_CONTENT;
    }
    if (!requestFromMember) {
        return BLOCK_CONTENT;
    }

    const planRequired = membersService.api.paymentConfigured;
    const memberHasPlan = !!(frame.original.context.member.plans || []).length;
    if (!planRequired) {
        return PERMIT_CONTENT;
    }
    if (memberHasPlan) {
        return PERMIT_CONTENT;
    }
    return BLOCK_CONTENT;
}

const forPost = (attrs, frame) => {
    const hideFormatsData = hideMembersOnlyContent(attrs, frame);
    if (hideFormatsData) {
        ['plaintext', 'html'].forEach((field) => {
            attrs[field] = '';
        });
    }
    if (labs.isSet('members')) {
        // CASE: Members always adds tags, remove if the user didn't originally ask for them
        const origQueryOrOptions = frame.original.query || frame.original.options || {};
        const origInclude = origQueryOrOptions.include;

        if (!origInclude || !origInclude.includes('tags')) {
            delete attrs.tags;
        }
    }

    return attrs;
};

module.exports.forPost = forPost;
<commit_msg>Removed serving primary_tag when members is enabled<commit_after>const labs = require('../../../../../../services/labs');
const membersService = require('../../../../../../services/members');
const MEMBER_TAG = '#members';
const PERMIT_CONTENT = false;
const BLOCK_CONTENT = true;

// Checks if request should hide memnbers only content
function hideMembersOnlyContent(attrs, frame) {
    const membersEnabled = labs.isSet('members');
    if (!membersEnabled) {
        return PERMIT_CONTENT;
    }

    const postHasMemberTag = attrs.tags && attrs.tags.find((tag) => {
        return (tag.name === MEMBER_TAG);
    });
    const requestFromMember = frame.original.context.member;
    if (!postHasMemberTag) {
        return PERMIT_CONTENT;
    }
    if (!requestFromMember) {
        return BLOCK_CONTENT;
    }

    const planRequired = membersService.api.paymentConfigured;
    const memberHasPlan = !!(frame.original.context.member.plans || []).length;
    if (!planRequired) {
        return PERMIT_CONTENT;
    }
    if (memberHasPlan) {
        return PERMIT_CONTENT;
    }
    return BLOCK_CONTENT;
}

const forPost = (attrs, frame) => {
    const hideFormatsData = hideMembersOnlyContent(attrs, frame);
    if (hideFormatsData) {
        ['plaintext', 'html'].forEach((field) => {
            attrs[field] = '';
        });
    }
    if (labs.isSet('members')) {
        // CASE: Members always adds tags, remove if the user didn't originally ask for them
        const origQueryOrOptions = frame.original.query || frame.original.options || {};
        const origInclude = origQueryOrOptions.include;

        if (!origInclude || !origInclude.includes('tags')) {
            delete attrs.tags;
            attrs.primary_tag = null;
        }
    }

    return attrs;
};

module.exports.forPost = forPost;
<|endoftext|>


<commit_before>import _ from 'lodash';

export class MetadataReducer {
  reduce(json, state) {
    let data = _.get(json, 'metadata-update', false);
    if (data) {
      this.associations(data, state);
      this.add(data, state);
      this.update(data, state);
      this.remove(data, state);
    }
  }

  associations(json, state) {
    let data = _.get(json, 'associations', false);
    if (data) {
      let metadata = state.associations;
      Object.keys(data).map((channel) => {
        let channelObj = data[channel];
        let app = data[channel]["app-name"];
        if (!metadata[app]) {
          metadata[app] = {};
        }
        metadata[app][channelObj["app-path"]] = channelObj;
      })
      state.associations = metadata;
    }
  }

  add(json, state) {
    let data = _.get(json, 'add', false);
    if (data) {
      let metadata = state.associations;
      let app = data["app-name"];
      if (!metadata[app]) {
        metadata[app] = {};
      }
      metadata[app][data["app-path"]] = data;
      state.associations = metadata;
    }
  }

  update(json, state) {
    let data = _.get(json, 'update-metadata', false);
    if (data) {
      let metadata = state.associations;
      let app = data["app-name"];
      metadata[app][data["app-path"]] = data;
      state.associations = metadata;
    }
  }

  remove(json, state) {
    let data = _.get(json, 'remove', false);
    if (data) {
      let metadata = state.associations;
      let app = data["app-name"];
      if (!metadata[app]) {
        return false;
      }
      delete metadata[app][data["app-path"]];
      state.associations = metadata;
    }
  }
}<commit_msg>link: safety check in metadata reducer<commit_after>import _ from 'lodash';

export class MetadataReducer {
  reduce(json, state) {
    let data = _.get(json, 'metadata-update', false);
    if (data) {
      this.associations(data, state);
      this.add(data, state);
      this.update(data, state);
      this.remove(data, state);
    }
  }

  associations(json, state) {
    let data = _.get(json, 'associations', false);
    if (data) {
      let metadata = state.associations;
      Object.keys(data).map((channel) => {
        let channelObj = data[channel];
        let app = data[channel]["app-name"];
        if (!(app in metadata)) {
          metadata[app] = {};
        }
        metadata[app][channelObj["app-path"]] = channelObj;
      })
      state.associations = metadata;
    }
  }

  add(json, state) {
    let data = _.get(json, 'add', false);
    if (data) {
      let metadata = state.associations;
      let app = data["app-name"];
      if (!(app in metadata)) {
        metadata[app] = {};
      }
      metadata[app][data["app-path"]] = data;
      state.associations = metadata;
    }
  }

  update(json, state) {
    let data = _.get(json, 'update-metadata', false);
    if (data) {
      let metadata = state.associations;
      let app = data["app-name"];
      metadata[app][data["app-path"]] = data;
      state.associations = metadata;
    }
  }

  remove(json, state) {
    let data = _.get(json, 'remove', false);
    if (data) {
      let metadata = state.associations;
      let app = data["app-name"];
      if (!(app in metadata)) {
        return false;
      }
      delete metadata[app][data["app-path"]];
      state.associations = metadata;
    }
  }
}<|endoftext|>


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

var fs = require('fs');
var path = require('path');
var argv = process.argv;
var api = {
    '.s3': require('../api-s3'),
    '.mbtiles': require('../api-mbtiles')
};
var Carmen = require('../index.js');
var Queue = require('../queue');
var f = argv[2];

if (!f) {
    console.warn('Usage: carmen-index.js <file>');
    process.exit(1);
}
if (!fs.existsSync(f)) {
    console.warn('File %s does not exist.', f);
    process.exit(1);
}
if (!api[path.extname(f)]) {
    console.warn('File %s format not recognized.', f);
    process.exit(1);
}

console.log('Indexing %s ...', f);

var from = new api[path.extname(f)](f, function() {});
var carmen = new Carmen({ from: from });

carmen._open(function(err) {
    if (err) throw err;
    from.startWriting(function(err) {
        if (err) throw err;
        var index = function(pointer) {
            from.indexable(pointer, function(err, docs, pointer) {
                if (err) throw err;
                if (!docs.length) return from.stopWriting(function(err) {
                    if (err) throw err;
                    console.log('Done.');
                });
                var start = +new Date;
                carmen.index(from, docs, function(err) {
                    if (err) throw err;
                    console.log('Indexed %s docs @ %s/s', docs.length, Math.floor(docs.length * 1000 / (+new Date - start)));
                    index(pointer);
                });
            });
        };
        index();
    });
});

<commit_msg>ENV var for skipping grid indexing.<commit_after>#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var argv = process.argv;
var api = {
    '.s3': require('../api-s3'),
    '.mbtiles': require('../api-mbtiles')
};
var Carmen = require('../index.js');
var Queue = require('../queue');
var f = argv[2];

if (!f) {
    console.warn('Usage: carmen-index.js <file>');
    process.exit(1);
}
if (!fs.existsSync(f)) {
    console.warn('File %s does not exist.', f);
    process.exit(1);
}
if (!api[path.extname(f)]) {
    console.warn('File %s format not recognized.', f);
    process.exit(1);
}

var nogrids = ('NOGRIDS' in process.env);
if (nogrids) console.log('Indexing without grids.');

console.log('Indexing %s ...', f);

var from = new api[path.extname(f)](f, function() {});
var carmen = new Carmen({ from: from });

carmen._open(function(err) {
    if (err) throw err;
    from.startWriting(function(err) {
        if (err) throw err;
        var index = function(pointer) {
            from.indexable(pointer, function(err, docs, pointer) {
                if (err) throw err;
                if (!docs.length) return from.stopWriting(function(err) {
                    if (err) throw err;
                    console.log('Done.');
                });
                var start = +new Date;
                carmen.index(from, docs, function(err) {
                    if (err) throw err;
                    console.log('Indexed %s docs @ %s/s', docs.length, Math.floor(docs.length * 1000 / (+new Date - start)));
                    index(pointer);
                });
            });
        };
        index({nogrids:nogrids});
    });
});

<|endoftext|>


<commit_before>'use strict';

const AddonTestApp = require('ember-cli-addon-tests').AddonTestApp;
const RSVP = require('rsvp');
const debug = require('./debug');

const defaultPort = 49741;

const emberCliFastbootVersion = '^1.0.0-beta.15';

class AppManager {
  constructor() {
    this.apps = [];
  }

  start(appName, options) {
    let app = this.getApp(appName);
    if (app) {
      debug(`Existing FastBoot test app "${appName}"`);
      return RSVP.resolve(app);
    }

    let port = defaultPort + this.apps.length;
    app = new AddonTestApp();

    debug(`Creating FastBoot test app "${appName}"`);
    return app.create(appName, {
      emberVersion: options.emberVersion,
      fixturesPath: options.fixturesPath
    })
      .then(function() {
        let installPackages = typeof options.installPackages === 'object' ? options.installPackages : {};
        let packages = Object.assign({
          'ember-cli-fastboot': emberCliFastbootVersion
        }, installPackages);

        app.editPackageJSON(function(pkg) {
          for (let pkgName in packages) {
            debug(`Added ${pkgName} to FastBoot test app "${appName}"`);
            pkg['devDependencies'][pkgName] = packages[pkgName];
          }
        });
        return app.run('npm', 'install')
          .then(() => {
            // run default blueprints of installed packages
            return RSVP.all(Object.keys(packages).map((pkgName) => app.runEmberCommand('generate', pkgName)))
              .catch(() => {});
          });
      })
      .then(function() {
        debug(`Starting FastBoot test app "${appName}" at port ${port}`);
        return app.startServer({
          command: 'fastboot',
          port
        });
      })
      .then(() => {
        let appInstance = {
          appName,
          app,
          port
        };
        this.apps.push(appInstance);
        return appInstance;
      });
  }

  stop(app) {
    let index = this.apps.indexOf(item);
    if (index === -1) {
      throw new Error('App not found');
    }
    debug(`Stopping FastBoot test app "${app.appName}"`);

    this.apps.splice(index, 1);
    app.app.stopServer();
  }

  stopAll() {
    debug('Stopping all FastBoot apps');

    this.apps.forEach((app) => {
      app.app.stopServer();
    });
    this.apps = [];
  }

  getApp(appName) {
    return this.apps.find((app) => app.appName === appName);
  }

}

module.exports = new AppManager();<commit_msg>Workaround for ember-cki-fastboot bug<commit_after>'use strict';

const AddonTestApp = require('ember-cli-addon-tests').AddonTestApp;
const RSVP = require('rsvp');
const debug = require('./debug');

const defaultPort = 49741;

const emberCliFastbootVersion = '^1.0.0-beta.15';

class AppManager {
  constructor() {
    this.apps = [];
  }

  start(appName, options) {
    let app = this.getApp(appName);
    if (app) {
      debug(`Existing FastBoot test app "${appName}"`);
      return RSVP.resolve(app);
    }

    let port = defaultPort + this.apps.length;
    app = new AddonTestApp();

    debug(`Creating FastBoot test app "${appName}"`);
    return app.create(appName, {
      emberVersion: options.emberVersion,
      fixturesPath: options.fixturesPath
    })
      .then(function() {
        let installPackages = typeof options.installPackages === 'object' ? options.installPackages : {};
        let packages = Object.assign({
          'ember-cli-fastboot': emberCliFastbootVersion
        }, installPackages);

        app.editPackageJSON(function(pkg) {
          for (let pkgName in packages) {
            debug(`Added ${pkgName} to FastBoot test app "${appName}"`);
            pkg['devDependencies'][pkgName] = packages[pkgName];
          }
        });
        return app.run('npm', 'install')
          .then(() => {
            // run default blueprints of installed packages
            return RSVP.all(Object.keys(packages).map((pkgName) => app.runEmberCommand('generate', pkgName)))
              .catch(() => {});
          });
      })
      // Run build because of https://github.com/tomdale/ember-cli-addon-tests/issues/49
      .then(() => app.runEmberCommand('build'))
      .then(function() {
        debug(`Starting FastBoot test app "${appName}" at port ${port}`);
        return app.startServer({
          command: 'fastboot',
          port
        });
      })
      .then(() => {
        let appInstance = {
          appName,
          app,
          port
        };
        this.apps.push(appInstance);
        return appInstance;
      });
  }

  stop(app) {
    let index = this.apps.indexOf(item);
    if (index === -1) {
      throw new Error('App not found');
    }
    debug(`Stopping FastBoot test app "${app.appName}"`);

    this.apps.splice(index, 1);
    app.app.stopServer();
  }

  stopAll() {
    debug('Stopping all FastBoot apps');

    this.apps.forEach((app) => {
      app.app.stopServer();
    });
    this.apps = [];
  }

  getApp(appName) {
    return this.apps.find((app) => app.appName === appName);
  }

}

module.exports = new AppManager();<|endoftext|>


<commit_before>/* eslint-env node, jasmine */

'use strict'

var call = require('..')

describe('argument validation', function() {
  it('throws if provided no arguments', function() {
    expect(function() {
      call()
    }).toThrow()
  })
  it('throws if provided one argument', function() {
    expect(function() {
      call('foo')
    }).toThrow()
  })
  it('throws if the first argument is not a function', function() {
    expect(function() {
      call('foo', 2)
    }).toThrow()
  })
  it('throws if the second argument is not a number', function() {
    expect(function() {
      call(function() {}, 'foo')
    }).toThrow()
  })
  it('throws if the second argument is less than zero', function() {
    expect(function() {
      call(function() {}, -1)
    }).toThrow()
  })
})

describe('calling n times', function() {
  var spy = jasmine.createSpy('spy')

  afterEach(function() {
    spy.calls.reset()
  })

  it('can call 0 times', function() {
    call(spy, 0)
    expect(spy).not.toHaveBeenCalled()
  })

  it('can call 1 time', function() {
    call(spy, 1)
    expect(spy.calls.count()).toEqual(1)
  })

  it('can call 2 and more times', function() {
    for (var n = 5; n !== 0; n--) {
      call(spy, n)
      expect(spy.calls.count()).toEqual(n)
      spy.calls.reset()
    }
  })
})

describe('returns return values', function() {
  it('returns return values in order', function() {
    var n = 100
    var i = 0
    var returns = call(
      function() {
        var returnVal = i.toString()
        i++
        return returnVal
      },
      n
    )
    // Reusing `i`
    for (i = 0; i < n; i++) {
      expect(returns[i]).toEqual(i.toString())
    }
  })
})
<commit_msg>Spec for calling a third argument callback<commit_after>/* eslint-env node, jasmine */

'use strict'

var call = require('..')

describe('argument validation', function() {
  it('throws if provided no arguments', function() {
    expect(function() {
      call()
    }).toThrow()
  })
  it('throws if provided one argument', function() {
    expect(function() {
      call('foo')
    }).toThrow()
  })
  it('throws if the first argument is not a function', function() {
    expect(function() {
      call('foo', 2)
    }).toThrow()
  })
  it('throws if the second argument is not a number', function() {
    expect(function() {
      call(function() {}, 'foo')
    }).toThrow()
  })
  it('throws if the second argument is less than zero', function() {
    expect(function() {
      call(function() {}, -1)
    }).toThrow()
  })
})

describe('the calls', function() {
  var spy = jasmine.createSpy('spy')

  afterEach(function() {
    spy.calls.reset()
  })

  it('can get called 0 times', function() {
    call(spy, 0)
    expect(spy).not.toHaveBeenCalled()
  })

  it('can called 1 time', function() {
    call(spy, 1)
    expect(spy.calls.count()).toEqual(1)
  })

  it('can get called 2 and more times', function() {
    for (var n = 5; n !== 0; n--) {
      call(spy, n)
      expect(spy.calls.count()).toEqual(n)
      spy.calls.reset()
    }
  })
})

describe('the return value', function() {
  it('is in order', function() {
    var n = 100
    var i = 0
    var returns = call(
      function() {
        var returnVal = i.toString()
        i++
        return returnVal
      },
      n
    )
    // Reusing `i`
    for (i = 0; i < n; i++) {
      expect(returns[i]).toEqual(i.toString())
    }
  })
})

describe('the callback function', function() {
  it('is called after all calls', function() {
    var cbCalled = false
    var callback = function() {
      cbCalled = true
    }
    var func = function() {
      cbCalled = false
    }
    call(func, 2, callback)
    expect(cbCalled).toEqual(true)
  })
})
<|endoftext|>


<commit_before>// auto-expand.js

(function($){

$(window).bind('resize', fillOutTextArea);
$(document).bind('change', findAutoExpandTextArea);
$(document).bind('keypress', findAutoExpandTextArea);
$(document).bind('input', findAutoExpandTextArea);
$(document).bind('paste', findAutoExpandTextArea);
$(document).bind("DOMNodeInserted", findAutoExpandTextArea);
$(document).ready(function(){setTimeout(fillOutTextArea, 0)});
$(window).load(function(event){
    fillOutTextArea();
});

function fillOutTextArea(){
    findAutoExpandTextAreaIn(document);
}

function findAutoExpandTextArea(event) {
    findAutoExpandTextAreaIn(event.target);
}

function findAutoExpandTextAreaIn(target) {
    var areas = $(".auto-expand", target);
    if ($(target).is(".auto-expand")) {
        areas = areas.add(target);
    }
    for (var i = 0; i < areas.length; i++) {
        expand(areas[i]);
    }
    $(areas).unbind("paste", targetAutoExpandTextArea);
    $(areas).bind("paste", targetAutoExpandTextArea);
}

function targetAutoExpandTextArea(event) {
    if (event.target && event.target.className.match(/\bauto-expand\b/)) {
        setTimeout(function(){
            expand(event.target);
        }, 0);
    }
}

function expand(area) {
    var contentWidth = getAvailableWidth(area);
    var contentHeight = getAvailableHeight(area);
    if ($(area).is(":input")) {
        expandTextArea(area, contentWidth, contentHeight);
    }
}

function expandTextArea(area, contentWidth, innerHeight) {
    var width = area.cols || area.size;
    var height = area.rows;
    var maxCols = Math.min(Math.floor(contentWidth / area.offsetWidth * width - 3), Math.floor(contentWidth / 8 - 3));
    var maxRows = Math.floor(innerHeight / area.offsetHeight * height - 3);
    if (!maxCols || maxCols < 20) {
        maxCols = 96;
    }
    if (!maxRows || maxRows < 3) {
        maxRows = 43;
    }
    var lines = area.value.split("\n");
    var cols = 20;
    var rows = Math.max(1, lines.length);
    for (var i = 0; i < lines.length; i++) {
        var len = lines[i].replace(/\t/g, "        ").length;
        if (cols < len + 1) {
            cols = len + 1;
        }
        rows += Math.floor(len / maxCols);
    }
    if (area.type == "textarea") {
        area.cols = Math.min(maxCols, cols + 1);
        area.rows = Math.min(maxRows, rows + 1);
    } else {
        area.size = Math.min(maxCols, cols + 1);
    }
}

function getAvailableHeight(area) {
    var innerHeight = $(area).height();
    var clientHeight = window.innerHeight || document.documentElement.clientHeight;

    var body = bottom($(area).parents('body>*')) - innerHeight;
    if (body > 0 && body <= clientHeight / 3)
        return clientHeight - body;
    var content = bottom($(area).parents('#content')) - innerHeight;
    if (content > 0 && content <= clientHeight / 3)
        return clientHeight - content;
    var form = bottom($(area).parents('form')) - innerHeight;
    if (form > 0 && form <= clientHeight / 3)
        return clientHeight - form;
    var formHeight = $(area).parents('form').outerHeight(true) - innerHeight;
    if (formHeight > 0 && formHeight <= clientHeight / 3)
        return clientHeight - formHeight;
    return clientHeight;
}

function bottom(element) {
    return $(element).offset().top + $(element).outerHeight(true);
}

function getAvailableWidth(area) {
    var parent = getParentBlock(area);
    var margin = $(area).outerWidth(true) - $(area).width();
    var breakFlag = false;
    $(area).parents().each(function(){
        if (this == parent) {
            breakFlag = true;
        } else if (!breakFlag) {
            margin += $(this).outerWidth(true) - $(this).width();
        }
    });
    var asideLeft = getAsideLeft(area);
    if ($(parent).offset().left + $(parent).outerWidth(true) <= asideLeft)
        return $(parent).width() - margin;
    return $(parent).width() - margin - $(parent).offset().left - $(parent).outerWidth(true) + asideLeft;
}

function getParentBlock(area) {
    var parent = null;
    var parents = $(area).parents();
    for (var i=0;i<parents.length;i++) {
        parent = parents[i];
        var floatStyle = $(parents[i]).css('float');
        if (floatStyle && floatStyle != 'none')
            break;
        if ($(parents[i]).css('display') == 'block')
            break;
    }
    if (parent)
        return parent;
    return $('body')[0];
}

function getAsideLeft(area) {
    var clientWidth = document.documentElement.clientWidth;
    var asideLeft = clientWidth;
    var areaTop = $(area).offset().top;
    $("#sidebar,.aside:visible,aside:visible").filter(function(){
        var top = $(this).offset().top;
        return areaTop < top + $(this).outerHeight(true) && areaTop + $(area).outerHeight(true) > top;
    }).each(function() {
        var left = $(this).offset().left;
        left -= parsePixel($(this).css("margin-left"));
        if (left < asideLeft) {
            asideLeft = left;
        }
    });
    return asideLeft;
}

function parsePixel(str) {
    if (!str)
        return 0;
    if (str.indexOf('px') > 0)
        return parseInt(str.substring(0, str.indexOf('px')));
    if (str == "thin")
        return 1;
    if (str == "medium")
        return 3;
    if (str == "thick")
        return 5;
    return 0;
}

$(window).bind('resize', fillOutFlex);
$(window).load(function(event){
    $('iframe').load(fillOutFlex);
    $('img').load(fillOutFlex);
    fillOutFlex();
});

function fillOutFlex(){
    var areas = $(".flex");
    areas.each(function() {
        flex(this);
    });
}

function flex(area) {
    if ($(area).is(":input")) {
        var contentWidth = getAvailableWidth(area);
        var contentHeight = getAvailableHeight(area);
        flexInput(area, contentWidth, contentHeight);
    } else if (area.nodeName.toLowerCase() == "iframe") {
        var contentWidth = getAvailableWidth(area);
        var contentHeight = getAvailableHeight(area);
        flexIframe(area, contentWidth, contentHeight);
    } else {
        var contentWidth = getAvailableWidth(area);
        var contentHeight = getAvailableHeight(area);
        flexBlock(area, contentWidth, contentHeight);
    }
}

function flexInput(area, contentWidth, innerHeight) {
    $(area).css('width', contentWidth);
    $(area).css('height', innerHeight);
    if (area.scrollHeight > innerHeight && window.parent != window) {
        var clientHeight = window.innerHeight || document.documentElement.clientHeight;
        var height = clientHeight + area.scrollHeight - innerHeight;
        parent.postMessage('PUT height\n\n' + height, '*');
    } else if (area.scrollWidth > contentWidth) {
        var clientWidth = document.documentElement.clientWidth;
        var width = clientWidth + area.scrollWidth - contentWidth;
        parent.postMessage('PUT width\n\n' + width, '*');
    }
}

function flexIframe(iframe, contentWidth, innerHeight) {
    $(iframe).css('width', contentWidth);
    $(iframe).css('height', innerHeight);
}

function flexBlock(area, contentWidth, innerHeight) {
    $(area).css('width', contentWidth);
    $(area).css('max-height', innerHeight);
    $(area).css('overflow', 'auto');
    if (area.scrollHeight > innerHeight && window.parent != window) {
        var clientHeight = window.innerHeight || document.documentElement.clientHeight;
        var height = clientHeight + area.scrollHeight - innerHeight;
        parent.postMessage('PUT height\n\n' + height, '*');
    } else if (area.scrollWidth > contentWidth) {
        var clientWidth = document.documentElement.clientWidth;
        var width = clientWidth + area.scrollWidth - contentWidth;
        parent.postMessage('PUT width\n\n' + width, '*');
    }
}

if (window.parent != window) {
    $(window).bind('load', function() {
        setTimeout(function() {
            var innerHeight = window.innerHeight || document.documentElement.clientHeight;
            if (innerHeight < document.height) {
                parent.postMessage('PUT height\n\n' + document.height, '*');
            } else {
                var maxHeight = innerHeight;
                $('.flex').each(function() {
                    if (this.scrollHeight > this.clientHeight) {
                        var height = document.documentElement.scrollHeight + this.scrollHeight - this.clientHeight;
                        if (height > maxHeight) {
                            maxHeight = height;
                        }
                    }
                });
                if (maxHeight > innerHeight) {
                    parent.postMessage('PUT height\n\n' + maxHeight, '*');
                }
            }
            var clientWidth = document.documentElement.clientWidth;
            if (clientWidth < document.documentElement.scrollWidth) {
                parent.postMessage('PUT width\n\n' + document.documentElement.scrollWidth, '*');
            } else {
                var maxWidth = clientWidth;
                $('.flex').each(function() {
                    if (this.scrollWidth > this.clientWidth) {
                        var width = clientWidth + this.scrollWidth - this.clientWidth;
                        if (width > maxWidth) {
                            maxWidth = width;
                        }
                    }
                });
                if (maxWidth > clientWidth) {
                    parent.postMessage('PUT width\n\n' + maxWidth, '*');
                }
            }
        }, 0);
    });
    $(window).bind('message', function(event) {
        var source = event.originalEvent.source;
        var data = event.originalEvent.data;
        if (data.indexOf('PUT height\n\n') == 0) {
            $('iframe.flex').each(function() {
                if (this.contentWindow == source) {
                    var innerHeight = window.innerHeight || document.documentElement.clientHeight;
                    var height = parseInt(data.substring(data.indexOf('\n\n') + 2));
                    height += innerHeight - $(this).height();
                    parent.postMessage('PUT height\n\n' + height, '*');
                    this.contentWindow.postMessage('OK\n\nPUT height', '*');
                }
            });
        } else if (data.indexOf('PUT width\n\n') == 0) {
            $('iframe.flex').each(function() {
                if (this.contentWindow == source) {
                    var width = parseInt(data.substring(data.indexOf('\n\n') + 2));
                    width += document.documentElement.scrollWidth - $(this).width();
                    parent.postMessage('PUT width\n\n' + width, '*');
                    this.contentWindow.postMessage('OK\n\nPUT width', '*');
                }
            });
        }
    });
}

})(jQuery);

<commit_msg>Fix js errors in dialogue pages<commit_after>// auto-expand.js

(function($){

$(window).bind('resize', fillOutTextArea);
$(document).bind('change', findAutoExpandTextArea);
$(document).bind('keypress', findAutoExpandTextArea);
$(document).bind('input', findAutoExpandTextArea);
$(document).bind('paste', findAutoExpandTextArea);
$(document).bind("DOMNodeInserted", findAutoExpandTextArea);
$(document).ready(function(){setTimeout(fillOutTextArea, 0)});
$(window).load(function(event){
    fillOutTextArea();
});

function fillOutTextArea(){
    findAutoExpandTextAreaIn(document);
}

function findAutoExpandTextArea(event) {
    findAutoExpandTextAreaIn(event.target);
}

function findAutoExpandTextAreaIn(target) {
    var areas = $(".auto-expand", target);
    if ($(target).is(".auto-expand")) {
        areas = areas.add(target);
    }
    for (var i = 0; i < areas.length; i++) {
        expand(areas[i]);
    }
    $(areas).unbind("paste", targetAutoExpandTextArea);
    $(areas).bind("paste", targetAutoExpandTextArea);
}

function targetAutoExpandTextArea(event) {
    if (event.target && event.target.className.match(/\bauto-expand\b/)) {
        setTimeout(function(){
            expand(event.target);
        }, 0);
    }
}

function expand(area) {
    var contentWidth = getAvailableWidth(area);
    var contentHeight = getAvailableHeight(area);
    if ($(area).is(":input")) {
        expandTextArea(area, contentWidth, contentHeight);
    }
}

function expandTextArea(area, contentWidth, innerHeight) {
    var width = area.cols || area.size;
    var height = area.rows;
    var maxCols = Math.min(Math.floor(contentWidth / area.offsetWidth * width - 3), Math.floor(contentWidth / 8 - 3));
    var maxRows = Math.floor(innerHeight / area.offsetHeight * height - 3);
    if (!maxCols || maxCols < 20) {
        maxCols = 96;
    }
    if (!maxRows || maxRows < 3) {
        maxRows = 43;
    }
    var lines = area.value.split("\n");
    var cols = 20;
    var rows = Math.max(1, lines.length);
    for (var i = 0; i < lines.length; i++) {
        var len = lines[i].replace(/\t/g, "        ").length;
        if (cols < len + 1) {
            cols = len + 1;
        }
        rows += Math.floor(len / maxCols);
    }
    if (area.type == "textarea") {
        area.cols = Math.min(maxCols, cols + 1);
        area.rows = Math.min(maxRows, rows + 1);
    } else {
        area.size = Math.min(maxCols, cols + 1);
    }
}

function getAvailableHeight(area) {
    var innerHeight = $(area).height();
    var clientHeight = window.innerHeight || document.documentElement.clientHeight;

    var body = bottom($(area).parents('body>*')) - innerHeight;
    if (body > 0 && body <= clientHeight / 3)
        return clientHeight - body;
    var content = bottom($(area).parents('#content')) - innerHeight;
    if (content > 0 && content <= clientHeight / 3)
        return clientHeight - content;
    var form = bottom($(area).parents('form')) - innerHeight;
    if (form > 0 && form <= clientHeight / 3)
        return clientHeight - form;
    var formHeight = $(area).parents('form').outerHeight(true) - innerHeight;
    if (formHeight > 0 && formHeight <= clientHeight / 3)
        return clientHeight - formHeight;
    return clientHeight;
}

function bottom(element) {
    if ($(element).length)
        return $(element).offset().top + $(element).outerHeight(true);
    return null;
}

function getAvailableWidth(area) {
    var parent = getParentBlock(area);
    var margin = $(area).outerWidth(true) - $(area).width();
    var breakFlag = false;
    $(area).parents().each(function(){
        if (this == parent) {
            breakFlag = true;
        } else if (!breakFlag) {
            margin += $(this).outerWidth(true) - $(this).width();
        }
    });
    var asideLeft = getAsideLeft(area);
    if ($(parent).offset().left + $(parent).outerWidth(true) <= asideLeft)
        return $(parent).width() - margin;
    return $(parent).width() - margin - $(parent).offset().left - $(parent).outerWidth(true) + asideLeft;
}

function getParentBlock(area) {
    var parent = null;
    var parents = $(area).parents();
    for (var i=0;i<parents.length;i++) {
        parent = parents[i];
        var floatStyle = $(parents[i]).css('float');
        if (floatStyle && floatStyle != 'none')
            break;
        if ($(parents[i]).css('display') == 'block')
            break;
    }
    if (parent)
        return parent;
    return $('body')[0];
}

function getAsideLeft(area) {
    var clientWidth = document.documentElement.clientWidth;
    var asideLeft = clientWidth;
    var areaTop = $(area).offset().top;
    $("#sidebar,.aside:visible,aside:visible").filter(function(){
        var top = $(this).offset().top;
        return areaTop < top + $(this).outerHeight(true) && areaTop + $(area).outerHeight(true) > top;
    }).each(function() {
        var left = $(this).offset().left;
        left -= parsePixel($(this).css("margin-left"));
        if (left < asideLeft) {
            asideLeft = left;
        }
    });
    return asideLeft;
}

function parsePixel(str) {
    if (!str)
        return 0;
    if (str.indexOf('px') > 0)
        return parseInt(str.substring(0, str.indexOf('px')));
    if (str == "thin")
        return 1;
    if (str == "medium")
        return 3;
    if (str == "thick")
        return 5;
    return 0;
}

$(window).bind('resize', fillOutFlex);
$(window).load(function(event){
    $('iframe').load(fillOutFlex);
    $('img').load(fillOutFlex);
    fillOutFlex();
});

function fillOutFlex(){
    var areas = $(".flex");
    areas.each(function() {
        flex(this);
    });
}

function flex(area) {
    if ($(area).is(":input")) {
        var contentWidth = getAvailableWidth(area);
        var contentHeight = getAvailableHeight(area);
        flexInput(area, contentWidth, contentHeight);
    } else if (area.nodeName.toLowerCase() == "iframe") {
        var contentWidth = getAvailableWidth(area);
        var contentHeight = getAvailableHeight(area);
        flexIframe(area, contentWidth, contentHeight);
    } else {
        var contentWidth = getAvailableWidth(area);
        var contentHeight = getAvailableHeight(area);
        flexBlock(area, contentWidth, contentHeight);
    }
}

function flexInput(area, contentWidth, innerHeight) {
    $(area).css('width', contentWidth);
    $(area).css('height', innerHeight);
    if (area.scrollHeight > innerHeight && window.parent != window) {
        var clientHeight = window.innerHeight || document.documentElement.clientHeight;
        var height = clientHeight + area.scrollHeight - innerHeight;
        parent.postMessage('PUT height\n\n' + height, '*');
    } else if (area.scrollWidth > contentWidth) {
        var clientWidth = document.documentElement.clientWidth;
        var width = clientWidth + area.scrollWidth - contentWidth;
        parent.postMessage('PUT width\n\n' + width, '*');
    }
}

function flexIframe(iframe, contentWidth, innerHeight) {
    $(iframe).css('width', contentWidth);
    $(iframe).css('height', innerHeight);
}

function flexBlock(area, contentWidth, innerHeight) {
    $(area).css('width', contentWidth);
    $(area).css('max-height', innerHeight);
    $(area).css('overflow', 'auto');
    if (area.scrollHeight > innerHeight && window.parent != window) {
        var clientHeight = window.innerHeight || document.documentElement.clientHeight;
        var height = clientHeight + area.scrollHeight - innerHeight;
        parent.postMessage('PUT height\n\n' + height, '*');
    } else if (area.scrollWidth > contentWidth) {
        var clientWidth = document.documentElement.clientWidth;
        var width = clientWidth + area.scrollWidth - contentWidth;
        parent.postMessage('PUT width\n\n' + width, '*');
    }
}

if (window.parent != window) {
    $(window).bind('load', function() {
        setTimeout(function() {
            var innerHeight = window.innerHeight || document.documentElement.clientHeight;
            if (innerHeight < document.height) {
                parent.postMessage('PUT height\n\n' + document.height, '*');
            } else {
                var maxHeight = innerHeight;
                $('.flex').each(function() {
                    if (this.scrollHeight > this.clientHeight) {
                        var height = document.documentElement.scrollHeight + this.scrollHeight - this.clientHeight;
                        if (height > maxHeight) {
                            maxHeight = height;
                        }
                    }
                });
                if (maxHeight > innerHeight) {
                    parent.postMessage('PUT height\n\n' + maxHeight, '*');
                }
            }
            var clientWidth = document.documentElement.clientWidth;
            if (clientWidth < document.documentElement.scrollWidth) {
                parent.postMessage('PUT width\n\n' + document.documentElement.scrollWidth, '*');
            } else {
                var maxWidth = clientWidth;
                $('.flex').each(function() {
                    if (this.scrollWidth > this.clientWidth) {
                        var width = clientWidth + this.scrollWidth - this.clientWidth;
                        if (width > maxWidth) {
                            maxWidth = width;
                        }
                    }
                });
                if (maxWidth > clientWidth) {
                    parent.postMessage('PUT width\n\n' + maxWidth, '*');
                }
            }
        }, 0);
    });
    $(window).bind('message', function(event) {
        var source = event.originalEvent.source;
        var data = event.originalEvent.data;
        if (data.indexOf('PUT height\n\n') == 0) {
            $('iframe.flex').each(function() {
                if (this.contentWindow == source) {
                    var innerHeight = window.innerHeight || document.documentElement.clientHeight;
                    var height = parseInt(data.substring(data.indexOf('\n\n') + 2));
                    height += innerHeight - $(this).height();
                    parent.postMessage('PUT height\n\n' + height, '*');
                    this.contentWindow.postMessage('OK\n\nPUT height', '*');
                }
            });
        } else if (data.indexOf('PUT width\n\n') == 0) {
            $('iframe.flex').each(function() {
                if (this.contentWindow == source) {
                    var width = parseInt(data.substring(data.indexOf('\n\n') + 2));
                    width += document.documentElement.scrollWidth - $(this).width();
                    parent.postMessage('PUT width\n\n' + width, '*');
                    this.contentWindow.postMessage('OK\n\nPUT width', '*');
                }
            });
        }
    });
}

})(jQuery);

<|endoftext|>