text:
package com.hippo.nimingban.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.NinePatchDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.h6ah4i.android.widget.advrecyclerview.animator.GeneralItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.animator.SwipeDismissItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemAdapter;
import com.h6ah4i.android.widget.advrecyclerview.draggable.ItemDraggableRange;
import com.h6ah4i.android.widget.advrecyclerview.draggable.RecyclerViewDragDropManager;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.RecyclerViewSwipeManager;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.SwipeableItemAdapter;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.SwipeableItemConstants;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultAction;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultActionRemoveItem;
import com.h6ah4i.android.widget.advrecyclerview.touchguard.RecyclerViewTouchActionGuardManager;
import com.h6ah4i.android.widget.advrecyclerview.utils.AbstractDraggableSwipeableItemViewHolder;
import com.h6ah4i.android.widget.advrecyclerview.utils.WrapperAdapterUtils;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.effect.ViewTransition;
import com.hippo.nimingban.GuideHelper;
import com.hippo.nimingban.R;
import com.hippo.nimingban.client.NMBRequest;
import com.hippo.nimingban.client.data.Site;
import com.hippo.nimingban.dao.ACForumRaw;
import com.hippo.nimingban.util.DB;
import com.hippo.nimingban.util.ForumAutoSortingUtils;
import com.hippo.nimingban.util.Settings;
import com.hippo.text.Html;
import com.hippo.util.DrawableManager;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.ViewUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.dao.query.LazyList;

public class SortForumsActivity extends TranslucentActivity {

    public static final String KEY_SITE = "site";

    private Site mSite;

    private boolean mAutoSorting = Settings.getForumAutoSorting();

    private View mTip;
    private EasyRecyclerView mRecyclerView;
    private ViewTransition mViewTransition;

    private RecyclerView.LayoutManager mLayoutManager;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.Adapter mWrappedAdapter;
    private RecyclerViewDragDropManager mRecyclerViewDragDropManager;
    private RecyclerViewSwipeManager mRecyclerViewSwipeManager;
    private RecyclerViewTouchActionGuardManager mRecyclerViewTouchActionGuardManager;

    private boolean mNeedUpdate;

    private NMBRequest mNMBRequest;

    // TODO support other site
    private LazyList<ACForumRaw> mLazyList;
    @SuppressLint("UseSparseArrays")
    private Map<Integer, CharSequence> mForumNames = new HashMap<>();

    private boolean handlerIntent(Intent intent) {
        if (intent == null) {
            return false;
        }

        int site = intent.getIntExtra(KEY_SITE, -1);
        if (Site.isValid(site)) {
            mSite = Site.fromId(site);
            return true;
        }

        return false;
    }

    @Override
    protected int getLightThemeResId() {
        return Settings.getColorStatusBar() ? R.style.NormalActivity : R.style.NormalActivity_NoStatus;
    }

    @Override
    protected int getDarkThemeResId() {
        return Settings.getColorStatusBar() ? R.style.NormalActivity_Dark : R.style.NormalActivity_Dark_NoStatus;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!handlerIntent(getIntent())) {
            finish();
            return;
        }

        setStatusBarColor(ResourcesUtils.getAttrColor(this, R.attr.colorPrimaryDark));
        ToolbarActivityHelper.setContentView(this, R.layout.activity_forum_sort);
        setActionBarUpIndicator(DrawableManager.getDrawable(this, R.drawable.v_arrow_left_dark_x24));

        mTip = findViewById(R.id.tip);
        mRecyclerView = (EasyRecyclerView) findViewById(R.id.recycler_view);
        mViewTransition = new ViewTransition(mTip, mRecyclerView);

        // Layout Manager
        mLayoutManager = new LinearLayoutManager(this);

        // touch guard manager  (this class is required to suppress scrolling while swipe-dismiss animation is running)
        mRecyclerViewTouchActionGuardManager = new RecyclerViewTouchActionGuardManager();
        mRecyclerViewTouchActionGuardManager.setInterceptVerticalScrollingWhileAnimationRunning(true);
        mRecyclerViewTouchActionGuardManager.setEnabled(true);

        // drag & drop manager
        mRecyclerViewDragDropManager = new RecyclerViewDragDropManager();
        mRecyclerViewDragDropManager.setDraggingItemShadowDrawable(
                (NinePatchDrawable) getResources().getDrawable(R.drawable.shadow_8dp));

        // swipe manager
        mRecyclerViewSwipeManager = new RecyclerViewSwipeManager();

        mAdapter = new ForumAdapter();
        mAdapter.setHasStableIds(true);
        mWrappedAdapter = mRecyclerViewDragDropManager.createWrappedAdapter(mAdapter);      // wrap for dragging
        mWrappedAdapter = mRecyclerViewSwipeManager.createWrappedAdapter(mWrappedAdapter);      // wrap for swiping

        final GeneralItemAnimator animator = new SwipeDismissItemAnimator();

        // Change animations are enabled by default since support-v7-recyclerview v22.
        // Disable the change animation in order to make turning back animation of swiped item works properly.
        animator.setSupportsChangeAnimations(false);

