text:
package com.taobao.weex.ui.view.refresh.core;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.view.NestedScrollingParent;
import android.support.v4.view.NestedScrollingParentHelper;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.FrameLayout;

public class WXSwipeLayout extends FrameLayout implements NestedScrollingParent {

  private NestedScrollingParentHelper parentHelper;
  private WXOnRefreshListener onRefreshListener;
  private WXOnLoadingListener onLoadingListener;

  /**
   * On refresh Callback, call on start refresh
   */
  public interface WXOnRefreshListener {

    void onRefresh();
  }

  /**
   * On loadmore Callback, call on start loadmore
   */
  public interface WXOnLoadingListener {

    void onLoading();
  }

  static class WXRefreshAnimatorListener implements Animator.AnimatorListener {

    @Override
    public void onAnimationStart(Animator animation) {
    }

    @Override
    public void onAnimationEnd(Animator animation) {
    }

    @Override
    public void onAnimationCancel(Animator animation) {
    }

    @Override
    public void onAnimationRepeat(Animator animation) {
    }
  }

  private WXRefreshView headerView;
  private WXRefreshView footerView;
  private View mTargetView;

  private static final int REFRESH_VIEW_HEIGHT = 80;
  private static final int PULL_REFRESH = 0;
  private static final int LOAD_MORE = 1;

  // Enable PullRefresh and Loadmore
  private boolean mPullRefreshEnable = false;
  private boolean mPullLoadEnable = false;

  // Is Refreshing
  volatile private boolean mRefreshing = false;

  // RefreshView Height
  private float loadingViewHeight = 0;

  // RefreshView Over Flow Height
  private float refreshViewFlowHeight = 0;

  // Drag Action
  private int mCurrentAction = -1;
  private boolean isConfirm = false;

  // RefreshView Attrs
  private int mRefreshViewBgColor;
  private int mProgressBgColor;
  private int mProgressColor;

  public WXSwipeLayout(Context context) {
    super(context);
    initAttrs(context, null);
  }

  public WXSwipeLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    initAttrs(context, attrs);
  }

  public WXSwipeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initAttrs(context, attrs);
  }

  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  public WXSwipeLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    initAttrs(context, attrs);
  }

  private void initAttrs(Context context, AttributeSet attrs) {

    if (getChildCount() > 1) {
      throw new RuntimeException("WXSwipeLayout should not have more than one child");
    }

    parentHelper = new NestedScrollingParentHelper(this);

    loadingViewHeight = dipToPx(context, REFRESH_VIEW_HEIGHT);
    refreshViewFlowHeight = loadingViewHeight * (float)1.5;

    if (isInEditMode() && attrs == null) {
      return;
    }

    mRefreshViewBgColor = Color.TRANSPARENT;
    mProgressBgColor = Color.TRANSPARENT;
    mProgressColor = Color.RED;
  }

  @Override
  protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    mTargetView = getChildAt(0);
    setRefreshView();
  }

  /**
   * Init refresh view or loading view
   */
  private void setRefreshView() {
    // SetUp HeaderView
    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 0);
    headerView = new WXRefreshView(getContext());
    headerView.setStartEndTrim(0, 0.75f);
    headerView.setBackgroundColor(mRefreshViewBgColor);
    headerView.setProgressBgColor(mProgressBgColor);
    headerView.setProgressColor(mProgressColor);
    addView(headerView, lp);

    // SetUp FooterView
    lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 0);
    lp.gravity = Gravity.BOTTOM;
    footerView = new WXRefreshView(getContext());
    footerView.setStartEndTrim(0.5f, 1.25f);
    footerView.setBackgroundColor(mRefreshViewBgColor);
    footerView.setProgressBgColor(mProgressBgColor);
    footerView.setProgressColor(mProgressColor);
    addView(footerView, lp);
  }

  @Override
  public boolean onInterceptTouchEvent(MotionEvent ev) {
    if ((!mPullRefreshEnable && !mPullLoadEnable)) {
      return false;
    }
    if (mRefreshing) {
      return true;
    }
    return super.onInterceptTouchEvent(ev);
  }

  /*********************************** NestedScrollParent *************************************/

  @Override
  public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
    return true;
  }

  @Override
  public void onNestedScrollAccepted(View child, View target, int axes) {
    parentHelper.onNestedScrollAccepted(child, target, axes);
  }

  /**
   * Callback on TouchEvent.ACTION_CANCLE or TouchEvent.ACTION_UP
   * handler : refresh or loading
   * @param child : child view of SwipeLayout,RecyclerView or Scroller
   */
  @Override
  public void onStopNestedScroll(View child) {
    parentHelper.onStopNestedScroll(child);
    handlerAction();
  }

  /**
   * With child view to processing move events
   * @param target the child view
   * @param dx move x
   * @param dy move y
   * @param consumed parent consumed move distance
   */
  @Override
  public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {

    if ((!mPullRefreshEnable && !mPullLoadEnable)) {
      return;
    }

    // Prevent Layout shake
    if (Math.abs(dy) > 200) {
      return;
    }

    if (!isConfirm) {
      if (dy < 0 && !canChildScrollUp()) {
        mCurrentAction = PULL_REFRESH;
        isConfirm = true;
      } else if (dy > 0 && !canChildScrollDown()) {
        mCurrentAction = LOAD_MORE;
        isConfirm = true;
      }
    }

    if (moveSpinner(-dy)) {
      consumed[1] += dy;
    }
  }

  @Override
  public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {

  }

  @Override
  public int getNestedScrollAxes() {
    return parentHelper.getNestedScrollAxes();
  }

  @Override
  public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
    return false;
  }

  @Override
  public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
    return false;
  }

  /**
   * Adjust the refresh or loading view according to the size of the gesture
   *
   * @param distanceY move distance of Y
   */
  private boolean moveSpinner(float distanceY) {

    if (mRefreshing) {
      return false;
    }

    if (!canChildScrollUp() && mPullRefreshEnable && mCurrentAction == PULL_REFRESH) {
      // Pull Refresh
      LayoutParams lp = (LayoutParams) headerView.getLayoutParams();
      lp.height += distanceY;
      if (lp.height < 0) {
        lp.height = 0;
      } else if (lp.height > refreshViewFlowHeight) {
        lp.height = (int) refreshViewFlowHeight;
      }
      if (lp.height == 0) {
        isConfirm = false;
        mCurrentAction = -1;
      }
      headerView.setLayoutParams(lp);
      headerView.setProgressRotation(lp.height / refreshViewFlowHeight);
      moveTargetView(lp.height);
      return true;
    } else if (!canChildScrollDown() && mPullLoadEnable && mCurrentAction == LOAD_MORE) {
      // Load more
      LayoutParams lp = (LayoutParams) footerView.getLayoutParams();
      lp.height -= distanceY;
      if (lp.height < 0) {
        lp.height = 0;
      } else if (lp.height > refreshViewFlowHeight) {
        lp.height = (int) refreshViewFlowHeight;
      }
      if (lp.height == 0) {
        isConfirm = false;
        mCurrentAction = -1;
      }
      footerView.setLayoutParams(lp);
      footerView.setProgressRotation(lp.height / refreshViewFlowHeight);
      moveTargetView(-lp.height);
      return true;
    }
    return false;
  }

  /**
   * Adjust contentView(Scroller or List) at refresh or loading time
   * @param h Height of refresh view or loading view
   */
  private void moveTargetView(float h) {
    mTargetView.setTranslationY(h);
  }

  /**
   * Decide on the action refresh or loadmore
   */
  private void handlerAction() {

    if (isRefreshing()) {
      return;
    }
    isConfirm = false;

    LayoutParams lp;
    if (mPullRefreshEnable && mCurrentAction == PULL_REFRESH) {
      lp = (LayoutParams) headerView.getLayoutParams();
      if (lp.height >= loadingViewHeight) {
        startRefresh(lp.height);
      } else if (lp.height > 0) {
        resetHeaderView(lp.height);
      } else {
        resetRefreshState();
      }
    }

    if (mPullLoadEnable && mCurrentAction == LOAD_MORE) {
      lp = (LayoutParams) footerView.getLayoutParams();
      if (lp.height >= loadingViewHeight) {
        startLoadmore(lp.height);
      } else if (lp.height > 0) {
        resetFootView(lp.height);
      } else {
        resetLoadmoreState();
      }
    }
  }

  /**
   * Start Refresh
   * @param headerViewHeight
   */
  private void startRefresh(int headerViewHeight) {
    mRefreshing = true;
    ValueAnimator animator = ValueAnimator.ofFloat(headerViewHeight, loadingViewHeight);
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
      @Override
      public void onAnimationUpdate(ValueAnimator animation) {
        LayoutParams lp = (LayoutParams) headerView.getLayoutParams();
        lp.height = (int) ((Float) animation.getAnimatedValue()).floatValue();
        headerView.setLayoutParams(lp);
        moveTargetView(lp.height);
      }
    });
    animator.addListener(new WXRefreshAnimatorListener() {
      @Override
      public void onAnimationEnd(Animator animation) {
        headerView.startAnimation();
        //TODO updateLoadText
        if (onRefreshListener != null) {
          onRefreshListener.onRefresh();
        }
      }
    });
    animator.setDuration(300);
    animator.start();
  }

  /**
   * Reset refresh state
   * @param headerViewHeight
   */
  private void resetHeaderView(int headerViewHeight) {
    headerView.stopAnimation();
    headerView.setStartEndTrim(0, 0.75f);
    ValueAnimator animator = ValueAnimator.ofFloat(headerViewHeight, 0);
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
      @Override
      public void onAnimationUpdate(ValueAnimator animation) {
        LayoutParams lp = (LayoutParams) headerView.getLayoutParams();
        lp.height = (int) ((Float) animation.getAnimatedValue()).floatValue();
        headerView.setLayoutParams(lp);
        moveTargetView(lp.height);
      }
    });
    animator.addListener(new WXRefreshAnimatorListener() {
      @Override
      public void onAnimationEnd(Animator animation) {
        resetRefreshState();

      }
    });
    animator.setDuration(300);
    animator.start();
  }

  private void resetRefreshState() {
    mRefreshing = false;
    isConfirm = false;
    mCurrentAction = -1;
    //TODO updateLoadText
  }

  /**
   * Start loadmore
   * @param headerViewHeight
   */
  private void startLoadmore(int headerViewHeight) {
    mRefreshing = true;
    ValueAnimator animator = ValueAnimator.ofFloat(headerViewHeight, loadingViewHeight);
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
      @Override
      public void onAnimationUpdate(ValueAnimator animation) {
        LayoutParams lp = (LayoutParams) footerView.getLayoutParams();
        lp.height = (int) ((Float) animation.getAnimatedValue()).floatValue();
        footerView.setLayoutParams(lp);
        moveTargetView(-lp.height);
      }
    });
    animator.addListener(new WXRefreshAnimatorListener() {
      @Override
      public void onAnimationEnd(Animator animation) {
        footerView.startAnimation();
        //TODO updateLoadText
        if (onLoadingListener != null) {
          onLoadingListener.onLoading();
        }
      }
    });
    animator.setDuration(300);
    animator.start();
  }

  /**
   * Reset loadmore state
   * @param headerViewHeight
   */
  private void resetFootView(int headerViewHeight) {
    footerView.stopAnimation();
    footerView.setStartEndTrim(0.5f, 1.25f);
    ValueAnimator animator = ValueAnimator.ofFloat(headerViewHeight, 0);
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
      @Override
      public void onAnimationUpdate(ValueAnimator animation) {
        LayoutParams lp = (LayoutParams) footerView.getLayoutParams();
        lp.height = (int) ((Float) animation.getAnimatedValue()).floatValue();
        footerView.setLayoutParams(lp);
        moveTargetView(-lp.height);
      }
    });
    animator.addListener(new WXRefreshAnimatorListener() {
      @Override
      public void onAnimationEnd(Animator animation) {
        resetLoadmoreState();

      }
    });
    animator.setDuration(300);
    animator.start();
  }

  private void resetLoadmoreState() {
    mRefreshing = false;
    isConfirm = false;
    mCurrentAction = -1;
    //TODO updateLoadText
  }

  /**
   * Whether child view can scroll up
   * @return
   */
  public boolean canChildScrollUp() {
    if (mTargetView == null) {
      return false;
    }
    if (Build.VERSION.SDK_INT < 14) {
      if (mTargetView instanceof AbsListView) {
        final AbsListView absListView = (AbsListView) mTargetView;
        return absListView.getChildCount() > 0
               && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
                                                                    .getTop() < absListView.getPaddingTop());
      } else {
        return ViewCompat.canScrollVertically(mTargetView, -1) || mTargetView.getScrollY() > 0;
      }
    } else {
      return ViewCompat.canScrollVertically(mTargetView, -1);
    }
  }

  /**
   * Whether child view can scroll down
   * @return
   */
  public boolean canChildScrollDown() {
    if (mTargetView == null) {
      return false;
    }
    if (Build.VERSION.SDK_INT < 14) {
      if (mTargetView instanceof AbsListView) {
        final AbsListView absListView = (AbsListView) mTargetView;
        if (absListView.getChildCount() > 0) {
          int lastChildBottom = absListView.getChildAt(absListView.getChildCount() - 1)
              .getBottom();
          return absListView.getLastVisiblePosition() == absListView.getAdapter().getCount() - 1
                 && lastChildBottom <= absListView.getMeasuredHeight();
        } else {
          return false;
        }

      } else {
        return ViewCompat.canScrollVertically(mTargetView, 1) || mTargetView.getScrollY() > 0;
      }
    } else {
      return ViewCompat.canScrollVertically(mTargetView, 1);
    }
  }

  public float dipToPx(Context context, float value) {
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, metrics);
  }

  public void setOnLoadingListener(WXOnLoadingListener onLoadingListener) {
    this.onLoadingListener = onLoadingListener;
  }

  public void setOnRefreshListener(WXOnRefreshListener onRefreshListener) {
    this.onRefreshListener = onRefreshListener;
  }

  /**
   * Callback on refresh finish
   */
  public void finishPullRefresh() {
    if (mCurrentAction == PULL_REFRESH) {
      resetHeaderView(headerView == null ? 0 : headerView.getMeasuredHeight());
    }
  }

  /**
   * Callback on loadmore finish
   */
  public void finishPullLoad() {
    if (mCurrentAction == LOAD_MORE) {
      resetFootView(footerView == null ? 0 : footerView.getMeasuredHeight());
    }
  }

  public WXRefreshView getHeaderView() {
    return headerView;
  }

  public WXRefreshView getFooterView() {
    return footerView;
  }

  public boolean isPullLoadEnable() {
    return mPullLoadEnable;
  }

  public void setPullLoadEnable(boolean mPullLoadEnable) {
    this.mPullLoadEnable = mPullLoadEnable;
  }

  public boolean isPullRefreshEnable() {
    return mPullRefreshEnable;
  }

  public void setPullRefreshEnable(boolean mPullRefreshEnable) {
    this.mPullRefreshEnable = mPullRefreshEnable;
  }

  public boolean isRefreshing() {
    return mRefreshing;
  }
}


