text:
package net.sunniwell.georgeconversion;

import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import net.sunniwell.georgeconversion.db.Money;
import net.sunniwell.georgeconversion.db.MoneyRealRateBean;
import net.sunniwell.georgeconversion.db.UpgradeBean;
import net.sunniwell.georgeconversion.interfaces.ItemSwipeListener;
import net.sunniwell.georgeconversion.recyclerview.CustomAdapter;
import net.sunniwell.georgeconversion.recyclerview.DragItemHelperCallback;
import net.sunniwell.georgeconversion.util.ColorDBUtil;
import net.sunniwell.georgeconversion.util.HttpUtil;
import net.sunniwell.georgeconversion.util.JSONParserUtil;
import net.sunniwell.georgeconversion.util.MoneyDBUtil;
import net.sunniwell.georgeconversion.util.SharedPreferenceUtil;
import net.sunniwell.georgeconversion.util.SortFieldComparator;
import net.sunniwell.georgeconversion.util.UpgradeUtil;

import org.litepal.tablemanager.Connector;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener
    , NavigationView.OnNavigationItemSelectedListener{
    public static final String TAG = "jpd-MainActivity";
    private NavigationView mNavigationView;
    private Button mNavBtn;
    private DrawerLayout mDrawerLayout;
    private View mHeaderView;
    private Button mRefreshBtn;
    private RecyclerView mRecyclerLayout;
    private List<Money> mMoneyList = new ArrayList<>();
    private CustomAdapter mAdapter;
    private ItemSwipeListener mListener;
    private Button mDeleteBtn;
    private static final int requestDefaultMoney = 1;
    private static final String DEFAULT_MONEY_NUMBER = "default_money_number";
    public static final int ENTER_MAIN_ACTIVITY_STATE_NORMAL = 0; // 正常进入主Acitivity状态
    public static final int ENTER_MAIN_ACTIVITY_STATE_FROM_NAVIGATION = 1; // 从设置返回主Activity状态
    public static final int ENTER_MAIN_ACTIVITY_STATE_FROM_SELECT_MONEY = 2; // 从货币选择界面返回主Activity状态
    /**
     * 主Activity默认进入方式
     */
    public static int currentEnterActivityState = ENTER_MAIN_ACTIVITY_STATE_NORMAL;
    /**
     * Money sortField字段排序的Comparator
     */
    private SortFieldComparator mComparator;
    /**
     * 主程序退出标记
     */
    private boolean isExit = false;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = true;
        }
    };
    private static final String UPDATE_URL = "http://maven.sunniwell.net:8082/doc/test/upgrade.json";

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item2:
                Intent intent = new Intent(MainActivity.this, NavigationSettingActivity.class);
                startActivityForResult(intent, 0);
                break;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0) {
            Log.d(TAG, "onActivityResult: 0");
            currentEnterActivityState = ENTER_MAIN_ACTIVITY_STATE_FROM_NAVIGATION;
            mToolBar.setBackgroundColor(Color.parseColor(ColorDBUtil.getDefaultColor().getColorStr()));
            mHeaderView.setBackgroundColor(Color.parseColor(ColorDBUtil.getDefaultColor().getColorStr()));
        }
        if (requestCode == 1) {
            Log.d(TAG, "onActivityResult: 1");
            currentEnterActivityState = ENTER_MAIN_ACTIVITY_STATE_FROM_SELECT_MONEY;
        }
    }

    /**
     * 获取当前网络是否可用
     * @return true-可用 flase-不可用
     */
    @TargetApi(21)
    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
        Network[] networks = manager.getAllNetworks();
        NetworkInfo info;
        for (Network network : networks) {
            info = manager.getNetworkInfo(network);
            if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                return true;
            }
        }
        return false;
    }

    /**
     * item右滑状态
     */
    private boolean isSwiped = false;

    private static final String JUHE_APP_KEY = "225642569f50a0dbceacd72a94ef3519";
    private static final String JUHE_REAL_MONEY_RAT_URL = "http://op.juhe.cn/onebox/exchange/currency?";
    private Toolbar mToolBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initData();
        initView();
        registerListener();
        init();
        checkUpdate();
        showMainpageData();
        refreshMoneyRate();
    }
    private void checkUpdate() {
        Log.d(TAG, "checkUpdate: ");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String response = HttpUtil.getByURLConnection(UPDATE_URL);
                if (response != null) {
                    UpgradeBean bean = JSONParserUtil.parseUpgradeJSON(response);
                    Log.d(TAG, "checkUpdate run: bean:" + bean);
                    UpgradeUtil.from(MainActivity.this).serverVersionName(bean.getVersionName())
                            .serverVersionCode(bean.getVersionCode()).serverIsForce(bean.getIsForce())
                            .description(bean.getDescription()).apkUrl(bean.getApkUrl()).update();

                }
            }
        }).start();
    }
    private void initData() {
        // 初始化Litepal数据库
        SQLiteDatabase db = Connector.getDatabase();
        if ("".equals(SharedPreferenceUtil.getString(this, DEFAULT_MONEY_NUMBER, ""))) {
            SharedPreferenceUtil.setString(this, DEFAULT_MONEY_NUMBER, "100");
        }
        if ("".equals(SharedPreferenceUtil.getString(this, "default_color", ""))) {
            SharedPreferenceUtil.setString(this, "default_color", "#3F51B5");
            SharedPreferenceUtil.setInt(this, "default_color_position", 6);
        }
        if (!SharedPreferenceUtil.getBoolean(this, "isConfigured", false)) {
            MoneyDBUtil.setDefaultMoneyList(this);
            SharedPreferenceUtil.setBoolean(this, "isConfigured", true);
        }
        // 判断初始主界面4个位置的pref
        if ("".equals(SharedPreferenceUtil.getString(this, "firstPos", ""))) {
            // 设置初始主界面3个位置的pref和对应的moneyCode
            setPositionRecordPrefs();
        }
        if (!SharedPreferenceUtil.getBoolean(this, "isColorConfigured", false)) {
            ColorDBUtil.setDefaultColorList(this);
            SharedPreferenceUtil.setBoolean(this, "isColorConfigured", true);
        }
    }
    private void initView() {

    }
    private void registerListener() {

    }

    /**
     * 设置初始主界面3个位置的pref和对应的moneyCode
     * "0"-"CNY"
     * "1"-"USD"
     * "2"-"EUR"
     * "3"-"HKD"
     */
    private void setPositionRecordPrefs() {
        SharedPreferenceUtil.setString(this, "0", "CNY");
        SharedPreferenceUtil.setString(this, "1", "USD");
        SharedPreferenceUtil.setString(this, "2", "EUR");
        SharedPreferenceUtil.setString(this, "3", "HKD");
    }

    /**
     * 设置Adapter数据,刷新RecyclerView
     */
    private void showMainpageData() {
        // 获取默认顺序的四种主要货币
        List<Money> list = MoneyDBUtil.getMain4Money();
        // 按照sortField字段对四种默认货币排序
        Collections.sort(list, mComparator);
        // 清空Adaptor数据
        mMoneyList.clear();
        // 为Adaptor添加数据
        mMoneyList.addAll(list);
        // 刷新RecyclerView的数据
        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (currentEnterActivityState == ENTER_MAIN_ACTIVITY_STATE_NORMAL) {
            Log.d(TAG, "onResume: current state is normal,need to refresh....");
            refreshMoneyRate();
        }
        showMainpageData();
    }

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

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_nav:
                mDrawerLayout.openDrawer(Gravity.LEFT);
                break;
            case R.id.toolbar_refresh:
                refreshMoneyRate();
                refreshAnim();
                break;
            default:
                break;
        }
    }

    /**
     * 打印list数据,仅用于测试
     * @param list 要打印的list
     */
    private void printList(List<Money> list) {
        for (int i = 0; i < list.size(); i++) {
            Log.d(TAG, "printList: " + list.get(i));
        }
    }

    /**
     * 刷新主界面货币数据并保存数据库
     */
    private void refreshMoneyRate() {
        Log.d(TAG, "refreshMoneyRate: ");
        new Thread(new Runnable() {
            @Override
            public void run() {
                int successsCount = 0;
                if (isNetworkAvailable()) {
                    List<Money> list = MoneyDBUtil.getMain4Money();
                    for (int i = 0; i < list.size(); i++) {
                        Money money = list.get(i);
                        if (!"CNY".equals(money.getCode())) {
                            String response = HttpUtil.postByURLConnection(JUHE_REAL_MONEY_RAT_URL, JUHE_APP_KEY,
                                    "CNY", money.getCode());
                            MoneyRealRateBean bean = JSONParserUtil.parseRealRateJSON(response);
                            Log.d(TAG, "run: bean:" + bean);
                            if (bean.getResults() != null) { // 正常获取到汇率数据
                                MoneyRealRateBean.Result[] results = bean.getResults();
                                String fromEx = results[0].getExchange();
                                String toEx = results[1].getExchange();
                                money.setBase1CNYToCurrent(Double.parseDouble(fromEx));
                                money.setBase1CurrentToCNY(Double.parseDouble(toEx));
                                money.save();
                                successsCount++;
                            } else { // 获取数据异常
                                if (bean.getErrorCode() == 10012) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(MainActivity.this, "超过每日可允许请求次数!", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    break;
                                }
                            }
                        } else {
                            successsCount++;
                        }
                    }
                    Log.d(TAG, "run: successCount:" + successsCount);
                    if (successsCount == 4) {
                        mMoneyList.clear();
                        Collections.sort(list, mComparator);
                        mMoneyList.addAll(list);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mAdapter.notifyDataSetChanged();
                                mAdapter.needToRefresh = true;
                            }
                        });
                    }
                }
            }
        }).start();
    }

    /**
     * 刷新旋转动画-1秒钟旋转360度
     */
    private void refreshAnim() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(mRefreshBtn, "rotation", 0f, 360f);
        animator.setDuration(1000);
        animator.start();
    }

    /**
     * 初始化数据库和各种控件
     */
    private void init() {
        mToolBar = (Toolbar)findViewById(R.id.tool_bar);
        mToolBar.setBackgroundColor(Color.parseColor(ColorDBUtil.getDefaultColor().getColorStr()));
        mComparator = new SortFieldComparator();
        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        mNavigationView = (NavigationView)findViewById(R.id.nav_layout);
        mNavigationView.setItemIconTintList(null);
        mNavigationView.setNavigationItemSelectedListener(this);
        mHeaderView = mNavigationView.getHeaderView(0);
        mHeaderView.setBackgroundColor(Color.parseColor(ColorDBUtil.getDefaultColor().getColorStr()));
        mNavBtn = (Button)findViewById(R.id.toolbar_nav);
        mRefreshBtn = (Button)findViewById(R.id.toolbar_refresh);
        mNavBtn.setOnClickListener(this);
        mRefreshBtn.setOnClickListener(this);
        mDeleteBtn = (Button)findViewById(R.id.button_delete);
        mDeleteBtn.setOnLongClickListener(this);
        mRecyclerLayout = (RecyclerView)findViewById(R.id.recycler_layout);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRecyclerLayout.setLayoutManager(manager);
        mAdapter = new CustomAdapter(this, mMoneyList);
        mRecyclerLayout.setAdapter(mAdapter);
//        recyclerLayout.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        mListener = new ItemSwipeListener() {
            @Override
            public void onItemSwipe(int position) {
                isSwiped = true;
                Intent intent = new Intent(MainActivity.this, SelectMoneyActivity.class);
                intent.putExtra("money_name", mMoneyList.get(position).getName());
                intent.putExtra("position", position);
                startActivityForResult(intent, 1);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
            }
        };
        ItemTouchHelper.Callback callback = new DragItemHelperCallback(mListener);
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(mRecyclerLayout);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
                Log.d(TAG, "onBackPressed: open.");
                mDrawerLayout.closeDrawers();
                return false;
            } else {
                exit();
                return false;
            }
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void exit() {
        if (!isExit) {
            Toast.makeText(this, "再按一次退出George汇率", Toast.LENGTH_LONG).show();
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    /**
     * 数字键盘的点击事件
     * @param view 点击的键盘按键
     */
    public void onButtonClicked(View view) {
        Button btn = (Button)view;
        Log.d(TAG, "onButtonClicked: text:" + btn.getText() + ",tag:" + btn.getTag());
        mAdapter.numberChanged(Integer.parseInt((String)btn.getTag()));
    }

    @Override
    public boolean onLongClick(View v) {
        Log.d(TAG, "onLongClick: ");
        mAdapter.longPressDeleteButton();
        return true;
    }
}


text:
module SampleRailsApi
  module ApplicationHelper
  end
end

redpajama_set_name: RedPajamaGithub


text:
import sqlite3
from math import sqrt
import sys

class DGFAnalyzer:
	DebugLevel = 0
	def __init__(self,Filename):
		self.Filename=Filename
		self.FunctionNames={}
		self.Address2Function={}
		conn=sqlite3.connect(self.Filename)
		conn.text_factory = str
		self.Cursor=conn.cursor()

	def CacheFunctionInfo(self):
		TmpCursor=conn.cursor()
		TmpCursor.execute("SELECT * FROM FileInfo")
		for row in TmpCursor:
			FileID=int(row[0])
			self.FunctionNames[FileID]={}
			self.Address2Function[FileID]={}

			self.Cursor.execute("SELECT FunctionAddress,StartAddress,Name FROM OneLocationInfo WHERE FileID="+str(FileID))
			for row in self.Cursor:
				function_address=int(row[0])
				block_address=int(row[1])
				name=row[2]
				if function_address!=0:
					self.Address2Function[FileID][block_address]=function_address
				if function_address==block_address:
					self.FunctionNames[FileID][function_address]=name

	def GetNames(self,FileID):
		if FileID==1:
			FileIDColumnName="TheSourceFileID"
			AddressColumnName="TheSourceAddress"
		else:
			FileIDColumnName="TheTargetFileID"
			AddressColumnName="TheTargetAddress"
		return (FileIDColumnName,AddressColumnName)

	def RetrieveFunctionBasicBlockMap(self,FileID):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)

		FunctionHash={}
		self.Cursor.execute( "SELECT FunctionAddress,StartAddress FROM OneLocationInfo WHERE FileID='" + str(FileID) + "' AND FunctionAddress!=0 ORDER BY FunctionAddress" );
		for row in self.Cursor:
			FunctionAddress = row[0]
			StartAddress = row[1]

			if not FunctionHash.has_key(FunctionAddress):
				FunctionHash[FunctionAddress] = []
			FunctionHash[FunctionAddress].append( StartAddress )

		if self.DebugLevel > 2:
			print len(FunctionHash.keys())
			print len(FunctionHash)

		FunctionMemberCounts=[]
		for FunctionAddress in FunctionHash.keys():
			FunctionMemberCounts.append( len(FunctionHash[FunctionAddress]) )
		FunctionMemberCounts.sort()
		return FunctionMemberCounts

	def RetrievePatternAddresses(self,FileID,Pattern):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)

		FunctionHash={}
		self.Cursor.execute( "SELECT FunctionAddress,StartAddress FROM OneLocationInfo WHERE FileID='" + str(FileID) + "' AND DisasmLines like '" + Pattern + "' ORDER BY FunctionAddress" );

		Results=[]
		for row in self.Cursor:
			Results.append( (row[0],row[1] ) )
		return Results

	def RetrieveDisasmLines(self,FileID,Address):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)

		FunctionHash={}
		self.Cursor.execute( "SELECT DisasmLines FROM OneLocationInfo WHERE FileID='" + str(FileID) + "' AND StartAddress='" + str(Address) + "'" );

		Results=[]
		for row in self.Cursor:
			return row[0]
		return ""

	def GetDisasmLinesLength(self,FileID):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)

		FunctionHash={}
		self.Cursor.execute( "SELECT DisasmLines FROM OneLocationInfo WHERE FileID='" + str(FileID) + "'");

		TotalLength=0
		for row in self.Cursor:
			TotalLength += len(row[0])
		return TotalLength

	def RetrieveFingerprint(self,FileID):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)

		FunctionHash={}
		self.Cursor.execute( "SELECT Fingerprint FROM OneLocationInfo WHERE FileID='" + str(FileID) + "'");

		TotalLength=0
		for row in self.Cursor:
			TotalLength += len(row[0])
		return TotalLength

	def GetMaximumFingerPrintLength(self,FileID):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)

		FunctionHash={}
		self.Cursor.execute( "SELECT StartAddress, Fingerprint FROM OneLocationInfo WHERE FileID='" + str(FileID) + "'");

		MaximumLength=0
		for row in self.Cursor:
			start_address = row[0]
			finger_print = row[1]
			if MaximumLength < len( finger_print ):
				MaximumLength = len( finger_print )
				MaximuLengthAddress = start_address

		return (MaximuLengthAddress, MaximumLength)

	def GetIdentifiedBlocksCount(self,FileID):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)
		self.Cursor.execute("SELECT COUNT(*) FROM OneLocationInfo WHERE FunctionAddress!=0 AND Fingerprint!='' AND FileID="+str(FileID)+" AND StartAddress IN (SELECT "+AddressColumnName+" FROM MatchMap)");
		for row in self.Cursor:
			return row[0]

	def GetIdentifiedFunctionsCount(self,FileID):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)
		self.Cursor.execute("SELECT COUNT(*) FROM OneLocationInfo WHERE FunctionAddress!=0 AND Fingerprint!='' AND BlockType=1 AND FileID="+str(FileID)+" AND StartAddress IN (SELECT "+AddressColumnName+" FROM MatchMap)");
		for row in self.Cursor:
			return row[0]

	def GetMapInfoCount(self,FileID):
		try:
			self.Cursor.execute("SELECT COUNT(*) FROM MapInfo WHERE FileID="+str(FileID))
			for row in self.Cursor:
				return row[0]
		except:
			return 0

	def GetMatchMapCount(self):
		try:
			self.Cursor.execute("SELECT COUNT(*) FROM MatchMap");
			for row in self.Cursor:
				return row[0]
		except:
			return 0

	def GetMatchedFunctionList(self, Options={"matched":1} , Offset = None, Limit = None, RetrieveCount = False ):
		if RetrieveCount:
			Columns = "COUNT(*)"
		else:
			Columns = "TheSourceFileID, TheTargetFileID, TheSourceAddress, EndAddress, TheTargetAddress, BlockType, MatchRate, TheSourceFunctionName, Type, TheTargetFunctionName, MatchCountForTheSource, NoneMatchCountForTheSource, MatchCountWithModificationForTheSource, MatchCountForTheTarget, NoneMatchCountForTheTarget, MatchCountWithModificationForTheTarget"

		Query = "SELECT " + Columns + " FROM FunctionMatchInfo"

		IncludeUnidentifiedBlock = True
		Conditions = []

		include_matched = False
		if ( Options.has_key( "matched" ) and Options[ "matched" ] == 1 ):
			include_matched = True
		include_modified = False
		if ( Options.has_key( "modified" ) and Options[ "modified" ] == 1 ):
			include_modified = True

		if include_matched and include_modified:
			pass
		elif include_matched:
			Conditions.append( 'MatchRate == 100 ' )
		elif include_modified:
			Conditions.append( 'MatchRate != 100 ' )

		if not ( Options.has_key( "unidentified" ) and Options[ "unidentified" ] == 1 ):
			Conditions.append( 'TheSourceAddress != 0 ' )
			Conditions.append( 'TheTargetAddress != 0 ' )

		ConditionStr = ''
		for Condition in Conditions:
			if ConditionStr == '':
				ConditionStr += Condition
			else:
				ConditionStr += ' AND ' + Condition

		if ConditionStr != '':
			Query += ' WHERE ' + ConditionStr

		if Limit:
			Query += ' LIMIT ' + str( Limit )

		if Offset:
			Query += ' OFFSET ' + str( Offset )

		if self.DebugLevel > 2:
			print Query

		Results=[]
		try:
			self.Cursor.execute( Query );

			if RetrieveCount:
				for ( Count ) in self.Cursor:
					return Count
			else:
				for ( TheSourceFileID, TheTargetFileID, TheSourceAddress, EndAddress, TheTargetAddress, BlockType, MatchRate, TheSourceFunctionName, Type, TheTargetFunctionName, MatchCountForTheSource, NoneMatchCountForTheSource, MatchCountWithModificationForTheSource, MatchCountForTheTarget, NoneMatchCountForTheTarget, MatchCountWithModificationForTheTarget ) in self.Cursor:
					result = {}
					result["TheSourceFunctionName"] = TheSourceFunctionName
					result["TheSourceAddress"] = TheSourceAddress
					result["TheTargetFunctionName"] = TheTargetFunctionName
					result["TheTargetAddress"] = TheTargetAddress
					result["MatchRate"] = MatchRate
					result["MatchCountForTheSource"] = MatchCountForTheSource
					result["MatchCountWithModificationForTheSource"] = MatchCountWithModificationForTheSource
					result["NoneMatchCountForTheSource"] = NoneMatchCountForTheSource
					result["MatchCountForTheTarget"] = MatchCountForTheTarget
					result["MatchCountWithModificationForTheTarget"] = MatchCountWithModificationForTheTarget
					result["NoneMatchCountForTheTarget"] = NoneMatchCountForTheTarget
					Results.append( result )
		except:
			pass
		return Results

	def GetFunctionMemberMatchList(self,Options=("matched")):
		#modified,unidentified
		pass

	def GetFunctionDisasmLinesHash( self, FileID, FunctionAddress ):
		#BOOL OneIDAClientManager::RetrieveOneLocationInfo( DWORD FunctionAddress )
		self.Cursor.execute( "SELECT StartAddress, DisasmLines, Name FROM OneLocationInfo WHERE FileID = '%u' AND FunctionAddress = '%d'" % ( FileID, FunctionAddress ) )
		DisasmLinesHash={}
		for row in self.Cursor:
			DisasmLinesHash[row[0]] = row[1]
		return DisasmLinesHash

	def DumpDisasmLineHash( self, DisasmLineHash ):
		addresses = DisasmLineHash.keys()
		addresses.sort()

		for address in addresses:
			print hex(address)
			print DisasmLineHash[address]
			print ""

	def GetMatchMapForFunction( self, FileID, FunctionAddress ):
		self.Cursor.execute( "SELECT TheSourceAddress, TheTargetAddress FROM MatchMap WHERE TheSourceAddress IN (SELECT StartAddress Name FROM OneLocationInfo WHERE FileID = '%u' AND FunctionAddress = '%d')" % ( FileID, FunctionAddress ) )
		MatchHash = {}
		for row in self.Cursor:
			MatchHash[row[0]] = row[1]
		return MatchHash

	def GetMatchedFunctionMemberList( self, FunctionAddresses ):
		DisasmLineHash=[]
		DisasmLineHash.append( self.GetFunctionDisasmLines( "Source", FunctionAddresses[0] ) )
		DisasmLineHash.append( self.GetFunctionDisasmLines( "Target", FunctionAddresses[1] ) )

		#self.DumpDisasmLineHash( DisasmLineHash[0] )
		#self.DumpDisasmLineHash( DisasmLineHash[1] )

		MatchMap = self.GetMatchMapForFunction( 1, FunctionAddresses[0] )

		#for Src in MatchMap.keys():
		#	print hex(Src), hex(MatchMap[Src])

		return ( DisasmLineHash, MatchMap )

		#BOOL OneIDAClientManager::Retrieve(DBWrapper *InputDB, int FileID, BOOL bRetrieveDataForAnalysis, DWORD FunctionAddress )
		#self.Cursor.execute( "SELECT Type, SrcBlock, Dst From MapInfo WHERE FileID = %u AND SrcBlock IN (SELECT StartAddress FROM OneLocationInfo WHERE FileID = '%d' AND FunctionAddress='%d') AND Dst IN (SELECT StartAddress FROM OneLocationInfo WHERE FileID = '%d' AND FunctionAddress='%d') ORDER BY ID ASC" % ( FileID, FileID, FunctionAddress, FileID, FunctionAddress ) )
		#for row in self.Cursor:
		#	print row

	def GetUnidentifiedFunctionsCount(self,FileID):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)
		self.Cursor.execute("SELECT COUNT(*) FROM OneLocationInfo WHERE FunctionAddress!=0 AND Fingerprint!='' AND BlockType=1 AND FileID="+str(FileID)+" AND StartAddress NOT IN (SELECT "+AddressColumnName+" FROM MatchMap)");
		for row in self.Cursor:
			return row[0]

	def GetFullMatchedBlocksCount(self):
		try:
			self.Cursor.execute("SELECT COUNT(*) FROM MatchMap WHERE MatchRate='100'");
			for row in self.Cursor:
				return row[0]
		except:
			return 0

	def GetUnidentifiedFunctions(self,FileID):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)
		self.Cursor.execute("SELECT Name FROM OneLocationInfo WHERE FunctionAddress!=0 AND Fingerprint!='' AND BlockType=1 AND FileID="+str(FileID)+" AND StartAddress NOT IN (SELECT "+AddressColumnName+" FROM MatchMap)");
		return self.Cursor

	def GetUnidentifiedBlocksCount(self,FileID):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)
		try:
			self.Cursor.execute("SELECT COUNT(*) FROM OneLocationInfo WHERE FunctionAddress!=0 AND Fingerprint!='' AND FileID="+str(FileID)+" AND StartAddress NOT IN (SELECT "+AddressColumnName+" FROM MatchMap)");
			for row in self.Cursor:
				return row[0]
		except:
			return 0

	def GetOneLocationInfoCount(self,FileID):
		self.Cursor.execute("SELECT COUNT(*) FROM OneLocationInfo WHERE FunctionAddress!=0 AND Fingerprint!='' AND FileID="+str(FileID))
		for row in self.Cursor:
			return row[0]

	def GetCount(self,FileID):
		(FileIDColumnName,AddressColumnName)=self.GetNames(FileID)
		query="SELECT FunctionAddress,StartAddress FROM OneLocationInfo WHERE FunctionAddress!=0 AND Fingerprint!='' AND FileID="+str(FileID)+" AND StartAddress NOT IN (SELECT "+AddressColumnName+" FROM MatchMap) ORDER BY FunctionAddress"
		if self.DebugLevel > 2:
			print query
		self.Cursor.execute(query);
		for row in self.Cursor:
			function_address=int(row[0])
			block_address=int(row[1])
			function_name="("+hex(function_address)+")"
			if self.FunctionNames[FileID].has_key(function_address):
				function_name=self.FunctionNames[FileID][function_address]
			if self.DebugLevel > 2:
				print function_name+"."+hex(block_address)

	def GetTypeStr(self,Type):
		Types=("Name","Fingerprint","Two Level fingerprint","Tree","Fingerprint Inside Function","Function")
		if len(Types)<=Type:
			return "Unknown"
		return Types[Type]

