text:
package com.alexjing.pullpushtorefresh.lib;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Scroller;

import com.alexjing.pullpushtorefresh.lib.annotation.PullState;

import static com.alexjing.pullpushtorefresh.lib.PullStateConstants.STATE_COMPLETE_DOWN;
import static com.alexjing.pullpushtorefresh.lib.PullStateConstants.STATE_COMPLETE_UP;
import static com.alexjing.pullpushtorefresh.lib.PullStateConstants.STATE_INIT;
import static com.alexjing.pullpushtorefresh.lib.PullStateConstants.STATE_LOADING_DOWN;
import static com.alexjing.pullpushtorefresh.lib.PullStateConstants.STATE_LOADING_UP;
import static com.alexjing.pullpushtorefresh.lib.PullStateConstants.STATE_PREPARE_DOWN;
import static com.alexjing.pullpushtorefresh.lib.PullStateConstants.STATE_PREPARE_UP;
import static com.alexjing.pullpushtorefresh.lib.PullStateConstants.STATE_PULL_DOWN;
import static com.alexjing.pullpushtorefresh.lib.PullStateConstants.STATE_PULL_UP;

/**
 * @author: haifeng jing(haifeng_jing@kingdee.com)
 * @date: 2016-06-30
 * @time: 14:37
 */
public class PullPushLayout extends ViewGroup implements PullPushConstants.View {
    private static final String TAG = "PullPushLayout";
    private View mHeaderView;
    private View mFooterView;
    private View mContentView;

    private int mHeaderId;
    private int mFooterId;
    private int mContentId;

    private PullPushConstants.Presenter mPresenter;
    private int mHeaderHeight;
    private int mFooterHeight;

    private TouchManager mTouchManager;

    private ScrollChecker mScrollChecker;

    public PullPushLayout(Context context) {
        this(context, null);
    }

    public PullPushLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PullPushLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPresenter = new PullPushPresenter(this);

        mTouchManager = new TouchManager();

        setVerticalFadingEdgeEnabled(false);

        mScrollChecker = new ScrollChecker();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 回收 ScrollerChecker
    }

    @Override
    protected void onFinishInflate() {
        final int childCount = getChildCount();
        if (childCount == 0) {

        } else if (childCount == 1) {
            // 默认没有 header & footer
            mContentView = getChildAt(0);
        } else if (childCount == 2) {
            // 默认没有 footer
            // TODO: 16-6-30 加入 id 判定

            mHeaderView = getChildAt(0);
            mContentView = getChildAt(1);
        } else if (childCount == 3) {
            // 分别为 footer & context & footer
            mHeaderView = getChildAt(0);
            mContentView = getChildAt(1);
            mFooterView = getChildAt(2);
        }

        if (mContentView != null) {
            mContentView.bringToFront();
            mContentView.setVerticalFadingEdgeEnabled(false);
        }

        if (mFooterView != null) super.onFinishInflate();
    }

    private float mDownY;
    private float mLastMoveY;
    private float mCurrentMoveY;

    private float mOffsetTotal = 0;

    // 分发事件
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (!isEnabled() || mContentView == null || (mHeaderView == null && mFooterView == null)) {
            return super.dispatchTouchEvent(ev);
        }
        final int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mTouchManager.down(ev);
                mScrollChecker.abortIfWorking();
                super.dispatchTouchEvent(ev);
                return true;
            case MotionEvent.ACTION_MOVE:
                if (mTouchManager.move(ev, mContentView.canScrollVertically(1),
                                       mContentView.canScrollVertically(-1))) {
                    int offset = mTouchManager.mCurrentOffset;
                    updatePosition(offset);
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (mTouchManager.up(ev)) {
//                    layoutChild();
                    mScrollChecker.tryToScrollTo(0,1000);
                }

                break;
        }

        return super.dispatchTouchEvent(ev);
    }

    // 测量、布局
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (mHeaderView != null) {
            measureChildWithMargins(mHeaderView, widthMeasureSpec, 0, heightMeasureSpec, 0);
            MarginLayoutParams lp = (MarginLayoutParams) mHeaderView.getLayoutParams();
            mHeaderHeight = mHeaderView.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
        }

        if (mContentView != null) {
            measureContentView(mContentView, widthMeasureSpec, heightMeasureSpec);
        }

        if (mFooterView != null) {
            measureChildWithMargins(mFooterView, widthMeasureSpec, 0, heightMeasureSpec, 0);
            MarginLayoutParams lp = (MarginLayoutParams) mFooterView.getLayoutParams();
            mFooterHeight = mFooterView.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
        }
    }

    private void measureContentView(View child, int parentWidthMeasureSpec,
                                    int parentHeightMeasureSpec) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                                                              getPaddingLeft() + getPaddingRight() +
                                                              lp.leftMargin + lp.rightMargin,
                                                              lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                                                               getPaddingTop() +
                                                               getPaddingBottom() + lp.topMargin,
                                                               lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        layoutChild();
    }

    private void layoutChild() {

        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();

        if (mHeaderView != null) {
            MarginLayoutParams lp = (MarginLayoutParams) mHeaderView.getLayoutParams();
            final int left = lp.leftMargin + paddingLeft;
            final int top = getTop() - mHeaderHeight;
            final int right = left + mHeaderView.getMeasuredWidth();
            final int bottom = top + mHeaderView.getMeasuredHeight();

            mHeaderView.layout(left, top, right, bottom);
        }

        if (mContentView != null) {
            MarginLayoutParams lp = (MarginLayoutParams) mContentView.getLayoutParams();
            final int left = lp.leftMargin + paddingLeft;
            final int top = lp.topMargin + paddingTop;
            final int right = left + mContentView.getMeasuredWidth();
            final int bottom = top + mContentView.getMeasuredHeight();

            mContentView.layout(left, top, right, bottom);
        }

        if (mFooterView != null) {
            MarginLayoutParams lp = (MarginLayoutParams) mFooterView.getLayoutParams();
            final int left = lp.leftMargin + paddingLeft;
            final int top = getBottom() - getPaddingBottom();
            final int right = left + mFooterView.getMeasuredWidth();
            final int bottom = top + mFooterView.getMeasuredHeight();

            mFooterView.layout(left, top, right, bottom);
        }
    }

    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
        return p != null && p instanceof LayoutParams;
    }

    @Override
    protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

    @Override
    protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
        return new LayoutParams(p);
    }

    @Override
    public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(), attrs);
    }

    @Override
    public void updateContentPosition(float vertical) {
        Log.d(TAG, "vertical:" + vertical);
        mContentView.offsetTopAndBottom((int) vertical);
    }

    public void updatePosition(int offset) {
        mContentView.offsetTopAndBottom(offset);
        mHeaderView.offsetTopAndBottom(offset);
        mFooterView.offsetTopAndBottom(offset);
    }

    @Override
    public boolean canVerticalScroll(int direction) {
        if (mContentView == null) {
            return true;
        }
        return mContentView.canScrollVertically(direction);
    }

    @Override
    public void resetChild() {
        layoutChild();
    }

    @Override
    public void setPresenter(PullPushConstants.Presenter presenter) {
        mPresenter = presenter;
    }

    // 创建统一 MarginLayoutParams
    public static class LayoutParams extends MarginLayoutParams {

        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
        }

        public LayoutParams(int width, int height) {
            super(width, height);
        }

        @SuppressWarnings({"unused"})
        public LayoutParams(MarginLayoutParams source) {
            super(source);
        }

        public LayoutParams(ViewGroup.LayoutParams source) {
            super(source);
        }
    }

    private class TouchManager implements TouchHandler {
        @PullState
        private int mPullState = STATE_INIT;

        private int mDownY;

        private int mLastMoveY;

        private int mCurrentMoveY;

        private int mSumOffset;

        private float mOffsetPercent = 0f;

        private float mCurrentOffsetPercent;

        private int mCurrentOffset;

        // 最大的系数
        private float mMaxCoefficient = 1f;

        public TouchManager() {
        }

        @Override
        public boolean down(MotionEvent ev) {
            mDownY = (int) ev.getY();
            mCurrentMoveY = mDownY;
            return false;
        }

        @Override
        public boolean move(MotionEvent ev, boolean canScrollDown, boolean canScrollUp) {
            mLastMoveY = mCurrentMoveY;
            mCurrentMoveY = (int) ev.getY();

            int offset = mCurrentMoveY - mLastMoveY;

            // offset > 0 下拉状态
            // offset < 0 上滑状态
            // 通过能否上下滚动来确定状态

            if (offset > 0 && mSumOffset >= 0 && canScrollUp) {
                mPullState = STATE_INIT;
                return false;
            }

            if (offset < 0 && mSumOffset <= 0 && canScrollDown) {
                mPullState = STATE_INIT;
                return false;
            }

            if (mSumOffset > 0) {
                mPullState = STATE_PULL_DOWN;
            } else if (mSumOffset < 0) {
                mPullState = STATE_PULL_UP;
            } else {
                mPullState = STATE_INIT;
            }

            int lastSumOffset = mSumOffset;
            setOffset(offset);

            offset = mSumOffset - lastSumOffset;

            mCurrentOffset = offset;

            float lastOffsetPercent = mOffsetPercent;

            if (mCurrentOffset > 0) {
                mOffsetPercent = mSumOffset / (mHeaderHeight * mMaxCoefficient);
            } else {
                mOffsetPercent = mSumOffset / (mFooterHeight * mMaxCoefficient);
            }

            mCurrentOffsetPercent = mOffsetPercent - lastOffsetPercent;
            return true;
        }

        @Override
        public boolean up(MotionEvent ev) {
            if (mSumOffset == 0) {
                return false;
            }
            // 当header 或 footer 完全显示的情况下 触发刷新
            if (mSumOffset > 0 && mSumOffset >= mHeaderHeight) {
                mPullState = STATE_PREPARE_DOWN;
            } else if (mSumOffset < 0 && Math.abs(mSumOffset) >= mFooterHeight) {
                mPullState = STATE_PREPARE_UP;
            } else {
                mPullState = mSumOffset > 0 ? STATE_COMPLETE_DOWN : STATE_COMPLETE_UP;
            }

            // 实际判断是否能刷新

            if (canPerformLoading()) {
                if (mPullState == STATE_PREPARE_DOWN) {
                    mPullState = STATE_LOADING_DOWN;
                }

                if (mPullState == STATE_PREPARE_UP) {
                    mPullState = STATE_LOADING_UP;
                }
            } else {

                if (mPullState == STATE_PREPARE_DOWN) {
                    mPullState = STATE_COMPLETE_DOWN;
                }

                if (mPullState == STATE_PREPARE_UP) {
                    mPullState = STATE_COMPLETE_UP;
                }

            }

            if (mCurrentOffset > 0) {
                mOffsetPercent = mSumOffset / mHeaderHeight * mMaxCoefficient;
            } else {
                mOffsetPercent = mSumOffset / mFooterHeight * mMaxCoefficient;
            }
            return true;
        }

        private boolean canPerformLoading() {
            switch (mPullState) {
                case STATE_PREPARE_DOWN:
                    // TODO: 16-7-4
                    break;
                case STATE_PREPARE_UP:
                    break;
            }

            return false;
        }

        public boolean isAlreadyHere(int to) {
            return mSumOffset == to;
        }

        public void setOffset(int offset){

            if (mSumOffset > 0) {
                mSumOffset = Math.max(0, mSumOffset + offset);
            } else if (mSumOffset < 0) {
                mSumOffset = Math.min(0, mSumOffset + offset);
            } else {
                mSumOffset += offset;
            }

            // 限制头和脚被拉的距离
            if (mSumOffset > 0) {
                if (mSumOffset > mHeaderHeight * mMaxCoefficient) {
                    mSumOffset = (int) (mHeaderHeight * mMaxCoefficient);
                }
            } else {
                if (Math.abs(mSumOffset) > mFooterHeight * mMaxCoefficient) {
                    mSumOffset = (int) (-mHeaderHeight * mMaxCoefficient);
                }
            }

        }
    }

    class ScrollChecker implements Runnable {

        private Scroller mScroller;

        private int mStart;
        private int mTo;

        private int mLastY;

        private long mDuration;

        private boolean isRunning;

        public ScrollChecker() {
            mScroller = new Scroller(getContext());
        }

        @Override
        public void run() {
            boolean finish = !mScroller.computeScrollOffset() || mScroller.isFinished();
            int currentY = mScroller.getCurrY();
            int deltaY = currentY - mLastY;
            if (deltaY != 0) {
                Log.d(TAG,"currentY:"+currentY + "  deltaY:"+deltaY);
            }

            if (!finish) {
                mLastY = currentY;
                updatePosition(deltaY);
                mTouchManager.setOffset(deltaY);
                post(this);
            } else {
                finish();
            }
        }

        private void finish() {
            reset();
        }

        private void reset() {
            isRunning = false;
            mLastY = 0;
            removeCallbacks(this);
        }

        public void abortIfWorking() {
            if (isRunning) {
                if (!mScroller.isFinished()) {
                    mScroller.forceFinished(true);
                }
                reset();
            }
        }

        public void tryToScrollTo(int to, long duration) {
            if (mTouchManager.isAlreadyHere(to)) {
                return;
            }

            mDuration = duration;

            mStart = mTouchManager.mSumOffset;
            mTo = to;

            int distance = mTo - mStart;
            removeCallbacks(this);

            if (!mScroller.isFinished()) {
                mScroller.forceFinished(true);
            }

            mLastY = 0;

            mScroller.startScroll(0, 0, 0, distance, (int) mDuration);

            post(this);

            isRunning = true;
        }
    }
}