        mRecyclerView.hasFixedSize();
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mWrappedAdapter);  // requires *wrapped* adapter
        mRecyclerView.setItemAnimator(animator);

        // NOTE:
        // The initialization order is very important! This order determines the priority of touch event handling.
        //
        // priority: TouchActionGuard > Swipe > DragAndDrop
        mRecyclerViewTouchActionGuardManager.attachRecyclerView(mRecyclerView);
        mRecyclerViewSwipeManager.attachRecyclerView(mRecyclerView);
        mRecyclerViewDragDropManager.attachRecyclerView(mRecyclerView);

        updateLazyList(false);

        if (Settings.getGuideSortForumsActivity()) {
            showEyeGuide();
        } else {
            // Eye guide was shown
            tryShowSecondGuide();
        }
    }

    private void showEyeGuide() {
        new GuideHelper.Builder(this)
                .setColor(ResourcesUtils.getAttrColor(this, R.attr.colorPrimary))
                .setPadding(LayoutUtils.dp2pix(this, 16))
                .setPaddingTop(LayoutUtils.dp2pix(this, 56))
                .setPaddingBottom(LayoutUtils.dp2pix(this, 56))
                .setMessagePosition(Gravity.LEFT)
                .setMessage(getString(R.string.click_eye_icon))
                .setButton(getString(R.string.get_it))
                .setBackgroundColor(0x73000000)
                .setOnDissmisListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tryShowSecondGuide();
                        Settings.putGuideSortForumsActivity(false);
                    }
                }).show();
    }

    private void tryShowSecondGuide() {
        if (Settings.getGuidePinningStar() && mAutoSorting) {
            showStarGuide();
        } else if (Settings.getGuideSortingFourBars() && !mAutoSorting) {
            showFourBarsGuide();
        }
    }

    private void showFourBarsGuide() {
        new GuideHelper.Builder(this)
                .setColor(ResourcesUtils.getAttrColor(this, R.attr.colorPrimary))
                .setPadding(LayoutUtils.dp2pix(this, 16))
                .setPaddingTop(LayoutUtils.dp2pix(this, 56))
                .setPaddingBottom(LayoutUtils.dp2pix(this, 56))
                .setMessagePosition(Gravity.RIGHT)
                .setMessage(getString(R.string.drag_four_bars_exchange))
                .setButton(getString(R.string.get_it))
                .setBackgroundColor(0x73000000)
                .setOnDissmisListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Settings.putGuideSortingFourBars(false);
                    }
                }).show();
    }

    private void showStarGuide() {
        new GuideHelper.Builder(this)
                .setColor(ResourcesUtils.getAttrColor(this, R.attr.colorPrimary))
                .setPadding(LayoutUtils.dp2pix(this, 16))
                .setPaddingTop(LayoutUtils.dp2pix(this, 56))
                .setPaddingBottom(LayoutUtils.dp2pix(this, 56))
                .setMessagePosition(Gravity.RIGHT)
                .setMessage(getString(R.string.click_star_icon_pin))
                .setButton(getString(R.string.get_it))
                .setBackgroundColor(0x73000000)
                .setOnDissmisListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Settings.putGuidePinningStar(false);
                    }
                }).show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mRecyclerViewDragDropManager != null) {
            mRecyclerViewDragDropManager.release();
            mRecyclerViewDragDropManager = null;
        }

        if (mRecyclerViewTouchActionGuardManager != null) {
            mRecyclerViewTouchActionGuardManager.release();
            mRecyclerViewTouchActionGuardManager = null;
        }

        if (mRecyclerView != null) {
            mRecyclerView.setItemAnimator(null);
            mRecyclerView.setAdapter(null);
            mRecyclerView = null;
        }

        if (mWrappedAdapter != null) {
            WrapperAdapterUtils.releaseAll(mWrappedAdapter);
            mWrappedAdapter = null;
        }
        mAdapter = null;
        mLayoutManager = null;

        if (mLazyList != null) {
            mLazyList.close();
            mForumNames.clear();
        }

        if (mNMBRequest != null) {
            mNMBRequest.cancel();
            mNMBRequest = null;
        }
    }

    @Override
    public void onBackPressed() {
        if (mNeedUpdate) {
            setResult(RESULT_OK);
        }

        super.onBackPressed();
    }

    private void updateLazyList(boolean animation) {
        LazyList<ACForumRaw> lazyList = DB.getACForumLazyList(mAutoSorting);
        if (mLazyList != null) {
            mLazyList.close();
            mForumNames.clear();
        }
        mLazyList = lazyList;

        mViewTransition.showView(mLazyList.isEmpty() ? 0 : 1, animation);
    }

    private static final int TYPE_FORUM = 0;
    private static final int TYPE_SWITCH = 1;

    private class ForumHolder extends AbstractDraggableSwipeableItemViewHolder implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

        public View swipeHandler;
        public ImageView visibility;
        public Switch autoSortingSwitch;
        public TextView forum;
        public View dragHandler;
        public ImageView pinning;

        public ForumHolder(View itemView, int viewType) {
            super(itemView);

            swipeHandler = itemView.findViewById(R.id.swipe_handler);
            visibility = (ImageView) itemView.findViewById(R.id.visibility);
            autoSortingSwitch = itemView.findViewById(R.id.auto_sorting_switch);
            forum = (TextView) itemView.findViewById(R.id.forum);
            dragHandler = itemView.findViewById(R.id.drag_handler);
            pinning = itemView.findViewById(R.id.pinning);

            if (viewType == TYPE_FORUM) {
                autoSortingSwitch.setVisibility(View.GONE);

                visibility.setOnClickListener(this);
                forum.setOnClickListener(this);
                pinning.setOnClickListener(this);

                StateListDrawable visibilityDrawable = new StateListDrawable();
                visibilityDrawable.addState(new int[]{android.R.attr.state_activated},
                        DrawableManager.getDrawable(SortForumsActivity.this, R.drawable.v_eye_on_x24));
                visibilityDrawable.addState(new int[]{},
                        DrawableManager.getDrawable(SortForumsActivity.this, R.drawable.v_eye_off_x24));
                visibility.setImageDrawable(visibilityDrawable);

                StateListDrawable pinningDrawable = new StateListDrawable();
                pinningDrawable.addState(new int[]{android.R.attr.state_activated},
                        DrawableManager.getDrawable(SortForumsActivity.this, R.drawable.v_star_x24));
                pinningDrawable.addState(new int[]{},
                        DrawableManager.getDrawable(SortForumsActivity.this, R.drawable.v_star_border_x24));
                pinning.setImageDrawable(pinningDrawable);
            } else if (viewType == TYPE_SWITCH) {
                visibility.setVisibility(View.GONE);
                dragHandler.setVisibility(View.GONE);
                pinning.setVisibility(View.GONE);

                autoSortingSwitch.setChecked(mAutoSorting);
                forum.setText(R.string.main_forum_auto_sorting);

                autoSortingSwitch.setOnCheckedChangeListener(this);
                forum.setOnClickListener(this);
            }
        }

        @Override
        public void onClick(@NonNull View v) {
            int position = getAdapterPosition();
            if (position > 0 && position <= mLazyList.size()) {
                if (visibility == v) {
                    ACForumRaw raw = mLazyList.get(position - 1);
                    DB.setACForumVisibility(raw, !raw.getVisibility());

                    // Update UI
                    visibility.setActivated(raw.getVisibility());

                    mNeedUpdate = true;
                } else if (pinning == v) {
                    List<ACForumRaw> changed = new ArrayList<>();
                    ACForumRaw clicked = mLazyList.get(position - 1);
                    boolean isClickedPinned = ForumAutoSortingUtils.isACForumPinned(clicked);

                    ACForumRaw first = mLazyList.get(0);
                    if (!isClickedPinned && ForumAutoSortingUtils.isACForumPinned(first)) {
                        // unpin the first if it's been pinned already
                        ForumAutoSortingUtils.unpinACForum(first);
                        changed.add(first);
                    }

                    if (!isClickedPinned) {
                        ForumAutoSortingUtils.pinACForum(clicked);
                    } else {
                        ForumAutoSortingUtils.unpinACForum(clicked);
                    }
                    changed.add(clicked);

                    DB.updateACForum(changed);
                    updateLazyList(false);
                    mNeedUpdate = true;

                    // don't know where the previous top will go, so update all the list
                    mAdapter.notifyDataSetChanged();
                }
            } else if (position == 0) {
                if (forum == v) {
                    autoSortingSwitch.performClick();
                }
            }
        }

        @Override
        public View getSwipeableContainerView() {
            return swipeHandler;
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (autoSortingSwitch == buttonView) {
                mAutoSorting = isChecked;
                Settings.putForumAutoSorting(isChecked);

                // update the list to sort them according to the present setting
                updateLazyList(false);
                // the list could be dramatically different so update them all
                mAdapter.notifyDataSetChanged();

                // show guide
                tryShowSecondGuide();

                mNeedUpdate = true;
            }
        }
    }

    private class ForumAdapter extends RecyclerView.Adapter<ForumHolder>
            implements DraggableItemAdapter<ForumHolder>,
            SwipeableItemAdapter<ForumHolder> {

        private static final long ID_SWITCH = -0xffL;

        @Override
        public ForumHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ForumHolder(getLayoutInflater().inflate(R.layout.item_forum_sort, parent, false), viewType);
        }

        @Override
        public void onBindViewHolder(ForumHolder holder, int position) {
            if (position > 0) {
                ACForumRaw raw = mLazyList.get(position - 1);
                holder.visibility.setActivated(raw.getVisibility());
                if (mAutoSorting) {
                    holder.dragHandler.setVisibility(View.GONE);
                    holder.pinning.setVisibility(View.VISIBLE);
                    holder.pinning.setActivated(ForumAutoSortingUtils.isACForumPinned(raw));
                } else {
                    holder.pinning.setVisibility(View.GONE);
                    holder.dragHandler.setVisibility(View.VISIBLE);
                }

                CharSequence name = mForumNames.get(position);
                if (name == null) {
                    if (raw.getDisplayname() == null) {
                        name = "Forum";
                    } else {
                        name = Html.fromHtml(raw.getDisplayname());
                    }
                    mForumNames.put(position, name);
                }
                holder.forum.setText(name);
            }
        }

        @Override
        public long getItemId(int position) {
            if (position > 0) {
                return mLazyList.get(position - 1).getId();
            } else {
                return ID_SWITCH;
            }
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0) {
                return TYPE_SWITCH;
            } else {
                return TYPE_FORUM;
            }
        }

        @Override
        public int getItemCount() {
            return mLazyList.size() + 1;
        }

        @Override
        public boolean onCheckCanStartDrag(ForumHolder holder, int position, int x, int y) {
            return position != 0 && ViewUtils.isViewUnder(holder.dragHandler, x, y, 0);
        }

        @Override
        public ItemDraggableRange onGetItemDraggableRange(ForumHolder holder, int position) {
            return new ItemDraggableRange(1, mLazyList.size());
        }

        @Override
        public void onMoveItem(int fromPosition, int toPosition) {
            if (fromPosition == toPosition) {
                return;
            }

            List<ACForumRaw> changed = new ArrayList<>(Math.abs(fromPosition - toPosition) + 1);
            if (fromPosition < toPosition) {
                for (int i = fromPosition; i <= toPosition; i++) {
                    changed.add(mLazyList.get(i - 1));
                }
            } else {
                for (int i = fromPosition; i >= toPosition; i--) {
                    changed.add(mLazyList.get(i - 1));
                }
            }

            int previousPriority = changed.get(changed.size() - 1).getPriority();
            for (ACForumRaw raw : changed) {
                int priority = raw.getPriority();
                raw.setPriority(previousPriority);
                previousPriority = priority;
            }

            DB.updateACForum(changed);
            updateLazyList(false);
            notifyItemMoved(fromPosition, toPosition);

            mNeedUpdate = true;
        }

        @Override
        public boolean onCheckCanDrop(int draggingPosition, int dropPosition) {
            return true;
        }

        @Override
        public int onGetSwipeReactionType(ForumHolder holder, int position, int x, int y) {
            if (position == 0 || mLazyList.get(position - 1).getOfficial()) {
                return SwipeableItemConstants.REACTION_CAN_NOT_SWIPE_ANY;
            } else {
                return SwipeableItemConstants.REACTION_CAN_SWIPE_BOTH_H;
            }
        }

        @Override
        public void onSetSwipeBackground(ForumHolder holder, int position, int type) {
            // Empty
        }

        @Override
        public void onSwipeItemStarted(ForumHolder holder, int position) {
            // Empty
        }

        @Override
        public SwipeResultAction onSwipeItem(ForumHolder holder, int position, int result) {
            switch (result) {
                // swipe right
                case SwipeableItemConstants.RESULT_SWIPED_RIGHT:
                case SwipeableItemConstants.RESULT_SWIPED_LEFT:
                    return new DeleteAction(position);
                case SwipeableItemConstants.RESULT_CANCELED:
                default:
                    return null;
            }
        }
    }

    private class DeleteAction extends SwipeResultActionRemoveItem {

        private int mPosition;

        public DeleteAction(int position) {
            mPosition = position;
        }

        @Override
        protected void onPerformAction() {
            super.onPerformAction();

            final int position = mPosition;
            final ACForumRaw raw = mLazyList.get(position - 1);
            if (raw != null) {
                DB.removeACForum(mLazyList.get(position - 1));
                updateLazyList(true);
                mAdapter.notifyItemRemoved(position);
                mNeedUpdate = true;
            }
        }
    }
}


text:
package payment

import (
	"database/sql"
	"fmt"
	"time"

	"github.com/fritzpay/paymentd/pkg/paymentd/payment"
	"github.com/fritzpay/paymentd/pkg/paymentd/payment_method"
	"github.com/fritzpay/paymentd/pkg/paymentd/project"
	. "github.com/smartystreets/goconvey/convey"
)

func WithPaymentInTx(tx *sql.Tx, f func(p *payment.Payment)) func() {
	return func() {
		pr := &project.Project{
			ID:          1,
			PrincipalID: 1,
		}
		method, err := payment_method.PaymentMethodByIDTx(tx, 1)
		So(err, ShouldBeNil)
		So(method.Active(), ShouldBeTrue)
		So(method.ID, ShouldNotEqual, 0)

		err = payment_method.InsertPaymentMethodStatusTx(tx, method)
		So(err, ShouldBeNil)

		p := &payment.Payment{
			Created:  time.Now(),
			Ident:    "test_" + fmt.Sprintf("%d", time.Now().UnixNano()),
			Amount:   1234,
			Subunits: 2,
			Currency: "EUR",
		}
		err = p.SetProject(pr)
		So(err, ShouldBeNil)
		p.Config.SetCountry("DE")
		p.Config.SetLocale("en-US")
		p.Config.SetPaymentMethodID(method.ID)

		err = payment.InsertPaymentTx(tx, p)
		So(err, ShouldBeNil)
		err = payment.InsertPaymentConfigTx(tx, p)
		So(err, ShouldBeNil)

		p, err = payment.PaymentByIDTx(tx, p.PaymentID())
		So(err, ShouldBeNil)

		f(p)
	}
}

redpajama_set_name: RedPajamaGithub


text:
class Clojurescript < Formula
  homepage "https://github.com/clojure/clojurescript"
  head "https://github.com/clojure/clojurescript.git"
  url "https://github.com/clojure/clojurescript/archive/r2913.tar.gz"
  sha1 "ff33a93516b3c91923667d667d34cc4b404489c8"

  bottle do
    cellar :any
    sha1 "aa8b2bd64da090c12d508e63bbf56a5128abfbcf" => :yosemite
    sha1 "f56c2dfcd8ee828a2734ea1c39c6c1f1c147178b" => :mavericks
    sha1 "63127cb547b78d3a7fac2770fe3ed56ce39acc10" => :mountain_lion
  end

  def install
    system "./script/bootstrap"
    inreplace %w[bin/cljsc script/repl script/repljs script/browser-repl],
      "#!/bin/sh", "#!/bin/sh\nCLOJURESCRIPT_HOME=#{libexec}"
    libexec.install Dir["*"]
    bin.write_exec_script libexec/"bin/cljsc"
  end

  def caveats; <<-EOS.undent
    This formula is useful if you need to use the ClojureScript compiler directly.
    For a more integrated workflow, Leiningen with lein-cljsbuild is recommended.
    EOS
  end

  test do
    (testpath/"t.cljs").write <<-EOF.undent
    (ns hello)
    (defn ^:export greet [n]
      (str "Hello " n))
    EOF

    system "#{bin}/cljsc", testpath/"t.cljs"
  end
end


text:
#ifndef OPENCV_CORE_SATURATE_HPP
#define OPENCV_CORE_SATURATE_HPP