"""
c.execute("SELECT COUNT(DISTINCT(TheSourceAddress)) FROM MatchMap WHERE MatchRate!=100")
for row in c:
	print 'Modified Blocks',row,sqrt(row[0])

Matches={}
IdentifiedFunctions={}
c.execute("SELECT TheSourceFileID,TheTargetFileID,TheSourceAddress,TheTargetAddress,Type,MatchRate,UnpatchedParentAddress,PatchedParentAddress FROM MatchMap")
for row in c:
	TheSourceFileID=int(row[0])
	TheTargetFileID=int(row[1])

	TheSourceAddress=int(row[2])
	TheTargetAddress=int(row[3])

	TheSourceFunctionAddress=0
	if self.Address2Function[TheSourceFileID].has_key(TheSourceAddress):
		TheSourceFunctionAddress=self.Address2Function[TheSourceFileID][TheSourceAddress]

	TheTargetFunctionAddress=0
	if self.Address2Function[TheTargetFileID].has_key(TheTargetAddress):
		TheTargetFunctionAddress=self.Address2Function[TheTargetFileID][TheTargetAddress]

	if not IdentifiedFunctions.has_key(TheSourceFileID):
		IdentifiedFunctions[TheSourceFileID]={}
	if not IdentifiedFunctions[TheSourceFileID].has_key(TheSourceFunctionAddress):
		IdentifiedFunctions[TheSourceFileID][TheSourceFunctionAddress]=[]

	if not IdentifiedFunctions.has_key(TheTargetFileID):
		IdentifiedFunctions[TheTargetFileID]={}
	if not IdentifiedFunctions[TheTargetFileID].has_key(TheTargetFunctionAddress):
		IdentifiedFunctions[TheTargetFileID][TheTargetFunctionAddress]=[]
	if not Matches.has_key(TheSourceFunctionAddress):
		Matches[TheSourceFunctionAddress]=[]
	Matches[TheSourceFunctionAddress].append((TheSourceAddress,TheTargetFunctionAddress,TheTargetAddress,row[4],row[5],row[6],row[7]))

TheSourceFileID=1
TheTargetFileID=2
DoPrintAll=False
for TheSourceFunctionAddress in Matches.keys():
	TheSourceFunctionName=''
	TheSourceFunctionName=hex(TheSourceFunctionAddress)
	if self.FunctionNames[TheSourceFileID].has_key(TheSourceFunctionAddress):
		TheSourceFunctionName=self.FunctionNames[TheSourceFileID][TheSourceFunctionAddress]
	TheLastTargetFunctionAddress=0
	for (TheSourceAddress,TheTargetFunctionAddress,TheTargetAddress,Type,MatchRate,TheParentSourceAddress,TheParentTargetAddress) in Matches[TheSourceFunctionAddress]:
		if TheLastTargetFunctionAddress!=TheTargetFunctionAddress:
			TheTargetFunctionName=hex(TheTargetFunctionAddress)
			if self.FunctionNames[TheTargetFileID].has_key(TheTargetFunctionAddress):
				TheTargetFunctionName=self.FunctionNames[TheTargetFileID][TheTargetFunctionAddress]
			print TheSourceFunctionName,TheTargetFunctionName
			TheLastTargetFunctionAddress=TheTargetFunctionAddress
		if MatchRate!=100 or DoPrintAll:
			print '\t',hex(TheSourceAddress),hex(TheTargetAddress),GetTypeStr(Type),MatchRate,hex(TheParentSourceAddress),hex(TheParentTargetAddress)

IdentifiedFunctions[TheTargetFileID][TheTargetFunctionAddress]=[]
for FileID in self.FunctionNames.keys():
	for FunctionAddress in self.FunctionNames[FileID].keys():
		if IdentifiedFunctions.has_key(FileID) and not IdentifiedFunctions[FileID].has_key(FunctionAddress):
			print 'Unidentified Function',FileID,self.FunctionNames[FileID][FunctionAddress],hex(FunctionAddress)

"""


