text:
package com.elven.danmaku.core.elements.disposal;

import com.elven.danmaku.core.elements.AbstractPlaceableGameElement;
import com.elven.danmaku.core.stage.StageView;

public interface DisposalRule {

	public boolean shouldDispose(AbstractPlaceableGameElement element, StageView stageView);
}

redpajama_set_name: RedPajamaGithub


text:
@echo off
SET APPNG_HOME=%~dp0\..\..
java -cp "%APPNG_HOME%"\WEB-INF\lib\*;"%APPNG_HOME%"\..\lib\* -Dlog4j.configuration=file:"%APPNG_HOME%"\WEB-INF\conf\log4j-cli.properties -Dappng.home="%APPNG_HOME%" org.appng.cli.CliBootstrap %*


text:
===================
drop-count.lua demo
===================

.. literalinclude:: drop-count_example.txt


text:
var app = angular.module('sentinelDashboardApp');

app.controller('SentinelClusterAppAssignManageController', ['$scope', '$stateParams', 'ngDialog',
    'MachineService', 'ClusterStateService',
    function ($scope, $stateParams, ngDialog, MachineService, ClusterStateService) {
        $scope.app = $stateParams.app;
        const UNSUPPORTED_CODE = 4041;

        const CLUSTER_MODE_CLIENT = 0;
        const CLUSTER_MODE_SERVER = 1;
        const DEFAULT_CLUSTER_SERVER_PORT = 18730;

        $scope.tmp = {
            curClientChosen: [],
            curRemainingClientChosen: [],
            curChosenServer: {},
        };

        function convertSetToString(set) {
            if (set === undefined) {
                return '';
            }
            let s = '';
            for (let i = 0; i < set.length; i++) {
                s = s + set[i];
                if (i < set.length - 1) {
                    s = s + ',';
                }
            }
            return s;
        }

        function convertStrToNamespaceSet(str) {
            if (str === undefined || str === '') {
                return [];
            }
            let arr = [];
            let spliced = str.split(',');
            spliced.forEach((v) => {
                arr.push(v.trim());
            });
            return arr;
        }

        function processAppSingleData(data) {
            if (data.state.server && data.state.server.namespaceSet) {
                data.state.server.namespaceSetStr = convertSetToString(data.state.server.namespaceSet);
                data.mode = data.state.stateInfo.mode;
            }
        }

        function removeFromArr(arr, v) {
            for (let i = 0; i < arr.length; i++) {
                if (arr[i] === v) {
                    arr.splice(i, 1);
                    break;
                }
            }
        }

        function resetChosen() {
            $scope.tmp.curClientChosen = [];
            $scope.tmp.curRemainingClientChosen = [];
        }

        function generateMachineId(e) {
            return e.ip + '@' + e.commandPort;
        }

        function applyClusterMap(appClusterMachineList) {
            if (!appClusterMachineList) {
                return;
            }
            let tmpMap = new Map();
            $scope.clusterMap = [];
            $scope.remainingClientAddressList = [];
            let tmpServerList = [];
            let tmpClientList = [];
            appClusterMachineList.forEach((e) => {
                if (e.mode === CLUSTER_MODE_CLIENT) {
                    tmpClientList.push(e);
                } else if (e.mode === CLUSTER_MODE_SERVER) {
                    tmpServerList.push(e);
                } else {
                    $scope.remainingClientAddressList.push(generateMachineId(e));
                }
            });
            tmpServerList.forEach((e) => {
                let ip = e.ip;
                let machineId = ip + '@' + e.commandPort;
                let group = {
                    ip: ip,
                    machineId: machineId,
                    port: e.state.server.port,
                    clientSet: [],
                    namespaceSetStr: e.state.server.namespaceSetStr,
                    belongToApp: true,
                };
                if (!tmpMap.has(ip)) {
                    tmpMap.set(ip, group);
                }
            });
            tmpClientList.forEach((e) => {
                let ip = e.ip;
                let machineId = ip + '@' + e.commandPort;

                let targetServer = e.state.client.clientConfig.serverHost;
                let targetPort = e.state.client.clientConfig.serverPort;
                if (targetServer === undefined || targetServer === '' ||
                    targetPort === undefined || targetPort <= 0) {
                    $scope.remainingClientAddressList.push(generateMachineId(e));
                    return;
                }

                if (!tmpMap.has(targetServer)) {
                    let group = {
                        ip: targetServer,
                        machineId: targetServer,
                        port: targetPort,
                        clientSet: [machineId],
                        belongToApp: false,
                    };
                    tmpMap.set(targetServer, group);
                } else {
                    let g = tmpMap.get(targetServer);
                    g.clientSet.push(machineId);
                }
            });
            tmpMap.forEach((v) => {
                if (v !== undefined) {
                    $scope.clusterMap.push(v);
                }
            });
        }

        $scope.onCurrentServerChange = () => {
            resetChosen();
        };

        $scope.remainingClientAddressList = [];

        $scope.moveToServerGroup = () => {
            let chosenServer = $scope.tmp.curChosenServer;
            if (!chosenServer || !chosenServer.machineId) {
                return;
            }
            $scope.tmp.curRemainingClientChosen.forEach(e => {
                chosenServer.clientSet.push(e);
                removeFromArr($scope.remainingClientAddressList, e);
            });
            resetChosen();
        };

        $scope.moveToRemainingSharePool = () => {
            $scope.tmp.curClientChosen.forEach(e => {
                $scope.remainingClientAddressList.push(e);
                removeFromArr($scope.tmp.curChosenServer.clientSet, e);
            });
            resetChosen();
        };

        function parseIpFromMachineId(machineId) {
            if (machineId.indexOf('@') === -1) {
                return machineId;
            }
            let arr = machineId.split('@');
            return arr[0];
        }

        $scope.addToServerList = () => {
            let group;
            $scope.tmp.curRemainingClientChosen.forEach(e => {
                group = {
                    machineId: e,
                    ip: parseIpFromMachineId(e),
                    port: DEFAULT_CLUSTER_SERVER_PORT,
                    clientSet: [],
                    namespaceSetStr: 'default,' + $scope.app,
                    belongToApp: true,
                };
                $scope.clusterMap.push(group);
                removeFromArr($scope.remainingClientAddressList, e);
                $scope.tmp.curChosenServer = group;
            });
            resetChosen();
        };

        $scope.removeFromServerList = () => {
            let chosenServer = $scope.tmp.curChosenServer;
            if (!chosenServer || !chosenServer.machineId) {
                return;
            }
            chosenServer.clientSet.forEach((e) => {
                if (e !== undefined) {
                    $scope.remainingClientAddressList.push(e);
                }
            });

            if (chosenServer.belongToApp || chosenServer.machineId.indexOf('@') !== -1) {
                $scope.remainingClientAddressList.push(chosenServer.machineId);
            } else {
                alert('提示:非本应用内机器将不会置回空闲列表中');
            }

            removeFromArr($scope.clusterMap, chosenServer);

            resetChosen();

            if ($scope.clusterMap.length > 0) {
                $scope.tmp.curChosenServer = $scope.clusterMap[0];
                $scope.onCurrentServerChange();
            } else {
                $scope.tmp.curChosenServer = {};
            }
        };

        function retrieveClusterAppInfo() {
            ClusterStateService.fetchClusterUniversalStateOfApp($scope.app).success(function (data) {
                if (data.code === 0 && data.data) {
                    $scope.loadError = undefined;
                    $scope.appClusterMachineList = data.data;
                    $scope.appClusterMachineList.forEach(processAppSingleData);
                    applyClusterMap($scope.appClusterMachineList);
                    if ($scope.clusterMap.length > 0) {
                        $scope.tmp.curChosenServer = $scope.clusterMap[0];
                        $scope.onCurrentServerChange();
                    }
                } else {
                    $scope.appClusterMachineList = {};
                    if (data.code === UNSUPPORTED_CODE) {
                        $scope.loadError = {message: '该应用的 Sentinel 客户端不支持集群限流,请升级至 1.4.0 以上版本并引入相关依赖。'}
                    } else {
                        $scope.loadError = {message: data.msg};
                    }
                }
            }).error(() => {
                $scope.loadError = {message: '未知错误'};
            });
        }

        retrieveClusterAppInfo();

        $scope.saveAndApplyAssign = () => {
            let ok = confirm('是否确认执行变更?');
            if (!ok) {
                return;
            }
            let cm = $scope.clusterMap;
            if (!cm) {
                cm = [];
            }
            cm.forEach((e) => {
                e.namespaceSet = convertStrToNamespaceSet(e.namespaceSetStr);
            });
            cm.namespaceSet = convertStrToNamespaceSet(cm.namespaceSetStr);
            let request = {
                clusterMap: cm,
                remainingList: $scope.remainingClientAddressList,
            };
            ClusterStateService.applyClusterFullAssignOfApp($scope.app, request).success((data) => {
                if (data.code === 0 && data.data) {
                    let failedServerSet = data.data.failedServerSet;
                    let failedClientSet = data.data.failedClientSet;
                    if (failedClientSet.length === 0 && failedServerSet.length === 0) {
                        alert('全部推送成功');
                    } else {
                        alert('推送完毕。token server 失败列表:' + JSON.stringify(failedServerSet) +
                            '; token client 失败列表:' + JSON.stringify(failedClientSet));
                    }

                    retrieveClusterAppInfo();
                } else {
                    if (data.code === UNSUPPORTED_CODE) {
                        alert('该应用的 Sentinel 客户端不支持集群限流,请升级至 1.4.0 以上版本并引入相关依赖。');
                    } else {
                        alert('推送失败:' + data.msg);
                    }
                }
            }).error(() => {
                alert('未知错误');
            });
        };
    }]);


text:
<?php
/**
 * Created by BADI.
 * DateTime: 21.11.2016 17:20
 */

namespace common\services;

use Yii;

class GetIntColumn
{
	private $column;

	public function __construct($column)
	{
		if (is_string($column)) {
			$this->column = $column;
		}
	}

	public function execute() {
		$column = $this->column;
		$hash = Yii::$app->db->createCommand("select {$column} from int_settings where id=1")->queryScalar();
		return $hash;
	}

	public function test($file){
		return $file;
	}
}


text:
package org.wso2.developerstudio.appfactory.core.repository;
import java.io.File;
import java.io.IOException;
import java.util.List;

import org.eclipse.jgit.api.*;
import org.eclipse.jgit.api.errors.*;
import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.wso2.developerstudio.appfactory.core.Activator;
import org.wso2.developerstudio.appfactory.core.authentication.Authenticator;
import org.wso2.developerstudio.appfactory.core.authentication.UserPasswordCredentials;
import org.wso2.developerstudio.appfactory.core.model.AppUserInfo;
import org.wso2.developerstudio.appfactory.core.model.AppVersionInfo;
import org.wso2.developerstudio.eclipse.distribution.project.ui.wizard.ProjectsImportPage;
import org.wso2.developerstudio.eclipse.distribution.project.ui.wizard.ProjectsImportPage.ProjectRecord;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