#include "opencv2/core/cvdef.h"
#include "opencv2/core/fast_math.hpp"

namespace cv
{

//! @addtogroup core_utils
//! @{

/////////////// saturate_cast (used in image & signal processing) ///////////////////

/** @brief Template function for accurate conversion from one primitive type to another.

 The function saturate_cast resembles the standard C++ cast operations, such as static_cast\<T\>()
 and others. It perform an efficient and accurate conversion from one primitive type to another
 (see the introduction chapter). saturate in the name means that when the input value v is out of the
 range of the target type, the result is not formed just by taking low bits of the input, but instead
 the value is clipped. For example:
 @code
 uchar a = saturate_cast<uchar>(-100); // a = 0 (UCHAR_MIN)
 short b = saturate_cast<short>(33333.33333); // b = 32767 (SHRT_MAX)
 @endcode
 Such clipping is done when the target type is unsigned char , signed char , unsigned short or
 signed short . For 32-bit integers, no clipping is done.

 When the parameter is a floating-point value and the target type is an integer (8-, 16- or 32-bit),
 the floating-point value is first rounded to the nearest integer and then clipped if needed (when
 the target type is 8- or 16-bit).

 This operation is used in the simplest or most complex image processing functions in OpenCV.

 @param v Function parameter.
 @sa add, subtract, multiply, divide, Mat::convertTo
 */
template<typename _Tp> static inline _Tp saturate_cast(uchar v)    { return _Tp(v); }
/** @overload */
template<typename _Tp> static inline _Tp saturate_cast(schar v)    { return _Tp(v); }
/** @overload */
template<typename _Tp> static inline _Tp saturate_cast(ushort v)   { return _Tp(v); }
/** @overload */
template<typename _Tp> static inline _Tp saturate_cast(short v)    { return _Tp(v); }
/** @overload */
template<typename _Tp> static inline _Tp saturate_cast(unsigned v) { return _Tp(v); }
/** @overload */
template<typename _Tp> static inline _Tp saturate_cast(int v)      { return _Tp(v); }
/** @overload */
template<typename _Tp> static inline _Tp saturate_cast(float v)    { return _Tp(v); }
/** @overload */
template<typename _Tp> static inline _Tp saturate_cast(double v)   { return _Tp(v); }
/** @overload */
template<typename _Tp> static inline _Tp saturate_cast(int64 v)    { return _Tp(v); }
/** @overload */
template<typename _Tp> static inline _Tp saturate_cast(uint64 v)   { return _Tp(v); }

template<> inline uchar saturate_cast<uchar>(schar v)        { return (uchar)std::max((int)v, 0); }
template<> inline uchar saturate_cast<uchar>(ushort v)       { return (uchar)std::min((unsigned)v, (unsigned)UCHAR_MAX); }
template<> inline uchar saturate_cast<uchar>(int v)          { return (uchar)((unsigned)v <= UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); }
template<> inline uchar saturate_cast<uchar>(short v)        { return saturate_cast<uchar>((int)v); }
template<> inline uchar saturate_cast<uchar>(unsigned v)     { return (uchar)std::min(v, (unsigned)UCHAR_MAX); }
template<> inline uchar saturate_cast<uchar>(float v)        { int iv = cvRound(v); return saturate_cast<uchar>(iv); }
template<> inline uchar saturate_cast<uchar>(double v)       { int iv = cvRound(v); return saturate_cast<uchar>(iv); }
template<> inline uchar saturate_cast<uchar>(int64 v)        { return (uchar)((uint64)v <= (uint64)UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); }
template<> inline uchar saturate_cast<uchar>(uint64 v)       { return (uchar)std::min(v, (uint64)UCHAR_MAX); }

template<> inline schar saturate_cast<schar>(uchar v)        { return (schar)std::min((int)v, SCHAR_MAX); }
template<> inline schar saturate_cast<schar>(ushort v)       { return (schar)std::min((unsigned)v, (unsigned)SCHAR_MAX); }
template<> inline schar saturate_cast<schar>(int v)          { return (schar)((unsigned)(v-SCHAR_MIN) <= (unsigned)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); }
template<> inline schar saturate_cast<schar>(short v)        { return saturate_cast<schar>((int)v); }
template<> inline schar saturate_cast<schar>(unsigned v)     { return (schar)std::min(v, (unsigned)SCHAR_MAX); }
template<> inline schar saturate_cast<schar>(float v)        { int iv = cvRound(v); return saturate_cast<schar>(iv); }
template<> inline schar saturate_cast<schar>(double v)       { int iv = cvRound(v); return saturate_cast<schar>(iv); }
template<> inline schar saturate_cast<schar>(int64 v)        { return (schar)((uint64)((int64)v-SCHAR_MIN) <= (uint64)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); }
template<> inline schar saturate_cast<schar>(uint64 v)       { return (schar)std::min(v, (uint64)SCHAR_MAX); }

template<> inline ushort saturate_cast<ushort>(schar v)      { return (ushort)std::max((int)v, 0); }
template<> inline ushort saturate_cast<ushort>(short v)      { return (ushort)std::max((int)v, 0); }
template<> inline ushort saturate_cast<ushort>(int v)        { return (ushort)((unsigned)v <= (unsigned)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); }
template<> inline ushort saturate_cast<ushort>(unsigned v)   { return (ushort)std::min(v, (unsigned)USHRT_MAX); }
template<> inline ushort saturate_cast<ushort>(float v)      { int iv = cvRound(v); return saturate_cast<ushort>(iv); }
template<> inline ushort saturate_cast<ushort>(double v)     { int iv = cvRound(v); return saturate_cast<ushort>(iv); }
template<> inline ushort saturate_cast<ushort>(int64 v)      { return (ushort)((uint64)v <= (uint64)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); }
template<> inline ushort saturate_cast<ushort>(uint64 v)     { return (ushort)std::min(v, (uint64)USHRT_MAX); }

template<> inline short saturate_cast<short>(ushort v)       { return (short)std::min((int)v, SHRT_MAX); }
template<> inline short saturate_cast<short>(int v)          { return (short)((unsigned)(v - SHRT_MIN) <= (unsigned)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); }
template<> inline short saturate_cast<short>(unsigned v)     { return (short)std::min(v, (unsigned)SHRT_MAX); }
template<> inline short saturate_cast<short>(float v)        { int iv = cvRound(v); return saturate_cast<short>(iv); }
template<> inline short saturate_cast<short>(double v)       { int iv = cvRound(v); return saturate_cast<short>(iv); }
template<> inline short saturate_cast<short>(int64 v)        { return (short)((uint64)((int64)v - SHRT_MIN) <= (uint64)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); }
template<> inline short saturate_cast<short>(uint64 v)       { return (short)std::min(v, (uint64)SHRT_MAX); }

template<> inline int saturate_cast<int>(unsigned v)         { return (int)std::min(v, (unsigned)INT_MAX); }
template<> inline int saturate_cast<int>(int64 v)            { return (int)((uint64)(v - INT_MIN) <= (uint64)UINT_MAX ? v : v > 0 ? INT_MAX : INT_MIN); }
template<> inline int saturate_cast<int>(uint64 v)           { return (int)std::min(v, (uint64)INT_MAX); }
template<> inline int saturate_cast<int>(float v)            { return cvRound(v); }
template<> inline int saturate_cast<int>(double v)           { return cvRound(v); }

template<> inline unsigned saturate_cast<unsigned>(schar v)  { return (unsigned)std::max(v, (schar)0); }
template<> inline unsigned saturate_cast<unsigned>(short v)  { return (unsigned)std::max(v, (short)0); }
template<> inline unsigned saturate_cast<unsigned>(int v)    { return (unsigned)std::max(v, (int)0); }
template<> inline unsigned saturate_cast<unsigned>(int64 v)  { return (unsigned)((uint64)v <= (uint64)UINT_MAX ? v : v > 0 ? UINT_MAX : 0); }
template<> inline unsigned saturate_cast<unsigned>(uint64 v) { return (unsigned)std::min(v, (uint64)UINT_MAX); }
// we intentionally do not clip negative numbers, to make -1 become 0xffffffff etc.
template<> inline unsigned saturate_cast<unsigned>(float v)  { return static_cast<unsigned>(cvRound(v)); }
template<> inline unsigned saturate_cast<unsigned>(double v) { return static_cast<unsigned>(cvRound(v)); }

template<> inline uint64 saturate_cast<uint64>(schar v)      { return (uint64)std::max(v, (schar)0); }
template<> inline uint64 saturate_cast<uint64>(short v)      { return (uint64)std::max(v, (short)0); }
template<> inline uint64 saturate_cast<uint64>(int v)        { return (uint64)std::max(v, (int)0); }
template<> inline uint64 saturate_cast<uint64>(int64 v)      { return (uint64)std::max(v, (int64)0); }

template<> inline int64 saturate_cast<int64>(uint64 v)       { return (int64)std::min(v, (uint64)LLONG_MAX); }

/** @overload */
template<typename _Tp> static inline _Tp saturate_cast(float16_t v) { return saturate_cast<_Tp>((float)v); }

// in theory, we could use a LUT for 8u/8s->16f conversion,
// but with hardware support for FP32->FP16 conversion the current approach is preferable
template<> inline float16_t saturate_cast<float16_t>(uchar v)   { return float16_t((float)v); }
template<> inline float16_t saturate_cast<float16_t>(schar v)   { return float16_t((float)v); }
template<> inline float16_t saturate_cast<float16_t>(ushort v)  { return float16_t((float)v); }
template<> inline float16_t saturate_cast<float16_t>(short v)   { return float16_t((float)v); }
template<> inline float16_t saturate_cast<float16_t>(unsigned v){ return float16_t((float)v); }
template<> inline float16_t saturate_cast<float16_t>(int v)     { return float16_t((float)v); }
template<> inline float16_t saturate_cast<float16_t>(uint64 v)  { return float16_t((float)v); }
template<> inline float16_t saturate_cast<float16_t>(int64 v)   { return float16_t((float)v); }
template<> inline float16_t saturate_cast<float16_t>(float v)   { return float16_t(v); }
template<> inline float16_t saturate_cast<float16_t>(double v)  { return float16_t((float)v); }

//! @}

} // cv

#endif // OPENCV_CORE_SATURATE_HPP


text:
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <stdbool.h>
#include <stdlib.h>

#include "format.h"
#include "c-ctype.h"
#include "xalloc.h"
#include "xvasprintf.h"
#include "gettext.h"

#define _(str) gettext (str)

/* C# format strings are described in the description of the .NET System.String
   class and implemented in
     pnetlib-0.5.6/runtime/System/String.cs
   and
     mcs-0.28/class/corlib/System/String.cs
   A format string consists of literal text (that is output verbatim), doubled
   braces ('{{' and '}}', that lead to a single brace when output), and
   directives.
   A directive
   - starts with '{',
   - is followed by a nonnegative integer m,
   - is optionally followed by ',' and an integer denoting a width,
   - is optionally followed by ':' and a sequence of format specifiers.
     (But the interpretation of the format specifiers is up to the IFormattable
     implementation, depending on the argument's runtime value. New classes
     implementing IFormattable can be defined by the user.)
   - is finished with '}'.
 */