text:
package usbong.android.builder.fragments.dialogs;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 * Use the {@link usbong.android.builder.fragments.dialogs.DeleteConfirmationDialogFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DeleteConfirmationDialogFragment extends DialogFragment {

    private Callback callback;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment AddingChildToItselfWarningDialogFragment.
     */
    public static DeleteConfirmationDialogFragment newInstance() {
        DeleteConfirmationDialogFragment fragment = new DeleteConfirmationDialogFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public DeleteConfirmationDialogFragment() {
        // Required empty public constructor
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
                .setMessage("Are you sure you want to delete?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (callback != null) {
                            callback.onYes();
                        }
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (callback != null) {
                            callback.onNo();
                        }
                    }
                })
                .create();
    }

    public interface Callback {
        void onYes();

        void onNo();
    }
}


text:
  <title>Pipeline-Demo</title>

Context-Demo


text:
$('i.glyphicon-refresh-animate').hide();
function updateRoutes(r) {
    _opts.routes.avaliable = r.avaliable;
    _opts.routes.assigned = r.assigned;
    search('avaliable');
    search('assigned');
}

$('#btn-new').click(function () {
    var $this = $(this);
    var route = $('#inp-route').val().trim();
    if (route != '') {
        $this.children('i.glyphicon-refresh-animate').show();
        $.post(_opts.newUrl, {route: route}, function (r) {
            $('#inp-route').val('').focus();
            updateRoutes(r);
        }).always(function () {
            $this.children('i.glyphicon-refresh-animate').hide();
        });
    }
});