public class JgitRepoManager {

    private String localPath;
    private String remotePath;
    private Repository localRepo;
    private Git git;
    private boolean cloned;
    UsernamePasswordCredentialsProvider provider;
    AppVersionInfo appVersionInfo;
    private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID);

    public JgitRepoManager(String localPath,String uri) throws IOException {
    	 this.localPath =localPath;
         this.remotePath = uri;
         File gitDir = new File(localPath +File.separator+ ".git");
         localRepo = FileRepositoryBuilder.create(gitDir);
         git = new Git(localRepo);
         if(remotePath.equals(git.getRepository().getConfig().getString("remote","origin", "url"))){
             setCloned(true);
         }
         UserPasswordCredentials credentials = Authenticator.getInstance().getCredentials();
         provider = new UsernamePasswordCredentialsProvider(credentials.getGitUser(), credentials.getPassword());

	}

    public JgitRepoManager(AppVersionInfo info) throws IOException {
        this(info.getLocalRepo(), info.getRepoURL());
        this.appVersionInfo = info;
    }

    public void createGitRepo() {
        try {
            File gitDir = new File(localPath + File.separator + ".git");
            localRepo = FileRepositoryBuilder.create(gitDir);
            // localRepo = new FileRepository(localPath +File.separator +".git");
            localRepo.create();
        } catch (Exception e) {
            log.error("Git Repository creation Error : ", e);
        }
    }

    public void gitClone() throws InvalidRemoteException, TransportException, GitAPIException, IOException   {
         Git.cloneRepository()
           .setCredentialsProvider(provider)
           .setURI(remotePath)
           .setDirectory(new File(localPath))
           .call();
         setRepoAuthor();
    }

    private void setRepoAuthor() throws IOException {
        String currentUser = Authenticator.getInstance().getCredentials().getGitUser();
        List<AppUserInfo> applicationDevelopers = appVersionInfo.getVersionGroup().getApplication()
                .getApplicationDevelopers();
        for (AppUserInfo user : applicationDevelopers) {
            if (currentUser.equals(user.getEmail())) {
                localRepo.getConfig().setString("user", null, "name", user.getFirstName() + " " + user.getLastName());
                localRepo.getConfig().setString("user", null, "email", user.getEmail());
                localRepo.getConfig().save();
            }
        }
    }

	public void branchCreate(String branch) throws IOException,
			JGitInternalException, GitAPIException {
			git.branchCreate()
				.setForce(true)
				.setName(branch)
				.setStartPoint("origin/" + branch)
				.call();
	}

	public void update() throws WrongRepositoryStateException,
			InvalidConfigurationException, DetachedHeadException,
			InvalidRemoteException, CanceledException, RefNotFoundException,
			NoHeadException, TransportException, GitAPIException {
		git.fetch()
		   .setCredentialsProvider(provider)
		   .call();
	}

    public void checkout(String branch) throws RefAlreadyExistsException, RefNotFoundException,
            InvalidRefNameException, CheckoutConflictException, GitAPIException, IOException {
        if ("trunk".equals(branch)) {
            branch = "master";
        }
        Ref ref = git.getRepository().getRef(branch);
        if (ref == null) {
            checkoutRemoteBranch(branch);
        } else {
            checkoutLocalBranch(branch);
        }
    }

	public void checkoutRemoteBranch(String branch) throws RefAlreadyExistsException,
			RefNotFoundException, InvalidRefNameException,
			CheckoutConflictException, GitAPIException {
	         git.fetch().setRemote("origin").setCredentialsProvider(provider).call();
		     git.checkout()
				.setCreateBranch(true)
				.setName(branch)
				.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
				.setStartPoint("origin/" + branch)
				.setForce(true)
				.call();
		     trackBranch(branch);

	}

	public void checkoutLocalBranch(String branch) throws RefAlreadyExistsException,
	RefNotFoundException, InvalidRefNameException,
	CheckoutConflictException, GitAPIException {
     git.checkout()
		.setCreateBranch(false)
		.setName(branch)
		.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
		.setStartPoint("origin/" + branch)
		.setForce(true)
		.call();

    }

	public void trackBranch(String branch)
			throws RefAlreadyExistsException, RefNotFoundException,
			InvalidRefNameException, GitAPIException {
		    git.branchCreate()
		       .setName(branch)
			   .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
			   .setStartPoint("origin/"+ branch)
			   .setForce(true)
			   .call();
	}
    public void importProject(ProjectRecord[] projects){
    	ProjectsImportPage importMainPage = new ProjectsImportPage();
    	importMainPage.createProjects(projects);
    }

    public void CloseRepo(){
    	localRepo.close();
    }
	public boolean isCloned() {
		return cloned;
	}
	public void setCloned(boolean cloned) {
		this.cloned = cloned;
	}
}


text:
package com.agimatec.validation.jsr303.groups;

import com.agimatec.validation.jsr303.example.Address;
import com.agimatec.validation.jsr303.example.First;
import com.agimatec.validation.jsr303.example.Last;
import com.agimatec.validation.jsr303.example.Second;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import javax.validation.ValidationException;
import javax.validation.groups.Default;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * GroupListComputer Tester.
 *
 * @author <Authors name>
 * @version 1.0
 * @since
04/09/2009

 */
public class GroupsComputerTest extends TestCase {
    GroupsComputer groupsComputer;

    public GroupsComputerTest(String name) {
        super(name);
    }

    public void setUp() throws Exception {
        super.setUp();
        groupsComputer = new GroupsComputer();
    }

    public void tearDown() throws Exception {
        super.tearDown();
    }

    public static Test suite() {
        return new TestSuite(GroupsComputerTest.class);
    }

    public void testComputeGroupsNotAnInterface() {
        Set<Class<?>> groups = new HashSet<Class<?>>();
        groups.add(String.class);
        try {
            groupsComputer.computeGroups(groups);
            fail();
        } catch (ValidationException ex) {

        }
    }

    public void testGroupChainForNull() {
        try {
            groupsComputer.computeGroups((Class<?>[]) null);
            fail();
        } catch (IllegalArgumentException ex) {

        }
    }

    public void testGroupChainForEmptySet() {
        try {
            groupsComputer.computeGroups(new HashSet<Class<?>>());
            fail();
        } catch (IllegalArgumentException ex) {

        }
    }

    public void testCyclicGroupSequences() {
        try {
            Set<Class<?>> groups = new HashSet<Class<?>>();
            groups.add(CyclicGroupSequence1.class);
            groupsComputer.computeGroups(groups);
            fail();
        } catch (ValidationException ex) {

        }
    }

    public void testCyclicGroupSequence() {
        try {
            Set<Class<?>> groups = new HashSet<Class<?>>();
            groups.add(CyclicGroupSequence.class);
            groupsComputer.computeGroups(groups);
            fail();
        } catch (ValidationException ex) {

        }
    }

    public void testGroupDuplicates() {
        Set<Class<?>> groups = new HashSet<Class<?>>();
        groups.add(First.class);
        groups.add(Second.class);
        groups.add(Last.class);
        Groups chain = groupsComputer.computeGroups(groups);
        assertEquals(3, chain.groups.size());

        groups.clear();
        groups.add(First.class);
        groups.add(First.class);
        chain = groupsComputer.computeGroups(groups);
        assertEquals(1, chain.groups.size());

        groups.clear();
        groups.add(First.class);
        groups.add(Last.class);
        groups.add(First.class);
        chain = groupsComputer.computeGroups(groups);
        assertEquals(2, chain.groups.size());
    }

    public void testSequenceResolution() {
        Set<Class<?>> groups = new HashSet<Class<?>>();
        groups.add(Address.Complete.class);
        Groups chain = groupsComputer.computeGroups(groups);
        Iterator<List<Group>> sequences = chain.getSequences().iterator();
        List<Group> sequence = sequences.next();

        assertEquals(Default.class, sequence.get(0).getGroup());
        assertEquals(Address.HighLevelCoherence.class, sequence.get(1).getGroup());
    }
}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>AMP #0</title>
  <link rel="canonical" href="amps.html" >
  <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
  <link href='https://fonts.googleapis.com/css?family=Questrial' rel='stylesheet' type='text/css'>

amp #0

    Lorem ipsum dolor sit amet, has nisl nihil convenire et, vim at aeque inermis reprehendunt. Propriae tincidunt id nec, elit nusquam te mea, ius noster platonem in. Mea an idque minim, sit sale deleniti apeirian et. Omnium legendos tractatos cu mea. Vix in stet dolorem accusamus. Iisque rationibus consetetur in cum, quo unum nulla legere ut. Simul numquam saperet no sit.

    <amp-img id="img0"
        src="https://lh4.googleusercontent.com/-okOlNNHeoOc/VbYyrlFYFII/AAAAAAABYdA/La-3j3c-QQI/w2004-h734-no/PANO_20150726_171347%257E2.jpg"
        width=527 height=193 layout="responsive"
        on="tap:lightbox1"
        role="button" tabindex="0"></amp-img>

    Or you can use a <button on="tap:lightbox1">button</button>.

  <amp-lightbox id="lightbox1" class="lightbox1" layout="nodisplay">

      <amp-img id="img0" src="https://lh4.googleusercontent.com/-okOlNNHeoOc/VbYyrlFYFII/AAAAAAABYdA/La-3j3c-QQI/w452-h900-p/PANO_20150726_171347%257E2.jpg" width=226 height=450 layout="responsive"></amp-img>
      <button on="tap:lightbox1.close">Close using on Attribute</button>
       You can also hit the ESC key to close

  </amp-lightbox>

    Lorem ipsum dolor sit amet, has nisl nihil convenire et, vim at aeque inermis reprehendunt. Propriae tincidunt id nec, elit nusquam te mea, ius noster platonem in. Mea an idque minim, sit sale deleniti apeirian et. Omnium legendos tractatos cu mea. Vix in stet dolorem accusamus. Iisque rationibus consetetur in cum, quo unum nulla legere ut. Simul numquam saperet no sit.

    Lorem ipsum dolor sit amet, has nisl nihil convenire et, vim at aeque inermis reprehendunt. Propriae tincidunt id nec, elit nusquam te mea, ius noster platonem in. Mea an idque minim, sit sale deleniti apeirian et. Omnium legendos tractatos cu mea. Vix in stet dolorem accusamus. Iisque rationibus consetetur in cum, quo unum nulla legere ut. Simul numquam saperet no sit.

    Lorem ipsum dolor sit amet, has nisl nihil convenire et, vim at aeque inermis reprehendunt. Propriae tincidunt id nec, elit nusquam te mea, ius noster platonem in. Mea an idque minim, sit sale deleniti apeirian et. Omnium legendos tractatos cu mea. Vix in stet dolorem accusamus. Iisque rationibus consetetur in cum, quo unum nulla legere ut. Simul numquam saperet no sit.

    Lorem ipsum dolor sit amet, has nisl nihil convenire et, vim at aeque inermis reprehendunt. Propriae tincidunt id nec, elit nusquam te mea, ius noster platonem in. Mea an idque minim, sit sale deleniti apeirian et. Omnium legendos tractatos cu mea. Vix in stet dolorem accusamus. Iisque rationibus consetetur in cum, quo unum nulla legere ut. Simul numquam saperet no sit.

    Lorem ipsum dolor sit amet, has nisl nihil convenire et, vim at aeque inermis reprehendunt. Propriae tincidunt id nec, elit nusquam te mea, ius noster platonem in. Mea an idque minim, sit sale deleniti apeirian et. Omnium legendos tractatos cu mea. Vix in stet dolorem accusamus. Iisque rationibus consetetur in cum, quo unum nulla legere ut. Simul numquam saperet no sit.