struct spec
{
  unsigned int directives;
  unsigned int numbered_arg_count;
};

static void *
format_parse (const char *format, bool translated, char *fdi,
              char **invalid_reason)
{
  const char *const format_start = format;
  struct spec spec;
  struct spec *result;

  spec.directives = 0;
  spec.numbered_arg_count = 0;

  for (; *format != '\0';)
    {
      char c = *format++;

      if (c == '{')
        {
          FDI_SET (format - 1, FMTDIR_START);
          if (*format == '{')
            format++;
          else
            {
              /* A directive.  */
              unsigned int number;

              spec.directives++;

              if (!c_isdigit (*format))
                {
                  *invalid_reason =
                    xasprintf (_("In the directive number %u, '{' is not followed by an argument number."), spec.directives);
                  FDI_SET (*format == '\0' ? format - 1 : format, FMTDIR_ERROR);
                  return NULL;
                }
              number = 0;
              do
                {
                  number = 10 * number + (*format - '0');
                  format++;
                }
              while (c_isdigit (*format));

              if (*format == ',')
                {
                  /* Parse width.  */
                  format++;
                  if (*format == '-')
                    format++;
                  if (!c_isdigit (*format))
                    {
                      *invalid_reason =
                        xasprintf (_("In the directive number %u, ',' is not followed by a number."), spec.directives);
                      FDI_SET (*format == '\0' ? format - 1 : format,
                               FMTDIR_ERROR);
                      return NULL;
                    }
                  do
                    format++;
                  while (c_isdigit (*format));
                }

              if (*format == ':')
                {
                  /* Parse format specifiers.  */
                  do
                    format++;
                  while (*format != '\0' && *format != '}');
                }

              if (*format == '\0')
                {
                  *invalid_reason =
                    xstrdup (_("The string ends in the middle of a directive: found '{' without matching '}'."));
                  FDI_SET (format - 1, FMTDIR_ERROR);
                  return NULL;
                }

              if (*format != '}')
                {
                  *invalid_reason =
                    (c_isprint (*format)
                     ? xasprintf (_("The directive number %u ends with an invalid character '%c' instead of '}'."), spec.directives, *format)
                     : xasprintf (_("The directive number %u ends with an invalid character instead of '}'."), spec.directives));
                  FDI_SET (format, FMTDIR_ERROR);
                  return NULL;
                }

              format++;

              if (spec.numbered_arg_count <= number)
                spec.numbered_arg_count = number + 1;
            }
          FDI_SET (format - 1, FMTDIR_END);
        }
      else if (c == '}')
        {
          FDI_SET (format - 1, FMTDIR_START);
          if (*format == '}')
            format++;
          else
            {
              *invalid_reason =
                (spec.directives == 0
                 ? xstrdup (_("The string starts in the middle of a directive: found '}' without matching '{'."))
                 : xasprintf (_("The string contains a lone '}' after directive number %u."), spec.directives));
              FDI_SET (*format == '\0' ? format - 1 : format, FMTDIR_ERROR);
              return NULL;
            }
          FDI_SET (format - 1, FMTDIR_END);
        }
    }

  result = XMALLOC (struct spec);
  *result = spec;
  return result;
}

static void
format_free (void *descr)
{
  struct spec *spec = (struct spec *) descr;

  free (spec);
}

static int
format_get_number_of_directives (void *descr)
{
  struct spec *spec = (struct spec *) descr;

  return spec->directives;
}

static bool
format_check (void *msgid_descr, void *msgstr_descr, bool equality,
              formatstring_error_logger_t error_logger,
              const char *pretty_msgid, const char *pretty_msgstr)
{
  struct spec *spec1 = (struct spec *) msgid_descr;
  struct spec *spec2 = (struct spec *) msgstr_descr;
  bool err = false;

  /* Check that the argument counts are the same.  */
  if (equality
      ? spec1->numbered_arg_count != spec2->numbered_arg_count
      : spec1->numbered_arg_count < spec2->numbered_arg_count)
    {
      if (error_logger)
        error_logger (_("number of format specifications in '%s' and '%s' does not match"),
                      pretty_msgid, pretty_msgstr);
      err = true;
    }

  return err;
}

struct formatstring_parser formatstring_csharp =
{
  format_parse,
  format_free,
  format_get_number_of_directives,
  NULL,
  format_check
};

#ifdef TEST

/* Test program: Print the argument list specification returned by
   format_parse for strings read from standard input.  */

#include <stdio.h>

static void
format_print (void *descr)
{
  struct spec *spec = (struct spec *) descr;
  unsigned int i;

  if (spec == NULL)
    {
      printf ("INVALID");
      return;
    }

  printf ("(");
  for (i = 0; i < spec->numbered_arg_count; i++)
    {
      if (i > 0)
        printf (" ");
      printf ("*");
    }
  printf (")");
}

int
main ()
{
  for (;;)
    {
      char *line = NULL;
      size_t line_size = 0;
      int line_len;
      char *invalid_reason;
      void *descr;

      line_len = getline (&line, &line_size, stdin);
      if (line_len < 0)
        break;
      if (line_len > 0 && line[line_len - 1] == '\n')
        line[--line_len] = '\0';

      invalid_reason = NULL;
      descr = format_parse (line, false, NULL, &invalid_reason);

      format_print (descr);
      printf ("\n");
      if (descr == NULL)
        printf ("%s\n", invalid_reason);

      free (invalid_reason);
      free (line);
    }

  return 0;
}

/*
 * For Emacs M-x compile
 * Local Variables:
 * compile-command: "/bin/sh ../libtool --tag=CC --mode=link gcc -o a.out -static -O -g -Wall -I.. -I../gnulib-lib -I../intl -DHAVE_CONFIG_H -DTEST format-csharp.c ../gnulib-lib/libgettextlib.la"
 * End:
 */

#endif /* TEST */


text:
<?php

// Copyright (c) Lellys Informática. All rights reserved. See License.txt in the project root for license information.
namespace Collections;

use BadFunctionCallException;

/**
 * Provides functionality to evaluate queries against a specific data source wherein the type of the data
 * is not specified.
 */
interface StackInterface
{

    /**
     * Inserts an object at the top of the Stack.
     * @param mixed $item The Object to push onto the Stack. The value can be null.
     * @return Stack
     */
    public function push($item);

    /**
     * Inserts multiples objects at the top of the Stack.
     * @param  CollectionInterface|array $items The Objects to push onto the Stack. The value can be null.
     * @return Stack
     */
    public function pushMultiple($items);

    /**
     * Removes and returns the object at the top of the Stack.
     * @return mixed The Object removed from the top of the Stack.
     * @throws BadFunctionCallException
     */
    public function pop();
}


text:
{% extends "base.html" %}

{% block content %}

    Edit Entry

<form role="form" method="POST">

        Content (delete and repost your entry if you posted the wrong time)
        <textarea class="form-control" id="content" name="content" placeholder="Entry content" rows="5" required>{{entry.content|striptags}}</textarea>

    <button type="submit" class="btn btn-primary btn-md">Submit</button>
    <button type="submit" class="btn btn-primary btn-md"  name="cancel">Cancel</button>

</form>
{% endblock %}


text:
package com.conversantmedia.util.concurrent;

/*
 * #%L
 * Conversant Disruptor
 * ~~
 * Conversantmedia.com © 2016, Conversant, Inc. Conversant® is a trademark of Conversant, Inc.
 * ~~
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import org.junit.*;

import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author John Cairns <jcairns@dotomi.com>
 *         Date: 4//25/12
 *         Time: 3:27 PM
 */
public class DisruptorBlockingQueueTest {

    final static boolean ALLOW_LONG_RUN = false;

    private ThreadPoolExecutor executor;

    @Before
    public void setup() {
        executor = new ThreadPoolExecutor(5, 5, 1, TimeUnit.MINUTES, new DisruptorBlockingQueue<>(1024));
    }

    @After
    public void teardown() {
        executor.shutdown();
    }

    @Test
    public void testAsSynchronousQueue() {
        final int cap = 1;
        BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);
        while(dbq.offer(Integer.valueOf(0)));

        Assert.assertFalse(dbq.offer(Integer.valueOf(10)));

        Assert.assertEquals(1, dbq.size());