$('.btn-assign').click(function () {
    var $this = $(this);
    var action = $this.data('action');
    var target = action == 'assign' ? 'avaliable' : 'assigned';
    var routes = $('select.list[data-target="' + target + '"]').val();

    if (routes.length) {
        $this.children('i.glyphicon-refresh-animate').show();
        $.post(_opts.assignUrl, {action: action, routes: routes}, function (r) {
            updateRoutes(r);
        }).always(function () {
            $this.children('i.glyphicon-refresh-animate').hide();
        });
    }
    return false;
});

$('#btn-refresh').click(function () {
    var $icon = $(this).children('span.glyphicon');
    $icon.addClass('glyphicon-refresh-animate');
    $.post(_opts.refreshUrl, function (r) {
        updateRoutes(r);
    }).always(function () {
        $icon.removeClass('glyphicon-refresh-animate');
    });
    return false;
});

$('.search[data-target]').keyup(function () {
    search($(this).data('target'));
});

function search(target) {
    var $list = $('select.list[data-target="' + target + '"]');
    $list.html('');
    var q = $('.search[data-target="' + target + '"]').val();
    $.each(_opts.routes[target], function () {
        var r = this;
        if (r.indexOf(q) >= 0) {
            $('<option>').text(r).val(r).appendTo($list);
        }
    });
}