text:
<?php
namespace Embed\Providers\OEmbed;

class Ted extends OEmbedImplementation
{
    /**
     * {@inheritdoc}
     */
    public static function getEndPoint()
    {
        return 'http://www.ted.com/talks/oembed.xml';
    }

    /**
     * {@inheritdoc}
     */
    public static function getPatterns()
    {
        return ['http://www.ted.com/talks/*'];
    }
}


text:
import { ItemSliding } from 'ionic-angular';

import { Session } from '../../../shared/entities';

export interface ToggleResult {
  slidingItem: ItemSliding;
  session: Session;
}


text:
package com.github.drinkjava2.jdbpro;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbutils.OutParameter;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.StatementConfiguration;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.github.drinkjava2.jdbpro.template.SqlTemplateEngine;
import com.github.drinkjava2.jdialects.Dialect;

/**
 * DbPro is the enhanced version of Apache Commons DbUtils's QueryRunner, add
 * below improvements:
 *
 *

 * 1)Use ConnectionManager to manage connection for better transaction support
 * 2)normal style methods but no longer throw SQLException, methods named as nXxxxx() format
 * 3)In-line style methods, methods named as iXxxxx() format
 * 4)SQL Template style methods, methods named as tXxxxx() format
 *

 *
 * @author Yong Zhu
 * @since 1.7.0
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class DbPro extends ImprovedQueryRunner implements NormalJdbcTool {// NOSONAR
	public DbPro() {
		super();
	}

	public DbPro(DataSource ds) {
		super(ds);
	}

	public DbPro(DataSource ds, Dialect dialect) {
		super(ds, dialect);
	}

	public DbPro(DataSource ds, StatementConfiguration stmtConfig) {
		super(ds, stmtConfig);
	}

	public DbPro(DataSource ds, Dialect dialect, StatementConfiguration stmtConfig) {
		super(ds, dialect, stmtConfig);
	}

	/**
	 * Quite execute a SQL, do not throw any exception, if any exception happen,
	 * return -1
	 */
	public int quiteExecute(String... sqls) {
		int result = 0;
		for (String sql : sqls)
			try {
				execute(sql);
			} catch (Exception e) {
				result = -1;
			}
		return result;
	}

	public void ________prepareMethods________() {// NOSONAR
	}

	/**
	 * Prepare a PreparedSQL for iXxxx (Single SQL) style, unknown objects (include
	 * null) will automatically looked as SQL pieces, more detail see doPrepare
	 * method
	 */
	public PreparedSQL prepare(Object... items) {
		return doPrepare(true, items);
	}

	/**
	 * Prepare a PreparedSQL for iXxxx (In-line) style or pXxxx style, For in-line
	 * style, unknown items be treated as String, SQL parameters must written in
	 * param() method, for example:
	 *
	 * ctx.iQuery(new SimpleCacheHandler(), connection, "select u.** from users u
	 * where u.age>?", param(20)," and u.id=?", param("001"), MapListHandler.class);
	 *
	 *
	 * pXxxx style only allow first appeared String as SQL, left unknown items will
	 * be treated as SQL parameters, for example:
	 *
	 * ctx.pQuery(MapListHandler.class, "select * from users where age>? and id=?",
	 * 20 , "001" , connection, new PaginHandler(2,5), sql(" and name=?"), "Tom" );
	 *
	 * In above examples connection and sqlHandlers are optional items, these
	 * optional items can appear at anywhere
	 *
	 * @param items
	 *            SQL String / SQL Parameters / Connection / ResultSetHandler class
	 *            or instance / SqlHandler class or instance
	 * @return a PreparedSQL instance
	 */
	private PreparedSQL doPrepare(boolean inlineStyle, Object... items) {// NOSONAR
		PreparedSQL ps = dealSqlItems(null, inlineStyle, items);
		ps.addGlobalAndThreadedHandlers(this);
		return ps;
	}

	/** Convert parameters to JDBC type, like java.util.Date to java.sql.Date */
	public void preparedParamsToJdbc(PreparedSQL ps) {
		//empty method for child class override
	}

	/**
	 * Deal with multiple SqlItems
	 */
	public PreparedSQL dealSqlItems(PreparedSQL lastPreSql, boolean inlineStyle, Object... items) {// NOSONAR
		if (items == null || items.length == 0)
			throw new DbProException("prepareSQL items can not be empty");
		PreparedSQL predSQL = lastPreSql;
		if (predSQL == null)
			predSQL = new PreparedSQL();
		for (Object item : items) {
			if (item == null) {
				if (inlineStyle)
					throw new DbProException("null value can not append as SQL piece");
				else
					predSQL.addParam(null);
			} else if (!dealOneSqlItem(inlineStyle, predSQL, item)) {
				if (item instanceof SqlItem)
					throw new DbProException("One SqlItem did not find explainer, type=" + ((SqlItem) item).getType());
				if (item.getClass().isArray()) {
					Object[] array = (Object[]) item;
					if (array.length != 0)
						dealSqlItems(predSQL, inlineStyle, (Object[]) item);
				} else if (inlineStyle)
					predSQL.addSql(item); // iXxxx style, unknown object look as SQL piece
				else
					predSQL.addParam(item); // pXxxx style, unknown object look as parameter
			}
		}
		predSQL.setSql(predSQL.getSqlBuilder().toString());
		return predSQL;
	}

	/**
	 * Here deal one SqlItem, if can deal it, return true, otherwise return false,
	 * subclass (like DbContext) can override this method
	 */
	protected boolean dealOneSqlItem(boolean inlineStyle, PreparedSQL predSQL, Object item) {// NOSONAR
		if (item instanceof String) {
			predSQL.addSqlOrParam(inlineStyle, (String) item);
		} else if (item instanceof PreparedSQL) {
			PreparedSQL psItem = (PreparedSQL) item;
			if (psItem.getSql() != null)
				predSQL.addSql(psItem.getSql());
			if (psItem.getParams() != null)
				for (Object obj : psItem.getParams())
					predSQL.addParam(obj);
		} else if (item instanceof SqlTemplateEngine) {
			predSQL.setTemplateEngine((SqlTemplateEngine) item);
		} else if (item instanceof Map<?, ?>) {
			predSQL.addTemplateMap((Map<String, Object>) item);
		} else if (item instanceof SqlOption) {
			if (SqlOption.USE_MASTER.equals(item)) {
				predSQL.setMasterSlaveOption(SqlOption.USE_MASTER);
			} else if (SqlOption.USE_SLAVE.equals(item)) {
				predSQL.setMasterSlaveOption(SqlOption.USE_SLAVE);
			} else if (SqlOption.USE_AUTO.equals(item)) {
				predSQL.setMasterSlaveOption(SqlOption.USE_AUTO);
			} else if (SqlOption.USE_BOTH.equals(item)) {
				predSQL.setMasterSlaveOption(SqlOption.USE_BOTH);
			} else if (SqlOption.EXECUTE.equals(item)) {
				predSQL.setOperationType(SqlOption.EXECUTE);
			} else if (SqlOption.UPDATE.equals(item)) {
				predSQL.setOperationType(SqlOption.UPDATE);
			} else if (SqlOption.QUERY.equals(item)) {
				predSQL.setOperationType(SqlOption.QUERY);
			} else if (SqlOption.INSERT.equals(item)) {
				predSQL.setOperationType(SqlOption.INSERT);
			} else
				return false;
		} else if (item instanceof SqlItem) {
			SqlItem sqItem = (SqlItem) item;
			SqlOption sqlItemType = sqItem.getType();
			if (SqlOption.OTHER.equals(sqlItemType))
				predSQL.addOther(sqItem);
			else if (SqlOption.PARAM.equals(sqlItemType)) {
				if(sqItem.getParameters()==null )
					predSQL.addParam(null);
				else for (Object pm : sqItem.getParameters())
					predSQL.addParam(pm);
			} else if (SqlOption.BIND.equals(sqlItemType)) {
				predSQL.addTemplateParam(sqItem);
			} else if (SqlOption.SQL.equals(sqlItemType)) {
				for (Object pm : sqItem.getParameters())
					predSQL.addSql(pm);
			} else if (SqlOption.QUESTION_PARAM.equals(sqlItemType)) {
				if (sqItem.getParameters() == null) {
					predSQL.addParam(null);
					predSQL.addSql("?");
				} else {
					int i = 0;
					for (Object pm : sqItem.getParameters()) {
						predSQL.addParam(pm);
						if (i > 0)
							predSQL.addSql(",");
						predSQL.addSql("?");
						i++;
					}
				}
			} else if (SqlOption.VALUES_QUESTIONS.equals(sqlItemType)) {
				predSQL.addSql(" values(");
				for (int i = 0; i < predSQL.getParamSize(); i++) {
					if (i > 0)
						predSQL.addSql(",");
					predSQL.addSql("?");
				}
				predSQL.addSql(")");
			} else if (SqlOption.ENABLE_HANDLERS.equals(sqlItemType)) {
				predSQL.enableAllHandlers();
			} else if (SqlOption.DISABLE_HANDLERS.equals(sqlItemType)) {
				predSQL.disableHandlers((Object[]) sqItem.getParameters());
			} else if (SqlOption.SWITCHTO.equals(sqlItemType)) {
				predSQL.setSwitchTo((DbPro) sqItem.getParameters()[0]);
			} else
				return false;
		} else if (item instanceof Text)
			predSQL.addSql(item.toString());
		else if (item instanceof Connection)
			predSQL.setConnection((Connection) item);
		else if (item instanceof DbPro)
			predSQL.setSwitchTo((DbPro) item);
		else if (item instanceof SqlHandler)
			predSQL.addHandler((SqlHandler) item);
		else if (item instanceof ResultSetHandler)
			predSQL.setResultSetHandler((ResultSetHandler) item);
		else if (item instanceof Class) {
			if (Text.class.isAssignableFrom((Class) item)) {
				String text = Text.classToString((Class) item);
				predSQL.addSqlOrParam(inlineStyle, text);
				return true;
			} else
				return false;
		} else if (item instanceof CustomizedSqlItem) {
			((CustomizedSqlItem) item).doPrepare(predSQL);
		} else if(sqlItemHandler!=null)
			return sqlItemHandler.handle(predSQL, item);
		  else
			return false;
		return true;
	}

	public void ________3letter_inlineStyles________() {// NOSONAR
	}

	/**
	 * Executes the in-line style query statement
	 *
	 * @param inlineSQL
	 *            the in-line style SQL
	 * @return An object generated by the handler.
	 */
	public <T> T qry(Object... inlineSQL) {
		PreparedSQL ps = prepare(inlineSQL);
		ps.ifNullSetType(SqlOption.QUERY);
		return (T) runPreparedSQL(ps);
	}

	/**
	 * Execute an In-line style query for an Object, only return the first row and
	 * first column's value if more than one column or more than 1 rows returned
	 *
	 * @param inlineSQL
	 * @param params
	 * @return An Object or null value determined by SQL content
	 */
	public <T> T qryObject(Object... inlineSQL) {
		PreparedSQL ps = prepare(inlineSQL);
		ps.ifNullSetType(SqlOption.QUERY);
		if (ps.getResultSetHandler() == null)
			ps.setResultSetHandler(new ScalarHandler<T>(1));
		return (T) runPreparedSQL(ps);
	}

	/**
	 * In-line style execute query and force return a long value, runtime exception
	 * may throw if result can not be cast to long.
	 */
	public long qryLongValue(Object... inlineSQL) {
		return ((Number) qryObject(inlineSQL)).longValue();// NOSONAR
	}

	/**
	 * In-line style execute query and force return a int, runtime exception may
	 * throw if result can not be cast to int.
	 */
	public int qryIntValue(Object... inlineSQL) {
		return ((Number) qryObject(inlineSQL)).intValue();// NOSONAR
	}

	 /**
     * In-line style execute query and force return a boolean, runtime exception may
     * throw if result can not be cast to boolean.
     */
    public boolean qryBooleanValue(Object... inlineSQL) {
        return (Boolean) qryObject(inlineSQL);// NOSONAR
    }

	/**
	 * In-line style execute query and force return a String object.
	 */
	public String qryString(Object... inlineSQL) {
		Object result = qryObject(inlineSQL);
		return result == null ? null : result.toString();
	}

	/**
	 * In-Line style execute query and force return a List<Map<String, Object>> type
	 * result.
	 */
	public List<Map<String, Object>> qryMapList(Object... items) {
		PreparedSQL ps = prepare(items);
		ps.addHandler(new MapListHandler());
		ps.ifNullSetType(SqlOption.QUERY);
		return (List<Map<String, Object>>) runPreparedSQL(ps);
	}

	/**
	 * In-Line style execute query and force return a Map<String, Object> type
	 * result, if no record found, return empty HashMap<String, Object> instance;
	 */
	public Map<String, Object> qryMap(Object... items) {
		List<Map<String, Object>> list = qryMapList(items);
		if (list.isEmpty())
			return new HashMap<String, Object>();
		return list.get(0);
	}

	/**
	 * In-Line style execute query and force return a Map<String, Object> type
	 * result, if no record found, return empty HashMap<String, Object> instance;
	 */
	public <T> List<T> qryList(Object... items) {
		return this.qry(new ColumnListHandler<T>(1), items);
	}

	/**
	 * Executes the in-line style INSERT, UPDATE, or DELETE statement
	 *
	 * @param inlineSQL
	 *            the in-line style SQL
	 * @return The number of rows updated.
	 */
	public int upd(Object... inlineSQL) {
		PreparedSQL ps = prepare(inlineSQL);
		ps.ifNullSetType(SqlOption.UPDATE);
		return (Integer) runPreparedSQL(ps);
	}

	/**
	 * Executes the in-line style insert statement
	 *
	 * @param inlineSQL
	 *            the in-line style SQL
	 * @return An object generated by the handler.
	 */
	public <T> T ins(Object... inlineSQL) {
		PreparedSQL ps = prepare(inlineSQL);
		ps.ifNullSetType(SqlOption.INSERT);
		return (T) runPreparedSQL(ps);
	}

	/**
	 * Executes the in-line style execute statement
	 *
	 * @param inlineSQL
	 *            the in-line style SQL
	 * @return A list of objects generated by the handler, or number of rows updated
	 *         if no handler
	 */
	public <T> T exe(Object... inlineSQL) {
		PreparedSQL ps = prepare(inlineSQL);
		ps.ifNullSetType(SqlOption.EXECUTE);
		return (T) runPreparedSQL(ps);
	}

	/**
	 * nXxxx style series methods are design to replace QueryRunner's xxxx method,
	 * the difference is nXxxx methods do not throw SqlException
	 */
	public void ________jdbcMethods________() {// NOSONAR

	}

	/**
	 * Query for an Object, only return the first row and first column's value if
	 * more than one column or more than 1 rows returned, a null object may return
	 * if no result found , DbProRuntimeException may be threw if some SQL operation
	 * Exception happen.
	 *
	 * @param sql
	 * @param params
	 * @return An Object or null, Object type determined by SQL content
	 */
	@Override
	public <T> T jdbcQueryForObject(String sql, Object... params) {
		PreparedSQL ps = new PreparedSQL(SqlOption.QUERY, null, SingleTonHandlers.scalarHandler, sql, params);
		ps.addGlobalAndThreadedHandlers(this);
		return (T) runPreparedSQL(ps);
	}

	/**
	 * Executes the given INSERT, UPDATE, or DELETE SQL statement.
	 *
	 * @param sql
	 *            the SQL
	 * @param params
	 *            the parameters if have
	 * @return The number of rows updated.
	 */
	@Override
	public int jdbcUpdate(String sql, Object... params) {
		PreparedSQL ps = new PreparedSQL(SqlOption.UPDATE, null, null, sql, params);
		ps.addGlobalAndThreadedHandlers(this);
		return (Integer) runPreparedSQL(ps);
	}

	/**
	 * Execute an statement, including a stored procedure call, which does not
	 * return any result sets. Any parameters which are instances of
	 * {@link OutParameter} will be registered as OUT parameters.
	 *

	 * Use this method when invoking a stored procedure with OUT parameters that
	 * does not return any result sets.
	 *
	 * @param sql
	 *            the SQL
	 * @return The number of rows updated.
	 */
	@Override
	public int jdbcExecute(String sql, Object... params) {
		PreparedSQL ps = new PreparedSQL(SqlOption.EXECUTE, null, null, sql, params);
		ps.addGlobalAndThreadedHandlers(this);
		return (Integer) runPreparedSQL(ps);
	}

	// ============================================================================

}