        Assert.assertEquals(Integer.valueOf(0), dbq.poll());
    }

    @Test
    public void testDisruptorBlockingQueueTestC1() {
        final int cap = 10;
        BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);
        while(dbq.offer(Integer.valueOf(0)));
        Assert.assertEquals(16, dbq.size());
    }

    @Test
    public void testDisruptorBlockingQueueTestC2() {

        final int cap = 50;

        Set<Integer> x = new HashSet<Integer>(cap);
        for(int i=0; i<2*cap; i++) {
            x.add(Integer.valueOf(i));
        }

        BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap, x);
        // next power of two
        Assert.assertEquals(64, dbq.size());
    }

    @Test
    public void testOffer() {

        final int cap = 16;
        BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);
        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
        }

        Assert.assertFalse(dbq.offer(Integer.valueOf(cap)));

        for(int i=0; i<cap; i++) {
            Assert.assertEquals(Integer.valueOf(i), dbq.poll());
        }

    }

    @Test
    public void offerTooManyTest() {
        final DisruptorBlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(8);

        for(int i=0; i<16; i++) {
            dbq.offer(i);
        }

        Assert.assertEquals(dbq.capacity(), dbq.size());
    }

    @Test
    public void remove() {

        final int cap = 10;
        BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);
        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
        }

        Integer i = dbq.peek();
        Integer x = dbq.remove();

        Assert.assertEquals(i, x);
        Assert.assertEquals(i, Integer.valueOf(0));
        Assert.assertFalse(i.equals(dbq.peek()));
    }

    @Test
    public void testPoll() {
        final int cap = 10;
        BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        Assert.assertNull(dbq.poll());

        dbq.offer(Integer.valueOf(1));
        dbq.offer(Integer.valueOf(2));
        Assert.assertEquals(dbq.poll(), Integer.valueOf(1));
        Assert.assertEquals(dbq.poll(), Integer.valueOf(2));

        Assert.assertNull(dbq.poll());
    }

    @Test
    public void inOutIn() {
        final int cap = 8;
        BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<>(cap);

        Assert.assertNull(dbq.poll());

        for(int i=0; i<10; i++) {
            for(int j=0; j<cap; j++) {
                dbq.offer(j);
            }

            Assert.assertFalse(dbq.offer(1000));

            for(int j=0; j<cap; j++) {
                Assert.assertEquals(Integer.valueOf(j), dbq.poll());
            }

            Assert.assertNull(dbq.poll());
        }
    }

    @Test
    public void testElement() {
        final int cap = 10;
        BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        try {
            dbq.element();
            Assert.fail();
        } catch(NoSuchElementException ex) {
            // expected
        }
    }

    @Test
    public void testPeek() {
        final int cap = 10;
        BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        try {

            Assert.assertNull(dbq.peek());

        } catch(NoSuchElementException nsex) {
            Assert.fail();
        }

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
            Assert.assertEquals(Integer.valueOf(0), dbq.peek());
        }

        for(int i=0; i<cap; i++) {
            Assert.assertEquals(Integer.valueOf(i), dbq.peek());
            dbq.poll(); // count up values checking peeks
        }
    }

    @Test
    public void testPut() throws InterruptedException {

        final int cap = 10;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
        }

        executor.execute(() -> {
            try {
                Thread.sleep(1000);
                // after a second remove one
                dbq.poll();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // in main thread add one
        // this operation must wait for thread
        dbq.put(Integer.valueOf(cap));

        boolean hasValCap = false;
        while(!dbq.isEmpty()) {
            if(dbq.poll().equals(Integer.valueOf(cap)))
                hasValCap = true;
        }
        Assert.assertTrue(hasValCap);

    }

    @Ignore // FIXME - this test flickers in parallel test runner
    public void testTimeOffer() throws InterruptedException {

        final int cap = 16;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
        }

        executor.execute(() -> {
            try {
                Thread.sleep(1500);
                // after a second remove one
                dbq.poll();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // expect to fail for only 50 ms
        Assert.assertFalse(dbq.offer(Integer.valueOf(cap), 50, TimeUnit.MILLISECONDS));

        Assert.assertTrue(dbq.offer(Integer.valueOf(cap), 16550, TimeUnit.MILLISECONDS));

        boolean hasValCap = false;
        while(!dbq.isEmpty()) {
            if(dbq.poll().equals(Integer.valueOf(cap)))
                hasValCap = true;
        }
        Assert.assertTrue(hasValCap);
    }

    @Ignore // timing test not suitable for build
    public void pollTimeIsAccurate() throws InterruptedException {
        final DisruptorBlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(256);

        final long startTime = System.nanoTime();

        for(int i=0; i<50; i++) {
            dbq.poll(100, TimeUnit.MICROSECONDS);
        }

        final long runTime = System.nanoTime()- startTime;

        final long expTime = 50*100*1000;
        Assert.assertTrue(runTime >= expTime/2);

        Assert.assertTrue(runTime <= expTime*2);
    }

    @Ignore // timing test are not suitable for build
    public void offerTimeIsAccurate() throws InterruptedException {
        final DisruptorBlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(256);

        for(int i=0; i<256; i++) {
            dbq.offer(1);
        }

        final long startTime = System.nanoTime();

        for(int i=0; i<50; i++) {
            dbq.offer(1, 100, TimeUnit.MICROSECONDS);
        }

        final long runTime = System.nanoTime()- startTime;

        final long expTime = 50*100*1000;
        Assert.assertTrue(runTime >= expTime/2);
        Assert.assertTrue(runTime <= expTime*2);

    }

    @Test
    public void testTake() throws InterruptedException {

        final int cap = 10;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        executor.execute(() -> {
            try {
                Thread.sleep(1000);
                // after a second remove one
                dbq.offer(Integer.valueOf(cap));
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // wait for value to be added
        Assert.assertEquals(Integer.valueOf(cap), dbq.take());
    }

    @Test
    public void testTimePoll() throws InterruptedException {
        final int cap = 10;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        executor.execute(() -> {
            try {
                Thread.sleep(1000);
                // after a second remove one
                dbq.offer(Integer.valueOf(cap));
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // wait for value to be added
        Assert.assertNull(dbq.poll(50, TimeUnit.MICROSECONDS));
        Assert.assertEquals(Integer.valueOf(cap),dbq.poll(50, TimeUnit.SECONDS) );
    }

    @Test
    public void testRemainingCapacity() {
        final int cap = 128;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {
            Assert.assertEquals(cap-i, dbq.remainingCapacity());
            dbq.offer(Integer.valueOf(i));
        }

    }

    @Test
    public void testDrainToC() {
        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
        }

        final List<Integer> c= new LinkedList();
        Assert.assertEquals(dbq.drainTo(c), cap);
        int i=0;
        for(final Integer a : c) {
            Assert.assertEquals(a, Integer.valueOf(i++));
        }

    }

    @Test
    public void drainToToCMax() {

        final int cap = 100;
        final int max = 75;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
        }

        final List<Integer> c= new LinkedList();
        Assert.assertEquals(dbq.drainTo(c, max), max);
        Assert.assertEquals(c.size(), max);
        int i=0;
        for(final Integer a : c) {
            Assert.assertEquals(a, Integer.valueOf(i++));
        }
    }

    @Test
    public void testSize() {
        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        Assert.assertEquals(0, dbq.size());

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
            Assert.assertEquals(i+1, dbq.size());
        }

        Assert.assertEquals(cap, dbq.size());

        for(int i=0; i<cap; i++) {
            Assert.assertEquals(dbq.size(), cap-i);
            dbq.poll();
        }

        Assert.assertEquals(0, dbq.size());

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
            Assert.assertEquals(i+1, dbq.size());
        }

        Assert.assertEquals(cap, dbq.size());

        for(int i=0; i<cap; i++) {
            Assert.assertEquals(dbq.size(), cap-i);
            dbq.poll();
        }

    }

    @Test
    public void testIsEmpty() {
        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        Assert.assertTrue(dbq.isEmpty());

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
            Assert.assertFalse(dbq.isEmpty());
        }

        for(int i=0; i<cap; i++) {
            Assert.assertFalse(dbq.isEmpty());
            dbq.poll();
        }

        Assert.assertTrue(dbq.isEmpty());

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
            Assert.assertFalse(dbq.isEmpty());
        }

        for(int i=0; i<cap; i++) {
            Assert.assertFalse(dbq.isEmpty());
            dbq.poll();
        }

        Assert.assertTrue(dbq.isEmpty());
    }

    @Test
    public void testContains() {

        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {
            Assert.assertFalse(dbq.contains(Integer.valueOf(i)));
        }

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
        }

        for(int i=0; i<cap; i++) {
            Assert.assertTrue(dbq.contains(Integer.valueOf(i)));
        }

        for(int i=cap; i<2*cap; i++) {
            Assert.assertFalse(dbq.contains(Integer.valueOf(i)));
        }
    }

    @Test
    public void testToArray() {

        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {

            Assert.assertTrue(dbq.offer(Integer.valueOf(i)));
        }

        Object[] objArray = dbq.toArray();
        for(int i=0; i<cap; i++) {
            Assert.assertEquals(objArray[i], Integer.valueOf(i));
        }

    }

    @Test
    public void testAdd() {
        final int cap = 16;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {

            dbq.add(Integer.valueOf(i));
        }

        try {
            dbq.add(Integer.valueOf(cap));
            Assert.fail();
        } catch(IllegalStateException ex) {
            // expected;
        }
    }

    @Test
    public void testRemoveObj() {
        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {

            dbq.offer(Integer.valueOf(i));
        }

        for(int i=0; i<cap; i+=2) {
            dbq.remove(Integer.valueOf(i));
        }

        Assert.assertEquals(dbq.size(), cap/2);

        for(int i=1; i<cap; i+=2) {
            Assert.assertEquals(Integer.valueOf(i), dbq.poll());
        }
    }

    @Test
    public void testRemoveObjDups() {
        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {
            // all just zeros and ones
            dbq.offer(Integer.valueOf(i&1));
        }

        // nothing removed
        dbq.remove(Integer.valueOf(777));

        Assert.assertEquals(dbq.size(), cap);

        dbq.remove(Integer.valueOf(1));

        Assert.assertEquals(dbq.size(), cap/2);

        for(int i=1; i<cap; i+=2) {
            Assert.assertEquals(Integer.valueOf(0), dbq.poll());
        }
    }

    @Test
    public void testContainsAll() {

        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {

            dbq.offer(Integer.valueOf(i));
        }

        Set<Integer> si = new HashSet(10);
        for(int i=0; i<cap/10; i++) {
            si.add(Integer.valueOf(i));
        }
        Assert.assertTrue(dbq.containsAll(si));

        si.add(Integer.valueOf(-1));
        Assert.assertFalse(dbq.containsAll(si));
        si.remove(-1);
        dbq.clear();
        Assert.assertFalse(dbq.containsAll(si));
    }

    @Test
    public void testAddAll() {

        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        Set<Integer> si = new HashSet(cap);
        for(int i=0; i<cap/10; i++) {
            si.add(Integer.valueOf(i));
        }
        dbq.addAll(si);
        Assert.assertTrue(dbq.containsAll(si));

        Set<Integer> ni = new HashSet(cap);
        for(int i=0; i<cap/10; i++) {
            ni.add(Integer.valueOf(-i));
        }
        dbq.addAll(ni);
        Assert.assertTrue(dbq.containsAll(si));
        Assert.assertTrue(dbq.containsAll(ni));

        for(int i=2*cap/10; i<2*cap; i++) {
            si.add(Integer.valueOf(i));
        }
        dbq.addAll(si);
        Assert.assertEquals(dbq.size(), 128);
    }

    @Test
    public void testAddAllReturnTrue() {

        final int cap = 8;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        final Set<Integer> set = new HashSet();

        for(int i=0; i<8; i++) {
            set.add(i);
        }

        Assert.assertTrue(dbq.addAll(set));

        Integer iVal = dbq.poll();
        while(iVal != null) {
            Assert.assertTrue(set.contains(iVal));
            iVal = dbq.poll();
        }

        for(int i=0; i<20; i++) {
            set.add(i);
        }

        // at least one will fail
        Assert.assertTrue(dbq.addAll(set));
    }

    @Test
    public void testRemoveAll() {

        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        Set<Integer> si = new HashSet(cap);
        for(int i=0; i<cap/10; i++) {
            si.add(Integer.valueOf(i));
        }

        dbq.addAll(si);
        Assert.assertTrue(dbq.containsAll(si));

        Set<Integer> ni = new HashSet(cap);
        for(int i=1; i<cap/10; i++) {
            ni.add(Integer.valueOf(-i));
        }

        dbq.addAll(ni);
        Assert.assertTrue(dbq.containsAll(si));
        Assert.assertTrue(dbq.containsAll(ni));

        Assert.assertTrue(dbq.removeAll(si));
        Assert.assertTrue(dbq.containsAll(ni));
        Assert.assertFalse(dbq.containsAll(si));

        Assert.assertTrue(dbq.removeAll(ni));
        Assert.assertFalse(dbq.containsAll(ni));
        Assert.assertFalse(dbq.containsAll(si));
    }

    @Test
    public void testRetainAll() {

        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        Set<Integer> removedEle = new HashSet<>(cap);
        for(int i=0; i<cap; i++) {
            final Integer iVal = Integer.valueOf(i);
            dbq.offer(iVal);
            removedEle.add(iVal);
        }

        Set<Integer> si = new HashSet(cap);
        for(int i=0; i<cap/10; i++) {
            final Integer iVal = Integer.valueOf(i);
            si.add(iVal);
            removedEle.remove(iVal);
        }

        Assert.assertTrue(dbq.retainAll(si));

        Assert.assertEquals(cap/10, dbq.size());

        Assert.assertTrue(dbq.containsAll(si));

        for(final Integer i : removedEle) {
            Assert.assertFalse(dbq.contains(i));
        }
    }

    @Test
    public void testRemoveAll_with_empty_Collection_returns_false_with_no_exception() {

        final int cap = 8;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<>(cap);

        final Set<Integer> set = new HashSet();

        for(int i=0; i<cap; i++) {
            set.add(i);
        }

        dbq.addAll(set);

        Assert.assertFalse(dbq.removeAll(Collections.emptySet()));
        Assert.assertEquals(cap, dbq.size());
    }

    @Test
    public void testRetainAll_with_equal_Collection_returns_false_with_no_exception() {
        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<>(cap);
        Set<Integer> si = new HashSet(cap);

        for(int i=0; i<cap; i++) {
            si.add(Integer.valueOf(i));
            dbq.offer(Integer.valueOf(i));
        }

        Assert.assertFalse(dbq.retainAll(si));
        Assert.assertEquals(cap, dbq.size());
    }

    @Test
    public void testClear() {
        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
        }

        Set<Integer> si = new HashSet(cap);
        for(int i=0; i<cap/10; i++) {
            si.add(Integer.valueOf(i));
        }

        Assert.assertTrue(dbq.containsAll(si));
        dbq.clear();
        Assert.assertFalse(dbq.containsAll(si));
        Assert.assertEquals(0, dbq.size());
        Assert.assertTrue(dbq.isEmpty());
        Assert.assertNull(dbq.poll());
    }

    @Test
    public void testIterator() {
        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
        }

        int i=0;
        for(final Integer c : dbq) {
            Assert.assertEquals(Integer.valueOf(i++), c);
        }
    }

    @Test
    public void testTypeToArray() {
        final int cap = 100;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

        for(int i=0; i<cap; i++) {
            dbq.offer(Integer.valueOf(i));
        }

        Integer[] t = new Integer[cap];
        dbq.toArray(t);
        for(int i=0; i<cap; i++) {
            Assert.assertEquals(Integer.valueOf(i), t[i]);
        }
    }

    @Test
    public void textIntMaxValue() {

        // the blocking queue depends on sequence numbers that are integers
        // be sure the blocking queue operates normally over
        // a range spanning integer values

        if(ALLOW_LONG_RUN) {
            final int cap = 3;
            final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(cap);

            long  nIter = 0;

            for(int i=0; i<Integer.MAX_VALUE; i++) {

                for(int a=0; a<cap; a++) {
                    Assert.assertEquals(dbq.size(), a);
                    dbq.offer(Integer.valueOf(a));
                    nIter++;
                }

                for(int a=0; a<cap; a++) {
                    Assert.assertEquals(dbq.size(), cap-a);
                    Assert.assertEquals("At i="+i, dbq.poll(),Integer.valueOf(a));
                }

                if(nIter % Integer.MAX_VALUE == 0) System.out.println(nIter+"times MAX_VALUE");

            }
        } else {
            System.out.println("max value test not executed");
        }
    }

    @Ignore // FIXME - Spurious failures
    public void testSequentialFeed() throws InterruptedException {

        final int feedCount = 8192;
        final BlockingQueue<Integer> dbq = new DisruptorBlockingQueue<Integer>(128);
        final AtomicInteger nFed = new AtomicInteger(0);
        final AtomicInteger nRead = new AtomicInteger(0);

        final int nFeeders = 128;

        for(int i=0; i<nFeeders; i++) {
            new Thread(){
                @Override
                public void run() {
                    try {
                        for(int i = 0; i<feedCount/nFeeders; i++) {
                            while(!dbq.offer(i, 50L, TimeUnit.MICROSECONDS)) yield();
                            nFed.incrementAndGet();
                        }
                    } catch(InterruptedException ex) {

                    }
                }
            }.start();
        }

        final int nReaders = 64;
        Thread[] t = new Thread[nReaders];
        for(int i=0; i<nReaders; i++) {
            t[i]=new Thread(){
                @Override
                public void run() {
                    try {
                        while(nRead.get()<feedCount) {
                            Integer r;
                            do {
                                r = dbq.poll(50, TimeUnit.MILLISECONDS);
                                if(r == null) yield();
                            } while((r == null) && (nRead.get()<feedCount));
                            if(r != null) {
                                // we can't control which thread will return
                                // first, but the expected still must be within
                                // the number of threads range
                                Assert.assertTrue(r.intValue()<=nRead.get()+nReaders+1);
                                nRead.incrementAndGet();
                            }
                        }
                    } catch(InterruptedException ex) {

                    }
                }
            };
            t[i].start();
        }
        for(int i=0;i<nReaders;i++)
            t[i].join();

        Assert.assertEquals(nFed.get(), nRead.get());

    }
}