// initial
search('avaliable');
search('assigned');


text:
using System;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using static QuantConnect.StringExtensions;

namespace QuantConnect.Orders
{
    /// <summary>
    /// Stop Market Order Type Definition
    /// </summary>
    public class StopLimitOrder : Order
    {
        /// <summary>
        /// Stop price for this stop market order.
        /// </summary>
        public decimal StopPrice { get; internal set; }

        /// <summary>
        /// Signal showing the "StopLimitOrder" has been converted into a Limit Order
        /// </summary>
        public bool StopTriggered { get; internal set; }

        /// <summary>
        /// Limit price for the stop limit order
        /// </summary>
        public decimal LimitPrice { get; internal set; }

        /// <summary>
        /// StopLimit Order Type
        /// </summary>
        public override OrderType Type
        {
            get { return OrderType.StopLimit; }
        }

        /// <summary>
        /// Default constructor for JSON Deserialization:
        /// </summary>
        public StopLimitOrder()
        {
        }

        /// <summary>
        /// New Stop Market Order constructor -
        /// </summary>
        /// <param name="symbol">Symbol asset we're seeking to trade</param>
        /// <param name="quantity">Quantity of the asset we're seeking to trade</param>
        /// <param name="limitPrice">Maximum price to fill the order</param>
        /// <param name="time">Time the order was placed</param>
        /// <param name="stopPrice">Price the order should be filled at if a limit order</param>
        /// <param name="tag">User defined data tag for this order</param>
        /// <param name="properties">The order properties for this order</param>
        public StopLimitOrder(Symbol symbol, decimal quantity, decimal stopPrice, decimal limitPrice, DateTime time, string tag = "", IOrderProperties properties = null)
            : base(symbol, quantity, time, tag, properties)
        {
            StopPrice = stopPrice;
            LimitPrice = limitPrice;

            if (string.IsNullOrEmpty(tag))
            {
                //Default tag values to display stop price in GUI.
                Tag = Invariant($"Stop Price: {stopPrice:C} Limit Price: {limitPrice:C}");
            }
        }

        /// <summary>
        /// Gets the order value in units of the security's quote currency
        /// </summary>
        /// <param name="security">The security matching this order's symbol</param>
        protected override decimal GetValueImpl(Security security)
        {
            // selling, so higher price will be used
            if (Quantity < 0)
            {
                return Quantity*Math.Max(LimitPrice, security.Price);
            }

            // buying, so lower price will be used
            if (Quantity > 0)
            {
                return Quantity*Math.Min(LimitPrice, security.Price);
            }

            return 0m;
        }

        /// <summary>
        /// Modifies the state of this order to match the update request
        /// </summary>
        /// <param name="request">The request to update this order object</param>
        public override void ApplyUpdateOrderRequest(UpdateOrderRequest request)
        {
            base.ApplyUpdateOrderRequest(request);
            if (request.StopPrice.HasValue)
            {
                StopPrice = request.StopPrice.Value;
            }
            if (request.LimitPrice.HasValue)
            {
                LimitPrice = request.LimitPrice.Value;
            }
        }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>
        /// A string that represents the current object.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        public override string ToString()
        {
            return Invariant($"{base.ToString()} at stop {StopPrice.SmartRounding()} limit {LimitPrice.SmartRounding()}");
        }

        /// <summary>
        /// Creates a deep-copy clone of this order
        /// </summary>
        /// <returns>A copy of this order</returns>
        public override Order Clone()
        {
            var order = new StopLimitOrder {StopPrice = StopPrice, LimitPrice = LimitPrice};
            CopyTo(order);
            return order;
        }
    }
}


text:
package me.scana.okgradle.internal.dsl.model.repositories;

import me.scana.okgradle.internal.dsl.model.repositories.MavenRepositoryModelImpl;
import me.scana.okgradle.internal.dsl.parser.elements.GradlePropertiesDslElement;
import me.scana.okgradle.internal.dsl.parser.repositories.MavenRepositoryDslElement;
import org.jetbrains.annotations.NotNull;

/**
 * Represents a repository defined with jcenter {}.
 */
public class JCenterRepositoryModel extends MavenRepositoryModelImpl {
  public JCenterRepositoryModel(@NotNull GradlePropertiesDslElement holder, @NotNull MavenRepositoryDslElement dslElement) {
    super(holder, dslElement, "BintrayJCenter2", "https://jcenter.bintray.com/");
  }
}


text:
package com.okode.cordova.sightcall.events;

import android.util.Log;

import com.okode.cordova.sightcall.Constants;

import org.json.JSONException;
import org.json.JSONObject;

public class CallStart implements Event {

    private static final String CALL_START_EVENT_NAME = "sightcall.callstart";
    private static final String CALL_ID_PARAM = "callId";
    private static final String CASE_REPORT_ID = "caseReportId";

    private String callId;
    private String caseReportId;

    public CallStart(String callId, String caseReportId) {
        this.callId = callId;
        this.caseReportId = caseReportId;
    }

    @Override
    public String getEventName() {
        return CALL_START_EVENT_NAME;
    }

    @Override
    public JSONObject getEventData() {
        JSONObject data = new JSONObject();
        try {
            data.putOpt(CALL_ID_PARAM, this.callId);
            data.putOpt(CASE_REPORT_ID, this.caseReportId);
        } catch (JSONException e) {
            Log.e(Constants.TAG, "Error constructing notification object. Message: " + e);
        }
        return data;
    }
}


text:
(function (playease) {
    var utils = playease.utils,
        events = playease.events,
        EventDispatcher = events.EventDispatcher,
        UI = playease.UI,

        CLASS_AD = 'pe-ad',

        _default = {
            kind: 'AD',
            visibility: true,
        };

    function AD(config, logger) {
        EventDispatcher.call(this, 'AD', { logger: logger });

        var _this = this,
            _logger = logger,
            _container;

        function _init() {
            _this.config = config;
            _container = utils.createElement('div', CLASS_AD);
        }

        _this.display = function (element) {
            _container.innerHTML = '';
            _container.appendChild(element);
        };

        _this.remove = function () {
            _container.innerHTML = '';
        };

        _this.element = function () {
            return _container;
        };

        _this.resize = function (width, height) {

        };

        _init();
    }

    AD.prototype = Object.create(EventDispatcher.prototype);
    AD.prototype.constructor = AD;
    AD.prototype.kind = 'AD';
    AD.prototype.CONF = _default;

    UI.register(AD);
})(playease);


text:
/**
 * Declare some globals
 * Do NOT touch this file just in case
 */

module.exports = Object.assign(global, {
	regeneratorRuntime: require('./vendor/regenerator-runtime'),
	babelHelpers: require('./vendor/babel-helpers'),
	_: require('./vendor/underscore'),
});

global.pify = require('./lib/wx-pify');


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>WebGL - 2D Geometry Translate</title>
<link type="text/css" href="resources/webgl-tutorials.css" rel="stylesheet" />

Drag sliders to translate.

<canvas id="canvas"></canvas>