text:
namespace views {
class Checkbox;
class NativeButton;
class RadioButton;
}
class FileDisplayArea;
class OptionsGroupView;
class PrefService;

////////////////////////////////////////////////////////////////////////////////
// ContentPageView

class ContentPageView : public OptionsPageView,
                        public views::ButtonListener {
 public:
  explicit ContentPageView(Profile* profile);
  virtual ~ContentPageView();

  // views::ButtonListener implementation:
  virtual void ButtonPressed(views::Button* sender);

 protected:
  // OptionsPageView implementation:
  virtual void InitControlLayout();
  virtual void NotifyPrefChanged(const std::wstring* pref_name);

  // views::View overrides:
  virtual void Layout();

 private:
  // Init all the dialog controls.
  void InitPasswordSavingGroup();
  void InitFormAutofillGroup();
  void InitBrowsingDataGroup();
  void InitThemesGroup();

  // Controls for the Password Saving group
  views::NativeButton* passwords_exceptions_button_;
  OptionsGroupView* passwords_group_;
  views::RadioButton* passwords_asktosave_radio_;
  views::RadioButton* passwords_neversave_radio_;

  // Controls for the Form Autofill group
  OptionsGroupView* form_autofill_group_;
  views::RadioButton* form_autofill_asktosave_radio_;
  views::RadioButton* form_autofill_neversave_radio_;

  // Controls for the Themes group
  OptionsGroupView* themes_group_;
  views::NativeButton* themes_reset_button_;

  // Controls for the browsing data group.
  OptionsGroupView* browsing_data_group_;
  views::Label* browsing_data_label_;
  views::NativeButton* import_button_;
  views::NativeButton* clear_data_button_;

  BooleanPrefMember ask_to_save_passwords_;
  BooleanPrefMember ask_to_save_form_autofill_;

  DISALLOW_COPY_AND_ASSIGN(ContentPageView);
};

#endif  // CHROME_BROWSER_VIEWS_OPTIONS_CONTENT_PAGE_VIEW_H_


text:
<!DOCTYPE html>

<html>
<head>
  <title>google-api-loader-test</title>
  <script src="bower_components/platform/platform.js"></script>
  <link rel="import" href="app-main.html">
</head>

<body unresolved>
  <app-main fit></app-main>
</body>
</html>