text:
namespace content {

using KeySystemCapabilityPtrMap =
    base::flat_map<std::string, media::mojom::KeySystemCapabilityPtr>;
using KeySystemSupportCB =
    base::RepeatingCallback<void(KeySystemCapabilityPtrMap)>;

// Observes key system support updates. The callback `cb` will be called with
// the current key system support, then called every time the key system support
// changes.
CONTENT_EXPORT void ObserveKeySystemSupportUpdate(KeySystemSupportCB cb);

}  // namespace content

#endif  // CONTENT_PUBLIC_RENDERER_KEY_SYSTEM_SUPPORT_H_

redpajama_set_name: RedPajamaGithub


text:
import re
import glob
import sys

if len(sys.argv) != 3:
    print('usage: python post.py directory versionNumber')
    sys.exit(1)

path = str(sys.argv[1])

insertVersion = re.compile(r'VERSION_VERSION_VERSION')
insertSTLLink = re.compile(r'WWW_STL_DOCU')

# tested with doxygen 1.7.5.1
hasAnchorDetails = re.compile(r'')

detailsHeading1 = re.compile(r'''
Detailed Description

''')

detailsHeading2 = re.compile(r'
Detailed Description
')

# tested with doxygen 1.7.5.1 and 1.8.2
detailsHeading3 = re.compile(r'
Detailed Description
')

mainHeading1 = re.compile(r'''()
(
.*

|)

(.*)( Class Template Reference| Struct Template Reference| Class Reference| Struct Reference)(

.*
|)
''')

mainHeading2 = re.compile(r'''()
(
.*

|

|)
(.*)()(

.*
|)
''')

# tested with doxygen 1.5.6
mainHeading3 = re.compile(r'''()
(

)
(.*)
(.*)()

''')

# tested with doxygen 1.7.5.1 and 1.7.6.1
mainHeading4 = re.compile(r'''(

)
(

)
(.*)

(.*)()

(?:)?

''')

# tested with doxygen 1.8.2
mainHeading5 = re.compile(r'''(

)
(

)
(.*)

(.*)()

(?:)?

''')

mainHeadingReplacement = '''\\1

%s\\3\\5

'''

# tested with doxygen 1.7.5.1
headingSummary = re.compile(r'''(

)

(?s).*?
''')

# tested with doxygen 1.8.2
headingSummary2 = re.compile(r'''(

)

(?s).*?
''')

# tested with doxygen 1.7.5.1
headingNavpath = re.compile(r'''()

(?s).*?
''')

# tested with doxygen 1.8.2
headingNavpath2 = re.compile(r'''()

.*

''')

detailsLink = '''

'''

indexPageHeading = re.compile(r'''((?:
)? (?:
\n)? )
((?:)?)
(.*)
 Version''')

indexPageHeadingReplacement = '''\\1
\\2
\\3
 Version'''

templateDeclaration = re.compile('''
([^<]*)
\s*

[^<]*	''')

templateDocumentation = '''(.*

\s*

)'''

templateDocumentationReplacement = '''\\1
          %s

'''

def convertHeadings(text):
    if hasAnchorDetails.search(text):
        text = detailsHeading1.sub('
Detailed Description
\n
', \
                      text, 1)
        text = detailsHeading2.sub(r'
Detailed Description
', text, 1)
        text = detailsHeading3.sub(r'
Detailed Description
', text, 1)
        mhr = mainHeadingReplacement % detailsLink
    else:
        mhr = mainHeadingReplacement % ''
    text = headingNavpath.sub("\\1", text, 1)
    text = headingNavpath2.sub("\\1", text, 1)
    text = headingSummary.sub("\\1", text, 1)
    text = headingSummary2.sub("\\1", text, 1)
    text = mainHeading1.sub(mhr, text, 1)
    text = mainHeading2.sub(mhr, text, 1)
    text = mainHeading3.sub(mhr, text, 1)
    text = mainHeading4.sub(mhr, text, 1)
    text = mainHeading5.sub(mhr, text, 1)
    return text

def insertMissingTemplateDeclarations(text):
    matches = templateDeclaration.findall(text)
    for k in matches:
        text = re.sub(templateDocumentation % k[1], templateDocumentationReplacement % k[0], text)
    return text

def processFile(fileName):
    print(fileName)          # log message
    if sys.version_info[0] < 3:
        f = open(fileName)
    else:
        f = open(fileName,encoding = "ISO-8859-1")
    text = f.read()
    f.close()

    text = insertVersion.sub(sys.argv[2], text)
    text = insertSTLLink.sub(r'http://www.sgi.com/tech/stl/', text)
    if re.search('.*/index.html', fileName) or re.search('.*\\index.html', fileName):
        text = re.sub(r'
\d+\.\d+\.\d+
', '', text)
        text = indexPageHeading.sub(indexPageHeadingReplacement, text)

    text = convertHeadings(text)

    text = insertMissingTemplateDeclarations(text)

    f = open(fileName, 'w+')
    f.write(text)
    f.close()

files = glob.glob(path + '/*.html')  # use given path to files
#files = glob.glob(path + '/index.html')

for file in files:
   processFile(file)


text:
angular.module('tokenApp').controller('loginController', ['authService', 'userService', '$scope',
    function (authService, userService, $scope) {
        $scope.pass = "";
        $scope.remember = true;
        $scope.login = function(pass, remember) {
            if (pass.trim() != ""){
                authService.setLogged(pass, remember);
            }
        }
    }]);


text:
<?php

/*
 * display complete application
 *
 */

session_start();

if ( !( isset( $_SESSION['Username'] ) && isset( $_SESSION['Name'] ) ) )
{
	echo "You must login first to visit this page.";
	die();
}

if ( ! isset (  $_POST['app_id'] ) )
{
	echo "Sorry, there was a problem.
";
	die();
}
else
{
	$id = $_POST['app_id'];
	$type = $_POST['app_type'];

	require_once "../../LocalSettings.php";
	require_once "../Globals.php";
	require "../ApplHandlingByStr.php";

	$sqlconn = new mysqli ( $eorgDBserver, $eorgDBuser, $eorgDBpasswd, $eorgDBname );

	if ( $sqlconn->connect_errno )
	{
		echo "Internal Server Error, Sorry for inconvenience.";
		die();
	}

	$qry = "SELECT * FROM $type WHERE $AppId = ?";
	$stmt = $sqlconn->prepare ( $qry );
	$stmt->bind_param ( 's', $id );

	echo <<<HTML
<!DOCTYPE html>

<title>Add User</title>
<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="../../image/gogreen.jpg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<br
<br

<br

HTML;

echo "$html";

if ($_SESSION['PostName'])
{
echo "<button onclick=\"document.location.href='../dashboard/PostDashBoard.php'\" > HOME </button> ";
}
else
echo "<button onclick=\"document.location.href='../../'\" > HOME </button> ";

$html = <<<HTML
<button onclick="document.location.href='handleAppl.php'" > BACK </button>

<br
<br

Application #[ $id ].

HTML;
echo "$html";

	if ( ! $stmt->execute() )
	{
		echo "Sorry, there is a problem with database.";
		die();
	}
	else
	{
		$result = $stmt->get_result();
		$row = $result->fetch_array();

		$qr = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = \"$eorgDBname\" AND TABLE_NAME = \"$type\"";
		$cols = $sqlconn->query($qr);

		$i = 0;

		while( $col = $cols->fetch_array() )
		{
			if( $col[0] == $stat )
			{
				echo "
 $col[0]	";
				showFullStatus( $row[$i] );
				echo "
";
			}
			else
			{
				echo "
 $col[0]	 ".$row[$i]."
";
			}
			$i++;
		}
	}

	echo <<<HTML

HTML;
}

?>


text:
<?php
class Giftcard extends CI_Model
{
	/*
	Determines if a given giftcard_id is an giftcard
	*/
	function exists( $giftcard_id )
	{
		$this->db->from('giftcards');
		$this->db->where('giftcard_id',$giftcard_id);
		$this->db->where('deleted',0);
		$query = $this->db->get();

		return ($query->num_rows()==1);
	}

	/*
	Returns all the giftcards
	*/
	function get_all($limit=10000,$offset=0,$col='giftcard_number',$order='asc')
	{
		$this->db->from('giftcards');
		$this->db->where('deleted',0);
		$this->db->order_by($col, $order);
		$this->db->limit($limit);
		$this->db->offset($offset);
		return $this->db->get();
	}

	function count_all()
	{
		$this->db->from('giftcards');
		$this->db->where('deleted',0);
		return $this->db->count_all_results();
	}

	/*
	Gets information about a particular giftcard
	*/
	function get_info($giftcard_id)
	{
		$this->db->from('giftcards');
		$this->db->where('giftcard_id',$giftcard_id);
		$this->db->where('deleted',0);

		$query = $this->db->get();

		if($query->num_rows()==1)
		{
			return $query->row();
		}
		else
		{
			//Get empty base parent object, as $giftcard_id is NOT an giftcard
			$giftcard_obj=new stdClass();

			//Get all the fields from giftcards table
			$fields = $this->db->list_fields('giftcards');

			foreach ($fields as $field)
			{
				$giftcard_obj->$field='';
			}

			return $giftcard_obj;
		}
	}

	/*
	Get an giftcard id given an giftcard number
	*/
	function get_giftcard_id($giftcard_number,$deleted=false)
	{
		$this->db->from('giftcards');
		$this->db->where('giftcard_number',$giftcard_number);
		if(!$deleted)
		{
			$this->db->where('deleted',0);
		}

		$query = $this->db->get();

		if($query->num_rows()==1)
		{
			return $query->row()->giftcard_id;
		}

		return false;
	}

	/*
	Gets information about multiple giftcards
	*/
	function get_multiple_info($giftcard_ids)
	{
		$this->db->from('giftcards');
		$this->db->where_in('giftcard_id',$giftcard_ids);
		$this->db->where('deleted',0);
		$this->db->order_by("giftcard_number", "asc");
		return $this->db->get();
	}

	/*
	Inserts or updates a giftcard
	*/
	function save(&$giftcard_data,$giftcard_id=false)
	{
		if (!$giftcard_id or !$this->exists($giftcard_id))
		{
			if($this->db->insert('giftcards',$giftcard_data))
			{
				$giftcard_data['giftcard_id']=$this->db->insert_id();
				return true;
			}
			return false;
		}

		$this->db->where('giftcard_id', $giftcard_id);
		return $this->db->update('giftcards',$giftcard_data);
	}

	/*
	Updates multiple giftcards at once
	*/
	function update_multiple($giftcard_data,$giftcard_ids)
	{
		$this->db->where_in('giftcard_id',$giftcard_ids);
		return $this->db->update('giftcards',$giftcard_data);
	}

	/*
	Deletes one giftcard
	*/
	function delete($giftcard_id)
	{
		$this->db->where('giftcard_id', $giftcard_id);
		return $this->db->update('giftcards', array('deleted' => 1, 'giftcard_number' => NULL));
	}

	function delete_completely($giftcard_id)
	{
		$this->db->where('giftcard_number', $giftcard_id);
		$this->db->delete('giftcards');
	}
	/*
	Deletes a list of giftcards
	*/
	function delete_list($giftcard_ids)
	{
		$this->db->where_in('giftcard_id',$giftcard_ids);
		return $this->db->update('giftcards', array('deleted' => 1, 'giftcard_number' => NULL));
 	}

 	/*
	Get search suggestions to find giftcards
	*/
	function get_search_suggestions($search,$limit=25)
	{
		$suggestions = array();

		$this->db->from('giftcards');
		$this->db->like('giftcard_number', $search);
		$this->db->where('deleted',0);
		$this->db->limit($limit);
		$by_number = $this->db->get();

		$temp_suggestions = array();
		foreach($by_number->result() as $row)
		{
			$temp_suggestions[] = $row->giftcard_number;
		}

		sort($temp_suggestions);
		foreach($temp_suggestions as $temp_suggestion)
		{
			$suggestions[]=array('label'=> $temp_suggestion);
		}

		$this->db->from('giftcards');
		$this->db->join('people','giftcards.customer_id=people.person_id');

		$this->db->where("(first_name LIKE '%".$this->db->escape_like_str($search)."%' or
		last_name LIKE '%".$this->db->escape_like_str($search)."%' or
		CONCAT(`first_name`,' ',`last_name`) LIKE '%".$this->db->escape_like_str($search)."%') and ".$this->db->dbprefix('giftcards').".deleted=0");

		$this->db->limit($limit);
		$by_name = $this->db->get();

		$temp_suggestions = array();
		foreach($by_name->result() as $row)
		{
			$temp_suggestions[] = $row->last_name.', '.$row->first_name;
		}

		sort($temp_suggestions);
		foreach($temp_suggestions as $temp_suggestion)
		{
			$suggestions[]=array('label'=> $temp_suggestion);
		}

		//only return $limit suggestions
		if(count($suggestions > $limit))
		{
			$suggestions = array_slice($suggestions, 0,$limit);
		}
		return $suggestions;

	}

	/*
	Preform a search on giftcards
	*/
	function search($search, $limit=20,$offset=0,$column="giftcard_number",$orderby='asc')
	{
		$this->db->from('giftcards');
		$this->db->join('people','giftcards.customer_id=people.person_id', 'left');

		$this->db->where("(first_name LIKE '%".$this->db->escape_like_str($search)."%' or
		last_name LIKE '%".$this->db->escape_like_str($search)."%' or
		CONCAT(`first_name`,' ',`last_name`) LIKE '%".$this->db->escape_like_str($search)."%' or
		CONCAT(`last_name`,', ',`first_name`) LIKE '%".$this->db->escape_like_str($search)."%' or giftcard_number LIKE '%".$this->db->escape_like_str($search)."%') and ".$this->db->dbprefix('giftcards').".deleted=0");

		$this->db->order_by($column, $orderby);
		$this->db->limit($limit);
		$this->db->offset($offset);
		return $this->db->get();
	}

	function search_count_all($search, $limit=10000)
	{
		$this->db->from('giftcards');
		$this->db->join('people','giftcards.customer_id=people.person_id', 'left');

		$this->db->where("(first_name LIKE '%".$this->db->escape_like_str($search)."%' or
		last_name LIKE '%".$this->db->escape_like_str($search)."%' or
		CONCAT(`first_name`,' ',`last_name`) LIKE '%".$this->db->escape_like_str($search)."%' or giftcard_number LIKE '%".$this->db->escape_like_str($search)."%') and ".$this->db->dbprefix('giftcards').".deleted=0");

		$this->db->limit($limit);
		$result=$this->db->get();
		return $result->num_rows();
	}

	public function get_giftcard_value( $giftcard_number )
	{
		if ( !$this->exists( $this->get_giftcard_id($giftcard_number)))
			return 0;

		$this->db->from('giftcards');
		$this->db->where('giftcard_number',$giftcard_number);
		return $this->db->get()->row()->value;
	}

	function update_giftcard_value( $giftcard_number, $value )
	{
		$this->db->where('giftcard_number', $giftcard_number);
		$this->db->update('giftcards', array('value' => $value));
	}
}
?>


text:
import {
  StyleSheet,
} from 'react-native';
import {
  COLOR_BG_DARK,
} from '../constant';

const SIDE_GAP = 10;
const COLOR = '#fff';

const styles = StyleSheet.create({
  navBar: {
    backgroundColor: COLOR_BG_DARK,
    position: 'relative',
  },
  header: {
    paddingHorizontal: SIDE_GAP,
    flexDirection: 'row',
    alignItems: 'stretch',
    justifyContent: 'space-between',
    position: 'relative',
    backgroundColor: 'transparent',
  },
  titleWrapper: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    flexDirection: 'column',
    justifyContent: 'center',
    overflow: 'hidden',
  },
  title: {
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 16,
    color: COLOR,
  },
  btn: {
    justifyContent: 'center',
    flex: 1,
  },
  btnText: {
    color: COLOR,
  },
});

export default styles;


text:
namespace blink {

namespace test {
class InputHandlerProxyEventQueueTest;
}

// CompositorThreadEventQueue is a coalescing queue. It will examine
// the current events in the queue and will attempt to coalesce with
// the last event.
class PLATFORM_EXPORT CompositorThreadEventQueue {
 public:
  CompositorThreadEventQueue();
  ~CompositorThreadEventQueue();

  // Adds an event to the queue. The event may be coalesced with the last event.
  void Queue(std::unique_ptr<EventWithCallback> event,
             base::TimeTicks timestamp_now);

  std::unique_ptr<EventWithCallback> Pop();

  bool empty() const { return queue_.empty(); }

  size_t size() const { return queue_.size(); }

 private:
  friend class test::InputHandlerProxyEventQueueTest;
  using EventQueue = base::circular_deque<std::unique_ptr<EventWithCallback>>;
  EventQueue queue_;

  DISALLOW_COPY_AND_ASSIGN(CompositorThreadEventQueue);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WIDGET_INPUT_COMPOSITOR_THREAD_EVENT_QUEUE_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace MDPBug
{
    public class App : Application
    {
        private NavigationPage _navPage;
        public App()
        {
            var mdp = new MasterPage();
             _navPage = new NavigationPage(new MainPage());
             mdp.Detail = _navPage;

            NavigationPage.SetHasBackButton(mdp.Detail, false);
            NavigationPage.SetHasNavigationBar(mdp.Detail, false);
            NavigationPage.SetBackButtonTitle(mdp.Detail, "Badjoras");

            NavigateLater();

            MainPage = mdp;
        }

        async Task NavigateLater()
        {
            bool clearBackstack = true;
                await Task.Delay(10000);
                await _navPage.PushAsync(new SecondPage(), true);

                NavigationPage.SetHasBackButton(_navPage, false);
                NavigationPage.SetHasNavigationBar(_navPage, false);
                NavigationPage.SetBackButtonTitle(_navPage, "Badjoras");
        }

    }
}


text:
package net.sf.jsqlparser.util.deparser;

import net.sf.jsqlparser.expression.ExpressionVisitor;
import net.sf.jsqlparser.statement.drop.Drop;

/**
 * A class to de-parse (that is, tranform from JSqlParser hierarchy into a
 * string) a {@link net.sf.jsqlparser.statement.delete.Delete}
 */
public class DropDeParser {

    protected StringBuilder buffer;
    protected ExpressionVisitor expressionVisitor;

    public DropDeParser() {
    }

    /**
     * @param aExpressionVisitor a {@link ExpressionVisitor} to de-parse
     * expressions. It has to share the same<br>
     * StringBuilder (buffer parameter) as this object in order to work
     * @param aBuffer the buffer that will be filled with the select
     */
    public DropDeParser(ExpressionVisitor aExpressionVisitor, StringBuilder aBuffer) {
        buffer = aBuffer;
        expressionVisitor = aExpressionVisitor;
    }

    public StringBuilder getBuffer() {
        return buffer;
    }

    public void setBuffer(StringBuilder aBuffer) {
        buffer = aBuffer;
    }

    public void deParse(Drop aDrop) {
        buffer.append(aDrop.getComment() != null ? aDrop.getComment() + " " + ExpressionDeParser.LINE_SEPARATOR : "").append("Drop")
                .append(aDrop.getTypeComment() != null ? " " + aDrop.getTypeComment() + ExpressionDeParser.LINE_SEPARATOR : "").append(" ")
                .append(aDrop.getType()).append(" ")
                .append(aDrop.getNameComment() != null ? " " + aDrop.getNameComment() + ExpressionDeParser.LINE_SEPARATOR : "")
                .append(aDrop.getName()).append(" ");
        if (aDrop.getParameters() != null && aDrop.getParameters().size() > 0) {
            for (int i = 0; i < aDrop.getParameters().size(); i++) {
                buffer.append(aDrop.getParameters().get(i)).append(" ");
                if (i < aDrop.getParameters().size() - 1) {
                    buffer.append(!"".equals(aDrop.getParametersComment().get(i)) ? " " + aDrop.getParametersComment().get(i) + ExpressionDeParser.LINE_SEPARATOR : "")
                            .append(", ");
                }
            }
        }
        buffer.append(!"".equals(aDrop.getEndComment()) ? " " + aDrop.getEndComment() : "");
    }

    public ExpressionVisitor getExpressionVisitor() {
        return expressionVisitor;
    }

    public void setExpressionVisitor(ExpressionVisitor aVisitor) {
        expressionVisitor = aVisitor;
    }
}


text:
namespace EnergyTrading.MDM.Test
{
    using System.Linq;
    using System.Runtime.Serialization;

    using Microsoft.Http;
    using NUnit.Framework;
    using EnergyTrading.Data.EntityFramework;
    using EnergyTrading.MDM.Data.EF.Configuration;

    [TestFixture]
    public class when_a_party_is_created_and_the_latest_detail_is_updated : IntegrationTestBase
    {
        private static HttpContent content;
        private static HttpClient client;
        private static MDM.Party entity;
        private static EnergyTrading.MDM.Contracts.Sample.Party updatedContract;

        [TestFixtureSetUp]
        public static void ClassInit()
        {
            Establish_context();
            Because_of();
        }

        protected static void Establish_context()
        {
            client = new HttpClient();
            entity = Script.PartyData.CreateBasicEntity();
            var getResponse = client.Get(ServiceUrl["Party"] + entity.Id);

            updatedContract = getResponse.Content.ReadAsDataContract<EnergyTrading.MDM.Contracts.Sample.Party>();
            updatedContract.Details.Name = "Bob";
            updatedContract.Identifiers.Remove(updatedContract.Identifiers.Where(id => id.IsMdmId).First());
            content = HttpContentExtensions.CreateDataContract(updatedContract);
        }

        protected static void Because_of()
        {
            client.DefaultHeaders.Add("If-Match", entity.Version.ToString());
            client.Post(ServiceUrl["Party"] + entity.Id, content);
        }

        [Test]
        public void should_update_the_latest_party_details()
        {
            var party = new DbSetRepository(new DbContextProvider(() => new SampleMappingContext())).FindOne<MDM.Party>(entity.Id);
            Assert.AreEqual(party.LatestDetails.Name, "Bob");
        }

        [Test]
        public void should_not_create_a_new_detail()
        {
            var party = new DbSetRepository(new DbContextProvider(() => new SampleMappingContext())).FindOne<MDM.Party>(entity.Id);
            Assert.AreEqual(party.Details.Count, 1);
        }
    }
}


text:
package com.jmace.MaceDrone.services;

import java.util.HashMap;
import java.util.Map;
import com.jmace.MaceDrone.msp.MultiWiiClient;
import com.jmace.MaceDrone.msp.MultiWiiClientFactory;
import com.jmace.MaceDrone.msp.MultiWiiRequest;

public class MWInformationService {

    private static MultiWiiClient client;

    static {
        client = MultiWiiClientFactory.getInstance();
    }

    public static Map<String, Object> getGPS() {
        try {
            return client.sendRequest(MultiWiiRequest.MSP_RAW_GPS);
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

}


text:
<?php

namespace Google\Service\OSConfig;

class VulnerabilityReportVulnerabilityDetailsReference extends \Google\Model
{
  /**
   * @var string
   */
  public $source;
  /**
   * @var string
   */
  public $url;

  /**
   * @param string
   */
  public function setSource($source)
  {
    $this->source = $source;
  }
  /**
   * @return string
   */
  public function getSource()
  {
    return $this->source;
  }
  /**
   * @param string
   */
  public function setUrl($url)
  {
    $this->url = $url;
  }
  /**
   * @return string
   */
  public function getUrl()
  {
    return $this->url;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(VulnerabilityReportVulnerabilityDetailsReference::class, 'Google_Service_OSConfig_VulnerabilityReportVulnerabilityDetailsReference');


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="${puGroupId}.common.Data" table="DATA">
        <id name="id" type="string" />
        <property name="type" type="long" />
        <property name="rawData" type="string" />
        <property name="data" type="string" />
        <property name="processed" type="boolean" />
    </class>
</hibernate-mapping>


text:
module ProcessMemory
  VERSION = '0.3.1'.freeze
end


text:
using System.Configuration;

namespace Jessica.Configuration
{
    public class JessicaConfiguration : ConfigurationSection
    {
        [ConfigurationProperty("environment", DefaultValue = "development", IsRequired = false)]
        public string Environment
        {
            get { return this["environment"].ToString().ToLower(); }
            set { this["environment"] = value; }
        }

        public bool IsDevelopment
        {
            get { return Environment.ToLower() == "development"; }
        }

        public bool IsProduction
        {
            get { return Environment.ToLower() == "production"; }
        }

        public bool IsTesting
        {
            get { return Environment.ToLower() == "testing"; }
        }

        [ConfigurationProperty("publicDir", DefaultValue = "public", IsRequired = false)]
        public string PublicDirectory
        {
            get { return this["publicDir"].ToString(); }
            set { this["publicDir"] = value; }
        }

        [ConfigurationProperty("viewsDir", DefaultValue = "views", IsRequired = false)]
        public string ViewsDirectory
        {
            get { return this["viewsDir"].ToString(); }
            set { this["viewsDir"] = value; }
        }
    }
}


text:
#pragma once
#include <aws/ce/CostExplorer_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace CostExplorer
{
namespace Model
{
  class AWS_COSTEXPLORER_API CreateAnomalyMonitorResult
  {
  public:
    CreateAnomalyMonitorResult();
    CreateAnomalyMonitorResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    CreateAnomalyMonitorResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
 The unique identifier of your newly created cost anomaly detection
     * monitor.

     */
    inline const Aws::String& GetMonitorArn() const{ return m_monitorArn; }

    /**
     *
 The unique identifier of your newly created cost anomaly detection
     * monitor.

     */
    inline void SetMonitorArn(const Aws::String& value) { m_monitorArn = value; }

    /**
     *
 The unique identifier of your newly created cost anomaly detection
     * monitor.

     */
    inline void SetMonitorArn(Aws::String&& value) { m_monitorArn = std::move(value); }

    /**
     *
 The unique identifier of your newly created cost anomaly detection
     * monitor.

     */
    inline void SetMonitorArn(const char* value) { m_monitorArn.assign(value); }

    /**
     *
 The unique identifier of your newly created cost anomaly detection
     * monitor.

     */
    inline CreateAnomalyMonitorResult& WithMonitorArn(const Aws::String& value) { SetMonitorArn(value); return *this;}

    /**
     *
 The unique identifier of your newly created cost anomaly detection
     * monitor.

     */
    inline CreateAnomalyMonitorResult& WithMonitorArn(Aws::String&& value) { SetMonitorArn(std::move(value)); return *this;}

    /**
     *
 The unique identifier of your newly created cost anomaly detection
     * monitor.

     */
    inline CreateAnomalyMonitorResult& WithMonitorArn(const char* value) { SetMonitorArn(value); return *this;}

  private:

    Aws::String m_monitorArn;
  };

} // namespace Model
} // namespace CostExplorer
} // namespace Aws


text:
import {
	Component,
	Directive,
	HostBinding,
	Input,
	ViewChildren,
	ViewChild,
	ContentChild,
	ElementRef,
	EventEmitter,
	Output,
	HostListener,
	ChangeDetectionStrategy,
} from '@angular/core'
import {Observable, Subject} from 'rxjs'
import {MdVirtualRepeat} from './repeater'
import style from './style.css!text'
import template from './container.html!text'
import {NUM_EXTRA, ELEMENT_MAX_PIXELS} from './constants'

@Component({
	selector: 'md-virtual-repeat-container',
	template,
	styles: [style],
	changeDetection: ChangeDetectionStrategy.OnPush
})
export class MdVirtualRepeatContainer {
	@ViewChild('scroller') scroller
	@ViewChild('sizer') sizer
	@ViewChild('offsetter') offsetter
	@Input('md-orient-horizontal') horizontal
	@Input() autoShrink
	@Input('md-auto-shrink-min') autoShrinkMin = 0
	@Input('md-offset-size') offsetSize = 0
	@Output() $mdResizeEnable = new EventEmitter
	@HostBinding('class') mdOrient = 'md-orient-vertical'
	constructor($element: ElementRef) {
		Object.assign(this, {$element})

		this.size = 0
		this.scrollSize = 0
		this.scrollOffset = 0
		this.repeater = null
		this.originalSize = null
		this.oldElementSize = null
		this.maxElementPixels = ELEMENT_MAX_PIXELS
	}
	@ContentChild(MdVirtualRepeat)
	set repeater(value) {
		this._repeater = value
		if (value) value.container = this
	}
	get repeater() {
		return this._repeater
	}
	@Output() topIndexChange = new EventEmitter
	@Input() topIndex = 0
	@HostListener('window:resize', ['$event'])
	@HostListener('$mdResize', ['$event'])
	@Output() sizeChange = new EventEmitter
	onResize(e) {
		this.sizeUpdates$.next(e)
	}
	ngAfterViewInit() {
		requestAnimationFrame(() => {
			this.updateSize()

			this.sizeUpdates$ = new Subject

			this.sizeUpdates$
				.debounceTime(10)
				.do(() => this.updateSize())
				.subscribe()

			this.sizeUpdates$.next(true)
			this.$mdResizeEnable.emit()
		})
	}
	ngOnChanges(changes) {
		if (changes.horizontal) {
			this.mdOrient = changes.horizontal.currentValue
				? 'md-orient-horizontal'
				: 'md-orient-vertical'
		}
		if (changes.topIndex) {
			const {currentValue, previousValue} = changes.topIndex
			if (currentValue !== previousValue) {
				this.scrollToIndex(currentValue)
			}
		}
	}
	ngOnDestroy() {
		this.sizeUpdates$.unsubscribe()
	}
	isHorizontal() {
		return this.horizontal
	}
	getSize() {
		return this.size
	}
	setSize_(size) {
		const dimension = this.getDimensionName_()

		this.size = size
		this.$element.nativeElement.style[dimension] = `${size}px`
	}
	unsetSize_() {
		this.$element.style[this.getDimensionName_()] = this.oldElementSize
		this.oldElementSize = null
	}
	updateSize() {
		if (this.originalSize) return

		this.size = this.isHorizontal()
			? this.$element.nativeElement.clientWidth
			: this.$element.nativeElement.clientHeight

		this.handleScroll_()

		this.repeater && this.repeater.containerUpdated()
	}
	getScrollSize() {
		return this.scrollSize
	}
	getDimensionName_() {
		return this.isHorizontal() ? 'width' : 'height'
	}
	sizeScroller_(size) {
		const dimension = this.getDimensionName_()
		const crossDimension = this.isHorizontal() ? 'height' : 'width'

		this.sizer.nativeElement.innerHTML = ''

		if (size < this.maxElementPixels) {
			this.sizer.nativeElement.style[dimension] = `${size}px`
		} else {
			this.sizer.nativeElement.style[dimension] = 'auto'
			this.sizer.nativeElement.style[crossDimension] = 'auto'

			const numChildren = Math.floor(size / this.maxElementPixels)
			const sizerChild = document.createElement('div')
			sizerChild.style[dimension] = `${this.maxElementPixels}px`
			sizerChild.style[crossDimension] = '1px'

			for (let i = 0; i < numChildren; i++) {
				this.sizer.nativeElement.appendChild(sizerChild.cloneNode(false))
			}

			sizerChild.style[dimension] = `${(size - (numChildren * this.maxElementPixels))}px`
			this.sizer.nativeElement.appendChild(sizerChild)
		}
		this.sizeChange.emit(size)
	}
	autoShrink_(size) {
		const shrinkSize = Math.max(size, this.autoShrinkMin * this.repeater.getItemSize())

		if (this.autoShrink && shrinkSize !== this.size) {
			if (this.oldElementSize === null) {
				this.oldElementSize = this.$element.nativeElement.style[this.getDimensionName_()]
			}

			const currentSize = this.originalSize || this.size

			if (!currentSize || shrinkSize < currentSize) {
				if (!this.originalSize) {
					this.originalSize = this.size
				}

				this.setSize_(shrinkSize)
			} else if (this.originalSize !== null) {
				this.unsetSize_()

				const _originalSize = this.originalSize
				this.originalSize = null

				if (!_originalSize) this.updateSize()

				this.setSize_(_originalSize || this.size)
			}

			this.repeater.containerUpdated()
		}
	}
	setScrollSize(itemsSize) {
		const size = itemsSize + this.offsetSize
		if (this.scrollSize === size) return

		this.sizeScroller_(size)
		this.autoShrink_(size)
		this.scrollSize = size
	}
	getScrollOffset() {
		return this.scrollOffset
	}
	scrollTo(position) {
		this.scroller.nativeElement[this.isHorizontal() ? 'scrollLeft' : 'scrollTop'] = position
		this.handleScroll_()
	}
	scrollToIndex(index) {
		const itemsSize = this.repeater.getItemSize()
		const itemsLength = this.repeater.itemsLength
		if (index > itemsLength) {
			index = itemsLength - 1
		}
		this.scrollTo(itemsSize * index)
	}
	resetScroll() {
		this.scrollTo(0)
	}
	handleScroll_() {
		const ltr = document.dir != 'rtl' && document.body.dir !== 'rtl'
		if (!ltr && this.maxSize) {
			this.scroller.nativeElement.scrollLeft = this.scrollSize
			this.maxSize = this.scroller.nativeElement.scrollLeft
		}
		const offset = this.isHorizontal() ?
			(ltr ? this.scroller.nativeElement.scrollLeft : this.maxSize - this.scroller.nativeElement.scrollLeft)
			: this.scroller.nativeElement.scrollTop
		if (offset === this.scrollOffset || offset > this.scrollSize - this.size) return

		const itemSize = this.repeater.getItemSize()
		if (!itemSize) return

		const numItems = Math.max(0, Math.floor(offset / itemSize) - NUM_EXTRA)

		const transform = (this.isHorizontal() ? 'translateX(' : 'translateY(') +
			(!this.isHorizontal() || ltr ? (numItems * itemSize) : - (numItems * itemSize)) + 'px)'

		this.scrollOffset = offset
		this.offsetter.nativeElement.style.webkitTransform = transform
		this.offsetter.nativeElement.style.transform = transform

		{
			const topIndex = Math.floor(offset / itemSize)
			if (topIndex !== this.topIndex && topIndex < this.repeater.getItemCount()) {
				this.topIndex = topIndex
				this.topIndexChange.emit(topIndex)
			}
		}

		this.repeater.containerUpdated()
	}
}


text:
<?php
	require_once('../support/config.php');
	if(isset($_POST['username'])&&isset($_POST['password'])&&isset($_POST['name'])&&isset($_POST['account'])&&isset($_POST['id'])){
		$username=$_POST['username'];
		$users_id=$_POST['id'];
		$rowcount= $connection->myQuery("SELECT * FROM users where username = '$username' AND user_id != $users_id")->rowcount();
		echo $rowcount;

		if($rowcount>0){
			setAlert("Uhh ohh Someone already has that username",'danger');
			redirect('../edit_userform.php?id='.$users_id);

		}else{

			$fullname=$_POST['name'];
			$account=$_POST['account'];
			$password = encryptIt($_POST['password']);
			$query= $connection->myQuery("UPDATE `users` SET `full_name` = '$fullname', `username` = '$username', `password` = '$password', `user_type` = '$account' WHERE `users`.`user_id` = $users_id");
			setAlert("Sucessfully changed user info",'success');
			redirect('../edit_userform.php?id='.$users_id);
		}

	}else{
		redirect('../index.php');
	}

?>


text:
<?php
/**
 * jobber job board platform
 *
 * @author     Filip C.T.E. <http://www.filipcte.ro> <me@filipcte.ro>
 * @license    You are free to edit and use this work, but it would be nice if you always referenced the original author ;)
 *             (see license.txt).
 *
 * Misc functions
 */

function add_single_quotes($arg)
{
	/* single quote and escape single quotes and backslashes */
	return "'" . addcslashes($arg, "'\\") . "'";
}

function get_countries_cloud()
{
	global $db;
	$country_array = array();

	$sql = 	'SELECT c.id, c.name, COUNT(*) AS nr
			 FROM '.DB_PREFIX.'countries c
			 INNER JOIN '.DB_PREFIX.'jobs j ON (j.country_id = c.id )
			 WHERE j.is_active = 1
			 GROUP BY c.name';

	$countries = $db->QueryArray($sql);

	foreach ($countries as $country)
	{
		$numberOfJobs = $country['nr'];

		$country_array[] = array('name' => $country['name'],
		                     'varname' => str_replace(' ', '-', $country['name']),
		                     'count' => $numberOfJobs,
		                     'tag_height' => get_cloud_tag_height($numberOfJobs));
	}

	return $country_array;
}

function get_cloud_tag_height($numberOfItems)
{
	if ($numberOfItems < 2)
	{
		$tag_height = 1;
	}
	else if ($numberOfItems >= 2 && $numberOfItems < 3)
	{
		$tag_height = 2;
	}
	else if ($numberOfItems >= 3 && $numberOfItems < 4)
	{
		$tag_height = 3;
	}
	else if ($numberOfItems >= 4 && $numberOfItems < 5)
	{
		$tag_height = 4;
	}
	else if ($numberOfItems >= 5 && $numberOfItems < 6)
	{
		$tag_height = 5;
	}
	else if ($numberOfItems >= 6)
	{
		$tag_height = 6;
	}

	return $tag_height;
}

function get_categories()
{
    global $db;
    $categories = array();
    $sql = 'SELECT *
                   FROM '.DB_PREFIX.'categories
                   ORDER BY category_order ASC';
    $result = $db->query($sql);
    while ($row = $result->fetch_assoc())
    {
        $categories[] = array('id' => $row['id'], 'name' => $row['name'], 'var_name' => $row['var_name'], 'title' => $row['title'], 'description' => $row['description'], 'keywords' => $row['keywords']);
    }
    return $categories;
}

function get_articles()
{
	global $db;
	$articles = array();
	$sql = 'SELECT id, title, page_title, url
	               FROM '.DB_PREFIX.'pages
	               ORDER BY title ASC';
	$result = $db->query($sql);
	while ($row = $result->fetch_assoc())
	{
		$articles[$row['url']] = $row;
	}
	return $articles;
}

function get_navigation($menu = false)
{
	global $db;

	$conditions = '';

	if (isset($menu) && ($menu == 'primary' || $menu == 'secondary' || $menu == 'footer1' || $menu == 'footer2' || $menu == 'footer3'))
		$conditions = ' WHERE menu = \''.$menu.'\'';

	$navigation = array();

	$sql = 'SELECT id, url, name, title, menu
				FROM '.DB_PREFIX.'links
				' . $conditions . '
				ORDER BY link_order ASC';

	$result = $db->query($sql);
	while ($row = $result->fetch_assoc())
	{
		$url_check = substr($row['url'], 0, 4);
		if ($url_check == 'http' || $url_check == 'www.') $outside = 1; else $outside = 0;

		$navigation[$row['menu']][] = array(
								'id' => $row['id'],
								'url' => $row['url'],
								'name' => $row['name'],
								'title' => $row['title'],
								'menu' => $row['menu'],
								'outside' => $outside);
	}
	return $navigation;
}

function get_countries()
{
	global $db;

	$countries = array();

	$sql = 'SELECT id, name
	               FROM '.DB_PREFIX.'countries
	               ORDER BY name ASC';

	$result = $db->query($sql);

	while ($row = $result->fetch_assoc())
	{
		$countries[] = array('id' => $row['id'], 'name' => $row['name'], 'ascii_name' => str_replace(' ', '-', $row['name']));
	}

	return $countries;
}

function get_categ_id_by_varname($var_name)
{
	global $db;
	$sql = 'SELECT id FROM '.DB_PREFIX.'categories WHERE var_name = "' . $var_name . '"';
	$result = $db->query($sql);
	$row = $result->fetch_assoc();
	if ($row) return $row['id'];
	return '';
}

function get_categ_name_by_varname($var_name)
{
    global $db;
    $sql = 'SELECT name FROM '.DB_PREFIX.'categories WHERE var_name = "' . $var_name . '"';
    $result = $db->query($sql);
    $row = $result->fetch_assoc();
    return $row['name'];
}

function get_country_id_by_asciiname($ascii_name)
{
	global $db;

	$country = null;

	$sql = 'SELECT id, name
	               FROM '.DB_PREFIX.'countries
	               WHERE name = "' . str_replace('-', ' ', $ascii_name) . '"';

	$result = $db->query($sql);
	$row = $result->fetch_assoc();

	if ($row)
		$country = array('id' => $row['id'], 'name' => $row['name']);

	return $country;
}

/**
* Converts the multidimensional array that results after calling parse_ini_file (filePath, processSections = true)
* to a JSON string.
* The resulting JSON string will look something like this:
* {"sectionOne": {"messageKeyOne": "messageTextOne", "messageKeyTwo": "messageTextTwo"}, "sectionTwo": {....},....}
*
* @author putypuruty
*/
function iniSectionsToJSON($iniSections)
{
	$translationsJson = "{";
	$sectionsCount = 0;

	foreach ($iniSections as $section => $sectionMessages)
	{
		$translationsJson = $translationsJson . "\"" . $section . "\": {";
		$sectionMessagesCount = 0;

		foreach ($sectionMessages as $messageKey => $messageText)
		{
			$translationsJson = $translationsJson . "\"".$messageKey . "\":\"" . preg_replace("/\r?\n/", "\\n", addslashes($messageText)) . "\"";

			$sectionMessagesCount++;

			if ($sectionMessagesCount < count($sectionMessages))
				$translationsJson .= ",";
		}
		$translationsJson .= "}";

		$sectionsCount++;

		if ($sectionsCount < count($iniSections))
			$translationsJson .= ",";
	}

	$translationsJson = $translationsJson."}";

	return $translationsJson;
}

/**
 * Returns the country with the specified ID or null
 * if the country was not found.
 *
 * @param $countryID
 * @return
 */
function get_country_by_id($countryID)
{
	global $db;

	$country = null;

	$sql = 'SELECT id, name
	               FROM '.DB_PREFIX.'countries
	               WHERE id = ' . $countryID;
	$result = $db->query($sql);

	$row = $result->fetch_assoc();

	if ($row)
		$country = array('id' => $row['id'], 'name' => $row['name']);

	return $country;
}

function get_types()
{
	global $db;
	$sql = 'SELECT id, name, var_name
		FROM '.DB_PREFIX.'types ';
	$result = $db->query($sql);
	$types = array();
	while($row = $result->fetch_assoc())
	{
		$types[] = array('id' => $row['id'], 'name' => $row['name'], 'var_name' => $row['var_name']);
	}
	return $types;
}

function get_type_id_by_varname($var_name)
{
	global $db;
	$sql = 'SELECT id FROM '.DB_PREFIX.'types WHERE
		var_name = "'.$var_name.'"';
	$result = $db->query($sql);
	$row = $result->fetch_assoc();

	if ($row)
		return $row['id'];
	return false;
}

function get_type_varname_by_id($id)
{
	global $db;
	$sql = 'SELECT var_name FROM '.DB_PREFIX.'types WHERE
		id = '.$id;
	$result = $db->query($sql);
	$row = $result->fetch_assoc();

	if ($row)
		return $row['var_name'];
	return false;
}

function get_category_by_var_name($var_name)
{
	global $db;
	$category = null;

	$sql = 'SELECT *
	               FROM '.DB_PREFIX.'categories
	               WHERE var_name = "' . $var_name . '"';

	$result = $db->query($sql);
	$row = $result->fetch_assoc();

	if ($row)
		$category = build_category_from_result_set_row($row);

	return $category;
}

function get_category_by_id($id)
{
	global $db;
	$category = null;

	$sql = 'SELECT *
	               FROM '.DB_PREFIX.'categories
	               WHERE id = ' . $id;

	$result = $db->query($sql);
	$row = $result->fetch_assoc();

	if ($row)
		$category = build_category_from_result_set_row($row);

	return $category;
}

function build_category_from_result_set_row($row)
{
	return array('id' => $row['id'], 'name' => $row['name'], 'var_name' => $row['var_name'],
			     'title' => $row['title'], 'description' => $row['description'],
			     'keywords' => $row['keywords'], 'category_order' => $row['category_order']);
}

function generate_sitemap($type)
{
    global $db;
    $sanitizer = new Sanitizer;

    // Get all links
    $result = $db->query('SELECT url FROM '.DB_PREFIX.'links');
    while ($row = $result->fetch_assoc()) if (!strstr($row['url'], 'http://')) $sitemap[BASE_URL . $row['url'] . '/'] = 1;

    // Get all custom pages
    $result = $db->query('SELECT url FROM '.DB_PREFIX.'pages');
    while ($row = $result->fetch_assoc()) $sitemap[BASE_URL . $row['url'] . '/'] = 1;

    // Get all categories
    $categories = get_categories();
    $i = 0; while($i < count($categories)) { $sitemap[BASE_URL . URL_JOBS . '/' . $categories[$i]['var_name'] . '/'] = 1; $i++; }

    // Get all countries
    $countries = get_countries();
    $i = 0; while($i < count($countries)) { $sitemap[BASE_URL . URL_JOBS_IN_COUNTRY . '/' . $countries[$i]['ascii_name'] . '/'] = 1; $i++; }

    // Get all companies
    $result = $db->query('SELECT company FROM '.DB_PREFIX.'jobs WHERE is_temp = 0 AND is_active = 1 GROUP BY company');
    while ($row = $result->fetch_assoc()) $sitemap[BASE_URL . URL_JOBS_AT_COMPANY . '/' . $sanitizer->sanitize_title_with_dashes($row['company']) . '/'] = 1;

    // Get all active Jobs
    $result = $db->query('SELECT id, title, company FROM '.DB_PREFIX.'jobs WHERE is_active = 1 AND is_temp = 0');
    while ($row = $result->fetch_assoc()) $sitemap[BASE_URL . URL_JOB . '/' . $row['id'] . '/' . $sanitizer->sanitize_title_with_dashes($row['title'])] = 1;

    // Generate output
    if ($type == 'xml')
    {
        header('Content-Type: text/xml; charset="utf-8"');

        echo '<?xml version="1.0" encoding="UTF-8"?>';
        echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

        foreach ($sitemap as $url => $value)
        {
            echo '<url><loc>'.$url.'</loc></url>';
        }
        echo '</urlset>';
    }
    else
    {
        foreach ($sitemap as $url => $value)
        {
            echo $url.'<br />';
        }
    }

}
?>


text:
class NumbersInWords::ToNumber
  delegate :to_s, to: :that
  delegate :powers_of_ten_to_i, :exceptions_to_i, :canonize, \
      :check_mixed, :check_one, :strip_minus, :check_decimal, :get_fraction_names,
    to: :language
  attr_reader :that, :language

  def initialize that, language=NumbersInWords.language
    @that = that
    @language = language
  end

  def language
    if @language.is_a? Module
      @language
    else
      @language = NumbersInWords.const_get(@language)
    end
  end

  def handle_negative(text, only_compress)
    stripped = strip_minus text
    if stripped
      stripped_n = NumbersInWords.in_numbers(stripped, language, only_compress)
      only_compress ? stripped_n.map{ |k| k * -1 } : -1 * stripped_n
    end
  end

  def in_numbers(only_compress = false)
    text = to_s.strip
    return text.to_f if text =~ /^-?\d+(.\d+)?$/

    text = strip_punctuation text

    i = handle_negative(text, only_compress)
    return i if i

    mixed = check_mixed text
    return mixed if mixed

    one = check_one text
    if one
      res = NumbersInWords.in_numbers(one[1], language)
      return only_compress ? [res] : res
    end

    h = handle_decimals text
    return h if h

    f = handle_fractions text
    return f if f
    integers = word_array_to_integers text.split(" ")

    NumbersInWords::NumberParser.parse integers, only_compress
  end

  def strip_punctuation text
    text = text.downcase.gsub(/[^a-z 0-9]/, " ")
    to_remove = true

    to_remove = text.gsub! "  ", " " while to_remove

    text
  end

  def handle_decimals text
    match = check_decimal text
    if match
      integer = NumbersInWords.in_numbers(match.pre_match)
      decimal = NumbersInWords.in_numbers(match.post_match)
      integer +=  "0.#{decimal}".to_f
    end
  end

  def decimal_portion text
    words    = text.split " "
    integers = word_array_to_integers words
    decimal  = "0." + integers.join()
    decimal.to_f
  end

  def handle_fractions text
    fracs = get_fraction_names
    if text.match(/(#{fracs.join('|')})/) # we have a fraction
      match = text.match(/\sand\s/)
      if match # there's a whole number prefix
        integer = match.pre_match.in_numbers
        fraction = fraction_portion match.post_match
        integer + fraction
      else # the fraction stands alone
        fraction_portion text
      end
    end
  end

  def fraction_portion text
    words    = text.split " "
    words    = words.collect(&:singularize)
    integers = word_array_to_integers words
    integers.inject(:*) # multiply them all together
  end

  #handles simple single word numbers
  #e.g. one, seven, twenty, eight, thousand etc
  def word_to_integer word
    text = canonize(word.to_s.chomp.strip)

    exception = exceptions_to_i[text]
    return exception if exception

    power = powers_of_ten_to_i[text]
    return 10 ** power if power
  end

  def word_array_to_integers words
    words.map { |i| word_to_integer i }.compact
  end
end


text:
CrugeMailer
===========

Permite enviar correos electronicos basados en esquema de vistas y patrones (views & layouts), ayudando ademas a la centralizacion del despacho de los correos.

creado por:

	Yii Framework en Español
	licencia: http://www.yiiframeworkenespanol.org/license

versiones:

	10-JUL-2012 Carlos Belisario <carlos.belisario.gonzalez@gmail.com>	addexception, sendEmail
	09-JUL-2012	Christian Salazar <christiansalazarh@gmail.com>			initial-commit

###Uso (ejemplo)

Supongamos que tienes un modelo cualquiera:

		$juanperez = new Usuario();					// tu modelo
		$juanperez->email = 'juanperez@gmail.com';	// argumentos de prueba
		$juanperez->nombres = "Juan Perez";			//

el componente se usaria asi:

		Yii::app()->crugemailer->tuMetodoConTuNombreEspecifico($juanperez,"asunto");

		Importante: tuMetodoConTuNombreEspecifico es un nombre de ejemplo,
		tu puedes poner aqui cosas reales como:
		$tumodelo->sendPasswordRecovery()

esa llamada invocaria a un layout y una vista para darle formato a ese correo electronico, las vistas de ejemplo serían:

1. crear en application.views.layouts un archivo mailer.php, con el layout deseado, comun para cada correo a ser enviado.

2. luego crear en applications.views.mailer la cantidad de archivos necesarios que representen a cada vista de cada correo a ser enviado.

###Como Implementar

	1. crea o busca una carpeta llamada "extensions" dentro de protected.
		ejemplo: E:\code\test3\protected\extensions

	2. copia todo el paquete original de CrugeMailer dentro de ella.
		ejemplo: E:\code\test3\protected\extensions\crugemailer\
		aqui adentro deben haber 3 archivos:
			ICrugeMailer		es una interfaz para que puedas crear tus implementaciones
			CrugeMailerBase		es el codigo base que tiene el trabajo fuerte
			CrugeMailer			es tu propia clase en la cual crearas tus propios metodos
								tal como en este ejemplo se creo a tuMetodoConTuNombreEspecifico()

	3. configura el componente en tu propio archivo protected/config/main.php de esta forma:
			'crugemailer'=>array(
				'class' => 'application.extensions.crugemailer.CrugeMailer',
				'mailfrom' => 'christiansalazarh@gmail.com',
				'subjectprefix' => 'Prefijo que deseas agregar, es opcional - ',
			),
		nota aqui que application.extensions.crugemailer.CrugeMailer es el nombre de la clase
		que tu has creado, la extension ya trae una clase lista para usar y ampliar, por tanto
		puedes usarla directamente.

		luego configura los 'imports' para que la extension CrugeMailer sea cargada:
			'import'=>array(
				'application.models.*',
				'application.components.*',
				'application.extensions.crugemailer.*',
			),

	4. crea un layout para tus correos llamado 'mailer.php' en:
		E:\code\test3\protected\views\layouts\mailer.php
		con el siguiente contenido de ejemplo:

Titulo General del Correo

mas contenido html

puedes darle cualquier contenido al correo usando html tal cual como siempre creas vistas
			en Yii

			<?php echo $content;?>

un pie de pagina

	5. crea una carpeta llamada "mailer" dentro de tu carpeta views
		E:\code\test3\protected\views\mailer  (aqui dentro iran las vistas de cada correo)

Una vez que hayas instalado cruge el uso de este dependera del nombre que le hayas dado al componente, en este caso (paso 3) le dimos el nombre: "crugemailer", por tanto la llamada y uso del componente sera: Yii::app()->crugemailer

###Agregando tus funciones

 Debemos crear una nueva clase que extienda de CrugeMailerBase y que implemente la interfaz ICrugeMailer la cual nos garantizara que nuestra clase extendida tendrá los metodos necesarios para funcionar, mientras que CrugeMailerBase nos dará el codigo necesario para que todo funcione transparentemente.

 El paquete ya trae su clase lista para usar: CrugeMailer, a la cual solo quedaria agregarle nuevos
 metodos y nada mas:

 *Ejemplo:*

  Necesitas hacer lo siguiente, crear un metodo llamado "enviarClave", el cual le enviara al usuario la clave de su usuario en tu sistema.

	Supongamos que el modelo Usuario existe (es un ejemplo usas cualquier cosa), y que tiene
	los atributos: nombres, email, password

	1. Editas CrugeMailer.php y agregas un nuevo metodo que cumpla tus necesidades:

		public function enviarClave(Usuario $usuario){
			$this->sendemail($usuario->email,self::t("recuperacion de clave")
				,$this->render('enviarclave',array('data'=>$usuario))
			);
		}

	2. Con este metodo ya podrias hacer la siguiente llamada:

		$model = Usuario::model()->findByAttributes(array('email'=>$correo));

		Yii::app()->crugemailer->enviarClave($model);

	3. El formato del correo se manejara asi:

		CrugeMailer cargara primero el layout que hiciste en el paso 4 arriba,
		y luego sustituira la variable php $content con el contenido de la vista de
		nombre "enviarclave", este nombre se lo diste cuando hiciste: $this->render, un poco mas arriba.

		Supongamos de nuevo que el contenido de
			E:\code\test3\protected\views\mailer\enviarclave.php
		es:

Estimado usuario: <?php echo $data->nombres;?>

su clave es: <?php echo $data->password;?>

		y que el contenido del layout almacenado en:
			E:\code\test3\protected\views\layouts\mailer.php
		es:

Titulo General del Correo

mas contenido html

puedes darle cualquier contenido al correo usando html tal cual como siempre creas vistas
			en Yii

			<?php echo $content;?>

un pie de pagina

		por tanto el correo que tu cliente recibira será:

Titulo General del Correo

mas contenido html

puedes darle cualquier contenido al correo usando html tal cual como siempre creas vistas
			en Yii

Estimado usuario: Juan Perez

su clave es: 12345678

un pie de pagina

###Probando en un action de siteController

Solo a modo de ejemplo para que veas como usarla:

	public function actionIndex()
	{
		$model = new Usuario();

		$model->email = 'juanperez@gmailx.com';
		$model->nombres = "Juan Perez";
		$model->password = "123456";

		Yii::app()->crugemailer->enviarClave($model);

		// aqui render('index') no tiene nada que ver con el ejemplo, es para mostrarte
		// que crugemailer no tiene nada que ver con renders de controllers normales,
		//
		$this->render('index');
	}

###Donde personalizar la funcion mail() ?

Para esto debes revisar el archivo /protected/extensions/crugemailer/CrugeMailerBase.php
el metodo (protected) es: sendemail, el cual por defecto usa a mail(), aqui tu podrias hacer
tus propias implementaciones y ajustes.


text:
package container

const (
	testAbsPath = "/foo"
)


text:
``Google Apps Script (GAS)``はGoogleのサービスを自動化させるためのスクリプト言語です。
現在は[V8ランタイムに対応(2020年3月17日)](https://cloud.google.com/blog/ja/products/g-suite/data-processing-just-got-easier-apps-scripts-new-v8-runtime)していて、
モダンなJavaScript環境のひとつとして使うことができます。

GASに関する情報を探していると、新しい書き方と古い書き方が
混ぜこぜで書いてあるコードがたくさんヒットします。
ここでは、GASをゼロから作成できる方法というより、
ウェブに落ちているコードを、どのように読み替えればいいのか、を
中心に整理しようと思います。

```{toctree}
---
maxdepth: 1
---
gas-variables.md
gas-class.md
gas-date.md
gas-gsheet-usage.md
gas-gmail-usage.md
```

## リファレンス

- [Drive Service](https://developers.google.com/apps-script/reference/drive)
- [Forms Service](https://developers.google.com/apps-script/reference/forms)
- [Gmail Service](https://developers.google.com/apps-script/reference/gmail)
- [Spreadsheet Service](https://developers.google.com/apps-script/reference/spreadsheet)
- [Group Service](https://developers.google.com/apps-script/reference/groups)
- [V8 Runtime Overview / Syntax Examples](https://developers.google.com/apps-script/guides/v8-runtime#v8_syntax_examples)


text:
<?php

class response
{

    public static function ajax($data = [])
    {
        sys::specify_params($data, ['status', 'message']);
        sys::array_key_default_value($data, 'location', false);

        return json::encode($data);
    }

}

?>