text:
package sk.upjs.ics.paz1c.fitnesscentrum.dao.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import sk.upjs.ics.paz1c.fitnesscentrum.ObjectFactory;
import sk.upjs.ics.paz1c.fitnesscentrum.dao.UdalostDao;
import sk.upjs.ics.paz1c.fitnesscentrum.entity.Udalost;
import sk.upjs.ics.paz1c.fitnesscentrum.entity.Zakaznik;
import sk.upjs.ics.paz1c.fitnesscentrum.rowmapper.UdalostRowMapper;

public class MySQLUdalostDao implements UdalostDao {

    private final JdbcTemplate jdbcTemplate;
    private final UdalostRowMapper udalostRowMapper;

    public MySQLUdalostDao() {
        this.jdbcTemplate = ObjectFactory.INSTANCE.getJdbcTemplate();
        this.udalostRowMapper = new UdalostRowMapper();
    }

    @Override
    public List<Udalost> dajVsetkyUdalostiOdZakaznika(Zakaznik zakaznik) {
        String sql = "SELECT * FROM udalost WHERE zakaznik_id = ?;";
        return jdbcTemplate.query(sql, udalostRowMapper, zakaznik.getId());
    }

    @Override
    public List<Udalost> dajVsetkyUdalostiTypu(String typ) {
        String sql = "SELECT * FROM udalost WHERE typ = ?;";
        return jdbcTemplate.query(sql, udalostRowMapper, typ);
    }

    @Override
    public List<Udalost> dajVsetkyUdalostiTypuOdZakaznika(Zakaznik zakaznik, String typ) {
        String sql = "SELECT * FROM udalost WHERE zakaznik_id = ? AND typ = ?;";
        return jdbcTemplate.query(sql, udalostRowMapper, zakaznik.getId(), typ);
    }

    @Override
    public List<Udalost> dajVsetkyUdalostiZoDna(LocalDateTime datum) {
        String sql = "SELECT * FROM udalost WHERE datum = ?;";
        return jdbcTemplate.query(sql, udalostRowMapper, datum.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }

    @Override
    public void pridajUdalost(Zakaznik zakaznik, String typ, String obsah) {
        String sql = "INSERT INTO udalost (zakaznik_id, typ, obsah) VALUES (?, ?, ?);";
        jdbcTemplate.update(sql, zakaznik.getId(), typ, obsah);
    }
}


text:
package org.apache.accumulo.test.functional;

import static org.apache.accumulo.fate.util.UtilWaitThread.sleepUninterruptibly;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.admin.ActiveScan;
import org.apache.accumulo.core.clientImpl.Namespace;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.IteratorUtil;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.ColumnVisibility;
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.apache.hadoop.io.Text;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ACCUMULO-2641 Integration test. ACCUMULO-2641 Adds scan id to thrift protocol so that
 * {@code org.apache.accumulo.core.client.admin.ActiveScan.getScanid()} returns a unique scan id.
 *
 *

 * The test uses the Minicluster and the {@code org.apache.accumulo.test.functional.SlowIterator} to
 * create multiple scan sessions. The test exercises multiple tablet servers with splits and
 * multiple ranges to force the scans to occur across multiple tablet servers for completeness.
 *
 *

 * This patch modified thrift, the TraceRepoDeserializationTest test seems to fail unless the
 * following be added:
 *
 *

 * private static final long serialVersionUID = -4659975753252858243l;
 *
 *

 * back into org.apache.accumulo.trace.thrift.TInfo until that test signature is regenerated.
 */
public class ScanIdIT extends AccumuloClusterHarness {

  private static final Logger log = LoggerFactory.getLogger(ScanIdIT.class);

  private static final int NUM_SCANNERS = 8;

  private static final int NUM_DATA_ROWS = 100;

  private static final Random random = new SecureRandom();

  private static final ExecutorService pool = Executors.newFixedThreadPool(NUM_SCANNERS);

  private static final AtomicBoolean testInProgress = new AtomicBoolean(true);

  private static final Map<Integer,Value> resultsByWorker = new ConcurrentHashMap<>();

  @Override
  protected int defaultTimeoutSeconds() {
    return 60;
  }

  /**
   * @throws Exception
   *           any exception is a test failure.
   */
  @Test
  public void testScanId() throws Exception {

    final String tableName = getUniqueNames(1)[0];
    try (AccumuloClient client = Accumulo.newClient().from(getClientProps()).build()) {
      client.tableOperations().create(tableName);

      addSplits(client, tableName);

      log.info("Splits added");

      generateSampleData(client, tableName);

      log.info("Generated data for {}", tableName);

      attachSlowIterator(client, tableName);

      CountDownLatch latch = new CountDownLatch(NUM_SCANNERS);

      List<ScannerThread> scanThreadsToClose = new ArrayList<>(NUM_SCANNERS);
      for (int scannerIndex = 0; scannerIndex < NUM_SCANNERS; scannerIndex++) {
        ScannerThread st = new ScannerThread(client, scannerIndex, tableName, latch);
        scanThreadsToClose.add(st);
        pool.submit(st);
      }

      // wait for scanners to report a result.
      while (testInProgress.get()) {

        if (resultsByWorker.size() < NUM_SCANNERS) {
          log.trace("Results reported {}", resultsByWorker.size());
          sleepUninterruptibly(750, TimeUnit.MILLISECONDS);
        } else {
          // each worker has reported at least one result.
          testInProgress.set(false);

          log.debug("Final result count {}", resultsByWorker.size());

          // delay to allow scanners to react to end of test and cleanly close.
          sleepUninterruptibly(1, TimeUnit.SECONDS);
        }

      }

      Set<Long> scanIds = getScanIds(client);
      assertTrue("Expected at least " + NUM_SCANNERS + " scanIds, but saw " + scanIds.size(),
          scanIds.size() >= NUM_SCANNERS);

      scanThreadsToClose.forEach(st -> {
        if (st.scanner != null) {
          st.scanner.close();
        }
      });

      while (!(scanIds = getScanIds(client)).isEmpty()) {
        log.debug("Waiting for active scans to stop...");
        Thread.sleep(200);
      }
      assertEquals("Expected no scanIds after closing scanners", 0, scanIds.size());

    }
  }

  private Set<Long> getScanIds(AccumuloClient client)
      throws AccumuloSecurityException, InterruptedException, AccumuloException {
    // all scanner have reported at least 1 result, so check for unique scan ids.
    Set<Long> scanIds = new HashSet<>();

    List<String> tservers = client.instanceOperations().getTabletServers();

    log.debug("tablet servers {}", tservers);

    for (String tserver : tservers) {

      List<ActiveScan> activeScans = null;
      for (int i = 0; i < 10; i++) {
        try {
          activeScans = client.instanceOperations().getActiveScans(tserver);
          break;
        } catch (AccumuloException e) {
          if (e.getCause() instanceof TableNotFoundException) {
            log.debug("Got TableNotFoundException, will retry");
            Thread.sleep(200);
            continue;
          }
          throw e;
        }
      }

      assertNotNull("Repeatedly got exception trying to active scans", activeScans);

      activeScans.removeIf(
          scan -> scan.getTable().startsWith(Namespace.ACCUMULO.name() + Namespace.SEPARATOR));
      log.debug("TServer {} has {} active non-metadata scans", tserver, activeScans.size());

      for (ActiveScan scan : activeScans) {
        log.debug("Tserver {} scan id {} ({})", tserver, scan.getScanid(), scan.getTable());
        scanIds.add(scan.getScanid());
      }
    }

    return scanIds;
  }

  /**
   * Runs scanner in separate thread to allow multiple scanners to execute in parallel.
   *

   * The thread run method is terminated when the testInProgress flag is set to false.
   */
  private static class ScannerThread implements Runnable {

    private final AccumuloClient accumuloClient;
    private Scanner scanner = null;
    private final int workerIndex;
    private final String tablename;
    private final CountDownLatch latch;

    public ScannerThread(final AccumuloClient accumuloClient, final int workerIndex,
        final String tablename, final CountDownLatch latch) {
      this.accumuloClient = accumuloClient;
      this.workerIndex = workerIndex;
      this.tablename = tablename;
      this.latch = latch;
    }