text:
@implementation ChallengeItem

+ (instancetype)challengeItemWithKey:(NSString *)key andPosition:(CGPoint)position
{
  ChallengeItem *item = [[ChallengeItem alloc] init];
  item.obstacleKey = key;
  item.position = position;
  return item;
}

@end

@interface ChallengeProvider()
@property (nonatomic) NSMutableArray *challenges;
@end

@implementation ChallengeProvider

+ (instancetype)getProvider
{
  static ChallengeProvider *sharedInstance = nil;
  @synchronized(self) {
    if (!sharedInstance) {
      sharedInstance = [[ChallengeProvider alloc] init];
      [sharedInstance loadChallenges];
    }
    return sharedInstance;
  }
}

- (NSArray *)getRandomChallenge
{
  return self.challenges[arc4random_uniform((uint)self.challenges.count)];
}

- (void)loadChallenges
{
  self.challenges = [NSMutableArray array];

  // Challenge 1
  NSMutableArray *challenge = [NSMutableArray array];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyMountainUp andPosition:CGPointMake(0, 105)]];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyMountainDown andPosition:CGPointMake(143, 250)]];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyCollectableStar andPosition:CGPointMake(23, 290)]];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyCollectableStar andPosition:CGPointMake(128, 50)]];
  [self.challenges addObject:challenge];

  // Challenge 2
  challenge = [NSMutableArray array];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyMountainUp andPosition:CGPointMake(90, 25)]];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyMountainDownAlternate andPosition:CGPointMake(0, 232)]];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyCollectableStar andPosition:CGPointMake(100, 243)]];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyCollectableStar andPosition:CGPointMake(152, 205)]];
  [self.challenges addObject:challenge];

  // Challenge 3
  challenge = [NSMutableArray array];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyMountainUp andPosition:CGPointMake(0, 82)]];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyMountainUpAlternate andPosition:CGPointMake(122, 0)]];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyMountainDown andPosition:CGPointMake(85, 320)]];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyCollectableStar andPosition:CGPointMake(10, 213)]];
  [challenge addObject:[ChallengeItem challengeItemWithKey:kKeyCollectableStar andPosition:CGPointMake(81, 116)]];
  [self.challenges addObject:challenge];
}

@end


text:
'use strict';

var React = require('React');
var ReactDOM = require('ReactDOM');
var ReactTestUtils = require('ReactTestUtils');
var div = React.createFactory('div');