text:
Flipped::Flipped(Definitions::MOWER_STATES myState, StateController& stateController, Resources& resources) : AbstractState(myState, stateController, resources) {}

void Flipped::selected(Definitions::MOWER_STATES lastState) {
  // mower has flipped over/or are in a steep slope, stop cutter and wheels.
  previousState = lastState;
  resources.cutter.stop(true);
  resources.wheelController.stop(false);
  timer = millis();
}

void Flipped::process() {
  // if mower has been unflipped for at least 4 seconds, then resume last state (usually mowing).
  if (resources.accelerometer.isFlipped()) {
    timer = millis();
  } else {
    if (timer + 5000 < millis()) {
      stateController.setState(previousState);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
(function() {
  var Client, EventEmitter, HttpClient, Mapper, Meta, Utils, http;
  var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
    for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
    function ctor() { this.constructor = child; }
    ctor.prototype = parent.prototype;
    child.prototype = new ctor;
    child.__super__ = parent.prototype;
    return child;
  }, __slice = Array.prototype.slice, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  Client = require('./client');
  Meta = require('./http_meta');
  Mapper = require('./mapper');
  Utils = require('./utils');
  http = require('http');
  EventEmitter = require('events').EventEmitter;
  HttpClient = (function() {
    __extends(HttpClient, Client);
    function HttpClient(options) {
      options = Utils.mixin(true, {}, Meta.defaults, options);
      HttpClient.__super__.constructor.call(this, options);
    }
    HttpClient.prototype.get = function() {
      var bucket, callback, key, meta, options, _ref;
      bucket = arguments[0], key = arguments[1], options = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      meta = new Meta(bucket, key, options);
      return this.execute('GET', meta, callback);
    };
    HttpClient.prototype.head = function() {
      var bucket, callback, key, meta, options, _ref;
      bucket = arguments[0], key = arguments[1], options = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      meta = new Meta(bucket, key, options);
      return this.execute('HEAD', meta, callback);
    };
    HttpClient.prototype.exists = function() {
      var bucket, callback, key, options, _ref;
      bucket = arguments[0], key = arguments[1], options = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      return this.head(bucket, key, options, function(err, data, meta) {
        if ((meta != null ? meta.statusCode : void 0) === 404) {
          return callback(null, false, meta);
        } else if (err) {
          return callback(err, data, meta);
        } else {
          return callback(err, true, meta);
        }
      });
    };
    HttpClient.prototype.getAll = function() {
      var bucket, callback, mapfunc, options, _ref;
      bucket = arguments[0], options = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      mapfunc = function(v, k, options) {
        var data, keys;
        data = options.noJSON ? Riak.mapValues(v)[0] : Riak.mapValuesJson(v)[0];
        if (options.where && !options.noJSON) {
          keys = [];
          for (var i in options.where) keys.push(i);
          if (keys.some(function(k) {
            return options.where[k] !== data[k];
          })) {
            return [];
          }
        }
        delete v.values;
        return [
          {
            meta: v,
            data: data
          }
        ];
      };
      return this.add(bucket).map(mapfunc, options).run(callback);
    };
    HttpClient.prototype.keys = function() {
      var bucket, callback, meta, options, _ref;
      bucket = arguments[0], options = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      meta = new Meta(bucket, void 0, options);
      meta.keys || (meta.keys = true);
      if (meta.keys === 'stream') {
        meta._emitter = new EventEmitter();
        meta._emitter.start = __bind(function() {
          return this.execute('GET', meta, function(err, data, meta) {
            if (meta) {
              delete meta._emitter;
            }
            return callback(err, data, meta);
          });
        }, this);
        return meta._emitter;
      } else {
        return this.get(bucket, void 0, meta, function(err, obj) {
          return callback(err, obj != null ? obj.keys : void 0);
        });
      }
    };
    HttpClient.prototype.count = function() {
      var bucket, buffer, callback, options, stream, _ref;
      bucket = arguments[0], options = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      options.keys = 'stream';
      buffer = [];
      stream = this.keys(bucket, options, function(err, data, meta) {
        return callback(err, buffer.length, meta);
      });
      stream.on('keys', function(keys) {
        var k, _i, _len, _results;
        _results = [];
        for (_i = 0, _len = keys.length; _i < _len; _i++) {
          k = keys[_i];
          _results.push(buffer.push(k));
        }
        return _results;
      });
      return stream.start();
    };
    HttpClient.prototype.walk = function() {
      var bucket, callback, key, linkPhases, map, options, spec, _ref;
      bucket = arguments[0], key = arguments[1], spec = arguments[2], options = 4 <= arguments.length ? __slice.call(arguments, 3) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      linkPhases = spec.map(function(unit) {
        return {
          bucket: unit[0] || '_',
          tag: unit[1] || '_',
          keep: unit[2] != null
        };
      });
      map = options.noJSON ? 'Riak.mapValues' : 'Riak.mapValuesJson';
      return this.add(key ? [[bucket, key]] : bucket).link(linkPhases).reduce({
        language: 'erlang',
        module: 'riak_kv_mapreduce',
        "function": 'reduce_set_union'
      }).map(map).run(options, callback);
    };
    HttpClient.prototype.save = function() {
      var bucket, callback, data, key, meta, options, verb, _ref;
      bucket = arguments[0], key = arguments[1], data = arguments[2], options = 4 <= arguments.length ? __slice.call(arguments, 3) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      meta = new Meta(bucket, key, options);
      meta.data = data || {};
      verb = options.method || (key ? 'PUT' : 'POST');
      return this.execute(verb, meta, callback);
    };
    HttpClient.prototype.update = function() {
      var bucket, callback, key, newData, options, _ref;
      bucket = arguments[0], key = arguments[1], newData = arguments[2], options = 4 <= arguments.length ? __slice.call(arguments, 3) : [];
      console.warn("[riak-js] db.update is deprecated, scheduled for removal on next release. Please port your code to db.get/db.save.");
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      return this.get(bucket, key, options, __bind(function(err, data) {
        if (err) {
          return callback(err);
        }
        data = Utils.mixin(true, {}, data, newData);
        return this.save(bucket, key, data, options, callback);
      }, this));
    };
    HttpClient.prototype.remove = function() {
      var bucket, callback, key, meta, options, _ref;
      bucket = arguments[0], key = arguments[1], options = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      meta = new Meta(bucket, key, options);
      return this.execute('DELETE', meta, callback);
    };
    HttpClient.prototype.add = function(inputs) {
      return new Mapper(this, inputs);
    };
    HttpClient.prototype.runJob = function() {
      var callback, options, _ref;
      _ref = this.ensure(arguments), options = _ref[0], callback = _ref[1];
      options.raw || (options.raw = 'mapred');
      return this.save('', '', options.data, options, callback);
    };
    HttpClient.prototype.end = function() {};
    HttpClient.prototype.buckets = function() {
      var callback, meta, options, _ref;
      _ref = this.ensure(arguments), options = _ref[0], callback = _ref[1];
      meta = new Meta('', '', options);
      meta.buckets = true;
      return this.execute('GET', meta, callback);
    };
    HttpClient.prototype.getProps = function() {
      var bucket, callback, options, _ref;
      bucket = arguments[0], options = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      return this.get(bucket, void 0, options, function(err, obj) {
        return callback(err, obj.props);
      });
    };
    HttpClient.prototype.updateProps = function() {
      var bucket, callback, options, props, _ref;
      bucket = arguments[0], props = arguments[1], options = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      options.method = 'PUT';
      return this.save(bucket, void 0, {
        props: props
      }, options, callback);
    };
    HttpClient.prototype.enableIndex = function() {
      var bucket, callback, options, _ref;
      bucket = arguments[0], options = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      return this.getProps(bucket, options, __bind(function(err, props) {
        var hook;
        hook = {
          mod: 'riak_search_kv_hook',
          fun: 'precommit'
        };
        if (!(props.precommit.some(function(p) {
          return p.mod === hook.mod;
        }))) {
          props.precommit.push(hook);
        }
        return this.updateProps(bucket, props, options, callback);
      }, this));
    };
    HttpClient.prototype.disableIndex = function() {
      var bucket, callback, options, _ref;
      bucket = arguments[0], options = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      return this.getProps(bucket, options, __bind(function(err, props) {
        var p;
        props.precommit = (function() {
          var _i, _len, _ref2, _results;
          _ref2 = props.precommit;
          _results = [];
          for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
            p = _ref2[_i];
            if (p.mod !== 'riak_search_kv_hook') {
              _results.push(p);
            }
          }
          return _results;
        })();
        return this.updateProps(bucket, props, options, callback);
      }, this));
    };
    HttpClient.prototype.search = function() {
      var callback, index, meta, options, query, _ref;
      index = arguments[0], query = arguments[1], options = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      options.raw || (options.raw = 'solr');
      options.rows || (options.rows = 10000);
      options.wt = 'json';
      options.q = query;
      meta = new Meta(index, 'select', options);
      return this.execute('GET', meta, function(err, data, meta) {
        return callback(err, data != null ? data.response : void 0, meta);
      });
    };
    HttpClient.prototype.addSearch = function(index, query) {
      return this.add({
        module: 'riak_search',
        "function": 'mapred_search',
        arg: [index, query]
      });
    };
    HttpClient.prototype.getLarge = function() {
      var callback, key, options, _ref;
      key = arguments[0], options = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      options.raw || (options.raw = 'luwak');
      options.responseEncoding = 'binary';
      return this.get(void 0, key, options, callback);
    };
    HttpClient.prototype.saveLarge = function() {
      var callback, data, key, options, _ref;
      key = arguments[0], data = arguments[1], options = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      options.raw || (options.raw = 'luwak');
      if (data instanceof Buffer) {
        return this.save(void 0, key, data, options, callback);
      } else {
        return callback(new Error('Data has to be a Buffer'));
      }
    };
    HttpClient.prototype.removeLarge = function() {
      var callback, key, options, _ref;
      key = arguments[0], options = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      _ref = this.ensure(options), options = _ref[0], callback = _ref[1];
      options.raw || (options.raw = 'luwak');
      return this.remove(void 0, key, options, callback);
    };
    HttpClient.prototype.ping = function() {
      var callback, meta, options, _ref;
      _ref = this.ensure(arguments), options = _ref[0], callback = _ref[1];
      meta = new Meta('', '', {
        raw: 'ping'
      });
      return this.execute('HEAD', meta, function(err) {
        return callback(null, !(err != null));
      });
    };
    HttpClient.prototype.stats = function() {
      var callback, meta, options, _ref;
      _ref = this.ensure(arguments), options = _ref[0], callback = _ref[1];
      meta = new Meta('', '', {
        raw: 'stats'
      });
      return this.execute('GET', meta, callback);
    };
    HttpClient.prototype.Meta = Meta;
    HttpClient.prototype.execute = function(verb, meta, callback) {
      var request;
      meta.method = verb.toUpperCase();
      meta.headers = meta.toHeaders();
      Client.debug("" + meta.method + " " + meta.path, meta);
      request = http.request(meta, __bind(function(response) {
        var buffer, firstChunk, tempBuffer;
        delete meta.agent;
        response.setEncoding(meta.responseEncoding);
        buffer = '';
        firstChunk = false;
        tempBuffer = '';
        response.on('data', function(chunk) {
          var head, m, tail;
          if (meta._emitter) {
            if (!firstChunk) {
              buffer += chunk;
              return firstChunk = true;
            } else {
              tempBuffer += chunk;
              m = tempBuffer.match(/\}\{?/);
              if (m != null ? m.index : void 0) {
                head = tempBuffer.substr(0, m.index + 1);
                tail = tempBuffer.substr(m.index + 1);
                tempBuffer = tail;
                try {
                  return meta._emitter.emit('keys', JSON.parse(head).keys);
                } catch (err) {
                  return this.emit('clientError', err);
                }
              }
            }
          } else {
            return buffer += chunk;
          }
        });
        return response.on('end', __bind(function() {
          var boundary, data, err, _ref;
          if (meta._emitter) {
            meta._emitter.emit('end');
          }
          meta = meta.loadResponse(response);
          buffer = (400 <= (_ref = meta.statusCode) && _ref <= 599) ? (err = new Error("HTTP error " + meta.statusCode + ": " + buffer), meta.statusCode === 404 ? err.message = void 0 : void 0, err.statusCode = meta.statusCode, err) : this.decodeBuffer(buffer, meta, verb);
          if (meta.statusCode === 300 && meta.contentType.match(/^multipart\/mixed/)) {
            boundary = Utils.extractBoundary(meta.contentType);
            buffer = Utils.parseMultipart(buffer, boundary).map(__bind(function(doc) {
              var _meta;
              _meta = new Meta(meta.bucket, meta.key);
              _meta.loadResponse({
                headers: doc.headers,
                statusCode: meta.statusCode
              });
              _meta.vclock = meta.vclock;
              return {
                meta: _meta,
                data: this.decodeBuffer(doc.body, _meta, verb)
              };
            }, this));
          }
          if (buffer instanceof Error) {
            err = buffer;
            data = buffer.message;
            err.notFound = (meta != null ? meta.statusCode : void 0) === 404;
          }
          return callback(err, buffer, meta);
        }, this));
      }, this));
      if (meta.data) {
        request.write(meta.data, meta.contentEncoding);
        delete meta.data;
      }
      request.on('error', __bind(function(err) {
        this.emit('clientError', err);
        return callback(err);
      }, this));
      request.end();
    };
    HttpClient.prototype.decodeBuffer = function(buffer, meta, verb) {
      try {
        if (meta.statusCode === 204 || verb === 'HEAD') {
          return;
        } else if (buffer === "") {
          return buffer;
        } else {
          return meta.decode(buffer);
        }
      } catch (e) {
        return new Error("Cannot convert response into " + meta.contentType + ": " + e.message + " -- Response: " + buffer);
      }
    };
    return HttpClient;
  })();
  module.exports = HttpClient;
}).call(this);


text:
//==================================================================================
// BSD 2-Clause License
//
// Copyright (c) 2014-2022, NJIT, Duality Technologies Inc. and other contributors
//
// All rights reserved.
//
// Author TPOC: contact@openfhe.org
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//==================================================================================

/*
  This file contains the vector manipulation functionality
 */

#ifndef LBCRYPTO_MATH_HAL_BIGINTFXD_MUBINVECFXD_H
#define LBCRYPTO_MATH_HAL_BIGINTFXD_MUBINVECFXD_H

#include <iostream>
#include <string>

#include "utils/inttypes.h"
#include "utils/serializable.h"

#include "math/hal/bigintfxd/ubintfxd.h"

/**
 * @namespace bigintfxd
 * The namespace of bigintfxd
 */
namespace bigintfxd {

// Forward declare this class for aliases
template <typename IntegerType>
class BigVectorFixedT;

using BigVector = BigVectorFixedT<BigInteger>;

/**
 * @brief The class for representing vectors of big binary integers.
 */
template <class IntegerType>
class BigVectorFixedT : public lbcrypto::BigVectorInterface<BigVectorFixedT<IntegerType>, IntegerType>,
                        public lbcrypto::Serializable {
public:
    // CONSTRUCTORS

    /**
   * Basic constructor.
   */
    BigVectorFixedT();

    static inline BigVectorFixedT Single(const IntegerType& val, const IntegerType& modulus) {
        BigVectorFixedT vec(1, modulus);
        vec[0] = val;
        return vec;
    }

    /**
   * Basic constructor for specifying the length of the vector and the modulus.
   *
   * @param length is the length of the big binary vector, in terms of the
   * number of entries.
   * @param modulus is the modulus of the ring.
   */
    explicit BigVectorFixedT(usint length, const IntegerType& modulus = 0);

    /**
   * Basic constructor for copying a vector
   *
   * @param bigVector is the big binary vector to be copied.
   */
    BigVectorFixedT(const BigVectorFixedT& bigVector);

    /**
   * Basic move constructor for moving a vector
   *
   * @param &&bigVector is the big binary vector to be moved.
   */
    BigVectorFixedT(BigVectorFixedT&& bigVector);  // move copy constructor

    /**
   * Basic constructor for specifying the length of the vector
   * the modulus and an initializer list.
   *
   * @param length is the length of the big binary vector, in terms of the
   * number of entries.
   * @param modulus is the modulus of the ring.
   * @param rhs is an initializer list of strings
   */

    BigVectorFixedT(usint length, const IntegerType& modulus, std::initializer_list<std::string> rhs);

    /**
   * Basic constructor for specifying the length of the vector
   * the modulus and an initializer list.
   *
   * @param length is the length of the big binary vector, in terms of the
   * number of entries.
   * @param modulus is the modulus of the ring.
   * @param rhs is an initializer list of usint
   */
    BigVectorFixedT(usint length, const IntegerType& modulus, std::initializer_list<uint64_t> rhs);

    /**
   * Destructor.
   */
    virtual ~BigVectorFixedT();

    // ASSIGNMENT OPERATORS

    /**
   * Assignment operator to assign value from rhs
   *
   * @param &rhs is the big binary vector to be assigned from.
   * @return Assigned BigVectorFixedT.
   */
    const BigVectorFixedT& operator=(const BigVectorFixedT& rhs);

    /**
   * Move assignment operator
   *
   * @param &&rhs is the big binary vector to be moved.
   * @return moved BigVectorFixedT object
   */
    const BigVectorFixedT& operator=(BigVectorFixedT&& rhs);

    /**
   * Initializer list for BigVectorFixedT.
   *
   * @param &&rhs is the list of strings containing integers to be assigned to
   * the BBV.
   * @return BigVectorFixedT object
   */
    const BigVectorFixedT& operator=(std::initializer_list<std::string> rhs);

    /**
   * Initializer list for BigVectorFixedT.
   *
   * @param &&rhs is the list of integers to be assigned to the BBV.
   * @return BigVectorFixedT object
   */
    const BigVectorFixedT& operator=(std::initializer_list<uint64_t> rhs);

    /**
   * Assignment operator to assign value val to first entry, 0 for the rest of
   * entries.
   *
   * @param val is the value to be assigned at the first entry.
   * @return Assigned BigVectorFixedT.
   */
    const BigVectorFixedT& operator=(uint64_t val) {
        this->m_data[0] = val;
        if (this->m_modulus != 0) {
            this->m_data[0] %= this->m_modulus;
        }
        for (size_t i = 1; i < GetLength(); ++i) {
            this->m_data[i] = 0;
        }
        return *this;
    }

    // ACCESSORS

    /**
   * Sets/gets a value at an index.
   * This method is slower than operator[] as it checks if index out of range
   *
   * @param index is the index to set a value at.
   */
    IntegerType& at(size_t i) {
        if (!this->IndexCheck(i)) {
            OPENFHE_THROW(lbcrypto::math_error, "BigVector index out of range");
        }
        return this->m_data[i];
    }

    const IntegerType& at(size_t i) const {
        if (!this->IndexCheck(i)) {
            OPENFHE_THROW(lbcrypto::math_error, "BigVector index out of range");
        }
        return this->m_data[i];
    }

    /**
   * operators to get a value at an index.
   * @param idx is the index to get a value at.
   * @return is the value at the index.
   */
    IntegerType& operator[](size_t idx) {
        return (this->m_data[idx]);
    }

    const IntegerType& operator[](size_t idx) const {
        return (this->m_data[idx]);
    }

    /**
   * Sets the vector modulus.
   *
   * @param value is the value to set.
   * @param value is the modulus value to set.
   */
    void SetModulus(const IntegerType& value);

    /**
   * Sets the vector modulus and changes the values to match the new modulus.
   *
   * @param value is the value to set.
   */
    void SwitchModulus(const IntegerType& value);

    /**
   * Gets the vector modulus.
   *
   * @return the vector modulus.
   */
    const IntegerType& GetModulus() const {
        return this->m_modulus;
    }

    /**
   * Gets the vector length.
   *
   * @return vector length.
   */
    size_t GetLength() const {
        return this->m_length;
    }

    // MODULAR ARITHMETIC OPERATIONS

    /**
   * Vector modulus operator.
   *
   * @param &modulus is the modulus to perform on the current vector entries.
   * @return is the result of the modulus operation on current vector.
   */
    BigVectorFixedT Mod(const IntegerType& modulus) const;

    /**
   * Vector modulus operator. In-place variant.
   *
   * @param &modulus is the modulus to perform on the current vector entries.
   * @return is the result of the modulus operation on current vector.
   */
    const BigVectorFixedT& ModEq(const IntegerType& modulus);

    /**
   * Scalar-to-vector modulus addition operation.
   *
   * @param &b is the scalar to perform operation with.
   * @return is the result of the modulus addition operation.
   */
    BigVectorFixedT ModAdd(const IntegerType& b) const;

    /**
   * Scalar-to-vector modulus addition operation. In-place variant.
   *
   * @param &b is the scalar to perform operation with.
   * @return is the result of the modulus addition operation.
   */
    const BigVectorFixedT& ModAddEq(const IntegerType& b);

    /**
   * Scalar modulus addition at a particular index.
   *
   * @param i is the index of the entry to add.
   * @param &b is the scalar to add.
   * @return is the result of the modulus addition operation.
   */
    BigVectorFixedT ModAddAtIndex(usint i, const IntegerType& b) const;

    /**
   * Scalar modulus addition at a particular index. In-place variant.
   *
   * @param i is the index of the entry to add.
   * @param &b is the scalar to add.
   * @return is the result of the modulus addition operation.
   */
    const BigVectorFixedT& ModAddAtIndexEq(usint i, const IntegerType& b);

    /**
   * Vector component wise modulus addition.
   *
   * @param &b is the vector to perform operation with.
   * @return is the result of the component wise modulus addition operation.
   */
    BigVectorFixedT ModAdd(const BigVectorFixedT& b) const;

    /**
   * Vector component wise modulus addition. In-place variant.
   *
   * @param &b is the vector to perform operation with.
   * @return is the result of the component wise modulus addition operation.
   */
    const BigVectorFixedT& ModAddEq(const BigVectorFixedT& b);

    /**
   * Scalar-from-vector modulus subtraction operation.
   *
   * @param &b is the scalar to perform operation with.
   * @return is the result of the modulus subtraction operation.
   */
    BigVectorFixedT ModSub(const IntegerType& b) const;

    /**
   * Scalar-from-vector modulus subtraction operation. In-place variant.
   *
   * @param &b is the scalar to perform operation with.
   * @return is the result of the modulus subtraction operation.
   */
    const BigVectorFixedT& ModSubEq(const IntegerType& b);

    /**
   * Vector component wise modulus subtraction.
   *
   * @param &b is the vector to perform operation with.
   * @return is the result of the component wise modulus subtraction operation.
   */
    BigVectorFixedT ModSub(const BigVectorFixedT& b) const;

    /**
   * Vector component wise modulus subtraction. In-place variant.
   *
   * @param &b is the vector to perform operation with.
   * @return is the result of the component wise modulus subtraction operation.
   */
    const BigVectorFixedT& ModSubEq(const BigVectorFixedT& b);

    /**
   * Scalar-to-vector modulus multiplication operation.
   * Generalized Barrett modulo reduction algorithm.
   *
   * @param &b is the scalar to perform operation with.
   * @return is the result of the modulus multiplication operation.
   */
    BigVectorFixedT ModMul(const IntegerType& b) const;

    /**
   * Scalar-to-vector modulus multiplication operation. In-place variant.
   * Generalized Barrett modulo reduction algorithm.
   *
   * @param &b is the scalar to perform operation with.
   * @return is the result of the modulus multiplication operation.
   */
    const BigVectorFixedT& ModMulEq(const IntegerType& b);

    /**
   * Vector component wise modulus multiplication.
   *
   * @param &b is the vector to perform operation with.
   * @return is the result of the component wise modulus multiplication
   * operation.
   */
    BigVectorFixedT ModMul(const BigVectorFixedT& b) const;

    /**
   * Vector component wise modulus multiplication. In-place variant.
   *
   * @param &b is the vector to perform operation with.
   * @return is the result of the component wise modulus multiplication
   * operation.
   */
    const BigVectorFixedT& ModMulEq(const BigVectorFixedT& b);

    /**
   * Scalar modulus exponentiation operation.
   *
   * @param &b is the scalar to perform operation with.
   * @return is the result of the modulus exponentiation operation.
   */
    BigVectorFixedT ModExp(const IntegerType& b) const;

    /**
   * Scalar modulus exponentiation operation. In-place variant.
   *
   * @param &b is the scalar to perform operation with.
   * @return is the result of the modulus exponentiation operation.
   */
    const BigVectorFixedT& ModExpEq(const IntegerType& b);

    /**
   * Modulus inverse operation.
   *
   * @return is the result of the component wise modulus inverse operation.
   */
    BigVectorFixedT ModInverse() const;

    /**
   * Modulus inverse operation. In-place variant.
   *
   * @return is the result of the component wise modulus inverse operation.
   */
    const BigVectorFixedT& ModInverseEq();

    /**
   * Modulus 2 operation, also a least significant bit.
   *
   * @return is the result of the component wise modulus 2 operation, also a
   * least significant bit.
   */
    BigVectorFixedT ModByTwo() const;

    /**
   * Modulus 2 operation, also a least significant bit. In-place variant.
   *
   * @return is the result of the component wise modulus 2 operation, also a
   * least significant bit.
   */
    const BigVectorFixedT& ModByTwoEq();

    /**
   * Vector multiplication without applying the modulus operation.
   *
   * @param &b is the vector to multiply.
   * @return is the result of the multiplication operation.
   */
    BigVectorFixedT MultWithOutMod(const BigVectorFixedT& b) const;

    /**
   * Vector multiplication without applying the modulus operation. In-place
   * variant.
   *
   * @param &b is the vector to multiply.
   * @return is the result of the multiplication operation.
   */
    const BigVectorFixedT& MultWithOutModEq(const BigVectorFixedT& b);

    /**
   * Multiply and Rounding operation. Returns [x*p/q] where [] is the rounding
   * operation.
   *
   * @param &p is the numerator to be multiplied.
   * @param &q is the denominator to be divided.
   * @return is the result of multiply and round operation.
   */
    BigVectorFixedT MultiplyAndRound(const IntegerType& p, const IntegerType& q) const;

    /**
   * Multiply and Rounding operation. Returns [x*p/q] where [] is the rounding
   * operation. In-place variant.
   *
   * @param &p is the numerator to be multiplied.
   * @param &q is the denominator to be divided.
   * @return is the result of multiply and round operation.
   */
    const BigVectorFixedT& MultiplyAndRoundEq(const IntegerType& p, const IntegerType& q);

    /**
   * Divide and Rounding operation. Returns [x/q] where [] is the rounding
   * operation.
   *
   * @param &q is the denominator to be divided.
   * @return is the result of divide and round operation.
   */
    BigVectorFixedT DivideAndRound(const IntegerType& q) const;

    /**
   * Divide and Rounding operation. Returns [x/q] where [] is the rounding
   * operation. In-place variant.
   *
   * @param &q is the denominator to be divided.
   * @return is the result of divide and round operation.
   */
    const BigVectorFixedT& DivideAndRoundEq(const IntegerType& q);

    // OTHER FUNCTIONS

    /**
   * Digit vector at a specific index for all entries for a given number base.
   * Warning: only power-of-2 bases are currently supported.
   * Example: for vector (83, 1, 45), index 2 and base 4 we have:
   *
   *                           index:0,1,2,3
   * |83|                           |3,0,1,1|                 |1|
   * |1 | --base 4 decomposition--> |1,0,0,0| --at index 2--> |0|
   * |45|                           |1,3,2,0|                 |2|
   *
   * The return vector is (1,0,2)
   *
   * @param index is the index to return the digit from in all entries.
   * @param base is the base to use for the operation.
   * @return is the digit at a specific index for all entries for a given number
   * base
   */
    BigVectorFixedT GetDigitAtIndexForBase(usint index, usint base) const;

    // STRINGS & STREAMS

    /**
   * ostream operator to output vector values to console
   *
   * @param os is the std ostream object.
   * @param &ptr_obj is the BigVectorFixedT object to be printed.
   * @return std ostream object which captures the vector values.
   */
    template <class IntegerType_c>
    friend std::ostream& operator<<(std::ostream& os, const BigVectorFixedT<IntegerType_c>& ptr_obj) {
        auto len = ptr_obj.m_length;
        os << "[";
        for (usint i = 0; i < len; i++) {
            os << ptr_obj.m_data[i];
            os << ((i == (len - 1)) ? "]" : " ");
        }
        os << " modulus: " << ptr_obj.m_modulus;
        return os;
    }

    // SERIALIZATION

    template <class Archive>
    typename std::enable_if<!cereal::traits::is_text_archive<Archive>::value, void>::type save(
        Archive& ar, std::uint32_t const version) const {
        ar(::cereal::make_nvp("m", m_modulus));
        ar(::cereal::make_nvp("l", m_length));
        ar(::cereal::binary_data(m_data, sizeof(IntegerType) * m_length));
    }

    template <class Archive>
    typename std::enable_if<cereal::traits::is_text_archive<Archive>::value, void>::type save(
        Archive& ar, std::uint32_t const version) const {
        ar(::cereal::make_nvp("m", m_modulus));
        ar(::cereal::make_nvp("l", m_length));
        for (size_t i = 0; i < m_length; i++) {
            ar(m_data[i]);
        }
    }

    template <class Archive>
    typename std::enable_if<!cereal::traits::is_text_archive<Archive>::value, void>::type load(
        Archive& ar, std::uint32_t const version) {
        if (version > SerializedVersion()) {
            OPENFHE_THROW(lbcrypto::deserialize_error, "serialized object version " + std::to_string(version) +
                                                           " is from a later version of the library");
        }
        ar(::cereal::make_nvp("m", m_modulus));
        ar(::cereal::make_nvp("l", m_length));
        m_data = new IntegerType[m_length]();
        ar(::cereal::binary_data(m_data, sizeof(IntegerType) * m_length));
    }

    template <class Archive>
    typename std::enable_if<cereal::traits::is_text_archive<Archive>::value, void>::type load(
        Archive& ar, std::uint32_t const version) {
        if (version > SerializedVersion()) {
            OPENFHE_THROW(lbcrypto::deserialize_error, "serialized object version " + std::to_string(version) +
                                                           " is from a later version of the library");
        }
        ar(::cereal::make_nvp("m", m_modulus));
        ar(::cereal::make_nvp("l", m_length));
        m_data = new IntegerType[m_length]();
        for (size_t i = 0; i < m_length; i++) {
            ar(m_data[i]);
        }
    }

    std::string SerializedObjectName() const {
        return "FXDInteger";
    }

    static uint32_t SerializedVersion() {
        return 1;
    }

private:
    // m_data is a pointer to the vector
    IntegerType* m_data;
    // m_length stores the length of the vector
    usint m_length;
    // m_modulus stores the internal modulus of the vector.
    IntegerType m_modulus = 0;

    // function to check if the index is a valid index.
    bool IndexCheck(size_t length) const {
        if (length > this->m_length) {
            return false;
        }
        return true;
    }
};

}  // namespace bigintfxd

#endif  // LBCRYPTO_MATH_HAL_BIGINTFXD_MUBINVECFXD_H


text:
package org.apache.geode.management.internal.pulse;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.awaitility.Awaitility;
import org.junit.Test;

import org.apache.geode.cache.Cache;
import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.execute.FunctionService;
import org.apache.geode.management.DistributedSystemMXBean;
import org.apache.geode.management.ManagementService;
import org.apache.geode.management.ManagementTestBase;
import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;

/**
 * This is for testing running functions
 */

class SimpleWaitFunction<T> implements Function<T> {
  private static CountDownLatch countDownLatch;

  public static void setLatch() {
    countDownLatch = new CountDownLatch(1);
  }

  public static void clearLatch() {
    countDownLatch.countDown();
  }

  @Override
  public void execute(FunctionContext<T> context) {
    try {
      countDownLatch.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

}

public class TestFunctionsDUnitTest extends ManagementTestBase {

  private static final long serialVersionUID = 1L;

  public TestFunctionsDUnitTest() {
    super();
  }

  private static Integer getNumOfRunningFunction() {

    Awaitility.waitAtMost(1, TimeUnit.MINUTES)
        .pollInterval(500, TimeUnit.MILLISECONDS).until(() -> {
          final ManagementService service = getManagementService();
          final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
          if (bean != null) {
            return bean.getNumRunningFunctions() > 0;
          }
          return false;
        });

    final DistributedSystemMXBean bean = getManagementService().getDistributedSystemMXBean();
    assertNotNull(bean);

    return bean.getNumRunningFunctions();
  }

  @Test
  public void testNumOfRunningFunctions() {
    initManagement(false);
    VM client = managedNodeList.get(2);
    client.invokeAsync(new SerializableRunnable() {
      public void run() {
        Cache cache = getCache();
        SimpleWaitFunction<Boolean> simpleWaitFunction = new SimpleWaitFunction();
        simpleWaitFunction.setLatch();
        Execution execution =
            FunctionService.onMember(cache.getDistributedSystem().getDistributedMember());
        execution.setArguments(Boolean.TRUE).execute(simpleWaitFunction);
      }
    });

    Integer numOfRunningFunctions =
        managingNode.invoke(TestFunctionsDUnitTest::getNumOfRunningFunction);

    assertTrue(numOfRunningFunctions > 0);

    client.invoke(new SerializableRunnable() {
      public void run() {
        SimpleWaitFunction.clearLatch();
      }
    });
  }

}


text:
package com.facebook.scrumptious;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.*;
import com.facebook.*;
import com.facebook.internal.Utility;
import com.facebook.model.*;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.ProfilePictureView;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Fragment that represents the main selection screen for Scrumptious.
 */
public class SelectionFragment extends Fragment {

    private static final String TAG = "SelectionFragment";
    private static final String MEAL_OBJECT_TYPE = "fb_sample_scrumps:meal";
    private static final String EAT_ACTION_TYPE = "fb_sample_scrumps:eat";
    private static final String DEFAULT_ACTION_IMAGE_URL =
            "http://facebooksampleapp.com/scrumptious/static/images/logo.png";

    private static final String PENDING_ANNOUNCE_KEY = "pendingAnnounce";
    private static final Uri M_FACEBOOK_URL = Uri.parse("http://m.facebook.com");
    private static final int USER_GENERATED_MIN_SIZE = 480;

    private static final int REAUTH_ACTIVITY_CODE = 100;
    private static final String PERMISSION = "publish_actions";

    private Button announceButton;
    private ListView listView;
    private ProgressDialog progressDialog;
    private List<BaseListElement> listElements;
    private ProfilePictureView profilePictureView;
    private TextView userNameView;
    private boolean pendingAnnounce;
    private MainActivity activity;
    private Uri photoUri;

    private UiLifecycleHelper uiHelper;
    private Session.StatusCallback sessionCallback = new Session.StatusCallback() {
        @Override
        public void call(final Session session, final SessionState state, final Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };
    private FacebookDialog.Callback nativeDialogCallback = new FacebookDialog.Callback() {
        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
            boolean resetSelections = true;
            if (FacebookDialog.getNativeDialogDidComplete(data)) {
                if (FacebookDialog.COMPLETION_GESTURE_CANCEL
                        .equals(FacebookDialog.getNativeDialogCompletionGesture(data))) {
                    // Leave selections alone if user canceled.
                    resetSelections = false;
                    showCancelResponse();
                } else {
                    showSuccessResponse(FacebookDialog.getNativeDialogPostId(data));
                }
            }

            if (resetSelections) {
                init(null);
            }
        }

        @Override
        public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
            new AlertDialog.Builder(getActivity())
                    .setPositiveButton(R.string.error_dialog_button_text, null)
                    .setTitle(R.string.error_dialog_title)
                    .setMessage(error.getLocalizedMessage())
                    .show();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (MainActivity) getActivity();
        uiHelper = new UiLifecycleHelper(getActivity(), sessionCallback);
        uiHelper.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        uiHelper.onResume();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.selection, container, false);

        profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
        profilePictureView.setCropped(true);
        userNameView = (TextView) view.findViewById(R.id.selection_user_name);
        announceButton = (Button) view.findViewById(R.id.announce_button);
        listView = (ListView) view.findViewById(R.id.selection_list);

        announceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handleAnnounce();
            }
        });

        init(savedInstanceState);

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode >= 0 && requestCode < listElements.size()) {
            listElements.get(requestCode).onActivityResult(data);
        } else {
            uiHelper.onActivityResult(requestCode, resultCode, data, nativeDialogCallback);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        for (BaseListElement listElement : listElements) {
            listElement.onSaveInstanceState(bundle);
        }
        bundle.putBoolean(PENDING_ANNOUNCE_KEY, pendingAnnounce);
        uiHelper.onSaveInstanceState(bundle);
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
        activity = null;
    }

    /**
     * Notifies that the session token has been updated.
     */
    private void tokenUpdated() {
        if (pendingAnnounce) {
            handleAnnounce();
        }
    }

    private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
        if (session != null && session.isOpened()) {
            if (state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
                tokenUpdated();
            } else {
                makeMeRequest(session);
            }
        } else {
            profilePictureView.setProfileId(null);
            userNameView.setText("");
        }
    }

    private void makeMeRequest(final Session session) {
        Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
            @Override
            public void onCompleted(GraphUser user, Response response) {
                if (session == Session.getActiveSession()) {
                    if (user != null) {
                        profilePictureView.setProfileId(user.getId());
                        userNameView.setText(user.getName());
                    }
                }
                if (response.getError() != null) {
                    handleError(response.getError());
                }
            }
        });
        request.executeAsync();

    }

    /**
     * Resets the view to the initial defaults.
     */
    private void init(Bundle savedInstanceState) {
        announceButton.setEnabled(false);

        listElements = new ArrayList<BaseListElement>();

        listElements.add(new EatListElement(0));
        listElements.add(new LocationListElement(1));
        listElements.add(new PeopleListElement(2));
        listElements.add(new PhotoListElement(3));

        if (savedInstanceState != null) {
            for (BaseListElement listElement : listElements) {
                listElement.restoreState(savedInstanceState);
            }
            pendingAnnounce = savedInstanceState.getBoolean(PENDING_ANNOUNCE_KEY, false);
        }

        listView.setAdapter(new ActionListAdapter(getActivity(), R.id.selection_list, listElements));

        Session session = Session.getActiveSession();
        if (session != null && session.isOpened()) {
            makeMeRequest(session);
        }
    }

    private void handleAnnounce() {
        pendingAnnounce = false;
        Session session = Session.getActiveSession();

        // if we have a session, then use the graph API to directly publish, otherwise use
        // the native open graph share dialog.
        if (session != null && session.isOpened()) {
            handleGraphApiAnnounce();
        } else {
            handleNativeShareAnnounce();
        }
    }

    private void handleGraphApiAnnounce() {
        Session session = Session.getActiveSession();

        List<String> permissions = session.getPermissions();
        if (!permissions.contains(PERMISSION)) {
            pendingAnnounce = true;
            requestPublishPermissions(session);
            return;
        }

        // Show a progress dialog because sometimes the requests can take a while.
        progressDialog = ProgressDialog.show(getActivity(), "",
                getActivity().getResources().getString(R.string.progress_dialog_text), true);

        // Run this in a background thread so we can process the list of responses and extract errors.
        AsyncTask<Void, Void, List<Response>> task = new AsyncTask<Void, Void, List<Response>>() {

            @Override
            protected List<Response> doInBackground(Void... voids) {
                EatAction eatAction = createEatAction();

                RequestBatch requestBatch = new RequestBatch();

                String photoStagingUri = null;

                if (photoUri != null) {
                    try {
                        Pair<File, Integer> fileAndMinDimemsion = getImageFileAndMinDimension();
                        if (fileAndMinDimemsion != null) {
                            Request photoStagingRequest =
                                    Request.newUploadStagingResourceWithImageRequest(Session.getActiveSession(),
                                            fileAndMinDimemsion.first, null);
                            photoStagingRequest.setBatchEntryName("photoStaging");
                            requestBatch.add(photoStagingRequest);
                            // Facebook SDK * pro-tip *
                            // We can use the result from one request in the batch as the input to another request.
                            // In this case, the result from the staging upload is "uri", which we will use as the
                            // input into the "url" field for images on the open graph action below.
                            photoStagingUri = "{result=photoStaging:$.uri}";
                            eatAction.setImage(getImageListForAction(photoStagingUri,
                                    fileAndMinDimemsion.second >= USER_GENERATED_MIN_SIZE));
                        }
                    } catch (FileNotFoundException e) {
                        // NOOP - if we can't upload the image, just skip it for now
                    }
                }
                MealGraphObject meal = eatAction.getMeal();
                if (meal.getCreateObject()) {
                    Request createObjectRequest =
                            Request.newPostOpenGraphObjectRequest(Session.getActiveSession(), meal, null);
                    createObjectRequest.setBatchEntryName("createObject");
                    requestBatch.add(createObjectRequest);
                    eatAction.setProperty("meal", "{result=createObject:$.id}");
                }

                Request request = Request.newPostOpenGraphActionRequest(Session.getActiveSession(), eatAction, null);
                requestBatch.add(request);

                return requestBatch.executeAndWait();
            }

            @Override
            protected void onPostExecute(List<Response> responses) {
                // We only care about the last response, or the first one with an error.
                Response finalResponse = null;
                for (Response response : responses) {
                    finalResponse = response;
                    if (response != null && response.getError() != null) {
                        break;
                    }
                }
                onPostActionResponse(finalResponse);
            }
        };

        task.execute();
    }

    private void handleNativeShareAnnounce() {
        FacebookDialog.OpenGraphActionDialogBuilder builder = createDialogBuilder();
        if (builder.canPresent()) {
            uiHelper.trackPendingDialogCall(builder.build().present());
        } else {
            // If we can't show the native open graph share dialog because the Facebook app
            // does not support it, then show then settings fragment so the user can log in.
            activity.showSettingsFragment();
        }
    }

    private FacebookDialog.OpenGraphActionDialogBuilder createDialogBuilder() {
        EatAction eatAction = createEatAction();

        boolean userGenerated = false;
        if (photoUri != null) {
            String photoUriString = photoUri.toString();
            Pair<File, Integer> fileAndMinDimemsion = getImageFileAndMinDimension();
            userGenerated = fileAndMinDimemsion.second >= USER_GENERATED_MIN_SIZE;

            // If we have a content: URI, we can just use that URI, otherwise we'll need to add it as an attachment.
            if (fileAndMinDimemsion != null && photoUri.getScheme().startsWith("content")) {
                eatAction.setImage(getImageListForAction(photoUriString, userGenerated));
            }
        }

        FacebookDialog.OpenGraphActionDialogBuilder builder = new FacebookDialog.OpenGraphActionDialogBuilder(
                getActivity(), eatAction, "meal")
                .setFragment(SelectionFragment.this);

        if (photoUri != null && !photoUri.getScheme().startsWith("content")) {
            builder.setImageAttachmentFilesForAction(Arrays.asList(new File(photoUri.getPath())), userGenerated);
        }

        return builder;
    }

    private Pair<File, Integer> getImageFileAndMinDimension() {
        File photoFile = null;
        String photoUriString = photoUri.toString();
        if (photoUriString.startsWith("file://")) {
            photoFile = new File(photoUri.getPath());
        } else if (photoUriString.startsWith("content://")) {
            String [] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getActivity().getContentResolver().query(photoUri, filePath, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePath[0]);
                String filename = cursor.getString(columnIndex);
                cursor.close();

                photoFile = new File(filename);
            }
        }

        if (photoFile != null) {
            InputStream is = null;
            try {
                is = new FileInputStream(photoFile);

                // We only want to get the bounds of the image, rather than load the whole thing.
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(is, null, options);

                return new Pair<File, Integer>(photoFile, Math.min(options.outWidth, options.outHeight));
            } catch (Exception e) {
                return null;
            } finally {
                Utility.closeQuietly(is);
            }
        }
        return null;
    }

    /**
     * Creates a GraphObject with the following format:
     * {
     *     url: ${uri},
     *     user_generated: true
     * }
     */
    private GraphObject getImageObject(String uri, boolean userGenerated) {
        GraphObject imageObject = GraphObject.Factory.create();
        imageObject.setProperty("url", uri);
        if (userGenerated) {
            imageObject.setProperty("user_generated", "true");
        }
        return imageObject;
    }

    private List<JSONObject> getImageListForAction(String uri, boolean userGenerated) {
        return Arrays.asList(getImageObject(uri, userGenerated).getInnerJSONObject());
    }

    private EatAction createEatAction() {
        EatAction eatAction = OpenGraphAction.Factory.createForPost(EatAction.class, EAT_ACTION_TYPE);
        for (BaseListElement element : listElements) {
            element.populateOGAction(eatAction);
        }
        return eatAction;
    }

    private void requestPublishPermissions(Session session) {
        if (session != null) {
            Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, PERMISSION)
                    // demonstrate how to set an audience for the publish permissions,
                    // if none are set, this defaults to FRIENDS
                    .setDefaultAudience(SessionDefaultAudience.FRIENDS)
                    .setRequestCode(REAUTH_ACTIVITY_CODE);
            session.requestNewPublishPermissions(newPermissionsRequest);
        }
    }

    private void onPostActionResponse(Response response) {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        if (getActivity() == null) {
            // if the user removes the app from the website, then a request will
            // have caused the session to close (since the token is no longer valid),
            // which means the splash fragment will be shown rather than this one,
            // causing activity to be null. If the activity is null, then we cannot
            // show any dialogs, so we return.
            return;
        }

        PostResponse postResponse = response.getGraphObjectAs(PostResponse.class);

        if (postResponse != null && postResponse.getId() != null) {
            showSuccessResponse(postResponse.getId());
            init(null);
        } else {
            handleError(response.getError());
        }
    }

    private void showSuccessResponse(String postId) {
        String dialogBody;
        if (postId != null) {
            dialogBody = String.format(getString(R.string.result_dialog_text_with_id), postId);
        } else {
            dialogBody = getString(R.string.result_dialog_text_default);
        }
        showResultDialog(dialogBody);
    }

    private void showCancelResponse() {
        showResultDialog(getString(R.string.result_dialog_text_canceled));
    }

    private void showResultDialog(String dialogBody) {
        new AlertDialog.Builder(getActivity())
                .setPositiveButton(R.string.result_dialog_button_text, null)
                .setTitle(R.string.result_dialog_title)
                .setMessage(dialogBody)
                .show();
    }

    private void handleError(FacebookRequestError error) {
        DialogInterface.OnClickListener listener = null;
        String dialogBody = null;

        if (error == null) {
            dialogBody = getString(R.string.error_dialog_default_text);
        } else {
            switch (error.getCategory()) {
                case AUTHENTICATION_RETRY:
                    // tell the user what happened by getting the message id, and
                    // retry the operation later
                    String userAction = (error.shouldNotifyUser()) ? "" :
                            getString(error.getUserActionMessageId());
                    dialogBody = getString(R.string.error_authentication_retry, userAction);
                    listener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent intent = new Intent(Intent.ACTION_VIEW, M_FACEBOOK_URL);
                            startActivity(intent);
                        }
                    };
                    break;

                case AUTHENTICATION_REOPEN_SESSION:
                    // close the session and reopen it.
                    dialogBody = getString(R.string.error_authentication_reopen);
                    listener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Session session = Session.getActiveSession();
                            if (session != null && !session.isClosed()) {
                                session.closeAndClearTokenInformation();
                            }
                        }
                    };
                    break;

                case PERMISSION:
                    // request the publish permission
                    dialogBody = getString(R.string.error_permission);
                    listener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            pendingAnnounce = true;
                            requestPublishPermissions(Session.getActiveSession());
                        }
                    };
                    break;

                case SERVER:
                case THROTTLING:
                    // this is usually temporary, don't clear the fields, and
                    // ask the user to try again
                    dialogBody = getString(R.string.error_server);
                    break;

                case BAD_REQUEST:
                    // this is likely a coding error, ask the user to file a bug
                    dialogBody = getString(R.string.error_bad_request, error.getErrorMessage());
                    break;

                case OTHER:
                case CLIENT:
                default:
                    // an unknown issue occurred, this could be a code error, or
                    // a server side issue, log the issue, and either ask the
                    // user to retry, or file a bug
                    dialogBody = getString(R.string.error_unknown, error.getErrorMessage());
                    break;
            }
        }

        new AlertDialog.Builder(getActivity())
                .setPositiveButton(R.string.error_dialog_button_text, listener)
                .setTitle(R.string.error_dialog_title)
                .setMessage(dialogBody)
                .show();
    }

    private void startPickerActivity(Uri data, int requestCode) {
        Intent intent = new Intent();
        intent.setData(data);
        intent.setClass(getActivity(), PickerActivity.class);
        startActivityForResult(intent, requestCode);
    }

    /**
     * Interface representing the Meal Open Graph object.
     */
    private interface MealGraphObject extends OpenGraphObject {
        public String getUrl();
        public void setUrl(String url);

        public String getId();
        public void setId(String id);
    }

    /**
     * Interface representing the Eat action.
     */
    private interface EatAction extends OpenGraphAction {
        public MealGraphObject getMeal();
        public void setMeal(MealGraphObject meal);
    }

    /**
     * Used to inspect the response from posting an action
     */
    private interface PostResponse extends GraphObject {
        String getId();
    }

    private class EatListElement extends BaseListElement {

        private static final String FOOD_KEY = "food";
        private static final String FOOD_URL_KEY = "food_url";

        private final String[] foodChoices;
        private final String[] foodUrls;
        private String foodChoiceUrl = null;
        private String foodChoice = null;

        public EatListElement(int requestCode) {
            super(getActivity().getResources().getDrawable(R.drawable.action_eating),
                    getActivity().getResources().getString(R.string.action_eating),
                    getActivity().getResources().getString(R.string.action_eating_default),
                    requestCode);
            foodChoices = getActivity().getResources().getStringArray(R.array.food_types);
            foodUrls = getActivity().getResources().getStringArray(R.array.food_og_urls);
        }

        @Override
        protected View.OnClickListener getOnClickListener() {
            return new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showMealOptions();
                }
            };
        }

        @Override
        protected void populateOGAction(OpenGraphAction action) {
            if (foodChoice != null && foodChoice.length() > 0) {
                EatAction eatAction = action.cast(EatAction.class);
                eatAction.setImageUrls(Arrays.asList(DEFAULT_ACTION_IMAGE_URL));
                if (foodChoiceUrl != null && foodChoiceUrl.length() > 0) {
                    MealGraphObject meal = GraphObject.Factory.create(MealGraphObject.class);
                    meal.setUrl(foodChoiceUrl);
                    eatAction.setMeal(meal);
                } else {
                    MealGraphObject meal = OpenGraphObject.Factory.createForPost(MealGraphObject.class,
                            MEAL_OBJECT_TYPE);
                    meal.setTitle(foodChoice);
                    eatAction.setMeal(meal);
                }
            }
        }

        @Override
        protected void onSaveInstanceState(Bundle bundle) {
            if (foodChoice != null && foodChoiceUrl != null) {
                bundle.putString(FOOD_KEY, foodChoice);
                bundle.putString(FOOD_URL_KEY, foodChoiceUrl);
            }
        }

        @Override
        protected boolean restoreState(Bundle savedState) {
            String food = savedState.getString(FOOD_KEY);
            String foodUrl = savedState.getString(FOOD_URL_KEY);
            if (food != null && foodUrl != null) {
                foodChoice = food;
                foodChoiceUrl = foodUrl;
                setFoodText();
                return true;
            }
            return false;
        }

        private void showMealOptions() {
            String title = getActivity().getResources().getString(R.string.select_meal);
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(title).
                    setCancelable(true).
                    setItems(foodChoices, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            foodChoiceUrl = foodUrls[i];
                            if (foodChoiceUrl.length() == 0) {
                                getCustomFood();
                            } else {
                                foodChoice = foodChoices[i];
                                setFoodText();
                                notifyDataChanged();
                            }
                        }
                    });
            builder.show();
        }

        private void getCustomFood() {
            String title = getActivity().getResources().getString(R.string.enter_meal);
            final EditText input = new EditText(getActivity());

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(title)
                    .setCancelable(true)
                    .setView(input)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            foodChoice = input.getText().toString();
                            setFoodText();
                            notifyDataChanged();
                        }
                    })
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                        }
                    });
            AlertDialog dialog = builder.create();
            // always popup the keyboard when the alert dialog shows
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            dialog.show();
        }

        private void setFoodText() {
            if (foodChoice != null && foodChoice.length() > 0) {
                setText2(foodChoice);
                announceButton.setEnabled(true);
            } else {
                setText2(getActivity().getResources().getString(R.string.action_eating_default));
                announceButton.setEnabled(false);
            }
        }
    }

    private class PeopleListElement extends BaseListElement {

        private static final String FRIENDS_KEY = "friends";

        private List<GraphUser> selectedUsers;

        public PeopleListElement(int requestCode) {
            super(getActivity().getResources().getDrawable(R.drawable.action_people),
                    getActivity().getResources().getString(R.string.action_people),
                    getActivity().getResources().getString(R.string.action_people_default),
                    requestCode);
        }

        @Override
        protected View.OnClickListener getOnClickListener() {
            return new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (Session.getActiveSession() != null &&
                            Session.getActiveSession().isOpened()) {
                        startPickerActivity(PickerActivity.FRIEND_PICKER, getRequestCode());
                    } else {
                        activity.showSettingsFragment();
                    }
                }
            };
        }

        @Override
        protected void onActivityResult(Intent data) {
            selectedUsers = ((ScrumptiousApplication) getActivity().getApplication()).getSelectedUsers();
            setUsersText();
            notifyDataChanged();
        }

        @Override
        protected void populateOGAction(OpenGraphAction action) {
            if (selectedUsers != null) {
                action.setTags(selectedUsers);
            }
        }

        @Override
        protected void onSaveInstanceState(Bundle bundle) {
            if (selectedUsers != null) {
                bundle.putByteArray(FRIENDS_KEY, getByteArray(selectedUsers));
            }
        }

        @Override
        protected boolean restoreState(Bundle savedState) {
            byte[] bytes = savedState.getByteArray(FRIENDS_KEY);
            if (bytes != null) {
                selectedUsers = restoreByteArray(bytes);
                setUsersText();
                return true;
            }
            return false;
        }

        private void setUsersText() {
            String text = null;
            if (selectedUsers != null) {
                if (selectedUsers.size() == 1) {
                    text = String.format(getResources().getString(R.string.single_user_selected),
                            selectedUsers.get(0).getName());
                } else if (selectedUsers.size() == 2) {
                    text = String.format(getResources().getString(R.string.two_users_selected),
                            selectedUsers.get(0).getName(), selectedUsers.get(1).getName());
                } else if (selectedUsers.size() > 2) {
                    text = String.format(getResources().getString(R.string.multiple_users_selected),
                            selectedUsers.get(0).getName(), (selectedUsers.size() - 1));
                }
            }
            if (text == null) {
                text = getResources().getString(R.string.action_people_default);
            }
            setText2(text);
        }

        private byte[] getByteArray(List<GraphUser> users) {
            // convert the list of GraphUsers to a list of String where each element is
            // the JSON representation of the GraphUser so it can be stored in a Bundle
            List<String> usersAsString = new ArrayList<String>(users.size());

            for (GraphUser user : users) {
                usersAsString.add(user.getInnerJSONObject().toString());
            }
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                new ObjectOutputStream(outputStream).writeObject(usersAsString);
                return outputStream.toByteArray();
            } catch (IOException e) {
                Log.e(TAG, "Unable to serialize users.", e);
            }
            return null;
        }

        private List<GraphUser> restoreByteArray(byte[] bytes) {
            try {
                @SuppressWarnings("unchecked")
                List<String> usersAsString =
                        (List<String>) (new ObjectInputStream(new ByteArrayInputStream(bytes))).readObject();
                if (usersAsString != null) {
                    List<GraphUser> users = new ArrayList<GraphUser>(usersAsString.size());
                    for (String user : usersAsString) {
                        GraphUser graphUser = GraphObject.Factory
                                .create(new JSONObject(user), GraphUser.class);
                        users.add(graphUser);
                    }
                    return users;
                }
            } catch (ClassNotFoundException e) {
                Log.e(TAG, "Unable to deserialize users.", e);
            } catch (IOException e) {
                Log.e(TAG, "Unable to deserialize users.", e);
            } catch (JSONException e) {
                Log.e(TAG, "Unable to deserialize users.", e);
            }
            return null;
        }
    }

    private class LocationListElement extends BaseListElement {

        private static final String PLACE_KEY = "place";

        private GraphPlace selectedPlace = null;

        public LocationListElement(int requestCode) {
            super(getActivity().getResources().getDrawable(R.drawable.action_location),
                    getActivity().getResources().getString(R.string.action_location),
                    getActivity().getResources().getString(R.string.action_location_default),
                    requestCode);
        }

        @Override
        protected View.OnClickListener getOnClickListener() {
            return new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (Session.getActiveSession() != null &&
                            Session.getActiveSession().isOpened()) {
                        startPickerActivity(PickerActivity.PLACE_PICKER, getRequestCode());
                    } else {
                        activity.showSettingsFragment();
                    }
                }
            };
        }

        @Override
        protected void onActivityResult(Intent data) {
            selectedPlace = ((ScrumptiousApplication) getActivity().getApplication()).getSelectedPlace();
            setPlaceText();
            notifyDataChanged();
        }

        @Override
        protected void populateOGAction(OpenGraphAction action) {
            if (selectedPlace != null) {
                action.setPlace(selectedPlace);
            }
        }

        @Override
        protected void onSaveInstanceState(Bundle bundle) {
            if (selectedPlace != null) {
                bundle.putString(PLACE_KEY, selectedPlace.getInnerJSONObject().toString());
            }
        }

        @Override
        protected boolean restoreState(Bundle savedState) {
            String place = savedState.getString(PLACE_KEY);
            if (place != null) {
                try {
                    selectedPlace = GraphObject.Factory
                            .create(new JSONObject(place), GraphPlace.class);
                    setPlaceText();
                    return true;
                } catch (JSONException e) {
                    Log.e(TAG, "Unable to deserialize place.", e);
                }
            }
            return false;
        }

        private void setPlaceText() {
            String text = null;
            if (selectedPlace != null) {
                text = selectedPlace.getName();
            }
            if (text == null) {
                text = getResources().getString(R.string.action_location_default);
            }
            setText2(text);
        }

    }

    private class PhotoListElement extends BaseListElement {
        private static final int CAMERA = 0;
        private static final int GALLERY = 1;
        private static final String PHOTO_URI_KEY = "photo_uri";
        private static final String TEMP_URI_KEY = "temp_uri";
        private static final String FILE_PREFIX = "scrumptious_img_";
        private static final String FILE_SUFFIX = ".jpg";

        private Uri tempUri = null;

        public PhotoListElement(int requestCode) {
            super(getActivity().getResources().getDrawable(R.drawable.action_photo),
                    getActivity().getResources().getString(R.string.action_photo),
                    getActivity().getResources().getString(R.string.action_photo_default),
                    requestCode);
            photoUri = null;
        }

        @Override
        protected View.OnClickListener getOnClickListener() {
            return new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showPhotoChoice();
                }
            };
        }

        @Override
        protected void onActivityResult(Intent data) {
            if (tempUri != null) {
                photoUri = tempUri;
            } else if (data != null) {
                photoUri = data.getData();
            }
            setPhotoText();
        }

        @Override
        protected void populateOGAction(OpenGraphAction action) {
        }

        @Override
        protected void onSaveInstanceState(Bundle bundle) {
            if (photoUri != null) {
                bundle.putParcelable(PHOTO_URI_KEY, photoUri);
            }
            if (tempUri != null) {
                bundle.putParcelable(TEMP_URI_KEY, tempUri);
            }
        }

        @Override
        protected boolean restoreState(Bundle savedState) {
            photoUri = savedState.getParcelable(PHOTO_URI_KEY);
            tempUri = savedState.getParcelable(TEMP_URI_KEY);
            setPhotoText();
            return true;
        }

        private void showPhotoChoice() {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            CharSequence camera = getResources().getString(R.string.action_photo_camera);
            CharSequence gallery = getResources().getString(R.string.action_photo_gallery);
            builder.setCancelable(true).
                    setItems(new CharSequence[] {camera, gallery}, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (i == CAMERA) {
                                startCameraActivity();
                            } else if (i == GALLERY) {
                                startGalleryActivity();
                            }
                        }
                    });
            builder.show();
        }

        private void setPhotoText() {
            if (photoUri == null) {
                setText2(getResources().getString(R.string.action_photo_default));
            } else {
                setText2(getResources().getString(R.string.action_photo_ready));
            }
        }

        private void startCameraActivity() {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            tempUri = getTempUri();
            if (tempUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
            }
            startActivityForResult(intent, getRequestCode());
        }

        private void startGalleryActivity() {
            tempUri = null;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            String selectPicture = getResources().getString(R.string.select_picture);
            startActivityForResult(Intent.createChooser(intent, selectPicture), getRequestCode());
        }

        private Uri getTempUri() {
            String imgFileName = FILE_PREFIX + System.currentTimeMillis() + FILE_SUFFIX;

            // Note: on an emulator, you might need to create the "Pictures" directory in /mnt/sdcard first
            //       % adb shell
            //       % mkdir /mnt/sdcard/Pictures
            File image = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), imgFileName);
            return Uri.fromFile(image);
        }
    }

    private class ActionListAdapter extends ArrayAdapter<BaseListElement> {
        private List<BaseListElement> listElements;

        public ActionListAdapter(Context context, int resourceId, List<BaseListElement> listElements) {
            super(context, resourceId, listElements);
            this.listElements = listElements;
            for (int i = 0; i < listElements.size(); i++) {
                listElements.get(i).setAdapter(this);
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                LayoutInflater inflater =
                        (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.listitem, null);
            }

            BaseListElement listElement = listElements.get(position);
            if (listElement != null) {
                view.setOnClickListener(listElement.getOnClickListener());
                ImageView icon = (ImageView) view.findViewById(R.id.icon);
                TextView text1 = (TextView) view.findViewById(R.id.text1);
                TextView text2 = (TextView) view.findViewById(R.id.text2);
                if (icon != null) {
                    icon.setImageDrawable(listElement.getIcon());
                }
                if (text1 != null) {
                    text1.setText(listElement.getText1());
                }
                if (text2 != null) {
                    text2.setText(listElement.getText2());
                }
            }
            return view;
        }

    }
}


text:
CheckoutController.class_eval do
  private
  def after_complete_with_openbravo
    after_complete_without_openbravo
    if defined? Delayed::Job
      Openbravo::Order.delay.create(@order)
    else
      Openbravo::Order.create(@order)
    end
  end
  alias_method_chain :after_complete, :openbravo
end