    /**
     * execute the scan across the sample data and put scan result into result map until
     * testInProgress flag is set to false.
     */
    @Override
    public void run() {

      latch.countDown();
      try {
        latch.await();
      } catch (InterruptedException e) {
        log.error("Thread interrupted with id {}", workerIndex);
        Thread.currentThread().interrupt();
        return;
      }

      log.debug("Creating scanner in worker thread {}", workerIndex);

      try {

        scanner = accumuloClient.createScanner(tablename, new Authorizations());

        // Never start readahead
        scanner.setReadaheadThreshold(Long.MAX_VALUE);
        scanner.setBatchSize(1);

        // create different ranges to try to hit more than one tablet.
        scanner.setRange(new Range(new Text(Integer.toString(workerIndex)), new Text("9")));

        scanner.fetchColumnFamily(new Text("fam1"));

        for (Map.Entry<Key,Value> entry : scanner) {

          // exit when success condition is met.
          if (!testInProgress.get()) {
            scanner.clearScanIterators();
            return;
          }

          Text row = entry.getKey().getRow();

          log.debug("worker {}, row {}", workerIndex, row);

          if (entry.getValue() != null) {

            Value prevValue = resultsByWorker.put(workerIndex, entry.getValue());

            // value should always being increasing
            if (prevValue != null) {

              log.trace("worker {} values {}", workerIndex,
                  String.format("%1$s < %2$s", prevValue, entry.getValue()));

              assertTrue(prevValue.compareTo(entry.getValue()) > 0);
            }
          } else {
            log.info("Scanner returned null");
            fail("Scanner returned unexpected null value");
          }

        }
        log.debug("Scanner ran out of data. (info only, not an error) ");
      } catch (TableNotFoundException e) {
        throw new IllegalStateException("Initialization failure. Could not create scanner", e);
      } finally {
        // don't close scanner here, because it will clean up the scan ids we're checking for
      }
    }
  }

  /**
   * Create splits on table and force migration by taking table offline and then bring back online
   * for test.
   *
   * @param client
   *          Accumulo client to test cluster or MAC instance.
   */
  private void addSplits(final AccumuloClient client, final String tableName) {

    SortedSet<Text> splits = createSplits();

    try {

      client.tableOperations().addSplits(tableName, splits);

      client.tableOperations().offline(tableName, true);

      sleepUninterruptibly(2, TimeUnit.SECONDS);
      client.tableOperations().online(tableName, true);

      for (Text split : client.tableOperations().listSplits(tableName)) {
        log.trace("Split {}", split);
      }

    } catch (AccumuloSecurityException | AccumuloException | TableNotFoundException e) {
      throw new IllegalStateException("Initialization failed. Could not add splits to " + tableName,
          e);
    }

  }

  /**
   * Create splits to distribute data across multiple tservers.
   *
   * @return splits in sorted set for addSplits.
   */
  private SortedSet<Text> createSplits() {

    SortedSet<Text> splits = new TreeSet<>();

    for (int split = 0; split < 10; split++) {
      splits.add(new Text(Integer.toString(split)));
    }

    return splits;
  }

  /**
   * Generate some sample data using random row id to distribute across splits.
   *

   * The primary goal is to determine that each scanner is assigned a unique scan id. This test does
   * check that the count value for fam1 increases if a scanner reads multiple value, but this is
   * secondary consideration for this test, that is included for completeness.
   *
   * @param accumuloClient
   *          Accumulo client to test cluster or MAC instance.
   */
  private void generateSampleData(AccumuloClient accumuloClient, final String tablename) {

    try (BatchWriter bw = accumuloClient.createBatchWriter(tablename)) {

      ColumnVisibility vis = new ColumnVisibility("public");

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

        Text rowId = new Text(String.format("%d", ((random.nextInt(10) * 100) + i)));

        Mutation m = new Mutation(rowId);
        m.put("fam1", "count", Integer.toString(i));
        m.put(new Text("fam1"), new Text("positive"), vis,
            new Value(Integer.toString(NUM_DATA_ROWS - i)));
        m.put(new Text("fam1"), new Text("negative"), vis,
            new Value(Integer.toString(i - NUM_DATA_ROWS)));

        log.trace("Added row {}", rowId);

        bw.addMutation(m);
      }
    } catch (TableNotFoundException | MutationsRejectedException ex) {
      throw new IllegalStateException("Initialization failed. Could not create test data", ex);
    }
  }

  /**
   * Attach the test slow iterator so that we have time to read the scan id without creating a large
   * dataset. Uses a fairly large sleep and delay times because we are not concerned with how much
   * data is read and we do not read all of the data - the test stops once each scanner reports a
   * scan id.
   *
   * @param accumuloClient
   *          Accumulo client to test cluster or MAC instance.
   */
  private void attachSlowIterator(AccumuloClient accumuloClient, final String tablename) {
    try {

      IteratorSetting slowIter =
          new IteratorSetting(50, "slowIter", "org.apache.accumulo.test.functional.SlowIterator");
      slowIter.addOption("sleepTime", "200");
      slowIter.addOption("seekSleepTime", "200");

      accumuloClient.tableOperations().attachIterator(tablename, slowIter,
          EnumSet.of(IteratorUtil.IteratorScope.scan));

    } catch (AccumuloException | AccumuloSecurityException | TableNotFoundException ex) {
      throw new IllegalStateException("Initialization failed. Could not attach slow iterator", ex);
    }
  }

}


text:
/**
 * Created by arik.blumin on 4/6/2016.
 */

var utils = require('./../utils.js');
var Q = require('q');
var globals = require('./../globals');
var logger = globals.logger;
var _ = require('lodash');
var constants = require('./../constants.js');
var D9 = constants.D9;

function logic(data) {

  var obj = {};

  obj.alldata = [];
  obj.groups = [];
  obj.loading = false;

  var AtomicRule = function (externalId,
                             name,
                             accountId,
                             vpcId,
                             region,
                             cloudAccountId,
                             naclId,
                             isDefault,
                             subnetId,
                             subnetCIDR,
                             protocol,
                             ruleNumber,
                             ruleAction,
                             egress,
                             cidrBlock,
                             portRange,
                             icmpTypeCode, tags) {
    var protocolMap = {
      '-1': "All Traffic",
      '1': "ICMP",
      '17': "UDP",
      '6': "TCP",

    };

    this.externalId = externalId;
    this.name = name;
    this.accountId = accountId;
    this.vpcId = vpcId;
    this.region = D9.Constants.RegionName[region];
    this.cloudAccountId = cloudAccountId;
    this.naclId = naclId;
    this.isDefault = isDefault;
    this.subnetId = subnetId;
    this.protocol = protocolMap[protocol];
    this.ruleNumber = ruleNumber;
    this.ruleAction = ruleAction;
    if (egress == true) {
      this.egress = "Inbound";
    } else if (egress === false) {
      this.egress = "Outbound";
    }
    this.subnetCIDR = subnetCIDR;
    this.cidrBlock = cidrBlock;
    if (portRange !== undefined && portRange !== null) {
      this.portRange = portRange.from.toString() + '-' + portRange.to.toString();
    }
    this.icmpTypeCode = icmpTypeCode;
    this.tags = tags;

    this.atomic_rule_id = this.naclId;

    if (protocol !== undefined) {
      this.atomic_rule_id = this.atomic_rule_id + this.protocol.toString() + '-';
    }
    if (portRange !== undefined && portRange !== null) {
      this.atomic_rule_id = this.atomic_rule_id + portRange.from.toString() + '-' + portRange.to.toString() + '-';
    }
    if (this.cidrBlock !== undefined) {
      this.atomic_rule_id = this.atomic_rule_id + this.cidrBlock.toString() + '-';
    }

  }

  obj.runReport = function () {
    obj.loading = true;
    obj.alldata = [];

    obj.alldata = [];
    obj.listOfValues = {};

    obj.cloudaccountsMap = {};
    _.each(data.cloudaccounts, function (cloud) {
      var key = "Guid_" + cloud.id;
      obj.cloudaccountsMap[key] = {name: cloud.name};
    });

    obj.subnetsMap = {};
    _.each(data.subnets, function (subnet) {
      obj.subnetsMap[subnet.subnetId] = {name: subnet.name, subnetCIDR: subnet.cidrBlock};
    });

    obj.vpcsInfoMap = {};
    _.each(data.vpcsInfo, function (vpcinfo) {
      obj.vpcsInfoMap[vpcinfo.externalId] = {name: vpcinfo.name};
    });

    // Transform the data from standard SG representation into a list of AtomicRule
    if (data.nacls) {
      _.each(data.nacls, function (nacl) {
        _.each(nacl.entries, function (entry) {
          _.each(nacl.associations, function (association) {
            var vpcname = "";
            if (obj.vpcsInfoMap[nacl.vpcId] && obj.vpcsInfoMap[nacl.vpcId].name !== "") {
              vpcname = obj.vpcsInfoMap[nacl.vpcId].name + " (" + nacl.vpcId + ")";
            } else {
              vpcname = nacl.vpcId;
            }

            var cloudAccountName = "";
            var key = "Guid_" + nacl.cloudAccountId;
            if (obj.cloudaccountsMap[key] && obj.cloudaccountsMap[key].name !== "") {
              cloudAccountName = obj.cloudaccountsMap[key].name;
            } else {
              cloudAccountName = nacl.cloudAccountId;
            }

            var ruleToAdd = new AtomicRule(nacl.externalId,
              nacl.name,
              nacl.accountId,
              vpcname,
              nacl.region,
              cloudAccountName,
              nacl.naclId,
              nacl.isDefault,
              obj.subnetsMap[association.subnetId].name,
              obj.subnetsMap[association.subnetId].subnetCIDR,
              entry.protocol,
              entry.ruleNumber,
              entry.ruleAction,
              entry.egress,
              entry.cidrBlock,
              entry.portRange,
              entry.icmpTypeCode,
              nacl.tags);
            obj.alldata.push(ruleToAdd);
          });
        });
      });
    }

    obj.loading = false;
  };

  obj.fieldsToAutoCompleate = [
    "vpcId",
    "region",
    "cloudAccountId",
    "subnetId",
    "protocol",
    "ruleAction",
    "egress",
    "cidrBlock",
    "portRange",
    "subnetCIDR"
  ];

  obj.runReport();
  return obj.alldata;
}