describe('ReactDOM', function() {
  // TODO: uncomment this test once we can run in phantom, which
  // supports real submit events.
  /*
  it('should bubble onSubmit', function() {
    var count = 0;
    var form;
    var Parent = React.createClass({
      handleSubmit: function() {
        count++;
        return false;
      },
      render: function() {
        return <Child />;
      }
    });
    var Child = React.createClass({
      render: function() {
        return <form><input type="submit" value="Submit" /></form>;
      },
      componentDidMount: function() {
        form = ReactDOM.findDOMNode(this);
      }
    });
    var instance = ReactTestUtils.renderIntoDocument(<Parent />);
    form.submit();
    expect(count).toEqual(1);
  });
  */

  it('allows a DOM element to be used with a string', function() {
    var element = React.createElement('div', {className: 'foo'});
    var instance = ReactTestUtils.renderIntoDocument(element);
    expect(ReactDOM.findDOMNode(instance).tagName).toBe('DIV');
  });

  it('should allow children to be passed as an argument', function() {
    var argDiv = ReactTestUtils.renderIntoDocument(
      div(null, 'child')
    );
    var argNode = ReactDOM.findDOMNode(argDiv);
    expect(argNode.innerHTML).toBe('child');
  });

  it('should overwrite props.children with children argument', function() {
    var conflictDiv = ReactTestUtils.renderIntoDocument(
      div({children: 'fakechild'}, 'child')
    );
    var conflictNode = ReactDOM.findDOMNode(conflictDiv);
    expect(conflictNode.innerHTML).toBe('child');
  });

  /**
   * We need to make sure that updates occur to the actual node that's in the
   * DOM, instead of a stale cache.
   */
  it('should purge the DOM cache when removing nodes', function() {
    var myDiv = ReactTestUtils.renderIntoDocument(

,

    );
    // Warm the cache with theDog
    myDiv = ReactTestUtils.renderIntoDocument(

,

,

    );
    // Remove theDog - this should purge the cache
    myDiv = ReactTestUtils.renderIntoDocument(

,

    );
    // Now, put theDog back. It's now a different DOM node.
    myDiv = ReactTestUtils.renderIntoDocument(

,

,

    );
    // Change the className of theDog. It will use the same element
    myDiv = ReactTestUtils.renderIntoDocument(

,

,

    );
    var root = ReactDOM.findDOMNode(myDiv);
    var dog = root.childNodes[0];
    expect(dog.className).toBe('bigdog');
  });

  it('allow React.DOM factories to be called without warnings', function() {
    spyOn(console, 'error');
    var element = React.DOM.div();
    expect(element.type).toBe('div');
    expect(console.error.calls.count()).toBe(0);
  });

  it('throws in render() if the mount callback is not a function', function() {
    function Foo() {
      this.a = 1;
      this.b = 2;
    }

    class A extends React.Component {
      state = {};

      render() {
        return
;
      }
    }

    var myDiv = document.createElement('div');
    expect(() => ReactDOM.render(, myDiv, 'no')).toThrowError(
      'ReactDOM.render(...): Expected the last optional `callback` argument ' +
      'to be a function. Instead received: string.'
    );
    expect(() => ReactDOM.render(, myDiv, {})).toThrowError(
      'ReactDOM.render(...): Expected the last optional `callback` argument ' +
      'to be a function. Instead received: Object.'
    );
    expect(() => ReactDOM.render(, myDiv, new Foo())).toThrowError(
      'ReactDOM.render(...): Expected the last optional `callback` argument ' +
      'to be a function. Instead received: Foo (keys: a, b).'
    );
  });

  it('throws in render() if the update callback is not a function', function() {
    function Foo() {
      this.a = 1;
      this.b = 2;
    }

    class A extends React.Component {
      state = {};

      render() {
        return
;
      }
    }

    var myDiv = document.createElement('div');
    ReactDOM.render(, myDiv);

    expect(() => ReactDOM.render(, myDiv, 'no')).toThrowError(
      'ReactDOM.render(...): Expected the last optional `callback` argument ' +
      'to be a function. Instead received: string.'
    );
    expect(() => ReactDOM.render(, myDiv, {})).toThrowError(
      'ReactDOM.render(...): Expected the last optional `callback` argument ' +
      'to be a function. Instead received: Object.'
    );
    expect(() => ReactDOM.render(, myDiv, new Foo())).toThrowError(
      'ReactDOM.render(...): Expected the last optional `callback` argument ' +
      'to be a function. Instead received: Foo (keys: a, b).'
    );
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.wso2.carbon.identity.framework</groupId>
        <artifactId>claim-mgt</artifactId>
        <version>5.6.21-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>org.wso2.carbon.identity.claim.metadata.mgt</artifactId>
    <packaging>bundle</packaging>
    <name>WSO2 Carbon - Identity Claim Metadata Management BE</name>
    <description>Advanced Claim metadata management for WSO2 Carbon</description>
    <url>http://wso2.org</url>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.user.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.registry.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.identity.framework</groupId>
            <artifactId>org.wso2.carbon.identity.base</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.identity.framework</groupId>
            <artifactId>org.wso2.carbon.identity.core</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Private-Package>org.wso2.carbon.identity.claim.metadata.mgt.internal</Private-Package>
                        <Import-Package>
                            javax.cache,
                            javax.xml.stream,

                            org.osgi.framework; version="${osgi.framework.imp.pkg.version.range}",
                            org.osgi.service.component; version="${osgi.service.component.imp.pkg.version.range}",
                            org.apache.commons.logging.*; version="${commons-logging.osgi.version.range}",
                            org.apache.commons.lang; version="${commons-lang.wso2.osgi.version.range}",

                            org.wso2.carbon.caching.impl; version="${carbon.kernel.package.import.version.range}",
                            org.wso2.carbon.context; version="${carbon.kernel.package.import.version.range}",
                            org.wso2.carbon.utils.*; version="${carbon.kernel.package.import.version.range}",
                            org.wso2.carbon.registry.core.service;version="${carbon.kernel.registry.imp.pkg.version}",
                            org.wso2.carbon.user.api; version="${carbon.user.api.imp.pkg.version.range}",
                            org.wso2.carbon.user.core.*; version="${carbon.kernel.package.import.version.range}",

                            org.wso2.carbon.identity.base; version="${carbon.identity.package.import.version.range}",
                            org.wso2.carbon.identity.core.model;
                            version="${carbon.identity.package.import.version.range}",
                            org.wso2.carbon.identity.core.util; version="${carbon.identity.package.import.version.range}"
                        </Import-Package>
                        <Export-Package>
                            !org.wso2.carbon.identity.claim.metadata.mgt.internal,
                            org.wso2.carbon.identity.claim.metadata.mgt.*;version="${carbon.identity.package.export.version}"
                        </Export-Package>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
Copyright 2007 Clodoaldo Pinto Neto

The software is licensed according to the terms of the PSF (Python Software Foundation) license found here: http://www.python.org/psf/license/


text:
import Button from './Button';
import withStyles from '../../withStyles';

export default withStyles('Button', Button.mapPropToStyles)(Button);


text:
PUBLISH_BLACKLIST=(
  # This is the old monolithic commons target - we no longer wish to publish this since
  # it would contain code duplicate to the individual package slices it contains.
  src/python/twitter/common

  # This is the old pex package, now moved out to the pantsbuild/pex github repo and
  # published from there.
  src/python/twitter/common/python
)

spec_excludes="'[$(echo ${PUBLISH_BLACKLIST[@]} | sed "s| |','|g")']"

./pants \
  --spec-excludes=\"${spec_excludes}\" \
  setup-py \
    --recursive \
    --run="register sdist upload" \
    src/python/twitter/common::


text:
package org.camunda.bpm.engine.test.api.authorization;

import static org.camunda.bpm.engine.authorization.Authorization.ANY;
import static org.camunda.bpm.engine.authorization.Permissions.CREATE;
import static org.camunda.bpm.engine.authorization.Permissions.CREATE_INSTANCE;
import static org.camunda.bpm.engine.authorization.Permissions.READ;
import static org.camunda.bpm.engine.authorization.Resources.PROCESS_DEFINITION;
import static org.camunda.bpm.engine.authorization.Resources.PROCESS_INSTANCE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.List;

import org.camunda.bpm.engine.AuthorizationException;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Test;

public class ConditionStartEventAuthorizationTest extends AuthorizationTest {

  private static final String SINGLE_CONDITIONAL_XML = "org/camunda/bpm/engine/test/bpmn/event/conditional/ConditionalStartEventTest.testSingleConditionalStartEvent1.bpmn20.xml";
  private static final String TRUE_CONDITIONAL_XML = "org/camunda/bpm/engine/test/bpmn/event/conditional/ConditionalStartEventTest.testStartInstanceWithTrueConditionalStartEvent.bpmn20.xml";
  protected static final String PROCESS_KEY = "conditionalEventProcess";
  protected static final String PROCESS_KEY_TWO = "trueConditionProcess";

  @Deployment(resources = { SINGLE_CONDITIONAL_XML, TRUE_CONDITIONAL_XML })
  @Test
  public void testWithAllPermissions() {
    // given two deployed processes with conditional start event

    createGrantAuthorization(PROCESS_DEFINITION, PROCESS_KEY_TWO, userId, CREATE_INSTANCE);
    createGrantAuthorization(PROCESS_DEFINITION, PROCESS_KEY, userId, READ, CREATE_INSTANCE);
    createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, CREATE);

    // when
    List<ProcessInstance> instances = runtimeService
        .createConditionEvaluation()
        .setVariable("foo", 42)
        .evaluateStartConditions();

    // then
    assertEquals(1, instances.size());
  }

  @Deployment(resources = { SINGLE_CONDITIONAL_XML })
  @Test
  public void testWithoutProcessDefinitionPermissions() {
    // given deployed process with conditional start event

    // user does not have process definition permissions
    createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, CREATE);

    // when
    try {
      runtimeService
          .createConditionEvaluation()
          .setVariable("foo", 42)
          .evaluateStartConditions();
      fail("expected exception");
    } catch (ProcessEngineException e) {
      assertTrue(e.getMessage().contains("No subscriptions were found during evaluation of the conditional start events."));
    }

  }

  @Deployment(resources = { SINGLE_CONDITIONAL_XML })
  @Test
  public void testWithoutCreateInstancePermissions() {
    // given deployed process with conditional start event

    // user does not have process definition CREATE_INSTANCE permissions
    createGrantAuthorization(PROCESS_DEFINITION, PROCESS_KEY, userId, READ);
    createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, CREATE);

    // when
    try {
      runtimeService
          .createConditionEvaluation()
          .setVariable("foo", 42)
          .evaluateStartConditions();
      fail("expected exception");
    } catch (AuthorizationException e) {
      assertTrue(e.getMessage().contains("The user with id 'test' does not have 'CREATE_INSTANCE' permission on resource 'conditionalEventProcess' of type 'ProcessDefinition'."));
    }

  }

  @Deployment(resources = { SINGLE_CONDITIONAL_XML })
  @Test
  public void testWithoutProcessInstanccePermission() {
    // given deployed process with conditional start event

    // the user doesn't have CREATE permission for process instances
    createGrantAuthorization(PROCESS_DEFINITION, PROCESS_KEY, userId, READ, CREATE_INSTANCE);

    // when
    try {
      runtimeService
          .createConditionEvaluation()
          .setVariable("foo", 42)
          .evaluateStartConditions();
      fail("expected exception");
    } catch (AuthorizationException e) {
      assertTrue(e.getMessage().contains("The user with id 'test' does not have 'CREATE' permission on resource 'ProcessInstance'."));
    }

  }

  @Deployment(resources = { SINGLE_CONDITIONAL_XML })
  @Test
  public void testWithRevokeAuthorizations() {
    // given deployed process with conditional start event

    createRevokeAuthorization(PROCESS_DEFINITION, PROCESS_KEY, userId, READ);
    createGrantAuthorization(PROCESS_DEFINITION, PROCESS_KEY, userId, CREATE_INSTANCE);
    createGrantAuthorization(PROCESS_INSTANCE, ANY, userId, CREATE);

    // when
    try {
      runtimeService
          .createConditionEvaluation()
          .setVariable("foo", 42)
          .evaluateStartConditions();
      fail("expected exception");
    } catch (ProcessEngineException e) {
      assertTrue(e.getMessage().contains("No subscriptions were found during evaluation of the conditional start events."));
    }
  }
}


text:
package org.apache.storm.sql.compiler;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.rel.type.RelDataTypeSystem;
import org.apache.calcite.rel.type.RelRecordType;
import org.apache.calcite.sql.type.JavaToSqlTypeConversionRules;
import org.apache.calcite.sql.type.SqlTypeName;

public class StormSqlTypeFactoryImpl extends JavaTypeFactoryImpl {

    public StormSqlTypeFactoryImpl() {
    }

    public StormSqlTypeFactoryImpl(RelDataTypeSystem typeSystem) {
        super(typeSystem);
    }

    @Override
    public RelDataType toSql(RelDataType type) {
        if (type instanceof JavaType) {
            JavaType javaType = (JavaType) type;
            SqlTypeName sqlTypeName = JavaToSqlTypeConversionRules.instance().lookup(javaType.getJavaClass());
            if (sqlTypeName == null) {
                sqlTypeName = SqlTypeName.ANY;
            }
            return createTypeWithNullability(createSqlType(sqlTypeName), type.isNullable());
        }
        return super.toSql(type);
    }
}


text:
<?php
class LoggerAppenderSocket extends \Mougrim\Logger\Appender\AppenderSocket
{
    public function write($priority, $message)
    {
        try {
            parent::write($priority, $message);
        } catch (\Mougrim\Logger\LoggerIOException $exception) {
            throw new LoggerIOException($exception->getMessage(), $exception->getCode(), $exception);
        }
    }
}


text:
'use strict';

var PING_MARKER_RADIUS = 10,
  MIN_PING_MARKER_RADIUS = 7,
  MAX_PING_MARKER_RADIUS = 16,
  PING_MARKER_BORDER_PERCENT = 0.2,
  MIN_PING_MARKER_BORDER = 1,
  refreshPings = function() { };

var R6MMainDrawing = (function($, window, document, undefined) {
  var getHandleTapFn = function getHandleTapFn(
    $pingMarkers,
    $pingMarkerAccents,
    $pingMarkersVertical,
    $pingMarkersHorizontal,
    $pingMarkersOtherFloor,
    isCameraCallback,
    SVG_DIM
  ) {
    return function handleTap(event) {
      var $targetEl = $(event.srcEvent.target);

      if (!isCameraCallback($targetEl)) {
        var $mapWrapper =  $(event.target).closest('.map-wrapper'),
          pingPosition = getPingPosition(event.center.x, event.center.y, $mapWrapper),
          newX = pingPosition.x,
          newY = pingPosition.y,
          originFloorIndex = $mapWrapper.attr('show-floor-index');

        movePingMarkers(
          $pingMarkers,
          $pingMarkerAccents,
          $pingMarkersVertical,
          $pingMarkersHorizontal,
          $pingMarkersOtherFloor,
          newX + SVG_DIM.LEFT_OFFSET,
          newY + SVG_DIM.TOP_OFFSET,
          originFloorIndex
        );
      }
    };
  };

  var getHidePingMarkersFn = function getHidePingMarkersFn(
    $pingMarkers,
    $pingMarkerAccents,
    $pingMarkersVertical,
    $pingMarkersHorizontal,
    $pingMarkersOtherFloor
  ) {
    return function hidePingMarkers() {
      movePingMarkers(
        $pingMarkers,
        $pingMarkerAccents,
        $pingMarkersVertical,
        $pingMarkersHorizontal,
        $pingMarkersOtherFloor,
        -10000,
        -10000
      );
    };
  };

  var getPingPosition = function getPingPosition(x, y, mapWrapper) {
    var centerX = mapWrapper.offset().left + (mapWrapper.width() / 2),
      centerY = mapWrapper.offset().top + (mapWrapper.height() / 2),
      $mapMain = mapWrapper.find('.map-main'),
      transforms = $mapMain.panzoom('getMatrix'),
      transformX = parseInt(transforms[4]),
      transformY = parseInt(transforms[5]),
      scale = transforms[0];

    return {
      x: Math.round((x - centerX - transformX) / scale),
      y: Math.round((y - centerY - transformY) / scale)
    };
  };

  var getResizePingMarkersFn = function getResizePingMarkersFn(
    $pingMarkers,
    $pingMarkerAccents,
    $mapMains,
    $pingMarkersOtherFloor
  ) {
    return function $resizePingMarkers() {
      var scale = $($mapMains[0]).panzoom('getMatrix')[0],
        radius = Math.round(PING_MARKER_RADIUS / scale),
        radius = Math.max(MIN_PING_MARKER_RADIUS, radius),
        radius = Math.min(MAX_PING_MARKER_RADIUS, radius),
        strokeWidth = Math.max(MIN_PING_MARKER_BORDER, Math.floor(radius * PING_MARKER_BORDER_PERCENT));

      radius -= strokeWidth;
      $pingMarkers.attr('r', radius);
      $pingMarkerAccents.attr('r', radius * 2);
      $pingMarkers.attr('stroke-width', strokeWidth);
      $pingMarkersOtherFloor.attr('stroke-width', strokeWidth);
    };
  };

  var movePingMarkers = function movePingMarkers(
    $pingMarkers,
    $pingMarkerAccents,
    $pingMarkersVertical,
    $pingMarkersHorizontal,
    $pingMarkersOtherFloor,
    x,
    y,
    originFloorIndex
  ) {
    $pingMarkers.attr('cx', x);
    $pingMarkers.attr('cy', y);
    $pingMarkerAccents.attr('cx', x);
    $pingMarkerAccents.attr('cy', y);
    $pingMarkersVertical.attr('x1', x);
    $pingMarkersVertical.attr('x2', x);
    $pingMarkersHorizontal.attr('y1', y);
    $pingMarkersHorizontal.attr('y2', y);

    refreshPings = function refreshPings() {
      $.each($pingMarkersOtherFloor, function(index, otherFloorMarker) {
        var $marker = $(otherFloorMarker);
        var currentFloorIndex = $marker.closest('.map-wrapper').attr('show-floor-index');

        if (!originFloorIndex || originFloorIndex == currentFloorIndex) {
          $marker.attr('transform', 'translate(-10000 -10000)');
        } else if (originFloorIndex < currentFloorIndex) {
          $marker.attr('transform', 'translate(' + (x - 9) + ' ' + (y - 5) + '), rotate(0)');
        } else {
          $marker.attr('transform', 'translate(' + (x + 9) + ' ' + (y + 5) + '), rotate(180)');
        }
      });

      $.each($pingMarkers, function(index, pingMarker) {
        var $marker = $(pingMarker);
        var currentFloorIndex = $marker.closest('.map-wrapper').attr('show-floor-index');

        if (!originFloorIndex || originFloorIndex == currentFloorIndex) {
          $marker.removeClass('other-floor');
        } else {
          $marker.addClass('other-floor');
        }
      });
    };
    refreshPings();

    $pingMarkers.addClass('highlight');
    $pingMarkerAccents.addClass('highlight');
    $pingMarkersVertical.addClass('highlight');
    $pingMarkersHorizontal.addClass('highlight');

    setTimeout(function() {
      $pingMarkers.removeClass('highlight');
      $pingMarkerAccents.removeClass('highlight');
      $pingMarkersVertical.removeClass('highlight');
      $pingMarkersHorizontal.removeClass('highlight');
    }, 100);
  };

  var populateStartingMarkers = function populateStartingMarkers($drawingMarkerWrappers, SVG_DIM) {
    var html = '';

    html += '<svg class="svg-elements drawing-markers" style="width: ' + SVG_DIM.WIDTH + 'px; left: -' + SVG_DIM.LEFT_OFFSET + 'px; height: ' + SVG_DIM.HEIGHT + 'px; top: -' + SVG_DIM.TOP_OFFSET + 'px;">';
    html += '<g>';
    html += '<line class="ping-marker vertical" x1="-9000" y1="35" x2="-10000" y2="' + (SVG_DIM.HEIGHT + 35) + '" stroke-width="2"/>';
    html += '<line class="ping-marker horizontal" x1="-25" y1="-10000" x2="' + (SVG_DIM.WIDTH - 25) + '" y2="-9000" stroke-width="2"/>';
    html += '<circle class="ping-marker accent" cx="-10000" cy="-10000" r="6" stroke-width="2"/>';
    html += '<circle class="ping-marker center" cx="-10000" cy="-10000" r="6" stroke-width="2"/>';
    html += '<polygon class="ping-marker other-floor" points="0,0 18,0 9,15.5884" stroke-width="2" transform="translate(-10000 -10000)"></polygon>';
    html += '</g>';
    html += '</svg>';
    $drawingMarkerWrappers.html(html);
  };

  var refreshPingsWrapper = function refreshPingsWrapper() {
    refreshPings();
  };

  var setup = function setup (
    $mapMains,
    $drawingMarkerWrappers,
    isCameraCallback,
    SVG_DIM
  ) {
    populateStartingMarkers($drawingMarkerWrappers, SVG_DIM);

    var $pingMarkers = $drawingMarkerWrappers.find('.ping-marker.center'),
      $pingMarkerAccents = $drawingMarkerWrappers.find('.ping-marker.accent'),
      $pingMarkersVertical = $drawingMarkerWrappers.find('.ping-marker.vertical'),
      $pingMarkersHorizontal = $drawingMarkerWrappers.find('.ping-marker.horizontal'),
      $pingMarkersOtherFloor = $drawingMarkerWrappers.find('.ping-marker.other-floor'),
      handleTap = getHandleTapFn($pingMarkers, $pingMarkerAccents, $pingMarkersVertical, $pingMarkersHorizontal, $pingMarkersOtherFloor, isCameraCallback, SVG_DIM),
      resizePingMarkers = getResizePingMarkersFn($pingMarkers, $pingMarkerAccents, $mapMains, $pingMarkersOtherFloor),
      hidePingMarkers = getHidePingMarkersFn($pingMarkers, $pingMarkerAccents, $pingMarkersVertical, $pingMarkersHorizontal, $pingMarkersOtherFloor);

    $mapMains.each(function(index, main) {
      var mc = new Hammer(main);

      mc.on('press', handleTap);
      mc.on('tap', handleTap);
    });
    $pingMarkers.on('click', hidePingMarkers);
    $mapMains.on('panzoomzoom', resizePingMarkers);
    resizePingMarkers();
  };

  return  {
    setup: setup,
    refreshPings: refreshPingsWrapper
  };
})(window.jQuery, window, document);


text:
'use strict';

import React from './lib/React';

var Children=React.Children;
var Component=React.Component;
var PureComponent=React.PureComponent;
var createElement=React.createElement;
var cloneElement=React.cloneElement;
var isValidElement=React.isValidElement;
var PropTypes=React.PropTypes;
var createClass=React.createClass;
var createFactory=React.createFactory;
var createMixin=React.createMixin;
var DOM=React.DOM;
var version=React.version;
var __spread=React.__spread;

export {
	Children,
	Component,
	PureComponent,

	createElement,
	cloneElement,
	isValidElement,
	PropTypes,
	createClass,
	createFactory,
	createMixin,
	DOM,
	version,
	__spread
};

export default {
	Children:Children,
	Component:Component,
	PureComponent:PureComponent,

	createElement:createElement,
	cloneElement:cloneElement,
	isValidElement:isValidElement,
	PropTypes:PropTypes,
	createClass:createClass,
	createFactory:createFactory,
	createMixin:createMixin,
	DOM:DOM,
	version:version,
	__spread:__spread
};


text:
import boto3
from datetime import datetime, timedelta
import logging
import os

logger = logging.getLogger()

def use_cloudwatch(region='us-east-1'):
    client = boto3.client('logs', region_name=region)
    return client

def get_bot_log_streams(
        region='us-east-1', min_ago=5, log_name=None, stream_prefix=None):
    client = use_cloudwatch(region=region)
    current_time = datetime.now()
    log_start = current_time - timedelta(minutes=min_ago)
    response = client.describe_log_streams(
        logGroupName='/aws/lambda/' + os.environ['FUNCTION_NAME']
        if not log_name else log_name,
        logStreamNamePrefix=log_start.strftime('%Y/%m/%d')
        if not stream_prefix else stream_prefix,
        descending=False,
        limit=5
    )
    high_date = {'lastEventTimestamp': 0}
    for i in response['logStreams']:
        if i['lastEventTimestamp'] > high_date['lastEventTimestamp']:
            high_date = i
        if high_date['lastEventTimestamp'] == 0:
            return False
    return high_date

def get_bot_logs(region='us-east-1', min_ago=5,
                 log_name=None, stream_prefix=None):
    '''Gets Log events and returns them as a list'''
    client = use_cloudwatch(region=region)
    log_name = log_name if log_name else '/aws/lambda/' + \
                                         os.environ['FUNCTION_NAME']
    stream_name = get_bot_log_streams(
        region=region, min_ago=min_ago,
        log_name=log_name, stream_prefix=stream_prefix)
    if stream_name:
        stream_name = stream_name['logStreamName']
    response = client.get_log_events(
        logGroupName=log_name,
        logStreamName=stream_name,
        startFromHead=True
    )
    return response['events']