text:
While on the [plane to Vegas](http://blog.diniscruz.com/2013/07/day-1-made-it-to-vegas-start-of-aspnet.html), I looked at a number of ASP.NET MVC apps (ping me if you know of other good ones to look at (with publicly available source code)).

I was trying to find one that had good examples of MVC ModelBinding Vulnerabilities (aka overposting), in a real-world-kinda-way (I have found tons of MVC ModelBinding Vulnerability examples which usually get dismissed with a _'that is not the recommended way to code MVC controllers'_).

So I think I found a great example (of what not to do) on the Contoso University sample.

This application is explained in detail in this article [Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10)](http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application)  and can be downloaded from [http://code.msdn.microsoft.com/ASPNET-MVC-Application-b01a9fe8/view/SourceCode](http://code.msdn.microsoft.com/ASPNET-MVC-Application-b01a9fe8/view/SourceCode) (as shown below, you can also get this from the official ASP.NET MVC website)

![](images/Screen_Shot_2013-07-31_at_11_33_35.png)

Remember that this is how developers learn about programming ASP.NET MVC, so it is important that the code samples they have access to (from reputable sources like http://www.asp.net/mvc) are rock solid and don't have MVC ModelBinding Vulnerabilities.

A quick look at the code showed numerous vulnerable controllers, and in this first (raw) PoC example, we are going to exploit the public **ActionResult Edit(int id, FormCollection formCollection, string[] selectedCourses)** method from the  [InstructorController.cs](http://code.msdn.microsoft.com/ASPNET-MVC-Application-b01a9fe8/sourcecode?fileId=93127&pathId=2009908151%20code.msdn.microsoft.com/ASPNET-MVC-Application-b01a9fe8/sourcecode?fileId=93127&pathId=2009908151) file.

This is what the vulnerable code looks like:

![](images/Screen_Shot_2013-07-31_at_11_38_48.png)

Here is the list of current Instructors (note the extra course on [Scratch](http://scratch.mit.edu/) (added in a previous execution of the PoC)

![](images/Screen_Shot_2013-07-31_at_11_39_50.png)

Here is the page that is used to edit an Instructor's details (and the one we will use on the exploit)

![](images/Screen_Shot_2013-07-31_at_11_51_25.png)

Here is the source code of the exploit PoC:

Here is the execution of the code shown above (with a new course on _'Exploit MVC'_ which was added by the exploit)

![](images/Screen_Shot_2013-07-31_at_11_45_14.png)

This is actually an interesting scenario, specially since the affected controller tries to prevent injection into the Courses field :)

My next series of blog posts will explain how this works, and how it was possible to **_'add a new course while editing an Instructor details'_**


text:
package com.rptools.controller;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.rptools.table.RPTable;
import com.rptools.table.TableReader;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@CommonsLog
@RestController("TablesController")
@RequestMapping("tables")
public class TablesController {
  private final TableReader tableReader;

  public TablesController(TableReader tableReader) {
    this.tableReader = tableReader;
  }

  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView main() {
    return new ModelAndView("main");
  }

  @RequestMapping(value = "list", method = RequestMethod.GET)
  public String list() {
    return serializeTable(tableReader.getTables());
  }

  private String serializeTable(RPTable table) {
    try {
      return JsonFormat.printer().print(table);
    } catch (InvalidProtocolBufferException e) {
      log.error("Exception serializing RPTable object " + table.getName(), e);
      return "";
    }
  }
}


text:
@interface FeiFanLoginViewController : BBSApiBaseViewController

@property(weak, nonatomic) IBOutlet WKWebView *webView;

- (IBAction)cancelLogin:(id)sender;

@property(strong, nonatomic) IBOutlet UIView *maskLoadingView;

@end


text:
from . import parser
from .. import util

class Attr(parser.Parser):

    def __init__(self, value, attr_type=None):
        if value in (None, parser.UNUSED):
            raise TypeError('May not assign {} to Attr()'.format(value))
        if attr_type is parser.AttrType.UNUSED:
            raise ValueError('Attr may not be UNUSED')
        self.__value = value
        if attr_type is None:
            if isinstance(value, str):
                self.__attr_type = parser.AttrType.STRING
            elif isinstance(value, tuple):
                self.__attr_type = parser.AttrType.TUPLE
            else:
                self.__attr_type = parser.AttrType.OBJECT
        else:
            attr_type.check_compatible(value)
            self.__attr_type = attr_type

    @property
    def attr_type(self):
        return self.__attr_type

    @property
    def value(self):
        return self.__value

    def _parse(self, state):
        state.commit(self.__value)

@util.singleton
class eoi(parser.Parser):

    @property
    def attr_type(self):
        return parser.AttrType.UNUSED

    def _parse(self, state):
        if state.read(1) == '':
            state.commit()

@util.singleton
class eps(parser.Parser):

    @property
    def attr_type(self):
        return parser.AttrType.UNUSED

    def _parse(self, state):
        state.succeed()


text:
// <copyright file="IPaymentService.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace Daemos.Console
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using Daemos.Scripting;

    public class InitializeResult : ISerializable
    {
        public InitializeResult(int transactionId)
        {
            this.TransactionId = transactionId;
        }

        public InitializeResult(IStateDeserializer deserializer)
        {
            this.TransactionId = deserializer.Deserialize<int>(nameof(this.TransactionId));
        }

        public int TransactionId { get; }

        public void Serialize(IStateSerializer serializer)
        {
            serializer.Serialize(nameof(this.TransactionId), this.TransactionId);
        }
    }

    public class AuthorizeResult : ISerializable
    {
        public AuthorizeResult(decimal amount)
        {
            this.Amount = amount;
        }

        public AuthorizeResult(IStateDeserializer deserializer)
        {
            this.Amount = deserializer.Deserialize<decimal>(nameof(this.Amount));
        }

        public decimal Amount { get; }

        public void Serialize(IStateSerializer serializer)
        {
            serializer.Serialize(nameof(this.Amount), this.Amount);
        }
    }

    public class CaptureResult : ISerializable
    {
        public CaptureResult(decimal capturedAmount, decimal remainingAmount)
        {
            this.CapturedAmount = capturedAmount;
            this.RemainingAmount = remainingAmount;
        }

        public CaptureResult(IStateDeserializer deserializer)
        {
            this.CapturedAmount = deserializer.Deserialize<decimal>(nameof(this.CapturedAmount));
            this.RemainingAmount = deserializer.Deserialize<decimal>(nameof(this.RemainingAmount));
        }

        public decimal CapturedAmount { get; }

        public decimal RemainingAmount { get; }

        public void Serialize(IStateSerializer serializer)
        {
            serializer.Serialize(nameof(this.CapturedAmount), this.CapturedAmount);
            serializer.Serialize(nameof(this.RemainingAmount), this.RemainingAmount);
        }
    }

    public class CompleteResult
    {
        public CompleteResult(int transactionId)
        {
            this.TransactionId = transactionId;
        }

        public int TransactionId { get; }
    }

    public interface IPaymentService
    {
        InitializeResult Initialize(int merchantId);

        AuthorizeResult Authorize(int transactionId, decimal maxAmount);

        CaptureResult Capture(int transactionId, decimal amount);

        CompleteResult Complete(int transactionId);
    }

    public class MockPaymentService : IPaymentService
    {
        private class TransactionInfo
        {
            public decimal AuthorizedAmount { get; set; }

            public int MerchantId { get; }

            public TransactionInfo(int merchantId)
            {
                this.MerchantId = merchantId;
            }

        }

        private static readonly Random RandomGenerator = new Random();
        private static readonly Dictionary<int, TransactionInfo> _transactions = new Dictionary<int, TransactionInfo>();

        public InitializeResult Initialize(int merchantId)
        {
            var transactionId = RandomGenerator.Next();
            _transactions.Add(transactionId, new TransactionInfo(merchantId));
            return new InitializeResult(transactionId);
        }

        public AuthorizeResult Authorize(int transactionId, decimal maxAmount)
        {
            var ti = _transactions[transactionId];
            ti.AuthorizedAmount = maxAmount;
            return new AuthorizeResult(maxAmount);
        }

        public CaptureResult Capture(int transactionId, decimal amount)
        {
            var ti = _transactions[transactionId];
            var resultAmount = ti.AuthorizedAmount - amount;
            if (resultAmount < 0m)
            {
                throw new InvalidOperationException("Cannot capture more than the authorized amount.");
            }
            ti.AuthorizedAmount = resultAmount;
            return new CaptureResult(amount, ti.AuthorizedAmount);
        }

        public CompleteResult Complete(int transactionId)
        {
            var ti = _transactions[transactionId];
            ti.AuthorizedAmount = 0m;
            return new CompleteResult(transactionId);
        }
    }
}


text:
package de.esri.osm.conversion;

import org.apache.http.StatusLine;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;

import de.esri.osm.config.Query;
import de.esri.osm.core.ArcGISRequestHandler;
import de.esri.osm.core.JsonRequestListener;
import de.esri.osm.core.TokenListener;
import de.esri.osm.data.ArcGISJSONObject;
import de.esri.osm.data.GeometryGenerationException;
import de.esri.osm.data.GeometryReaderException;
import de.esri.osm.data.GeometryTypeSupportException;
import de.esri.osm.data.OSMJSON2ArcGISJSONConverter;

/**
 * Handles the conversion process from a single OSM Overpass object to an ArcGIS feature service.
 *
 * @author Eva Peters
 *
 */
public class FeatureHandler {

	private static Logger log = LogManager.getLogger(FeatureHandler.class.getName());

	private JSONObject osmElement;

	private String json;

	private Query query;

	private TokenHandler tokenHandler;

	public FeatureHandler(JSONObject osmElement, Query query, TokenHandler tokenHandler)
	{
		this.osmElement = osmElement;
		this.query = query;
		this.tokenHandler = tokenHandler;
	}

	/**
	 * Starts the process of conversion and adding the feature to the feature service.
	 */
	public void start()
	{
		convert();
	}

	/**
	 * Converts OSM JSON to ArcGIS JSON and continues to update the token.
	 */
	private void convert()
	{
		try
		{
			ArcGISJSONObject arcGISJSONObject = OSMJSON2ArcGISJSONConverter.convert(this.osmElement, this.query);
			this.json = arcGISJSONObject.toString();

			updateToken();
		}
		catch (GeometryTypeSupportException e)
		{
			log.error(e.getMessage() + " This feature is skipped.");
		} catch (GeometryGenerationException e)
		{
			log.error(e.getMessage() + " This feature is skipped.");
		} catch (GeometryReaderException e)
		{
			log.error(e.getMessage() + " This feature is skipped.");
		}
	}

	/**
	 * Updates the token and continues with adding the feature.
	 */
	private void updateToken()
	{
		log.debug("Check token for add features");
		tokenHandler.generateValidToken(new TokenListener() {

			@Override
			public void onSuccess(String message) {
				log.debug(message);

				addFeature();
			}

			@Override
			public void onError(String message) {
				log.error(message);
			}
		});
	}

	/**
	 * Adds the feature to the feature class.
	 */
	private void addFeature()
	{
		String featureClassUrl = query.getArcgis().getFeatureClass();
		String token = tokenHandler.getToken();

		log.debug("Start adding features to feature service " + featureClassUrl);
		ArcGISRequestHandler.addFeatures(featureClassUrl, json, token, new JsonRequestListener()
		{
			@Override
			public void onSuccess(JSONObject json) {
				log.debug("Success requesting addFeatures: " + json.toString());
			}

			@Override
			public void onFailure(Throwable error) {
				log.error("Error requesting addFeatures: " + error.getMessage());
			}

			@Override
			public void onError(JSONObject jsonObject, StatusLine statusLine) {
				log.error("Error requesting addFeatures - code: " + statusLine.getStatusCode() + ", error: " + jsonObject.toString());
			}
		});
	}
}


text:
#ifndef _MP_IDENTIFY_H_
#define _MP_IDENTIFY_H_

enum{
	MP_IDENTIFY,
	MP_PROJECT,
	MP_PARTICLE,
};

class MpIdentify
{
	public:
		virtual int getClassType();
		virtual const char* className();
};

#endif /*_MP_IDENTIFY_H_*/


text:
layout: default
title: CAS - Logback Configuration
category: Logs & Audits
---

{% include variables.html %}

# Logback Logging

CAS does also support [Logback](https://logback.qos.ch/) as an alternative logging engine. At a high level,
the Logback architecture is similar to that of [Log4j](Logging.html) where you have `Logger`, `Appender`
and `Layout` components typically defined inside a `logback.xml` file.

Refer to the [Logback documentation](https://logback.qos.ch/documentation.html) to learn more.

## Configuration

Support is enabled by including the following dependency in the WAR overlay:

{% include casmodule.html group="org.apereo.cas" module="cas-server-support-logback" %}

You must also make sure the following modules and dependencies are excluded from the WAR overlay:

```groovy
configurations.all {
    exclude(group: "org.apache.logging.log4j", module: "log4j-api")
    exclude(group: "org.apache.logging.log4j", module: "log4j-web")
    exclude(group: "org.apache.logging.log4j", module: "log4j-jcl")
    exclude(group: "org.apache.logging.log4j", module: "log4j-slf4j-impl")

    exclude(group: "org.apereo.cas", module: "cas-server-core-logging")
}
```

YMMV

Logback support for Java 9 and above is still not quite finalized and released. In the WAR overlay, you may need to strictly force
the Logback and Slf4j module versions to 1.2.3 and 1.7.5 respectively to get around JDK compatibility issues.
This is expected to be fixed in future CAS releases once Logback is officially released and you should keep an eye out for related changes and fixes in the CAS release notes.

A sample `logback.xml` file follows:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%white(%d{yyyy-MM-dd HH:mm:ss}) %highlight(%-5level) %cyan(%logger{15}) - %msg%n</Pattern>
        </layout>
    </appender>
    <logger name="org.apereo.cas" level="info" additivity="false">
        <appender-ref ref="console" />
    </logger>
    <root level="info">
        <appender-ref ref="console" />
    </root>
</configuration>
```

Be Careful

Sanitizing log data to remove sensitive ticket ids such as ticket-granting tickets or proxy-granting tickets is not handled by CAS when Logback is used. While this
may be worked out in future releases, you should be extra careful to cleanse log data prior to sharing it with external systems such as Splunk or Syslog, etc.

{% include casproperties.html properties="cas.logging" thirdPartyStartsWith="logging." %}


text:
This is a simple single resource REST app I created using the hapi framework.
This is made for adding animals to a nosql, mongodb database.

##Required dependencies are
####hapi - install with:
npm install hapi -S
####mongoose- install with:
npm install hapi -S

##WARNING!!!
####Make sure that any requests you make match the name completely.
####Names are case sensitive. So if you have a animal with
#####name='Jake the dog'
#####make sure that you request the name exactly as it is
#####and  make sure that you put quotes around the value of
#####a property if it is more than one word,
#####IE: name='Jake the dog'

#NOTE:
###You can copy and paste each example in the order they
###are shown and this will walk you through each request in ###a way so you can see firsthand how this app works.

#POST
###path: /animals
Animals are added to a database through a POST request with the following parameters.
name:
type:
####Example POST request using httpie
http POST localhost:7777/animals name=dog type=mammal
#GET
###path: /animals/{name}
Animal Information can be viewed as a list all-together, or listed one by one if searched by the name parameter of the animal.
####Example:
httpie request To get a list of all of the animals in the database
http GET localhost:7777/animals
####Example:
httpie request to get an individual animal from the database
http GET localhost:7777/animals/dog
#PUT
###path: /animals/{name}
Animals can be updated using a PUT request to localhost:7777/animals/{name}
Replace {name} with the current name of the animal you wish to update.
Afterwards enter the PUT request data in either JSON format or however your
request app/package that you are using requires. I use httpie because you don't have to enter it in JSON format, and you can just enter it straight in,
as long as you put quotes around the property value if it is more than
one word.
####EXAMPLE:
An example PUT request using http is;
http PUT localhost:7777/animals/dog name='Jake the dog' type=Canine
#DELETE
###path: /animals/{name}
Animals can be deleted one by one by making a DELETE request, with the path
of an existing animal in the database by its name.
####EXAMPLE:
An example DELETE request using httpie
http DELETE localhost:7777/animals/'Jake the dog'


text:
This page was generated with Wiki Builder. Do not change the format!

## Info

* **URI:** [[/Activity/User/{param1}/Following/|https://www.bungie.net/Platform/Activity/User/{param1}/Following/]]
* **Basepath:** https://www.bungie.net/Platform
* **Method:** GET
* **Service:** [[Activity|Endpoints#Activity]]
* **Permissions:** None
* **Officially Supported:** No

## Parameters
### Path Parameters
Name | Schema | Required | Description
---- | ------ | -------- | -----------
param1 | string | Yes |

### Query String Parameters
None

## Example
### Request
GET https://www.bungie.net/Platform/Activity/User/{param1}/Following/

### Response
PlatformErrorCode: 200
```javascript
{
    // Type: [#/components/schemas/Activity.GetEntitiesFollowedByUser]
    "Response": null,
    // Type: [[PlatformErrorCodes|Exceptions-PlatformErrorCodes]]:Enum
    "ErrorCode": 0,
    // Type: integer:int32
    "ThrottleSeconds": 0,
    // Type: string
    "ErrorStatus": "",
    // Type: string
    "Message": "",
    // Type: Dictionary<string,string>
    "MessageData": {
        "{string}": ""
    },
    // Type: object
}

```

## References


text:
package com.example.android.qcircleview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Camera extends Activity {
    private android.hardware.Camera mCamera;
    private CameraPreview mPreview;
    private PictureCallback mPicture;
    private ImageButton capture;
    private ImageButton capture2;
    private ImageButton flash;
    private Button switchCamera;
    private MediaRecorder mediaRecorder;
    private Context myContext;
    private LinearLayout cameraPreview;
    private boolean cameraFront = false;
    public static boolean camera;
    public static Activity camera1;
    private boolean isLighOn1 = false;
    private android.hardware.Camera.Parameters p;
    private String mediaFile1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        setContentView(R.layout.camera_view);
        Menu.menu1.finish();
        camera = true;
        camera1 = this;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        ImageButton retour4 = (ImageButton) findViewById(R.id.retour4);
        retour4.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent startIntent = new Intent(getApplication(), MainActivity.class);
                startActivity(startIntent);
                finish();
                if (SlidingTabsBasicFragment.myThread == null) {
                    SlidingTabsBasicFragment.myThread = new Thread(SlidingTabsBasicFragment.runnable);
                    SlidingTabsBasicFragment.myThread.start();
                }
            }
        });
        myContext = this;
        initialize();
        flash = (ImageButton) findViewById(R.id.flash);
        flash.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if (isLighOn1) {

                    Log.i("info", "torch is turn off!");

                    p.setFlashMode(android.hardware.Camera.Parameters.FLASH_MODE_OFF);
                    mCamera.setParameters(p);
                    Drawable off = getApplicationContext().getResources().getDrawable(R.drawable.lightning);
                    flash.setBackground(off);
                    isLighOn1 = false;

                } else {

                    Log.i("info", "torch is turn on!");

                    p.setFlashMode(android.hardware.Camera.Parameters.FLASH_MODE_TORCH);

                    mCamera.setParameters(p);
                    Drawable on = getApplicationContext().getResources().getDrawable(R.drawable.lightning_off);
                    flash.setBackground(on);
                    isLighOn1 = true;

                }

            }
        });
    }

    private int findFrontFacingCamera() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = android.hardware.Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            CameraInfo info = new CameraInfo();
            android.hardware.Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
                cameraId = i;
                cameraFront = true;
                break;
            }
        }
        return cameraId;
    }

    private int findBackFacingCamera() {
        int cameraId = -1;
        //Search for the back facing camera
        //get the number of cameras
        int numberOfCameras = android.hardware.Camera.getNumberOfCameras();
        //for every camera check
        for (int i = 0; i < numberOfCameras; i++) {
            CameraInfo info = new CameraInfo();
            android.hardware.Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
                cameraId = i;
                cameraFront = false;
                break;
            }
        }
        return cameraId;
    }

    public void onResume() {
        super.onResume();
        if (!hasCamera(myContext)) {
            Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
            toast.show();
            finish();
        }
        if (mCamera == null) {
            //if the front facing camera does not exist
            if (findFrontFacingCamera() < 0) {
                Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
                switchCamera.setVisibility(View.GONE);
            }
            mCamera = android.hardware.Camera.open(findBackFacingCamera());
            p = mCamera.getParameters();
            mPicture = getPictureCallback();
            mPreview.refreshCamera(mCamera);
        }
    }

    public void initialize() {
        cameraPreview = (LinearLayout) findViewById(R.id.camera_preview);
        mPreview = new CameraPreview(myContext, mCamera);
        cameraPreview.addView(mPreview);

        capture = (ImageButton) findViewById(R.id.button_capture);
        capture.setOnClickListener(captrureListener);

        capture2 = (ImageButton) findViewById(R.id.video);
        capture2.setOnClickListener(captrureListener2);

        /*switchCamera = (Button) findViewById(R.id.button_ChangeCamera);
        switchCamera.setOnClickListener(switchCameraListener);*/
    }

    /*OnClickListener switchCameraListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            //get the number of cameras
            int camerasNumber = android.hardware.Camera.getNumberOfCameras();
            if (camerasNumber > 1) {
                //release the old camera instance
                //switch camera, from the front and the back and vice versa

                releaseCamera();
                chooseCamera();
            } else {
                Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
                toast.show();
            }
        }
    };

    public void chooseCamera() {
        //if the camera preview is the front
        if (cameraFront) {
            int cameraId = findBackFacingCamera();
            if (cameraId >= 0) {
                //open the backFacingCamera
                //set a picture callback
                //refresh the preview

                mCamera = android.hardware.Camera.open(cameraId);
                mPicture = getPictureCallback();
                mPreview.refreshCamera(mCamera);
            }
        } else {
            int cameraId = findFrontFacingCamera();
            if (cameraId >= 0) {
                //open the backFacingCamera
                //set a picture callback
                //refresh the preview

                mCamera = android.hardware.Camera.open(cameraId);
                mPicture = getPictureCallback();
                mPreview.refreshCamera(mCamera);
            }
        }
    }*/

    @Override
    protected void onPause() {
        super.onPause();
        //when on Pause, release camera in order to be used from other applications
        releaseCamera();
    }

    private boolean hasCamera(Context context) {
        //check if the device has camera
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            return true;
        } else {
            return false;
        }
    }

    private PictureCallback getPictureCallback() {
        PictureCallback picture = new PictureCallback() {

            @Override
            public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
                //make a new picture file
                File pictureFile = getOutputMediaFile();

                if (pictureFile == null) {
                    return;
                }
                try {
                    //write the file
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    fos.write(data);
                    fos.close();
                    Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName() + " in Gallery", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.TOP, 0, 250);
                    //REFRESHING THE ANDROID PHONE PHOTO GALLERY IS BEGUN
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        Intent mediaScanIntent = new Intent(
                                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri contentUri = Uri.fromFile(pictureFile);
                        mediaScanIntent.setData(contentUri);
                        sendBroadcast(mediaScanIntent);
                    } else {
                        sendBroadcast(new Intent(
                                Intent.ACTION_MEDIA_MOUNTED,
                                Uri.parse("file://"
                                        + Environment.getExternalStorageDirectory())));
                    }
                    //REFRESHING THE ANDROID PHONE PHOTO GALLERY IS COMPLETE
                    toast.show();

                } catch (FileNotFoundException e) {
                } catch (IOException e) {
                }

                //refresh camera to continue preview
                mPreview.refreshCamera(mCamera);
            }
        };
        return picture;
    }

    OnClickListener captrureListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            mCamera.takePicture(null, null, mPicture);
        }
    };
    boolean recording = false;
    OnClickListener captrureListener2 = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (recording) {

                // stop recording and release camera
                mediaRecorder.stop(); // stop the recording
                releaseMediaRecorder(); // release the MediaRecorder object
                File mediaStorageDir = new File("/sdcard/DCIM/", "Camera");
                File videoFile;
                videoFile = new File(mediaStorageDir.getPath() + File.separator + mediaFile1);
                Drawable off = getApplicationContext().getResources().getDrawable(android.R.drawable.presence_video_online);
                capture2.setBackground(off);
                Toast toast1 = Toast.makeText(Camera.this, "Video captured! saved in Gallery", Toast.LENGTH_LONG);
                toast1.setGravity(Gravity.TOP, 0, 250);
                //REFRESHING THE ANDROID PHONE PHOTO GALLERY IS BEGUN
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    Intent mediaScanIntent = new Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri contentUri = Uri.fromFile(videoFile);
                    mediaScanIntent.setData(contentUri);
                    sendBroadcast(mediaScanIntent);
                } else {
                    sendBroadcast(new Intent(
                            Intent.ACTION_MEDIA_MOUNTED,
                            Uri.parse("file://"
                                    + Environment.getExternalStorageDirectory())));
                }
                toast1.show();
                recording = false;
            } else {
                if (!prepareMediaRecorder()) {
                    Toast toast2 = Toast.makeText(Camera.this, "Fail in prepareMediaRecorder()!\n - Ended -", Toast.LENGTH_LONG);
                    toast2.setGravity(Gravity.TOP, 0, 250);
                    toast2.show();
                    finish();
                }
                // work on UiThread for better performance
                runOnUiThread(new Runnable() {
                    public void run() {
                        // If there are stories, add them to the table

                        try {
                            mediaRecorder.start();
                            Drawable on = getApplicationContext().getResources().getDrawable(android.R.drawable.presence_video_busy);
                            capture2.setBackground(on);
                        } catch (final Exception ex) {
                            // Log.i("---","Exception in thread");
                        }
                    }
                });

                recording = true;
            }
        }
    };

    //make picture and save to a folder
    private static File getOutputMediaFile() {
        //make a new file directory inside the "sdcard" folder
        File mediaStorageDir = new File("/sdcard/DCIM/", "Camera");

        //if this "JCGCamera folder does not exist
        if (!mediaStorageDir.exists()) {
            //if you cannot make this folder return
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        //take the current timeStamp
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        //and make a media file:
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");

        return mediaFile;
    }

    private void releaseMediaRecorder() {
        if (mediaRecorder != null) {
            mediaRecorder.reset(); // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = null;
            mCamera.lock(); // lock camera for later use
        }
    }

    private boolean prepareMediaRecorder() {

        mediaRecorder = new MediaRecorder();
        //take the current timeStamp
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        //and make a media file:
        mediaFile1 = "VID_" + timeStamp + ".mp4";

        mCamera.unlock();
        mediaRecorder.setCamera(mCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));

        mediaRecorder.setOutputFile("/sdcard/DCIM/Camera/" + mediaFile1);
        mediaRecorder.setMaxDuration(600000); //set maximum duration 60 sec.
        mediaRecorder.setMaxFileSize(50000000); //set maximum file size 50M

        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }
        return true;

    }

    private void releaseCamera() {
        // stop and release camera
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    public void onDestroy() {
        camera = false;
        super.onDestroy();

    }
}


text:
package hpoweb.data;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLClass;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
import com.vaadin.server.VaadinService;

import de.charite.phenowl.annotations.AnnotationUtils;
import de.charite.phenowl.hpowl.util.ExtendedOwlOntology;
import de.charite.phenowl.hpowl.util.OwlAxiomClass;
import hpo.DiseaseGeneMapper;
import hpoweb.uicontent.table.HpoClassTableEntry;

public class HpData {

	private ExtendedOwlOntology extOwlOntology;

	private AnnotationUtils annotationUtils;

	private ExtendedOwlOntology extOwlOntologyWithLogicalDefs;

	public HpData() {
		String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath();

		final String xmlFile = basepath + "/WEB-INF/data/hp/catalog-v001.xml";
		String inputOntologyFile = basepath + "/WEB-INF/data/hp/hp.owl";

		Set<OwlAxiomClass> remove = new HashSet<>();
		remove.add(OwlAxiomClass.EQUIVALENCE);
		extOwlOntology = new ExtendedOwlOntology(inputOntologyFile, xmlFile, remove);

		extOwlOntologyWithLogicalDefs = new ExtendedOwlOntology(inputOntologyFile, xmlFile);
		// debug
		OWLClass cls = extOwlOntology.getOWLClassForIRI(IRI.create("http://purl.obolibrary.org/obo/HP_0100533"));
		System.out.println("ancestors of " + cls);
		for (OWLClass c : extOwlOntology.getAncestorsAsserted(cls)) {
			System.out.println(" - " + extOwlOntology.getLabel(c.getIRI()));
		}

		annotationUtils = new AnnotationUtils(extOwlOntology);
		String datapath = basepath + "/WEB-INF/data/biodata/";
		DiseaseGeneMapper.setOrphanetPath(datapath);
		annotationUtils.setDataPath(datapath);
		annotationUtils.parseAssociation();
	}

	public ExtendedOwlOntology getExtOwlOntology() {
		return extOwlOntology;
	}

	public AnnotationUtils getAnnotationUtils() {
		return annotationUtils;
	}

	public ExtendedOwlOntology getExtOwlOntologyWithLogicalDefs() {
		return extOwlOntologyWithLogicalDefs;
	}

	/**
	 * @param tableContent
	 * @return
	 */
	public HashMultimap<OWLClass, OWLClass> getLevelOneBins(List<HpoClassTableEntry> tableContent) {

		HashMultimap<OWLClass, OWLClass> ret = HashMultimap.create();

		ImmutableSet<OWLClass> targets = extOwlOntology.getChildrenAsserted(extOwlOntology.getClassForId("HP:0000118"));

		for (HpoClassTableEntry hpoCTE : tableContent) {
			OWLClass cls = extOwlOntology.getClassForId(hpoCTE.getHpoId());
			ImmutableSet<OWLClass> anc = extOwlOntology.getAncestorsAsserted(cls);
			for (OWLClass a : anc) {
				if (targets.contains(a)) {
					ret.put(a, cls);
				}
			}
		}
		return ret;
	}

}


text:
======================
Workflows Topic Guide
======================

One of the most challenging aspects of building a compelling user experience
is crafting complex multi-part workflows. Horizon's ``workflows`` module
aims to bring that capability within everyday reach.

  .. seealso::

    For detailed API information refer to the :doc:`Workflows Reference
    Guide </ref/workflows>`.

Workflows
=========

Workflows are complex forms with tabs, each workflow must consist of classes
extending the :class:`~horizon.workflows.Workflow`,
:class:`~horizon.workflows.Step` and :class:`~horizon.workflows.Action`

Complex example of a workflow
------------------------------

The following is a complex example of how data is exchanged between
urls, views, workflows and templates:

#. In ``urls.py``, we have the named parameter. E.g. ``resource_class_id``. ::

    RESOURCE_CLASS = r'^(?P<resource_class_id>[^/]+)/%s$'

    urlpatterns = [
        url(RESOURCE_CLASS % 'update', UpdateView.as_view(), name='update')
    ]

#. In ``views.py``, we pass data to the template and to the action(form)
   (action can also pass data to the ``get_context_data`` method and to the
   template). ::

    class UpdateView(workflows.WorkflowView):
        workflow_class = UpdateResourceClass

        def get_context_data(self, **kwargs):
            context = super(UpdateView, self).get_context_data(**kwargs)
            # Data from URL are always in self.kwargs, here we pass the data
            # to the template.
            context["resource_class_id"] = self.kwargs['resource_class_id']
            # Data contributed by Workflow's Steps are in the
            # context['workflow'].context list. We can use that in the
            # template too.
            return context

        def _get_object(self, *args, **kwargs):
            # Data from URL are always in self.kwargs, we can use them here
            # to load our object of interest.
            resource_class_id = self.kwargs['resource_class_id']
            # Code omitted, this method should return some object obtained
            # from API.

        def get_initial(self):
            resource_class = self._get_object()
            # This data will be available in the Action's methods and
            # Workflow's handle method.
            # But only if the steps will depend on them.
            return {'resource_class_id': resource_class.id,
                    'name': resource_class.name,
                    'service_type': resource_class.service_type}

#. In ``workflows.py`` we process the data, it is just more complex django
   form. ::

    class ResourcesAction(workflows.Action):
        # The name field will be automatically available in all action's
        # methods.
        # If we want this field to be used in the another Step or Workflow,
        # it has to be contributed by this step, then depend on in another
        # step.
        name = forms.CharField(max_length=255,
                               label=_("Testing Name"),
                               help_text="",
                               required=True)

        def handle(self, request, data):
            pass
            # If we want to use some data from the URL, the Action's step
            # has to depend on them. It's then available in
            # self.initial['resource_class_id'] or data['resource_class_id'].
            # In other words, resource_class_id has to be passed by view's
            # get_initial and listed in step's depends_on list.

            # We can also use here the data from the other steps. If we want
            # the data from the other step, the step needs to contribute the
            # data and the steps needs to be ordered properly.

    class UpdateResources(workflows.Step):
        action_class = ResourcesAction
        # This passes data from Workflow context to action methods
        # (handle, clean). Workflow context consists of URL data and data
        # contributed by other steps.
        depends_on = ("resource_class_id",)

        # By contributing, the data on these indexes will become available to
        # Workflow and to other Steps (if they will depend on them). Notice,
        # that the resources_object_ids key has to be manually added in
        # contribute method first.
        contributes = ("resources_object_ids", "name")

        def contribute(self, data, context):
            # We can obtain the http request from workflow.
            request = self.workflow.request
            if data:
                # Only fields defined in Action are automatically
                # available for contribution. If we want to contribute
                # something else, We need to override the contribute method
                # and manually add it to the dictionary.
                context["resources_object_ids"] =\
                    request.POST.getlist("resources_object_ids")

            # We have to merge new context with the passed data or let
            # the superclass do this.
            context.update(data)
            return context

    class UpdateResourceClass(workflows.Workflow):
        default_steps = (UpdateResources,)

        def handle(self, request, data):
            pass
            # This method is called as last (after all Action's handle
            # methods). All data that are listed in step's 'contributes='
            # and 'depends_on=' are available here.
            # It can be easier to have the saving logic only here if steps
            # are heavily connected or complex.

            # data["resources_object_ids"], data["name"] and
            # data["resources_class_id"] are available here.


text:
#ifndef UTIL_H
#define UTIL_H

#include <opencv2\opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#if CV_VERSION_MAJOR <= 2
#include "line_descriptor\descriptor.hpp"
#endif
#include <set>
#include <cmath>
#include "common.h"

/* Calculate the BGR historgram. */
void hist_cal(const cv::Mat &roi, float *pre_ptr, int j, int dim, const cv::Mat &mask) ;

/* Calculate the HSV historgram. */
void computeHsvColorHist(const cv::Mat &img, cv::Mat &hists, const cv::Mat& mask);

/* Iteration threshold calculation, get the threshold which can seperate the fre-ground and background. */
int iterationThreshold(cv::UMat &m);

/* µ±Á½ÌõÏߺϲ¢³ÉÒ»Ìõʱ,ÈÝÒ׳öÏÖ³åÍ»,³åÍ»Ôò²»¸üÐÂÐÅÏ¢,³åÍ»ÊÇ(0,1)ºÍ(1,0),³öÏÖÇé¿öÊÇÁ½ÌõÏߺϲ¢¹ý³ÌÖÐ,»á³öÏÖÁ½ÌõÏßÖ®¼ä»¹ÓнϴóµÄ·ì϶,µ¼Ö²»ÄÜÅжÏΪ(1,1)
   When two lines merging, */
void line_status_insert(std::set<std::pair<int, int>> &status, std::pair<int, int> &judge);
void imfill(cv::UMat &src, cv::UMat &dst, float aspect_ratio_d=0, float aspect_ratio_up=0, float area_d=300, float area_up=0, float work_scale=1.f, bool isDebug=false, cv::Scalar color=cv::Scalar(255));
void connect_hor_lines_dev(const std::vector<cv::Vec4i> &lines, std::vector<cv::Vec4f> &final_result, const cv::UMat &debug, float up_down_thres, cv::Point2f hor_f, float dist_thres=2.0, float angle_thres_ratio=80.0f);
void intersection(cv::Point2f l0, cv::Point2f l1, cv::Point2f &r);
cv::Point2f intersection(cv::Point2f l0, cv::Point2f l1);

float get_hor_lines_dev(const cv::UMat &img, cv::UMat &mask, std::vector<cv::Point2f> &lines_form, std::vector<std::pair<int, int>> &judge,
	std::vector<std::pair<int, int>> &lines_range, const int real_width,
	float length_ratio=0.25, float isPanel=0.5, int sample_h=25, int sample_w=80, int sample_step=180, int step_num=0, bool isDebug=false);
float get_hor_lines_dev(const cv::UMat &mask, std::vector<cv::Point2f> &lines_form, std::vector<std::pair<int, int>> &judge, std::vector<std::pair<int, int>> &lines_range,
	const int real_width, float length_ratio=0.25, float isPanel=0.5, int sample_h=25, int sample_w=80, int sample_step=180, int step_num=0, const float scale=1.f, bool isDebug=false);
void connect_lines_dev(const std::vector<cv::Vec4i> &lines, std::vector<cv::Vec4f> &final_result, std::vector<std::pair<int, int> > &line_range,
	const cv::UMat &debug, const int real_width, float dist_thres=2.0, float lenght_ratio=0.25, float angle_thres_ratio=80.0f, float scale=1.f);
void createMask(const cv::UMat &img, cv::UMat &panel_mask_8u, cv::UMat &basic_edge_8u, float scale = 0.8, float ar_down = 0, float ar_up = 2.8f,
	std::pair<float, float> &minMaxHeight = std::pair<float, float>(), int row_num = 0, int col_num = 0);
//float getCompletedPanel(const  cv::UMat &_img, cv::UMat &panel_mask, cv::UMat &basic_edge_8u,
//	cv::UMat &dilate_edge_8u, std::map<int, cv::Point2f> &panelCen, std::map<int, int> &component2panel,
//	std::map<int, cv::Vec4f> &bound, cv::Mat &labels, float scale, float aspect_ratio = 2.0f,  bool isSplit = true,
//	std::pair<float, float> &minMaxHeight=std::pair<float, float>(), int row_num=0, int col_num=0);
cv::UMat detectSunshineMask(const cv::UMat &_img, float scale);
//cv::line_descriptor::KeyLine getKeyLine(const cv::Point2f &lines_form, const std::pair<int, int> &lines_range, int width, int class_id=0);
cv::Rect detectFoot(const cv::UMat &_img, float work_scale, float scale = 0.4f);
cv::Rect detectFoot_caffe(const cv::UMat &_img, float work_scale, float scale = 0.4f);
//cv::Rect detectInfraredLeg(const cv::UMat &_img, float work_scale, float scale = 0.4f){ assert(false); }
cv::Rect detectSunshine(const cv::UMat &_img, const cv::UMat &mask, float scale = 0.4f);
float projectDirectionDistance(float av_k, cv::Point2f position);
bool IsNotEdgePanel(std::vector<cv::Point2f> &lines_form, std::vector<std::pair<int, int>> &lines_range, std::vector<int> &panel_idx, cv::Size &size);
void getSobelEdge(const cv::UMat &img, cv::UMat &result);

template <class T>
void reorder_points(std::vector<T> &points);
std::pair<int, int> getMatch_dev(std::pair<cv::Vec4f, cv::Vec4f> &panel_inter_points, std::vector<cv::Vec4f> &inter_points);

///// Infrared
//void createCoraseInfraredMask(const cv::UMat &_img, cv::UMat &panel_mask_8u, cv::UMat &edge_mask, float scale){ assert(false); }

// convert UTF - 8 string to wstring
std::wstring utf8_to_wstring(const std::string& str);

// convert wstring to UTF-8 string
std::string wstring_to_utf8(const std::wstring& str);
#endif


text:
package com.intellij.codeInspection.bulkOperation;

import com.intellij.psi.CommonClassNames;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.stream.Stream;

/**
 * @author Tagir Valeev
 */
public class JdkBulkMethodInfoProvider implements BulkMethodInfoProvider {
  private static BulkMethodInfo[] INFOS = {
    new BulkMethodInfo(CommonClassNames.JAVA_UTIL_COLLECTION, "add", "addAll"),
    new BulkMethodInfo(CommonClassNames.JAVA_UTIL_LIST, "remove", "removeAll")
  };

  @NotNull
  @Override
  public Stream<BulkMethodInfo> consumers() {
    return Arrays.stream(INFOS);
  }
}


text:
/** \file Projectile.cpp
    \author Samuel J. Crawford, Brooks MacLachlan, and W. Spencer Smith
    \brief Contains the entire Projectile program
*/
#include "Projectile.hpp"

#define _USE_MATH_DEFINES

#include <algorithm>
#include <fstream>
#include <iostream>
#include <limits>
#include <math.h>
#include <string>

using std::ifstream;
using std::ofstream;
using std::string;

/** \brief Controls the flow of the program
    \param argc Number of command-line arguments
    \param argv List of command-line arguments
    \return exit code
*/
int main(int argc, const char *argv[]) {
    string filename = argv[1];
    double g_vect = 9.8;
    double epsilon = 2.0e-2;
    double v_launch;
    double theta;
    double p_target;
    get_input(filename, v_launch, theta, p_target);
    input_constraints(v_launch, theta, p_target);
    double t_flight = func_t_flight(v_launch, theta, g_vect);
    double p_land = func_p_land(v_launch, theta, g_vect);
    double d_offset = func_d_offset(p_target, p_land);
    string s = func_s(p_target, epsilon, d_offset);
    write_output(s, d_offset);

    return 0;
}

double func_t_flight(double v_launch, double theta, double g_vect) {
    return 2.0 * v_launch * sin(theta) / g_vect;
}

double func_p_land(double v_launch, double theta, double g_vect) {
    return 2.0 * pow(v_launch, 2.0) * sin(theta) * cos(theta) / g_vect;
}

double func_d_offset(double p_target, double p_land) {
    return p_land - p_target;
}

string func_s(double p_target, double epsilon, double d_offset) {
    if (fabs(d_offset / p_target) < epsilon) {
        return "The target was hit.";
    }
    else if (d_offset < 0.0) {
        return "The projectile fell short.";
    }
    else {
        return "The projectile went long.";
    }
}

void get_input(string filename, double &v_launch, double &theta, double &p_target) {
    ifstream infile;
    infile.open(filename, std::fstream::in);
    infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    infile >> v_launch;
    infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    infile >> theta;
    infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    infile >> p_target;
    infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    infile.close();
}

void input_constraints(double v_launch, double theta, double p_target) {
    if (!(v_launch > 0.0)) {
        std::cout << "Warning: ";
        std::cout << "v_launch has value ";
        std::cout << v_launch;
        std::cout << ", but is suggested to be ";
        std::cout << "above ";
        std::cout << 0.0;
        std::cout << "." << std::endl;
    }
    if (!(0.0 < theta && theta < M_PI / 2.0)) {
        std::cout << "Warning: ";
        std::cout << "theta has value ";
        std::cout << theta;
        std::cout << ", but is suggested to be ";
        std::cout << "between ";
        std::cout << 0.0;
        std::cout << " and ";
        std::cout << (M_PI / 2.0);
        std::cout << " ((pi)/(2))";
        std::cout << "." << std::endl;
    }
    if (!(p_target > 0.0)) {
        std::cout << "Warning: ";
        std::cout << "p_target has value ";
        std::cout << p_target;
        std::cout << ", but is suggested to be ";
        std::cout << "above ";
        std::cout << 0.0;
        std::cout << "." << std::endl;
    }
}

void write_output(string s, double d_offset) {
    ofstream outputfile;
    outputfile.open("output.txt", std::fstream::out);
    outputfile << "s = ";
    outputfile << s << std::endl;
    outputfile << "d_offset = ";
    outputfile << d_offset << std::endl;
    outputfile.close();
}


text:
@interface AllTableViewController : UITableViewController

@end


text:
<?php

/**
 * Body Signer Interface used to apply Body-Based Signature to a message
 *
 * @package    Swift
 * @subpackage Signed
 * @author     Xavier De Cock <xdecock@gmail.com>
 */
interface Swift_Signers_BodySigner extends Swift_Signer
{
    /**
     * Change the Swift_Signed_Message to apply the singing.
     *
     * @param Swift_Signed_Message $message
     *
     * @return Swift_Signers_BodySigner
     */
    public function signMessage(Swift_SignedMessage $message);

    /**
     * Return the list of header a signer might tamper
     *
     * @return array
     */
    public function getAlteredHeaders();
}