function get(id) {
  var url = "https://secure.dome9.com/api/CloudSubnet";
  if (id) {
    url += '/' + id;
  }
  var requestOptions = {
    url: url,
    method: 'GET',
    headers: {
      'Accept': 'application/json'
    },
    json: true
  };

  return Q(this.connection.requestV2WebApi(requestOptions)).fail(function (reason) {
    throw 'cannot perform dome9/CloudSubnet.get, reason:' + JSON.stringify(reason);
  });
}

function CloudSubnet(dome9Connection) {
  this.connection = dome9Connection;
}

CloudSubnet.prototype = {
  get: get,
  logic: logic
};

module.exports = function (dome9Connection) {
  return new CloudSubnet(dome9Connection);
};


text:
game.GameTimerManager = Object.extend({
    init: function(x, y, settings) {
        //sets all variables that i went over in Pause screen
        this.now = new Date().getTime();
        this.lastCreep = new Date().getTime();

        this.paused = false;
        this.alwaysUpdate = true;
    },
    update: function() {
        //timers for gold and enemies
        this.now = new Date().getTime();
        this.goldTimerCheck();
        this.creepTimerCheck();

        return true;
    },
    goldTimerCheck: function() {
        if (Math.round(this.now / 1000) % 10 === 0 && (this.now - this.lastCreep >= 1000)) {
            //adds gold
            game.data.gold += (game.data.exp1 + 1);
            console.log("curent gold: " + game.data.gold);
        }
    },
    creepTimerCheck: function() {

    }
});


text:
         <script>
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

            ga('create', 'UA-92535217-1', 'auto');
            ga('send', 'pageview');

         </script>
         <script type="text/javascript" src="angular/inline.bundle.js"></script>
         <script type="text/javascript" src="angular/polyfills.bundle.js"></script>
         <script type="text/javascript" src="angular/styles.bundle.js"></script>
         <script type="text/javascript" src="angular/vendor.bundle.js"></script>
         <script type="text/javascript" src="angular/main.bundle.js"></script>
         <script src='https://www.google.com/recaptcha/api.js?onload=reCAPTCHAOnLoad&render=explicit' async defer></script>
    </body>
</html>


text:
//
//  Header.h
//  Wizard
//
//  Created by Evan Miller on 3/31/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#include "readstat.h"
#include "readstat_bits.h"

#pragma pack(push, 1)

// SAV files

typedef struct sav_file_header_record_s {
    char     rec_type[4];
    char     prod_name[60];
    int32_t  layout_code;
    int32_t  nominal_case_size;
    int32_t  compressed;
    int32_t  weight_index;
    int32_t  ncases;
    double   bias; /* TODO is this portable? */
    char     creation_date[9];
    char     creation_time[8];
    char     file_label[64];
    char     padding[3];
} sav_file_header_record_t;

typedef struct sav_variable_record_s {
    int32_t  type;
    int32_t  has_var_label;
    int32_t  n_missing_values;
    int32_t  print;
    int32_t  write;
    char     name[8];
} sav_variable_record_t;

typedef struct sav_info_record_header_s {
    int32_t  rec_type;
    int32_t  subtype;
    int32_t  size;
    int32_t  count;
} sav_info_record_t;

typedef struct sav_machine_integer_info_record_s {
    int32_t  version_major;
    int32_t  version_minor;
    int32_t  version_revision;
    int32_t  machine_code;
    int32_t  floating_point_rep;
    int32_t  compression_code;
    int32_t  endianness;
    int32_t  character_code;
} sav_machine_integer_info_record_t;

typedef struct sav_machine_floating_point_info_record_s {
    double   sysmis;
    double   highest;
    double   lowest;
} sav_machine_floating_point_info_record_t;

typedef struct sav_dictionary_termination_record_s {
    int32_t  rec_type;
    int32_t  filler;
} sav_dictionary_termination_record_t;

#pragma pack(pop)

typedef struct sav_format_s {
    int    type;
    int    width;
    int    decimal_places;
} sav_format_t;

typedef struct sav_varinfo_s {
    readstat_types_t type;
    int              labels_index;
    int              index;
    int              offset;
    int              width;
    int              string_length;
    sav_format_t     print_format;
    sav_format_t     write_format;
    int              n_segments;
    int              n_missing_values;
    int              missing_range;
    double           missing_values[3];
    char             name[8*4+1];
    char             longname[64*4+1];
    char            *label;
} sav_varinfo_t;

typedef struct sav_ctx_s {
    sav_varinfo_t *varinfo;
    size_t         varinfo_capacity;
    iconv_t        converter;
    int            var_index;
    int            var_offset;
    int            var_count;
    int            record_count;
    int            value_labels_count;
    int            data_is_compressed:1;
    int            machine_needs_byte_swap:1;
} sav_ctx_t;

#define SAV_RECORD_TYPE_VARIABLE         2
#define SAV_RECORD_TYPE_VALUE_LABEL      3
#define SAV_RECORD_TYPE_DOCUMENT         6
#define SAV_RECORD_TYPE_HAS_DATA         7
#define SAV_RECORD_TYPE_DICT_TERMINATION 999

#define SAV_RECORD_SUBTYPE_INTEGER_INFO  3
#define SAV_RECORD_SUBTYPE_FP_INFO       4
#define SAV_RECORD_SUBTYPE_VAR_DISPLAY   11
#define SAV_RECORD_SUBTYPE_LONG_VAR_NAME 13
#define SAV_RECORD_SUBTYPE_VERY_LONG_STR 14

#define SAV_FLOATING_POINT_REP_IEEE      1
#define SAV_FLOATING_POINT_REP_IBM       2
#define SAV_FLOATING_POINT_REP_VAX       3

#define SAV_ENDIANNESS_BIG               1
#define SAV_ENDIANNESS_LITTLE            2

#define SAV_HIGHEST_DOUBLE   0x7FEFFFFFFFFFFFFFUL
#define SAV_MISSING_DOUBLE   0xFFEFFFFFFFFFFFFFUL
#define SAV_LOWEST_DOUBLE    0xFFEFFFFFFFFFFFFEUL