text:
package org.guzz.jdbc;

import java.util.List;

import org.guzz.orm.se.SearchExpression;
import org.guzz.orm.se.Terms;
import org.guzz.test.DBBasedTestCase;
import org.guzz.test.User;
import org.guzz.transaction.ReadonlyTranSession;
import org.guzz.transaction.TransactionManager;
import org.guzz.transaction.WriteTranSession;

/**
 *
 *
 *
 * @author liukaixuan(liukaixuan@gmail.com)
 */
public class TestObjectBatcher extends DBBasedTestCase {

	protected void prepareEnv() throws Exception{
		for(int i = 1 ; i < 1000 ; i++){
			executeUpdate(getDefaultConn(), "insert into TB_USER values(" + i + ", 'name " + i + "', 'psw " + i + "', " + ((i%2==0)?1:0) + ", " + i + ", " + getDateFunction() + ")") ;
		}
	}

	protected int countUser(TransactionManager tm){
		ReadonlyTranSession session = tm.openNoDelayReadonlyTran() ;
		SearchExpression se = SearchExpression.forClass(User.class) ;

		int count = (int) session.count(se) ;

		session.close() ;

		return count ;
	}

	public void testInsert() throws Exception{
		WriteTranSession session = tm.openRWTran(false) ;
		ObjectBatcher batcher = session.createObjectBatcher() ;
		batcher.setBatchSize(98) ;

		int count = countUser(tm) ;

		for(int loop = 0 ; loop < 980 ; loop++){
			User user = new User() ;
			user.setUserName("hello un " + loop) ;

			batcher.insert(user) ;
		}

		batcher.executeBatch() ;

		session.commit() ;
		session.close() ;

		int count2 = countUser(tm) ;
		assertEquals(count2, 980 + count) ;
	}

	public void testUpdate() throws Exception{
		WriteTranSession session = tm.openRWTran(false) ;
		ReadonlyTranSession read = tm.openNoDelayReadonlyTran() ;

		int countBefore = countUser(tm) ;

		SearchExpression se = SearchExpression.forClass(User.class, 1, 345) ;
		List users = read.list(se) ;

		ObjectBatcher batcher = session.createObjectBatcher() ;
		batcher.setBatchSize(20) ;

		for(int i = 0 ; i < users.size() ; i++){
			User u = (User) users.get(i) ;
			u.setFavCount(new Integer(3849021)) ;
			batcher.update(u) ;
		}

		batcher.executeBatch() ;
		session.commit() ;
		session.close() ;

		se = SearchExpression.forLoadAll(User.class) ;
		se.and(Terms.eq("favCount", 3849021)) ;
		int newUserSize = (int) read.count(se) ;
		read.close() ;

		assertEquals(users.size(), newUserSize) ;

		int countAfter = countUser(tm) ;
		assertEquals(countBefore, countAfter) ;
	}

	public void testDelete() throws Exception{
		WriteTranSession session = tm.openRWTran(true) ;
		ObjectBatcher batcher = session.createObjectBatcher() ;

		int dropCount = 19 ;
		batcher.setBatchSize(dropCount) ;

		int count = countUser(tm) ;

		for(int loop = 0 ; loop < 10 ; loop++){
			int countBefore = countUser(tm) ;

			ReadonlyTranSession read = tm.openNoDelayReadonlyTran() ;
			SearchExpression se = SearchExpression.forClass(User.class, 1, 345) ;
			List users = read.list(se) ;
			read.close() ;

			for(int i = 0 ; i < dropCount; i++){
				User user = (User) users.get(i) ;

				batcher.delete(user) ;
			}

			batcher.executeBatch() ;

			int countAfter = countUser(tm) ;
			assertEquals(countAfter, countBefore - dropCount) ;
		}

		session.close() ;

		int count2 = countUser(tm) ;
		assertEquals(count2, count - 10 * dropCount) ;
	}

	public void testOnlyAllowOneOP() throws Exception{
		WriteTranSession session = tm.openRWTran(false) ;
		ObjectBatcher batcher = session.createObjectBatcher() ;

		User user = new User() ;
		user.setUserName("hello un a") ;

		batcher.insert(user) ;

		try{
			batcher.update(user) ;
			fail("operation shouldn't be allowed.") ;
		}catch(Exception e){
		}

		try{
			batcher.delete(user) ;
			fail("operation shouldn't be allowed.") ;
		}catch(Exception e){
		}

		session.close() ;
	}

}


text:
module Hackerrank::Thor::Crawlers
  class HackerrankCrawler
    HACKERRANK_URL = "https://www.hackerrank.com".freeze
    HACKERRANK_REST_URL = "#{HACKERRANK_URL}/rest/".freeze

    def challenge_get(path)
      get_json(path)
    end

    def url_html(path)
      html_path = path.gsub(/contests\/master\//, "")
      parse_uri(html_path).to_s
    end

    def url_json(path)
      parse_uri(path, :format => :json).to_s
    end

    private

    def get_json(path)
      parse_uri(path, :format => :json).read
    end

    def parse_uri(path, options = {})
      base_path = options[:format] == :json ? HACKERRANK_REST_URL : HACKERRANK_URL
      request_url = File.join(base_path, path)
      request_url.concat(".json") if options[:format] == :json
      URI.parse(request_url)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
#ifndef CONVEX_PLANE_COLLISION_ALGORITHM_H
#define CONVEX_PLANE_COLLISION_ALGORITHM_H

#include "btCollisionAlgorithm.h"
#include "btBroadphaseProxy.h"
#include "btCollisionCreateFunc.h"
class btPersistentManifold;
#include "btCollisionDispatcher.h"

#include "btVector3.h"

/// btSphereBoxCollisionAlgorithm  provides sphere-box collision detection.
/// Other features are frame-coherency (persistent data) and collision response.
class btConvexPlaneCollisionAlgorithm : public btCollisionAlgorithm
{
	bool		m_ownManifold;
	btPersistentManifold*	m_manifoldPtr;
	bool		m_isSwapped;
	int			m_numPerturbationIterations;
	int			m_minimumPointsPerturbationThreshold;

public:

	btConvexPlaneCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* col0,btCollisionObject* col1, bool isSwapped, int numPerturbationIterations,int minimumPointsPerturbationThreshold);

	virtual ~btConvexPlaneCollisionAlgorithm();

	virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	void collideSingleContact (const btQuaternion& perturbeRot, btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
		if (m_manifoldPtr && m_ownManifold)
		{
			manifoldArray.push_back(m_manifoldPtr);
		}
	}

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		int	m_numPerturbationIterations;
		int m_minimumPointsPerturbationThreshold;

		CreateFunc()
			: m_numPerturbationIterations(1),
			m_minimumPointsPerturbationThreshold(1)
		{
		}

		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvexPlaneCollisionAlgorithm));
			if (!m_swapped)
			{
				return new(mem) btConvexPlaneCollisionAlgorithm(0,ci,body0,body1,false,m_numPerturbationIterations,m_minimumPointsPerturbationThreshold);
			} else
			{
				return new(mem) btConvexPlaneCollisionAlgorithm(0,ci,body0,body1,true,m_numPerturbationIterations,m_minimumPointsPerturbationThreshold);
			}
		}
	};

};

#endif //CONVEX_PLANE_COLLISION_ALGORITHM_H


text:
require 'simple_test'
require 'constants'

describe SimpleTest::Compare, "#==" do
  subject { described_class.new(A_TEST) }

  before do
    Object.class_variable_set :@@tests, []
    subject == A_TEST
  end

  it "adds test to objects tests" do
    expect(Object.tests).to eq([subject])
  end

  its(:method) { should == :== }
end

describe SimpleTest::Compare, "#!=" do
  subject { described_class.new(A_TEST) }

  before do
    Object.class_variable_set :@@tests, []
    subject != A_TEST
  end

  it "adds test to objects tests" do
    expect(Object.tests).to eq([subject])
  end

  its(:method) { should == :!= }
end

describe SimpleTest::Compare, "#run" do
  subject { described_class.new(A_TEST) }

  before { Object.class_variable_set :@@tests, [] }

  context "when expectations match" do
    context "when are supposed to match" do
      before { subject == A_TEST }

      it { expect { subject.run }.not_to raise_error }
    end

    context "when are supposed to be different" do
      before { subject != A_TEST }

      it { expect { subject.run }.to raise_error(SimpleTest::FailingTestError) }
    end
  end

  context "when expectations does not match" do
    context "when are supposed to be different" do
      before { subject != ANOTHER_TEST }

      it { expect { subject.run }.not_to raise_error }
    end

    context "when are supposed to match" do
      before { subject == ANOTHER_TEST }

      it { expect { subject.run }.to raise_error(SimpleTest::FailingTestError) }
    end
  end
end


text:
'use strict';

let fs    = require('fs');
let path  = require('path');
let Koa   = require('koa');
let log   = Bento.Log;
const app = new Koa();

const cors = require('@koa/cors');
app.use(cors());

Bento._app = function *() {
  yield Bento._bootstrap();
  yield registerMiddleware();
  yield startServer();
};

function *registerMiddleware() {
  log.title('MIDDLEWARE');
  Bento.api('middleware').forEach((target) => {
    let targetPath = path.join(Bento.ROOT_PATH, 'middleware', target + '.js');
    if (fs.existsSync(targetPath)) {
      log.silent('info')(`Loading [${ target }]`);
      require(targetPath)(app);
    }
  });
}

function *startServer() {
  log.title('STARTING SERVERS');
  log.silent('info')(`listening on server port: ${ Bento.config.api.port }`);

  yield require('./bootstrap/modules');

  app.listen(Bento.config.api.port, "0.0.0.0");
}


text:
import { connect } from 'react-redux';

import {
  setYear,
  incrementYear,
  decrementYear,
  toggleDrawer,
  closeDrawer,
  setDrawer,
  clubSelectMenuOpen,
  clubSelectMenuClose,
} from '../actions';
import App from '../components/App.jsx';
import { setUrl } from '../util';
import {
  getSet,
  getGender,
  getSelectedCrews,
  getResults,
  getClubs,
  getYear,
} from '../selectors';

const mapStateToProps = (state, ownProps) => {
  const set = getSet(state, ownProps);
  const gender = getGender(state, ownProps);
  const selectedCrews = getSelectedCrews(state, ownProps);
  const results = getResults(state, ownProps);
  const year = getYear(state, ownProps);
  const clubs = getClubs(state, ownProps);

  if (
    ownProps.params.eventId === undefined ||
    ownProps.params.genderId === undefined
  ) {
    setTimeout(() => setUrl(set, gender, selectedCrews));
  }

  return {
    set,
    gender,
    selectedCrews,
    results,
    year,
    clubs,
    width: state.ui.width,
    drawerOpen: state.ui.drawerOpen,
    clubSelectMenuOpen: state.ui.clubSelectMenuOpen,
    clubSelectMenuAnchorElement: state.ui.clubSelectMenuAnchorElement,
  };
};

const mapDispatchToProps = {
  onSetYear: setYear,
  onIncrementYearClick: incrementYear,
  onDecrementYearClick: decrementYear,
  onDrawerToggleClick: toggleDrawer,
  onDrawerCloseClick: closeDrawer,
  onSetDrawerClick: setDrawer,
  onClubSelectOpenClick: clubSelectMenuOpen,
  onClubSelectRequestClose: clubSelectMenuClose,
};

const AppContainer = connect(mapStateToProps, mapDispatchToProps)(App);

export default AppContainer;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"
><TITLE
>Qtc.Gui.QWindowStateChangeEvent</TITLE
><LINK HREF="haddock.css" REL="stylesheet" TYPE="text/css"
>

Qtc.Gui.QWindowStateChangeEvent

class QqWindowStateChangeEvent x1

class QqWindowStateChangeEvent_nf x1

isOverride

oldState

qWindowStateChangeEvent_delete


text:
<?php

namespace Requests;

if (defined("\Requests\Version") === false) {
    require_once(realpath(__DIR__ . "/Api.php"));
}

class Session
{
    private $parsedUrl;
    private $method;
    private $namedParams;
    private $preparedParams;
    private $availableRequesters;

    private $requester;
    public $headers;

    /**
     * Sets up default settings
     *
     * @api
     */
    public function __construct()
    {
        $this->namedParams = [
            "params"=>[],
            "data"=>[],
            "headers"=>[],
            "cookies"=>[],
            "auth"=>[],
            "timeout"=>30,
            "allowRedirects"=>false,
            "proxies"=>[],
            "verify"=>true,
            "cert"=>[]];

        $this->availableRequesters = ["Requests\Requesters\Curl"];
    }

    /**
     * @param $name
     * @return null|String
     */
    public function __get($name)
    {
        $name = strtolower($name);
        if (array_key_exists($name, $this->headers)) {
            return $this->headers[$name];
        } else {
            return null;
        }
    }

    /**
     * Run the request
     *
     * @api
     *
     * @param $method Request method defined in constants
     * @param $url String URL we are requesting
     * @param $namedParams Array w/ keys as string for the request
     *
     * @return \Requests\Response
     *
     */
    public function request($method, $url, $namedParams)
    {
        $this->method = $method;
        $this->namedParams = array_merge($this->namedParams, $namedParams);
        $this->parseUrl($url);
        $this->prepareParams();
        return $this->send();
    }

    private function parseUrl($url)
    {
        $parsedUrl = parse_url($url);
        if (!isset($parsedUrl["scheme"])) {
            throw new \Exception("URL is missing the scheme.");
        }
        if (!isset($parsedUrl["host"])) {
            throw new \Exception("URL is missing the host.");
        }

        $this->parsedUrl = $parsedUrl;
    }

    private function prepareParams()
    {
        // Build the URL
        $this->preparedParams["url"] = $this->parsedUrl["scheme"] . "://" . $this->parsedUrl["host"] . ":" . $this->parsedUrl["port"];

        if ($this->parsedUrl["path"]) {
            $this->preparedParams["url"] .= $this->parsedUrl["path"];
        }

        if ($this->parsedUrl["query"]) {
            parse_str($this->parsedUrl["query"], $params);
            $this->namedParams["params"] = array_merge($params, $this->namedParams["params"]);
        }
        if (count($this->namedParams["params"])) {
            $this->preparedParams["url"] .= "?" . http_build_query($this->namedParams['params']);
        }

        if ($this->parsedUrl["fragment"]) {
            $this->preparedParams["url"] .= "#{$this->parsedUrl["fragment"]}";
        }

        // Build the auth params
        if ($this->namedParams["auth"]) {
            $this->preparedParams["auth"] = $this->namedParams["auth"];
        } elseif ($this->parsedUrl["user"] && $this->parsedUrl["pass"]) {
            $this->preparedParams["auth"] = ["user" => $this->parsedUrl["user"], "pass" => $this->parsedUrl["pass"]];
        } else {
            $this->preparedParams["auth"] = [];
        }

        // Build the proxy
        if (array_key_exists($this->parsedUrl["scheme"], $this->namedParams["proxies"])) {
            $this->preparedParams["proxy"] = $this->namedParams["proxies"][$this->parsedUrl["scheme"]];
        }

        // Verify SSL
        // TODO: Need to handle a string path (CA_BUNDLE?)
        $this->preparedParams["verify"] = (bool)$this->namedParams["verify"];

        // Build everything else
        $this->preparedParams["data"] = $this->namedParams["data"];
        $this->preparedParams["headers"] = $this->namedParams["headers"];
        $this->preparedParams["cookies"] = $this->namedParams["cookies"];
        $this->preparedParams["timeout"] = $this->namedParams["timeout"];
        $this->preparedParams["allowRedirects"] = $this->namedParams["allowRedirects"];
        $this->preparedParams["cert"] = $this->namedParams["cert"];
    }

    private function send()
    {
        $this->setRequester();
        $this->requester->setMethod($this->method);
        $this->requester->setParams($this->preparedParams);
        $response = $this->requester->request();
        $this->parseHeaders(explode("\r\n", $this->requester->getRequestHeaders()));
        return new Response($response, $this);
    }

    private function setRequester()
    {
        foreach ($this->availableRequesters AS $requester) {
            if ($requester::isAvailable($this->method, $this->parsedUrl['scheme'])) {
                $this->requester = new $requester();
            }
        }

        if (isset($this->requester) === false) {
            throw new \Exception("No requester is available for {$this->method} and {$this->parsedUrl['scheme']}");
        }
    }

    private function parseHeaders($headers)
    {
        $requestHeaders = [];
        foreach ($headers AS $header) {
            if (strpos($header, ":") === false) {
                $requestHeaders["method"] = trim($header);
            } else {
                $parts = explode(":", $header);
                $requestHeaders[trim(strtolower($parts[0]))] = trim($parts[1]);
            }
        }

        $this->headers = new \Requests\Headers($requestHeaders);
    }
}


text:
package ar.com.javacuriosities.concurrency.fork_join_pool;

import java.util.concurrent.RecursiveAction;

public class NewUserTask extends RecursiveAction {

    @Override
    protected void compute() {
        System.out.println("New User Task - " + Thread.currentThread().getName());
        invokeAll(new CreateUserCredentialsTask(), new CreateUserEmailTask(), new UploadUserImageTask());
    }

    private static final class CreateUserCredentialsTask extends RecursiveAction {

        @Override
        protected void compute() {
            try {
                Thread.sleep(1000);
                System.out.println("Create User Credentials Task - " + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                // Log and Handle exception
                e.printStackTrace();
            }
        }
    }

    private static final class CreateUserEmailTask extends RecursiveAction {

        @Override
        protected void compute() {
            try {
                Thread.sleep(1000);
                System.out.println("Create User Email Task - " + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                // Log and Handle exception
                e.printStackTrace();
            }
        }
    }

    private static final class UploadUserImageTask extends RecursiveAction {

        @Override
        protected void compute() {
            try {
                Thread.sleep(1000);
                System.out.println("Upload User Image Task - " + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                // Log and Handle exception
                e.printStackTrace();
            }
        }
    }
}


text:
<?php

/**
 * Valida el largo del texto del campo. Si el campo no existe no devuelve errores.
 *
 */
class EqualToFieldValidator extends Validador {

	private $fieldName;
	private $otherField;

	public function __construct($fieldName, $otherField){
		$this->fieldName = $fieldName;
		$this->otherField = $otherField;
	}

	protected function validar(array $campos){
		$errors = array();
		if(!array_key_exists($this->fieldName, $campos) || !$campos[$this->fieldName])
			return $errors;

		if(!array_key_exists($this->otherField, $campos) || !$campos[$this->otherField])
			return $errors;

		if($campos[$this->fieldName] != $campos[$this->otherField])
			array_push($errors, new ErrorValidacion($this->fieldName, "Este campo debe ser igual a $this->otherField"));

		return $errors;
	}
}

class EqualToFieldValidatorFactory extends ValidatorFactory {

	public function getValidator($field, $attribs){
		return new EqualToFieldValidator($field, $attribs['constraints'][EqualToFieldValidatorFactory::getName()]['field']);
	}

	public static function getName() {
		return 'EqualToField';
	}
}


text:
package io.github.metteo.ws.jaxws;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "echo_2_0", namespace = "http://metteo.github.io/ws/user")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "echo_2_0", namespace = "http://metteo.github.io/ws/user")
public class Echo_2_0 {

    @XmlElement(name = "request", namespace = "")
    private io.github.metteo.ws.Request_2_0 request;

    /**
     *
     * @return
     *     returns Request_2_0
     */
    public io.github.metteo.ws.Request_2_0 getRequest() {
        return this.request;
    }

    /**
     *
     * @param request
     *     the value for the request property
     */
    public void setRequest(io.github.metteo.ws.Request_2_0 request) {
        this.request = request;
    }

}


text:
'use strict';

var assert = require('chai').assert;
var landingparty = require('../../../lib/landingparty');
var pluck = require('lodash.pluck');
var skipInNode = require('../../../../lib/mocha-helpers').skipInNode;
var fh2 = require('../../../lib/fixtures-v2');

describe('Services', function() {
  describe('Conversation', function() {
    skipInNode(describe)('Security', function() {
      this.timeout(60000);
      var party = {
        spock: true,
        mccoy: true,
        checkov: false
      };

      before(function beamDown() {
        return landingparty.beamDown(party);
      });

      var conversation;
      before(function createConveration() {
        return party.spock.spark.conversation.create({
          displayName: 'Test Conversation',
          participants: pluck(party, 'id')
        })
          .then(function(c) {
            conversation = c;
          });
      });

      var safeInboundHtmlString;
      var safeOutboundHtmlString;
      var unsafeHtmlString;
      var plaintextString;
      beforeEach(function() {
        unsafeHtmlString = 'Hi <script></script><spark-mention data-object-type="person" data-object-id="' + party.mccoy.spark.device.userId + '">McCoy</spark-mention>';
        safeInboundHtmlString = 'Hi <spark-mention data-object-type="person" data-object-id="' + party.mccoy.spark.device.userId + '">McCoy</spark-mention>';
        safeOutboundHtmlString = 'Hi <script></script><spark-mention data-object-type="person" data-object-id="' + party.mccoy.spark.device.userId + '">McCoy</spark-mention>';
        plaintextString = 'Hi McCoy';
      });

      describe('#post()', function() {
        it('posts only safe html', function() {
          return party.spock.spark.conversation.post(conversation, {
            displayName: plaintextString,
            content: unsafeHtmlString,
            mentions: {
              items: [{
                id: party.mccoy.id,
                objectType: 'person'
              }]
            }
          })
            .then(function(activity) {
              assert.equal(activity.object.displayName, plaintextString);
              assert.equal(activity.object.content, safeOutboundHtmlString);
            });
        });
      });

      describe('#share()', function() {

        var fixtures = {
          sampleTextOne: 'sample-text-one.txt'
        };

        before(function() {
          return fh2.fetchFixtures(fixtures);
        });

        it('posts only safe html', function() {
          return party.spock.spark.conversation.share(conversation, {
            displayName: plaintextString,
            content: unsafeHtmlString,
            files: [fixtures.sampleTextOne]
          })
            .then(function(activity) {
              console.log(activity);
              assert.equal(activity.object.displayName, plaintextString);
              assert.equal(activity.object.content, safeOutboundHtmlString);
            });
        });
      });

      describe('#processActivityEvent()', function() {
        it('exposes only safe html', function() {
          // Set the timeout high enough to detect a mercury disconnect and
          // reconnect
          this.timeout(40000);
          var waitForPost = new Promise(function(resolve) {
            party.spock.spark.mercury.on('conversation.activity', function(message) {
              if (message.activity.verb === 'post') {
                resolve(message.activity);
              }
            });
          });

          return party.spock.spark.request({
            method: 'POST',
            api: 'conversation',
            resource: 'activities',
            body: {
              verb: 'post',
              actor: {
                id: party.spock.spark.device.userId,
                objectType: 'person'
              },
              object: {
                objectType: 'comment',
                displayName: plaintextString,
                content: unsafeHtmlString,
                mentions: {
                  items: [{
                    id: party.mccoy.id,
                    objectType: 'person'
                  }]
                }
              },
              target: {
                objectType: 'conversation',
                id: conversation.id,
                url: conversation.url
              }
            }
          })
            .then(function() {
              return Promise.resolve(waitForPost);
            })
            .then(function(activity) {
              assert.equal(activity.object.displayName, plaintextString);
              assert.equal(activity.object.content, safeInboundHtmlString);
            });
        });
      });
    });
  });
});


text:
namespace Ui { class LassoToolsWidget;}

class LassoToolsWidget : public QWidget, public ApplicationContextProvider
{
    Q_OBJECT

public:
    LassoToolsWidget(QWidget* _parent = nullptr);
    ~LassoToolsWidget();

    void setContext(ApplicationContext *_context) override;

private slots:
    void on_actionPolygonalLassoClicked_toggled();

private:
    Ui::LassoToolsWidget *mUi;
};


text:
package com.laithlab.rhythm.db;

import io.realm.RealmObject;
import io.realm.annotations.RealmClass;

@RealmClass
public class Song extends RealmObject {
    private String id;
    private String songTitle;
    private long songDuration;
    private String songLocation;
    private String albumId;
    private int noOfPlayed;
    private long lastPlayed;

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public void setSongTitle(String songTitle) {
        this.songTitle = songTitle;
    }

    public String getSongTitle() {
        return songTitle;
    }

    public void setSongDuration(long songDuration) {
        this.songDuration = songDuration;
    }

    public long getSongDuration() {
        return songDuration;
    }

    public void setSongLocation(String songLocation) {
        this.songLocation = songLocation;
    }

    public String getSongLocation() {
        return songLocation;
    }

    public void setAlbumId(String albumId) {
        this.albumId = albumId;
    }

    public String getAlbumId() {
        return albumId;
    }

    public void setNoOfPlayed(int noOfPlayed) {
        this.noOfPlayed = noOfPlayed;
    }

    public int getNoOfPlayed() {
        return noOfPlayed;
    }

    public void setLastPlayed(long lastPlayed) {
        this.lastPlayed = lastPlayed;
    }

    public long getLastPlayed() {
        return lastPlayed;
    }
}


text:
// +build !linux,!windows

package dockertools

import (
	"k8s.io/kubernetes/pkg/api/v1"

	dockertypes "github.com/docker/engine-api/types"
)

func getContainerIP(container *dockertypes.ContainerJSON) string {
	return ""
}

func getNetworkingMode() string {
	return ""
}

func containerProvidesPodIP(name *KubeletContainerName) bool {
	return false
}

// Returns nil as both Seccomp and AppArmor security options are not valid on Windows
func (dm *DockerManager) getSecurityOpts(pod *v1.Pod, ctrName string) ([]dockerOpt, error) {
	return nil, nil
}


text:
using System.Collections.Generic;
using System.Linq;

namespace Umbraco.Cms.Core.Models.Email
{
    /// <summary>
    /// Represents an email when sent with notifications.
    /// </summary>
    public class NotificationEmailModel
    {
        public NotificationEmailAddress? From { get; }

        public IEnumerable<NotificationEmailAddress?>? To { get; }

        public IEnumerable<NotificationEmailAddress>? Cc { get; }

        public IEnumerable<NotificationEmailAddress>? Bcc { get; }

        public IEnumerable<NotificationEmailAddress>? ReplyTo { get; }

        public string? Subject { get; }

        public string? Body { get; }

        public bool IsBodyHtml { get; }

        public IList<EmailMessageAttachment>? Attachments { get; }

        public bool HasAttachments => Attachments != null && Attachments.Count > 0;

        public NotificationEmailModel(
            NotificationEmailAddress? from,
            IEnumerable<NotificationEmailAddress?>? to,
            IEnumerable<NotificationEmailAddress>? cc,
            IEnumerable<NotificationEmailAddress>? bcc,
            IEnumerable<NotificationEmailAddress>? replyTo,
            string? subject,
            string? body,
            IEnumerable<EmailMessageAttachment>? attachments,
            bool isBodyHtml)
        {
            From = from;
            To = to;
            Cc = cc;
            Bcc = bcc;
            ReplyTo = replyTo;
            Subject = subject;
            Body = body;
            IsBodyHtml = isBodyHtml;
            Attachments = attachments?.ToList();
        }

    }
}


text:
.genesis-metaboxes .bottom-buttons .button-primary {
	margin-left: 10px;
}

.genesis-layout-selector label.box {
	float: right;
}

.genesis-widget-column {
	float: right;
}


text:
'use strict';

angular.module('mean.subscribe').config(['$stateProvider',
    function ($stateProvider) {
        $stateProvider
            .state('subscribe mailsend page', {
                url: '/subscribe/mailsend',
                templateUrl: 'subscribe/views/mailsend.html'
            })
            .state('subscribe page', {
                url: '/subscribe',
                templateUrl: 'subscribe/views/subscrib.html',
                ifState: true

            })
            .state('unsubscribe page', {
                url: '/subscribe/unsubscribe',
                templateUrl: 'subscribe/views/unsubscribe.html',
            })
            .state('subscribe send mail page', {
                url: '/subscribe/sendmail',
                templateUrl: 'subscribe/views/sendmail.html',
                sendMail: true //only admin user can go in this state
            });
    }
]);


text:
<?php

  namespace osCommerce\OM\Core\Site\Admin\Application\CreditCards\Model;

  use osCommerce\OM\Core\OSCOM;
  use osCommerce\OM\Core\Cache;

  class delete {
    public static function execute($id) {
      $data = array('id' => $id);

      if ( OSCOM::callDB('Admin\CreditCards\Delete', $data) ) {
        Cache::clear('credit-cards');

        return true;
      }

      return false;
    }
  }
?>


text:
package org.uberfire.ext.security.management.client.widgets.management.events;

import org.uberfire.workbench.events.UberFireEvent;

public class SaveGroupEvent implements UberFireEvent {

    private final String name;

    public SaveGroupEvent(final String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "SaveGroupEvent [name=" + name + "]";
    }

}


text:
using System;

// Class mapping for the integrity verdict Json payload,
// To be serialized using the UnityEngine.JsonUtility class
// See the Play Integrity documentation for details about
// the integrity verdict fields and values
[Serializable]
public class RequestDetails
{
    public string requestPackageName;
    public string timestampMillis;
    public string nonce;
}

[Serializable]
public class AppIntegrity
{
    public string appRecognitionVerdict;
    public string packageName;
    public string[] certificateSha256Digest;
    public string versionCode;
}

[Serializable]
public class DeviceIntegrity
{
    public string[] deviceRecognitionVerdict;
}

[Serializable]
public class AccountDetails
{
    public string appLicensingVerdict;
}

[Serializable]
public class IntegrityVerdict
{
    public RequestDetails requestDetails;
    public AppIntegrity appIntegrity;
    public DeviceIntegrity deviceIntegrity;
    public AccountDetails accountDetails;
}


text:
<?php

namespace Sift\Exception;

/**
 * Corresponds to an HTTP 50x; generated if the Sift Science API is having
 * problems.
 */
class ServerErrorException extends HttpException
{
    /**
     * Wrap a Guzzle\Http\Exception\ServerErrorResponseException
     */
    public static function fromServerErrorResponseException($ex)
    {
        return new self($ex->getMessage(), 0, $ex);
    }
}


text:
<?php
/**
 * [Models 原始模型]
 * @author [haigle] [991382548@qq.com]
 */

namespace App\Haigle\Models;

use Illuminate\Database\Eloquent\Model;

class Sys extends Model {

    protected $table = 'sys';

}


text:
from bodies.humanoid import HumanoidBody
from data.python_templates import material
import bodyparts

class DraconianBody(HumanoidBody):
    uid = "draconian"
    name = "Draconian"

    template_outer_material = material.DragonScale
    template_left_hand = bodyparts.DraconianHand
    template_right_hand = bodyparts.DraconianHand
    template_left_foot = bodyparts.DraconianFoot
    template_right_foot = bodyparts.DraconianFoot
    template_teeth = bodyparts.DraconianTeeth

    template_muzzle = bodyparts.DraconianMuzzle
    template_tail = bodyparts.DraconianTail

    def __init__(self):
        super().__init__()
        self.muzzle = self.template_muzzle(self.name, "", attached_to=self.head)
        self.tail = self.template_tail(self.name, "", attached_to=self.torso)
        self.bodyparts += (
            self.muzzle,
            self.tail,
        )


text:
pyjac.libgen package
====================

Submodules
----------

.. toctree::

   pyjac.libgen.libgen

Module contents
---------------

.. automodule:: pyjac.libgen
    :members:
    :undoc-members:
    :show-inheritance:


text:
title: Go to Market
layout: default
---

                        Concur App Center: Go to Market

                        Let us help you prepare for your

                        App Center launch.

Overview

Now that you're an App Center partner it's time to prepare for your launch! This page will provide you with the resources needed for your initial launch as well as ongoing reference.

Please view our Go to Market presentation to learn about next steps.

                          Apps for My Business

                          Apps for Me

*If you're not yet a Concur App Center partner please contact our Business Development team to discuss an agreement

App Certification

As you scope and fine tune your app, you should also be preparing for your app certification and scheduling a demo with the Concur partner enablement team to showcase your app. Below are key resource documents to help you through this process.

App Center Application Submission Form: Review to prepare for the technical and UX components required during your app demo. After fully developing and testing your app you can submit for certification and demo scheduling.

                         View

Apps for Me Release Schedule: Review to understand additional requirements within the Apps for Me category. Please plan accordingly based on key target dates and deadlines.

                         View

Marketing Your App

As you prepare to launch your app you'll have various marketing assets and activities to prepare. Below are key resource documents to guide you through your marketing planning.

App Center Partner Listing Form: Review to prepare your app for listing in the Concur App Center. Your listing will serve as the location where companies and users will learn more about your app, leading to inquiries or end user connections.

                         Download

Concur Brand Guidelines: Become familiar with our Concur brand guidelines prior to developing your various marketing assets, which can include a partner landing page, brochures or videos.

                         View

App Center Badge Use Guidelines: Learn more about the App Center Badge available to you. Review the guidelines to incorporate it into your marketing assets.

                         View

App Center PR Toolkit: Use our press release template to announce your launch into the Concur App Center. Also included are guidelines for social media activities via Twitter, LinkedIn and more.

                         View

Deploying Your App for Customers

Apps within our Apps for My Business category will require planning around prospecting, inquiry management, deal submissions and app deployments. Below are key resource documents to assist you in these areas.

App Center FAQ's: Access to view common questions and answers to assist in Concur App Center discussions with prospects/clients.

                         View

App Center Lead Submission Process: Review to become familiarized with our lead submission process as well as how to accept/reject leads.

                         View

Deal & Deployment Notification Form: Understand the required notification form for all new deals to ensure proper tracking and deployment.

                         View

App Center Letter of Authorization: Familiarize yourself with the required document for all client deals and deployments.

                         View

Enabling Apps – Client Facing Guide – Basic Configurations: Share this guide with clients for quick app deployments.

                         View

Marketing Support

Contact us or join us for our weekly office hours.

Office Hours:

Tuesdays from 8:30-9:00 AM and Thursdays from 2:30-3:00 PM, both PST.

Phone/Conference Code:

1-866-668-0721/396-255-2607

Contact Form:

For App Center marketing support please complete and submit the form below.

                         Contact Marketing Support


text:
package edu.hbut.livestock.http.coding;

import java.sql.Date;

import edu.hbut.livestock.entity.Immunization;
import edu.hbut.livestock.entity.ImmunizationId;

/**
 * Ïû¶¾¼Ç¼ ±àÂë
 *
 * @author xiaowu
 *
 */
public class ImmunizationMarshall extends
		BaseGETMarshall<Immunization, ImmunizationId> {

	@Override
	public String marshall(Immunization t) {
		String[] params = new String[] {
				Immunization.IMMUNIZATIONTIME,FMT.format(t.getId().getImmunizationTime()),

				Immunization.TOTALCOUNT,t.getTotalCount()+"",

				Immunization.VACCINE, t.getVaccine(),

				Immunization.VACCINEFACTORY, t.getVaccineFactory(),

				Immunization.BATCHNUMBER, t.getBatchNumber()+"",

				Immunization.DOSAGE, t.getDosage()+"",

				Immunization.IMMUNIZATIONMETHOD, t.getImmunizationMethod()

		};
		StringBuilder sb = new StringBuilder(toUri(params));
		appendHeaderDate(t.getHeaderDate(), sb);
		return sb.toString();
	}

	@Override
	public String marshallId(ImmunizationId id) {
		String[] params = new String[] {
				Immunization.USERID,id.getUserid(),
				Immunization.IMMUNIZATIONTIME,FMT.format(id.getImmunizationTime()),
				Immunization.HOUSEID,id.getHouseid()+""};
		return toUri(params);
	}

	@Override
	public String marshall(ImmunizationId id, Date headerDate, int start,
			int count) {
		String[] params = new String[] {
				Immunization.IMMUNIZATIONTIME,FMT.format(id.getImmunizationTime()),
				Immunization.USERID, id.getUserid(),
				Immunization.HOUSEID,id.getHouseid()+"",
				START_LINE,Integer.toString(start),
				MAX_COUNT, Integer.toString(count) };
		StringBuilder sb = new StringBuilder(toUri(params));
		appendHeaderDate(headerDate, sb);
		return sb.toString();

	}

	@Override
	public String marshall(ImmunizationId id, Date headerDate) {
		String[] params = new String[] {
				Immunization.IMMUNIZATIONTIME,
				FMT.format(id.getImmunizationTime()) };
		StringBuilder sb = new StringBuilder(toUri(params));
		appendHeaderDate(headerDate, sb);
		return sb.toString();
	}

	@Override
	public String marshall(Immunization t, int start, int count) {
		String[] params = new String[] {
				Immunization.IMMUNIZATIONTIME,FMT.format(t.getId().getImmunizationTime()),

				Immunization.TOTALCOUNT,t.getTotalCount()+"",

				Immunization.VACCINE, t.getVaccine(),

				Immunization.VACCINEFACTORY, t.getVaccineFactory(),

				Immunization.BATCHNUMBER, t.getBatchNumber()+"",

				Immunization.DOSAGE, t.getDosage()+"",

				Immunization.IMMUNIZATIONMETHOD, t.getImmunizationMethod(),

				START_LINE, Integer.toString(start), MAX_COUNT,
				Integer.toString(count)

		};
		StringBuilder sb = new StringBuilder(toUri(params));
		appendHeaderDate(t.getHeaderDate(), sb);
		return sb.toString();
	}

}


text:
cask 'thingsmacsandboxhelper' do
  version '3.21'
  sha256 'adcc57f686125fa7670fa9d20193f1704c5eb0eb2c70863257007c785940374c'

  # culturedcode.cachefly.net/ was verified as official when first introduced to the cask
  url "https://culturedcode.cachefly.net/things/thingssandboxhelper/#{version}/ThingsHelper.zip"
  appcast 'https://culturedcode.com/things/mac/help/things-sandboxing-helper-things3/'
  name 'ThingsMacSandboxHelper'
  homepage "https://culturedcode.com/things/mac/help/things-sandboxing-helper-things#{version.major}/"

  app 'ThingsMacSandboxHelper.app'
end


text:
package org.apache.spark.sql.execution.datasources

import org.apache.spark.sql.{Dataset, Row, SaveMode, SparkSession}
import org.apache.spark.sql.catalyst.plans.QueryPlan
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.execution.command.RunnableCommand

/**
 * Saves the results of `query` in to a data source.
 *
 * Note that this command is different from [[InsertIntoDataSourceCommand]]. This command will call
 * `CreatableRelationProvider.createRelation` to write out the data, while
 * [[InsertIntoDataSourceCommand]] calls `InsertableRelation.insert`. Ideally these 2 data source
 * interfaces should do the same thing, but as we've already published these 2 interfaces and the
 * implementations may have different logic, we have to keep these 2 different commands.
 */
case class SaveIntoDataSourceCommand(
    query: LogicalPlan,
    provider: String,
    partitionColumns: Seq[String],
    options: Map[String, String],
    mode: SaveMode) extends RunnableCommand {

  override protected def innerChildren: Seq[QueryPlan[_]] = Seq(query)

  override def run(sparkSession: SparkSession): Seq[Row] = {
    DataSource(
      sparkSession,
      className = provider,
      partitionColumns = partitionColumns,
      options = options).write(mode, Dataset.ofRows(sparkSession, query))

    Seq.empty[Row]
  }
}


text:
package org.springside.modules.security.springsecurity.cxf;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 清除SecurityContext的Interceptor.
 *
 * @author calvin
 */
public class SpringSecurityOutInterceptor extends AbstractPhaseInterceptor<Message> {

	public SpringSecurityOutInterceptor() {
		super(Phase.PRE_PROTOCOL);
	}

	public void handleMessage(Message message) throws Fault {
		SecurityContextHolder.clearContext();
	}
}


text:
/* globals confirm */
(function() {
  'use strict';

  function SnakeControlCtrl($scope, $rootScope, CONFIG) {

    this.setTempDirection = function(direction) {
      $rootScope.tempDirection = direction;
    };

    this.setUpDirection = function() {
      this.setTempDirection(CONFIG.DIRECTIONS.UP);
    };

    this.setDownDirection = function() {
      this.setTempDirection(CONFIG.DIRECTIONS.DOWN);
    };

    this.setLeftDirection = function() {
      this.setTempDirection(CONFIG.DIRECTIONS.LEFT);
    };

    this.setRightDirection = function() {
      this.setTempDirection(CONFIG.DIRECTIONS.RIGHT);
    };

  }

  angular.module('snakeGameApp')
    .controller('SnakeControlCtrl', SnakeControlCtrl);

  SnakeControlCtrl.$inject = ['$scope', '$rootScope', 'CONFIG'];

}());


text:
<?php

declare(strict_types=1);

namespace Phpml\Metric;

use Phpml\Exception\InvalidArgumentException;

class ClassificationReport
{
    public const MICRO_AVERAGE = 1;

    public const MACRO_AVERAGE = 2;

    public const WEIGHTED_AVERAGE = 3;

    /**
     * @var array
     */
    private $truePositive = [];

    /**
     * @var array
     */
    private $falsePositive = [];

    /**
     * @var array
     */
    private $falseNegative = [];

    /**
     * @var array
     */
    private $support = [];

    /**
     * @var array
     */
    private $precision = [];

    /**
     * @var array
     */
    private $recall = [];

    /**
     * @var array
     */
    private $f1score = [];

    /**
     * @var array
     */
    private $average = [];

    public function __construct(array $actualLabels, array $predictedLabels, int $average = self::MACRO_AVERAGE)
    {
        $averagingMethods = range(self::MICRO_AVERAGE, self::WEIGHTED_AVERAGE);
        if (!in_array($average, $averagingMethods, true)) {
            throw new InvalidArgumentException('Averaging method must be MICRO_AVERAGE, MACRO_AVERAGE or WEIGHTED_AVERAGE');
        }

        $this->aggregateClassificationResults($actualLabels, $predictedLabels);
        $this->computeMetrics();
        $this->computeAverage($average);
    }

    public function getPrecision(): array
    {
        return $this->precision;
    }

    public function getRecall(): array
    {
        return $this->recall;
    }

    public function getF1score(): array
    {
        return $this->f1score;
    }

    public function getSupport(): array
    {
        return $this->support;
    }

    public function getAverage(): array
    {
        return $this->average;
    }

    private function aggregateClassificationResults(array $actualLabels, array $predictedLabels): void
    {
        $truePositive = $falsePositive = $falseNegative = $support = self::getLabelIndexedArray($actualLabels, $predictedLabels);

        foreach ($actualLabels as $index => $actual) {
            $predicted = $predictedLabels[$index];
            ++$support[$actual];

            if ($actual === $predicted) {
                ++$truePositive[$actual];
            } else {
                ++$falsePositive[$predicted];
                ++$falseNegative[$actual];
            }
        }

        $this->truePositive = $truePositive;
        $this->falsePositive = $falsePositive;
        $this->falseNegative = $falseNegative;
        $this->support = $support;
    }

    private function computeMetrics(): void
    {
        foreach ($this->truePositive as $label => $tp) {
            $this->precision[$label] = $this->computePrecision($tp, $this->falsePositive[$label]);
            $this->recall[$label] = $this->computeRecall($tp, $this->falseNegative[$label]);
            $this->f1score[$label] = $this->computeF1Score((float) $this->precision[$label], (float) $this->recall[$label]);
        }
    }

    private function computeAverage(int $average): void
    {
        switch ($average) {
            case self::MICRO_AVERAGE:
                $this->computeMicroAverage();

                return;
            case self::MACRO_AVERAGE:
                $this->computeMacroAverage();

                return;
            case self::WEIGHTED_AVERAGE:
                $this->computeWeightedAverage();

                return;
        }
    }

    private function computeMicroAverage(): void
    {
        $truePositive = array_sum($this->truePositive);
        $falsePositive = array_sum($this->falsePositive);
        $falseNegative = array_sum($this->falseNegative);

        $precision = $this->computePrecision($truePositive, $falsePositive);
        $recall = $this->computeRecall($truePositive, $falseNegative);
        $f1score = $this->computeF1Score((float) $precision, (float) $recall);

        $this->average = compact('precision', 'recall', 'f1score');
    }

    private function computeMacroAverage(): void
    {
        foreach (['precision', 'recall', 'f1score'] as $metric) {
            $values = $this->{$metric};
            if (count($values) == 0) {
                $this->average[$metric] = 0.0;

                continue;
            }

            $this->average[$metric] = array_sum($values) / count($values);
        }
    }

    private function computeWeightedAverage(): void
    {
        foreach (['precision', 'recall', 'f1score'] as $metric) {
            $values = $this->{$metric};
            if (count($values) == 0) {
                $this->average[$metric] = 0.0;

                continue;
            }

            $sum = 0;
            foreach ($values as $i => $value) {
                $sum += $value * $this->support[$i];
            }

            $this->average[$metric] = $sum / array_sum($this->support);
        }
    }

    /**
     * @return float|string
     */
    private function computePrecision(int $truePositive, int $falsePositive)
    {
        $divider = $truePositive + $falsePositive;
        if ($divider == 0) {
            return 0.0;
        }

        return $truePositive / $divider;
    }

    /**
     * @return float|string
     */
    private function computeRecall(int $truePositive, int $falseNegative)
    {
        $divider = $truePositive + $falseNegative;
        if ($divider == 0) {
            return 0.0;
        }

        return $truePositive / $divider;
    }

    private function computeF1Score(float $precision, float $recall): float
    {
        $divider = $precision + $recall;
        if ($divider == 0) {
            return 0.0;
        }

        return 2.0 * (($precision * $recall) / $divider);
    }

    private static function getLabelIndexedArray(array $actualLabels, array $predictedLabels): array
    {
        $labels = array_values(array_unique(array_merge($actualLabels, $predictedLabels)));
        sort($labels);
        $labels = array_combine($labels, array_fill(0, count($labels), 0));

        return $labels;
    }
}


text:
/**
 * @private
 *
 * Scroll position implementation
 */
Ext.define('Ext.util.translatable.ScrollPosition', {
    extend: 'Ext.util.translatable.Abstract',

    wrapperWidth: 0,

    wrapperHeight: 0,

    baseCls: 'x-translatable',

    config: {
        useWrapper: true
    },

    getWrapper: function() {
        var wrapper = this.wrapper,
            baseCls = this.baseCls,
            element = this.getElement(),
            nestedStretcher, container;

        if (!wrapper) {
            container = element.getParent();

            if (!container) {
                return null;
            }

            if (this.getUseWrapper()) {
                wrapper = element.wrap({
                    className: baseCls + '-wrapper'
                }, true);
            }
            else {
                wrapper = container.dom;
            }

            wrapper.appendChild(Ext.Element.create({
                className: baseCls + '-stretcher'
            }, true));

            this.nestedStretcher = nestedStretcher = Ext.Element.create({
                className: baseCls + '-nested-stretcher'
            }, true);

            element.appendChild(nestedStretcher);

            element.addCls(baseCls);
            container.addCls(baseCls + '-container');

            this.container = container;
            this.wrapper = wrapper;

            this.refresh();
        }

        return wrapper;
    },

    doTranslate: function(x, y) {
        var wrapper = this.getWrapper();

        if (wrapper) {
            if (typeof x == 'number') {
                wrapper.scrollLeft = this.wrapperWidth - x;
            }

            if (typeof y == 'number') {
                wrapper.scrollTop = this.wrapperHeight - y;
            }
        }

        return this.callParent(arguments);
    },

    refresh: function() {
        var wrapper = this.getWrapper();

        if (wrapper) {
            this.wrapperWidth = wrapper.offsetWidth;
            this.wrapperHeight = wrapper.offsetHeight;

            this.callParent(arguments);
        }
    },

    destroy: function() {
        var element = this.getElement(),
            baseCls = this.baseCls;

        if (this.wrapper) {
            if (this.getUseWrapper()) {
                element.unwrap();
            }

            this.container.removeCls(baseCls + '-container');
            element.removeCls(baseCls);
            element.removeChild(this.nestedStretcher);
        }

        this.callParent(arguments);
    }

});


text:
<?php

/*
 * This file is part of vaibhavpandeyvpz/silex-skeleton package.
 *
 * (c) Vaibhav Pandey <contact@vaibhavpandey.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.md.
 */

/** @noinspection HtmlUnknownTarget */
return [
    'add' => 'Add',
    'add_user' => 'Add User',
    'administrator' => 'Administrator',
    'app' => 'Project Name',
    'author' => 'Your Name',
    'back_to_home' => 'Back to Home',
    'close' => 'Close',
    'confirm_password' => 'Confirm Password',
    'confirm_user_delete' => 'Are you sure to delete selected user?',
    'created_at' => 'Created At',
    'dashboard' => 'Dashboard',
    'delete' => 'Delete',
    'details' => 'Details',
    'edit' => 'Edit',
    'edit_user' => 'Edit User',
    'email' => 'Email',
    'enabled' => 'Enabled',
    'facebook' => 'Facebook',
    'forgot_password' => 'Forgot Password',
    'forgot_password_help' => 'Remember your password? Login here.',
    'google' => 'Google',
    'hi' => 'Hi! %name%',
    'home' => 'Home',
    'id' => 'ID',
    'locked' => 'Locked',
    'login' => 'Login',
    'login_help' => 'Need an account? Register here.',
    'login_social_help' => 'Or you can login quickly using any of the below social services:',
    'logout' => 'Logout',
    'menu' => 'Menu',
    'name' => 'Name',
    'never' => 'Never',
    'new_password' => 'New Password',
    'no' => 'No',
    'password' => 'Password',
    'profile' => 'Profile',
    'refresh' => 'Refresh',
    'register' => 'Register',
    'register_help' => 'Already registered? Login here.',
    'remember_me' => 'Remember me',
    'reset_password' => 'Reset Password',
    'roles' => 'Roles',
    'send_link' => 'Send Link',
    'update' => 'Update',
    'updated_at' => 'Updated At',
    'users' => 'User|Users',
    'yes' => 'Yes',
];


text:
<?php
/**
 *
 * PHP version 5.5
 *
 * @package Cache
 * @author  Sergey V.Kuzin <sergey@kuzin.name>
 * @license MIT
 */

namespace Cache;

use \Couchbase;

class CouchbaseCache extends CacheItemPool
{
    public function __construct()
    {
        parent::__construct(new \Doctrine\Common\Cache\CouchbaseCache());
    }

    /**
     * Sets the Couchbase instance to use.
     *
     * @param Couchbase $couchbase
     *
     * @return void
     */
    public function setCouchbase(Couchbase $couchbase)
    {
        $this->provider->setCouchbase($couchbase);
    }

    /**
     * Gets the Couchbase instance used by the cache.
     *
     * @return Couchbase|null
     */
    public function getCouchbase()
    {
        return $this->provider->getCouchbase();
    }
}


text:
var objectAssign = require('object-assign-deep');
var config = require('./config.unit');

if (process.env.CI) {
  var ci = require('./config.ci');
  config = objectAssign(config, ci);
  config.browsers = ci.browsers;
}

if (process.env.WORKER === 'true') {
  config = require('./config.worker')(config, 'unit');

  // only run worker test on Chrome for CI
  if (process.env.CI) config.browsers = ['bs_chrome_49'];
}

module.exports = function(suite) {
  config.logLevel = suite.LOG_INFO,
  suite.set(config);
};


text:
require 'spec_helper'
require 'base64'

describe 'postfix' do

  describe package('postfix') do
    it { should be_installed }
  end

  describe service('postfix') do
    it { should be_running }
  end

  describe file('/etc/postfix/header_checks') do
    it 'is a file' do
      expect(subject).to be_file
    end
    it 'has filters' do
      expect(subject).to contain('filter_11101').after(/^\/\^To:/)
      expect(subject).to contain('filter_11102').after(/^\/\^To:/)
    end
  end

  credentials0 = Base64.strict_encode64("\0user0\0passwd0")

  describe file('/tmp/11100') do
    it 'is a file' do
      expect(subject).to be_file
    end
    it 'contains credentials user0:passwd0' do
      expect(subject).to contain(credentials0).after(/AUTH PLAIN/)
    end
    it 'is a mail' do
      expect(subject).to contain('<no-filter@example.com>').after(/RCPT TO/)
    end
  end

  credentials1 = Base64.strict_encode64("\0user1\0passwd1")

  describe file('/tmp/11101') do
    it 'is a file' do
      expect(subject).to be_file
    end
    it 'contains credentials user1:passwd1' do
      expect(subject).to contain(credentials1).after(/AUTH PLAIN/)
    end
    it 'is a mail filtered correctly' do
      expect(subject).to contain('<filter_11101@example.com>').after(/RCPT TO/)
    end
  end

  credentials2 = Base64.strict_encode64("\0user2\0passwd2")

  describe file('/tmp/11102') do
    it 'is a file' do
      expect(subject).to be_file
    end
    it 'contains credentials user2:passwd2' do
      expect(subject).to contain(credentials2).after(/AUTH PLAIN/)
    end
    it 'is a mail filtered correctly' do
      expect(subject).to contain('<filter_11102@example.com>').after(/RCPT TO/)
    end
  end

end


text:
title: "Rated blue for bright"
excerpt: "PaperFaces portrait of Wendy Rose drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-wendy-rose-sktchy-lg.jpg
  thumb: paperfaces-wendy-rose-sktchy-150.jpg
tags: [portrait, illustration, Paper by 53, Sktchy]
---

PaperFaces portrait of Wendy Rose, inspiration found via Sktchy.

{% include boilerplate/paperfaces-2.html %}

Work in progress screenshots (Paper by 53).


text:
from opendc.models.model import Model
from opendc.models.object import Object
from opendc.models.tile import Tile

class Rack(Model):
    JSON_TO_PYTHON_DICT = {
        'rack': {
            'id': 'id',
            'name': 'name',
            'capacity': 'capacity',
            'powerCapacityW': 'power_capacity_w',
            'topologyId': 'topology_id'
        }
    }

    PATH = '/v1/tiles/{tileId}/rack'

    TABLE_NAME = 'racks'
    COLUMNS = ['id', 'name', 'capacity', 'power_capacity_w', 'topology_id']
    COLUMNS_PRIMARY_KEY = ['id']

    @classmethod
    def from_tile_id(cls, tile_id):
        """Get a Rack from the ID of the Tile it's on."""

        tile = Tile.from_primary_key((tile_id,))

        if not tile.exists():
            return Rack(id=-1)

        return cls.from_primary_key((tile.object_id,))

    def google_id_has_at_least(self, google_id, authorization_level):
        """Return True if the user has at least the given auth level over this Rack."""

        # Get the Tile

        try:
            tile = Tile.query('object_id', self.id)[0]
        except:
            return False

        # Check the Tile's Authorization

        return tile.google_id_has_at_least(google_id, authorization_level)

    def insert(self):
        """Insert a Rack by first inserting an object."""

        obj = Object(type='RACK')
        obj.insert()

        self.id = obj.id
        self.insert_with_id(is_auto_generated=False)

    def delete(self):
        """Delete a Rack by deleting its associated object."""

        obj = Object.from_primary_key((self.id,))
        obj.delete()


text:
(function() {
  'use strict';
  angular.module('civic.common')
    .directive('evidenceSelectorItem', evidenceSelectorItem);

  // @ngInject
  function evidenceSelectorItem() {
    return {
      restrict: 'E',
      scope: {
        item: '=',
        removeFn: '='
      },
      templateUrl: 'components/directives/evidenceSelectorItem.tpl.html',
      controller: evidenceSelectorItemController
    };
  }

  // @ngInject
  function evidenceSelectorItemController($scope, $state, _, Genes, Variants, ConfigService) {
    var ctrl = $scope.ctrl = {};
    ctrl.item = $scope.item;
    ctrl.removeItem = $scope.removeFn;

    // item data could be provided by two different evidence item endpoints, extracting gene/variant id differs
    var gene_id = _.isUndefined(ctrl.item.gene_id) ? ctrl.item.state_params.gene.id : ctrl.item.gene_id;
    var variant_id = _.isUndefined(ctrl.item.variant_id) ? ctrl.item.state_params.variant.id : ctrl.item.variant_id;

    if($scope.ctrl.item.phenotypes.length > 0) {
      $scope.ctrl.item.phenotypesStr = _.chain($scope.ctrl.item.phenotypes)
        .sortBy('hpo_class')
        .map(function(item) {
          return '' + item.hpo_class + '';
        })
        .value()
        .join(', ');
    } else {
      $scope.ctrl.item.phenotypesStr = '--';
    }

    Genes.get(gene_id).then(function(gene) {
      ctrl.item.gene = gene;
    });

    Variants.get(variant_id).then(function(variant) {
      ctrl.item.variant = variant;
    });

  }
})();


text:
//-----------------------------------------------------------------------------
// file: chuck_table.h
// desc: chuck table
//
// No algorithm should use these functions directly, because
// programming with void* is too error-prone.  Instead,
// each module should make "wrapper" functions that take
// well-typed arguments and call the TAB_ functions.
//
// copyright (c) 1997 Andrew W. Appel.
//
// original author: Andrew Appel (appel@cs.princeton.edu)
// modified: Ge Wang (gewang@cs.princeton.edu)
// date: Autumn 2002
//-----------------------------------------------------------------------------
#ifndef __CHUCK_TABLE_H__
#define __CHUCK_TABLE_H__

typedef struct TAB_table_ * TAB_table;
typedef long (* TAB_eq_func)( void * lhs, void * rhs );
typedef long (* TAB_hash_func)( void * key );

/* Make a new table mapping "keys" to "values". */
TAB_table TAB_empty(void);
TAB_table TAB_empty2(unsigned long size);
TAB_table TAB_empty3( TAB_eq_func eq, TAB_hash_func hash, unsigned int size );
void TAB_delete( TAB_table t );

/* Enter the mapping "key"->"value" into table "t",
 *    shadowing but not destroying any previous binding for "key". */
void TAB_enter(TAB_table t, void *key, void *value);

/* Look up the most recent binding for "key" in table "t" */
void *TAB_look(TAB_table t, void *key);

/* Pop the most recent binding and return its key.
 * This may expose another binding for the same key, if there was one. */
void *TAB_pop(TAB_table t);
void *TAB_topv(TAB_table t);

/* Call "show" on every "key"->"value" pair in the table,
 *  including shadowed bindings, in order from the most
 *  recent binding of any key to the oldest binding in the table */
void TAB_dump(TAB_table t, void (*show)(void *key, void *value));

/* str eq function */
long str_eq( void * lhs, void * rhs );
long str_hash( void * key );

#endif


text:
namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Device Test
//===--------------------------------------------------------------------===//

class DeviceTest : public PelotonTest {};

#define DATA_FILE_LEN 1024 * 1024 * UINT64_C(512)  // 512 MB
#define DATA_FILE_NAME "peloton.pmem"

TEST_F(DeviceTest, BenchmarkTest) {

  std::vector<std::string> data_file_dirs = {NVM_DIR, HDD_DIR};
  int data_fd;
  size_t data_file_len = DATA_FILE_LEN;
  oid_t num_trials = 3;
  std::size_t begin_chunk_size = 9, end_chunk_size = 21; // lg base 2

  // Go over all the dirs
  for(auto data_file_dir : data_file_dirs){

    // Create a data file
    std::string data_file_name = data_file_dir + DATA_FILE_NAME;
    LOG_INFO("Data File Name : %s", data_file_name.c_str());

    if ((data_fd = open(data_file_name.c_str(), O_CREAT | O_RDWR | O_DIRECT | O_SYNC, 0666)) < 0) {
      LOG_ERROR("%s: No such file or directory", data_file_name.c_str());
      return;
    }

    // Allocate the data file
    if ((errno = posix_fallocate(data_fd, 0, data_file_len)) != 0) {
      LOG_ERROR("%s: posix_fallocate", data_file_name.c_str());
      return;
    }

    // Go over all the chunk sizes
    for(oid_t chunk_size_itr = begin_chunk_size;
        chunk_size_itr <= end_chunk_size;
        chunk_size_itr++){

      // READS
      for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) {

      }

      // WRITES
      for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) {

      }

    }

    // Close the pmem file
    close(data_fd);
  }

}

}  // End test namespace
}  // End peloton namespace


text:
var Config = Backbone.Model.extend({
    defaults: {
        username: "ibraihim-islam",
        repo: "ibrahim-islam.github.io",
        post_per_page: 5
    },
    url: 'config.json'
});

var Issue = Backbone.Model.extend({
	initialize: function(options){
        var config = options.config.toJSON();
        this.urlRoot = 'https://api.github.com/repos/'+ config.username +'/'+ config.repo +'/issues';
    },
    sync: function (method, model, options) {
        if (method !== 'read') return Backbone.sync.apply(this, arguments);

        var xhr = Backbone.ajax({
            type: 'GET',
            dataType: 'json',
            url: _.result(model, 'url')
        });

        return xhr.then(function (issue) {
            var markdown = new Markdown({
                text: issue.body || 'body'
            });

            var data = JSON.stringify( markdown.toJSON() );
            var success = options.success;

            return Backbone.ajax({
                url: _.result(markdown, 'url'),
                dataType: 'html',
                contentType: 'application/json',
                type: 'POST',
                data: data
            }).then(function(htmlbody) {
                var resp = _.extend({}, issue, {
                    body: htmlbody
                });
                success(resp);
            });
        });
    }
});

var Issues = Backbone.Collection.extend({
    initialize: function(options){
        var config = options.config.toJSON();
        this.url = 'https://api.github.com/repos/'
        + config.username
        +'/'+
        config.repo
        +'/issues?per_page='
        + config.post_per_page
        + '&page=' +
        options.page;
    }
});

var Markdown = Backbone.Model.extend({
    defaults: {
        'text': '',
        'mode': 'markdown'
    },
    url: 'https://api.github.com/markdown'
});

var LoadMore = Backbone.Model.extend({
    defaults: {
        'pageNumber': 2
    }
});


text:
package command

import (
	"strings"
	"sync"

	"github.com/hashicorp/terraform/terraform"
)

// CountHook is a hook that counts the number of resources
// added, removed, changed during the course of an apply.
type CountHook struct {
	Added   int
	Changed int
	Removed int

	ToAdd          int
	ToChange       int
	ToRemove       int
	ToRemoveAndAdd int

	pending map[string]countHookAction

	sync.Mutex
	terraform.NilHook
}

func (h *CountHook) Reset() {
	h.Lock()
	defer h.Unlock()

	h.pending = nil
	h.Added = 0
	h.Changed = 0
	h.Removed = 0
}

func (h *CountHook) PreApply(
	n *terraform.InstanceInfo,
	s *terraform.InstanceState,
	d *terraform.InstanceDiff) (terraform.HookAction, error) {
	h.Lock()
	defer h.Unlock()

	if h.pending == nil {
		h.pending = make(map[string]countHookAction)
	}

	action := countHookActionChange
	if d.GetDestroy() {
		action = countHookActionRemove
	} else if s.ID == "" {
		action = countHookActionAdd
	}

	h.pending[n.HumanId()] = action

	return terraform.HookActionContinue, nil
}

func (h *CountHook) PostApply(
	n *terraform.InstanceInfo,
	s *terraform.InstanceState,
	e error) (terraform.HookAction, error) {
	h.Lock()
	defer h.Unlock()

	if h.pending != nil {
		if a, ok := h.pending[n.HumanId()]; ok {
			delete(h.pending, n.HumanId())

			if e == nil {
				switch a {
				case countHookActionAdd:
					h.Added += 1
				case countHookActionChange:
					h.Changed += 1
				case countHookActionRemove:
					h.Removed += 1
				}
			}
		}
	}

	return terraform.HookActionContinue, nil
}

func (h *CountHook) PostDiff(
	n *terraform.InstanceInfo, d *terraform.InstanceDiff) (
	terraform.HookAction, error) {
	h.Lock()
	defer h.Unlock()

	// We don't count anything for data sources
	if strings.HasPrefix(n.Id, "data.") {
		return terraform.HookActionContinue, nil
	}

	switch d.ChangeType() {
	case terraform.DiffDestroyCreate:
		h.ToRemoveAndAdd += 1
	case terraform.DiffCreate:
		h.ToAdd += 1
	case terraform.DiffDestroy:
		h.ToRemove += 1
	case terraform.DiffUpdate:
		h.ToChange += 1
	}

	return terraform.HookActionContinue, nil
}


text:
ActiveRecord::Schema.define(version: 20160310022314) do

  create_table "fake_students", force: :cascade do |t|
    t.integer  "race"
    t.string   "gender"
    t.string   "name"
    t.string   "email"
    t.string   "school"
    t.string   "year"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>
#include <utility>
#include <vector>

#include "base/containers/flat_set.h"
#include "chrome/browser/bluetooth/bluetooth_chooser_context_factory.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/test/base/testing_profile.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/permissions/contexts/bluetooth_chooser_context.h"
#include "components/permissions/object_permission_context_base.h"
#include "components/permissions/test/object_permission_context_base_mock_permission_observer.h"
#include "content/public/test/browser_task_environment.h"
#include "device/bluetooth/public/cpp/bluetooth_uuid.h"
#include "device/bluetooth/test/mock_bluetooth_adapter.h"
#include "device/bluetooth/test/mock_bluetooth_device.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom.h"
#include "url/gurl.h"
#include "url/origin.h"

using blink::mojom::WebBluetoothRequestDeviceOptionsPtr;
using device::BluetoothUUID;
using device::BluetoothUUIDHash;
using permissions::BluetoothChooserContext;
using testing::NiceMock;

namespace {

constexpr char kDeviceAddressKey[] = "device-address";
constexpr char kDeviceNameKey[] = "name";
constexpr char kServicesKey[] = "services";
constexpr char kManufacturerDataKey[] = "manufacturer-data";
constexpr char kWebBluetoothDeviceIdKey[] = "web-bluetooth-device-id";

const uint32_t kGamepadBluetoothClass = 0x0508;

constexpr char kDeviceAddress1[] = "00:00:00:00:00:00";
constexpr char kDeviceAddress2[] = "11:11:11:11:11:11";

constexpr char kGlucoseUUIDString[] = "00001808-0000-1000-8000-00805f9b34fb";
constexpr char kHeartRateUUIDString[] = "0000180d-0000-1000-8000-00805f9b34fb";
constexpr char kBatteryServiceUUIDString[] =
    "0000180f-0000-1000-8000-00805f9b34fb";
constexpr char kBloodPressureUUIDString[] =
    "00001813-0000-1000-8000-00805f9b34fb";
constexpr char kCyclingPowerUUIDString[] =
    "00001818-0000-1000-8000-00805f9b34fb";
const BluetoothUUID kGlucoseUUID(kGlucoseUUIDString);
const BluetoothUUID kHeartRateUUID(kHeartRateUUIDString);
const BluetoothUUID kBatteryServiceUUID(kBatteryServiceUUIDString);
const BluetoothUUID kBloodPressureUUID(kBloodPressureUUIDString);
const BluetoothUUID kCyclingPowerUUID(kCyclingPowerUUIDString);

WebBluetoothRequestDeviceOptionsPtr CreateOptionsForServicesAndManufacturerData(
    const std::vector<BluetoothUUID>& filter_services,
    const std::vector<BluetoothUUID>& optional_services,
    const std::vector<uint16_t>& optional_manufacturer_data) {
  auto filter = blink::mojom::WebBluetoothLeScanFilter::New();
  filter->services = filter_services;

  std::vector<blink::mojom::WebBluetoothLeScanFilterPtr> scan_filters;
  scan_filters.push_back(std::move(filter));

  auto options = blink::mojom::WebBluetoothRequestDeviceOptions::New();
  options->filters = std::move(scan_filters);
  options->optional_services = optional_services;
  options->optional_manufacturer_data = optional_manufacturer_data;
  return options;
}

WebBluetoothRequestDeviceOptionsPtr CreateOptionsForServices(
    const std::vector<BluetoothUUID>& filter_services,
    const std::vector<BluetoothUUID>& optional_services) {
  return CreateOptionsForServicesAndManufacturerData(
      filter_services, optional_services, /*optional_manufacturer_data=*/{});
}

WebBluetoothRequestDeviceOptionsPtr CreateOptionsForServices(
    const std::vector<BluetoothUUID>& filter_services) {
  return CreateOptionsForServices(filter_services, /*optional_services=*/{});
}

WebBluetoothRequestDeviceOptionsPtr CreateOptionsForManufacturerData(
    const std::vector<uint16_t>& optional_manufacturer_data) {
  return CreateOptionsForServicesAndManufacturerData(
      /*services=*/{}, /*optional_services=*/{}, optional_manufacturer_data);
}

}  // namespace

class FakeBluetoothAdapter : public device::MockBluetoothAdapter {
 public:
  FakeBluetoothAdapter() = default;

  // Move-only class.
  FakeBluetoothAdapter(const FakeBluetoothAdapter&) = delete;
  FakeBluetoothAdapter& operator=(const FakeBluetoothAdapter&) = delete;

 private:
  ~FakeBluetoothAdapter() override = default;
};

class FakeBluetoothDevice : public device::MockBluetoothDevice {
 public:
  FakeBluetoothDevice(device::MockBluetoothAdapter* adapter,
                      const char* name,
                      const std::string& address)
      : device::MockBluetoothDevice(adapter,
                                    kGamepadBluetoothClass,
                                    name,
                                    address,
                                    /*paired=*/true,
                                    /*connected=*/true) {}

  // Move-only class.
  FakeBluetoothDevice(const FakeBluetoothDevice&) = delete;
  FakeBluetoothDevice& operator=(const FakeBluetoothDevice&) = delete;
};

class BluetoothChooserContextTest : public testing::Test {
 public:
  BluetoothChooserContextTest()
      : foo_url_("https://foo.com"),
        bar_url_("https://bar.com"),
        foo_origin_(url::Origin::Create(foo_url_)),
        bar_origin_(url::Origin::Create(bar_url_)) {}

  ~BluetoothChooserContextTest() override = default;

  // Move-only class.
  BluetoothChooserContextTest(const BluetoothChooserContextTest&) = delete;
  BluetoothChooserContextTest& operator=(const BluetoothChooserContextTest&) =
      delete;

  void SetUp() override {
    fake_adapter_ = base::MakeRefCounted<FakeBluetoothAdapter>();
    fake_device1_ = GetBluetoothDevice("Wireless Gizmo", kDeviceAddress1);
    fake_device2_ = GetBluetoothDevice("Wireless Gadget", kDeviceAddress2);
  }

 protected:
  Profile* profile() { return &profile_; }

  BluetoothChooserContext* GetChooserContext(Profile* profile) {
    auto* chooser_context =
        BluetoothChooserContextFactory::GetForProfile(profile);
    chooser_context->AddObserver(&mock_permission_observer_);
    return chooser_context;
  }

  std::unique_ptr<NiceMock<FakeBluetoothDevice>> GetBluetoothDevice(
      const char* name,
      std::string address) {
    return std::make_unique<NiceMock<FakeBluetoothDevice>>(fake_adapter_.get(),
                                                           name, address);
  }

  // Mock Observer
  NiceMock<permissions::MockPermissionObserver> mock_permission_observer_;

  const GURL foo_url_;
  const GURL bar_url_;
  const url::Origin foo_origin_;
  const url::Origin bar_origin_;
  std::unique_ptr<NiceMock<FakeBluetoothDevice>> fake_device1_;
  std::unique_ptr<NiceMock<FakeBluetoothDevice>> fake_device2_;

 private:
  content::BrowserTaskEnvironment task_environment_;
  scoped_refptr<FakeBluetoothAdapter> fake_adapter_;
  TestingProfile profile_;
};

// Check that Web Bluetooth device permissions are granted and revoked properly,
// and that the WebBluetoothDeviceId and device address can be retrieved using
// each other.
TEST_F(BluetoothChooserContextTest, CheckGrantAndRevokePermission) {
  const std::vector<BluetoothUUID> services = {kGlucoseUUID,
                                               kBloodPressureUUID};
  const std::vector<uint16_t> manufacturer_codes = {0x0001, 0x0002};
  WebBluetoothRequestDeviceOptionsPtr options =
      CreateOptionsForServicesAndManufacturerData(
          services, /*optional_services=*/{}, manufacturer_codes);

  BluetoothChooserContext* context = GetChooserContext(profile());

  EXPECT_FALSE(
      context->GetWebBluetoothDeviceId(foo_origin_, fake_device1_->GetAddress())
          .IsValid());
  EXPECT_CALL(mock_permission_observer_,
              OnObjectPermissionChanged(
                  absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                  ContentSettingsType::BLUETOOTH_CHOOSER_DATA));

  blink::WebBluetoothDeviceId device_id = context->GrantServiceAccessPermission(
      foo_origin_, fake_device1_.get(), options.get());

  EXPECT_TRUE(context->HasDevicePermission(foo_origin_, device_id));
  EXPECT_EQ(context->GetWebBluetoothDeviceId(foo_origin_,
                                             fake_device1_->GetAddress()),
            device_id);
  EXPECT_EQ(context->GetDeviceAddress(foo_origin_, device_id),
            fake_device1_->GetAddress());
  EXPECT_TRUE(
      context->IsAllowedToAccessAtLeastOneService(foo_origin_, device_id));
  for (const auto& service : services) {
    EXPECT_TRUE(
        context->IsAllowedToAccessService(foo_origin_, device_id, service));
  }

  base::Value expected_object(base::Value::Type::DICTIONARY);
  expected_object.SetStringKey(kDeviceAddressKey, kDeviceAddress1);
  expected_object.SetStringKey(kDeviceNameKey,
                               fake_device1_->GetNameForDisplay());
  expected_object.SetStringKey(kWebBluetoothDeviceIdKey, device_id.str());
  base::Value expected_services(base::Value::Type::DICTIONARY);
  expected_services.SetBoolKey(kGlucoseUUIDString, /*val=*/true);
  expected_services.SetBoolKey(kBloodPressureUUIDString, /*val=*/true);
  expected_object.SetKey(kServicesKey, std::move(expected_services));
  base::Value expected_manufacturer_data(base::Value::Type::LIST);
  expected_manufacturer_data.Append(0x01);
  expected_manufacturer_data.Append(0x02);
  expected_object.SetKey(kManufacturerDataKey,
                         std::move(expected_manufacturer_data));

  std::vector<std::unique_ptr<BluetoothChooserContext::Object>> origin_objects =
      context->GetGrantedObjects(foo_origin_);
  ASSERT_EQ(1u, origin_objects.size());
  EXPECT_EQ(expected_object, origin_objects[0]->value);
  EXPECT_FALSE(origin_objects[0]->incognito);

  std::vector<std::unique_ptr<BluetoothChooserContext::Object>>
      all_origin_objects = context->GetAllGrantedObjects();
  ASSERT_EQ(1u, all_origin_objects.size());
  EXPECT_EQ(foo_origin_.GetURL(), all_origin_objects[0]->origin);
  EXPECT_EQ(expected_object, all_origin_objects[0]->value);
  EXPECT_FALSE(all_origin_objects[0]->incognito);

  testing::Mock::VerifyAndClearExpectations(&mock_permission_observer_);
  EXPECT_CALL(mock_permission_observer_,
              OnObjectPermissionChanged(
                  absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                  ContentSettingsType::BLUETOOTH_CHOOSER_DATA));
  EXPECT_CALL(mock_permission_observer_, OnPermissionRevoked(foo_origin_));

  context->RevokeObjectPermission(foo_origin_, origin_objects[0]->value);

  EXPECT_FALSE(context->HasDevicePermission(foo_origin_, device_id));
  EXPECT_FALSE(
      context->GetWebBluetoothDeviceId(foo_origin_, fake_device1_->GetAddress())
          .IsValid());

  origin_objects = context->GetGrantedObjects(foo_origin_);
  EXPECT_EQ(0u, origin_objects.size());

  all_origin_objects = context->GetAllGrantedObjects();
  EXPECT_EQ(0u, all_origin_objects.size());
}

// Check that Web Bluetooth permissions granted in incognito mode remain only
// in the incognito session.
TEST_F(BluetoothChooserContextTest, GrantPermissionInIncognito) {
  const std::vector<BluetoothUUID> services{kGlucoseUUID, kBloodPressureUUID};
  WebBluetoothRequestDeviceOptionsPtr options =
      CreateOptionsForServices(services);

  BluetoothChooserContext* context = GetChooserContext(profile());
  BluetoothChooserContext* incognito_context = GetChooserContext(
      profile()->GetPrimaryOTRProfile(/*create_if_needed=*/true));

  EXPECT_CALL(mock_permission_observer_,
              OnObjectPermissionChanged(
                  absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                  ContentSettingsType::BLUETOOTH_CHOOSER_DATA));
  blink::WebBluetoothDeviceId device_id = context->GrantServiceAccessPermission(
      foo_origin_, fake_device1_.get(), options.get());

  EXPECT_TRUE(context->HasDevicePermission(foo_origin_, device_id));
  EXPECT_EQ(device_id, context->GetWebBluetoothDeviceId(
                           foo_origin_, fake_device1_->GetAddress()));
  EXPECT_EQ(context->GetDeviceAddress(foo_origin_, device_id),
            fake_device1_->GetAddress());
  EXPECT_TRUE(
      context->IsAllowedToAccessAtLeastOneService(foo_origin_, device_id));
  for (const auto& service : services) {
    EXPECT_TRUE(
        context->IsAllowedToAccessService(foo_origin_, device_id, service));
  }

  EXPECT_FALSE(incognito_context->HasDevicePermission(foo_origin_, device_id));
  EXPECT_FALSE(
      incognito_context
          ->GetWebBluetoothDeviceId(foo_origin_, fake_device1_->GetAddress())
          .IsValid());

  testing::Mock::VerifyAndClearExpectations(&mock_permission_observer_);
  EXPECT_CALL(mock_permission_observer_,
              OnObjectPermissionChanged(
                  absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                  ContentSettingsType::BLUETOOTH_CHOOSER_DATA));
  blink::WebBluetoothDeviceId incognito_device_id =
      incognito_context->GrantServiceAccessPermission(
          foo_origin_, fake_device1_.get(), options.get());

  EXPECT_FALSE(context->HasDevicePermission(foo_origin_, incognito_device_id));
  EXPECT_NE(incognito_device_id, context->GetWebBluetoothDeviceId(
                                     foo_origin_, fake_device1_->GetAddress()));
  EXPECT_TRUE(
      incognito_context->HasDevicePermission(foo_origin_, incognito_device_id));
  EXPECT_EQ(incognito_device_id, incognito_context->GetWebBluetoothDeviceId(
                                     foo_origin_, fake_device1_->GetAddress()));
  EXPECT_EQ(
      incognito_context->GetDeviceAddress(foo_origin_, incognito_device_id),
      fake_device1_->GetAddress());
  EXPECT_TRUE(incognito_context->IsAllowedToAccessAtLeastOneService(
      foo_origin_, incognito_device_id));
  for (const auto& service : services) {
    EXPECT_TRUE(incognito_context->IsAllowedToAccessService(
        foo_origin_, incognito_device_id, service));
  }

  {
    std::vector<std::unique_ptr<BluetoothChooserContext::Object>>
        origin_objects = context->GetGrantedObjects(foo_origin_);
    EXPECT_EQ(1u, origin_objects.size());

    std::vector<std::unique_ptr<BluetoothChooserContext::Object>>
        all_origin_objects = context->GetAllGrantedObjects();
    ASSERT_EQ(1u, all_origin_objects.size());
    EXPECT_FALSE(all_origin_objects[0]->incognito);
  }
  {
    std::vector<std::unique_ptr<BluetoothChooserContext::Object>>
        origin_objects = incognito_context->GetGrantedObjects(foo_origin_);
    EXPECT_EQ(1u, origin_objects.size());

    // GetAllGrantedObjects() on an incognito session only returns objects
    // relevant to it.
    std::vector<std::unique_ptr<BluetoothChooserContext::Object>>
        all_origin_objects = incognito_context->GetAllGrantedObjects();
    ASSERT_EQ(1u, all_origin_objects.size());
    EXPECT_TRUE(all_origin_objects[0]->incognito);
  }
}

// Check that granting device permission with new services updates the
// permission.
TEST_F(BluetoothChooserContextTest, CheckGrantWithServiceUpdates) {
  const std::vector<BluetoothUUID> services1{kGlucoseUUID, kBloodPressureUUID};
  WebBluetoothRequestDeviceOptionsPtr options1 =
      CreateOptionsForServices(services1);

  BluetoothChooserContext* context = GetChooserContext(profile());

  EXPECT_CALL(mock_permission_observer_,
              OnObjectPermissionChanged(
                  absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                  ContentSettingsType::BLUETOOTH_CHOOSER_DATA));
  blink::WebBluetoothDeviceId device_id1 =
      context->GrantServiceAccessPermission(foo_origin_, fake_device1_.get(),
                                            options1.get());
  EXPECT_TRUE(
      context->IsAllowedToAccessAtLeastOneService(foo_origin_, device_id1));
  for (const auto& service : services1) {
    EXPECT_TRUE(
        context->IsAllowedToAccessService(foo_origin_, device_id1, service));
  }

  const std::vector<BluetoothUUID> services2{kHeartRateUUID, kBloodPressureUUID,
                                             kCyclingPowerUUID};
  WebBluetoothRequestDeviceOptionsPtr options2 =
      CreateOptionsForServices(services2);

  testing::Mock::VerifyAndClearExpectations(&mock_permission_observer_);
  EXPECT_CALL(mock_permission_observer_,
              OnObjectPermissionChanged(
                  absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                  ContentSettingsType::BLUETOOTH_CHOOSER_DATA));
  blink::WebBluetoothDeviceId device_id2 =
      context->GrantServiceAccessPermission(foo_origin_, fake_device1_.get(),
                                            options2.get());
  EXPECT_EQ(device_id2, device_id1);

  base::flat_set<BluetoothUUID> services_set(services1);
  services_set.insert(services2.begin(), services2.end());
  for (const auto& service : services_set) {
    EXPECT_TRUE(
        context->IsAllowedToAccessService(foo_origin_, device_id2, service));
  }
}

// Check that permissions are granted to the union of filtered and optional
// services.
TEST_F(BluetoothChooserContextTest, CheckGrantWithOptionalServices) {
  const std::vector<BluetoothUUID> services{kGlucoseUUID, kBloodPressureUUID};
  const std::vector<BluetoothUUID> optional_services{kBatteryServiceUUID};
  WebBluetoothRequestDeviceOptionsPtr options =
      CreateOptionsForServices(services, optional_services);

  BluetoothChooserContext* context = GetChooserContext(profile());

  EXPECT_CALL(mock_permission_observer_,
              OnObjectPermissionChanged(
                  absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                  ContentSettingsType::BLUETOOTH_CHOOSER_DATA));
  blink::WebBluetoothDeviceId device_id = context->GrantServiceAccessPermission(
      foo_origin_, fake_device1_.get(), options.get());

  EXPECT_TRUE(
      context->IsAllowedToAccessAtLeastOneService(foo_origin_, device_id));
  for (const auto& service : services) {
    EXPECT_TRUE(
        context->IsAllowedToAccessService(foo_origin_, device_id, service));
  }
  for (const auto& service : optional_services) {
    EXPECT_TRUE(
        context->IsAllowedToAccessService(foo_origin_, device_id, service));
  }
}

// Check that permissions for manufacturer data are granted and updated
// properly.
TEST_F(BluetoothChooserContextTest, CheckGrantWithOptionalManufacturerData) {
  BluetoothChooserContext* context = GetChooserContext(profile());

  // Grant permission with only manufacturer data.
  {
    const std::vector<uint16_t> optional_manufacturer_data({0x0001, 0x0002});
    WebBluetoothRequestDeviceOptionsPtr options =
        CreateOptionsForManufacturerData(optional_manufacturer_data);
    EXPECT_CALL(mock_permission_observer_,
                OnObjectPermissionChanged(
                    absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                    ContentSettingsType::BLUETOOTH_CHOOSER_DATA));
    blink::WebBluetoothDeviceId device_id =
        context->GrantServiceAccessPermission(foo_origin_, fake_device1_.get(),
                                              options.get());

    for (const uint16_t manufacturer_code : optional_manufacturer_data) {
      EXPECT_TRUE(context->IsAllowedToAccessManufacturerData(
          foo_origin_, device_id, manufacturer_code));
    }
    EXPECT_FALSE(context->IsAllowedToAccessManufacturerData(foo_origin_,
                                                            device_id, 0x0003));
  }

  // Grant permission again with different manufacturer data.
  {
    const std::vector<uint16_t> optional_manufacturer_data({0x0002, 0x0003});
    WebBluetoothRequestDeviceOptionsPtr options =
        CreateOptionsForManufacturerData(optional_manufacturer_data);
    EXPECT_CALL(mock_permission_observer_,
                OnObjectPermissionChanged(
                    absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                    ContentSettingsType::BLUETOOTH_CHOOSER_DATA));
    blink::WebBluetoothDeviceId device_id =
        context->GrantServiceAccessPermission(foo_origin_, fake_device1_.get(),
                                              options.get());

    for (const uint16_t manufacturer_code : optional_manufacturer_data) {
      EXPECT_TRUE(context->IsAllowedToAccessManufacturerData(
          foo_origin_, device_id, manufacturer_code));
    }
    // Access permission for manufacturer code 0x0001 should still be available.
    EXPECT_TRUE(context->IsAllowedToAccessManufacturerData(foo_origin_,
                                                           device_id, 0x0001));
  }
}

// Check that the Bluetooth guard permission prevents Web Bluetooth from being
// used even if permissions exist for a pair of origins.
TEST_F(BluetoothChooserContextTest, BluetoothGuardPermission) {
  const std::vector<BluetoothUUID> services1{kGlucoseUUID, kBloodPressureUUID};
  WebBluetoothRequestDeviceOptionsPtr options1 =
      CreateOptionsForServices(services1);
  const std::vector<BluetoothUUID> services2{kHeartRateUUID, kCyclingPowerUUID};
  WebBluetoothRequestDeviceOptionsPtr options2 =
      CreateOptionsForServices(services2);

  auto* map = HostContentSettingsMapFactory::GetForProfile(profile());
  map->SetContentSettingDefaultScope(foo_url_, foo_url_,
                                     ContentSettingsType::BLUETOOTH_GUARD,
                                     CONTENT_SETTING_BLOCK);

  BluetoothChooserContext* context = GetChooserContext(profile());
  EXPECT_CALL(mock_permission_observer_,
              OnObjectPermissionChanged(
                  absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                  ContentSettingsType::BLUETOOTH_CHOOSER_DATA))
      .Times(4);

  blink::WebBluetoothDeviceId foo_device_id1 =
      context->GrantServiceAccessPermission(foo_origin_, fake_device1_.get(),
                                            options1.get());
  blink::WebBluetoothDeviceId foo_device_id2 =
      context->GrantServiceAccessPermission(foo_origin_, fake_device1_.get(),
                                            options2.get());
  blink::WebBluetoothDeviceId bar_device_id1 =
      context->GrantServiceAccessPermission(bar_origin_, fake_device1_.get(),
                                            options1.get());
  blink::WebBluetoothDeviceId bar_device_id2 =
      context->GrantServiceAccessPermission(bar_origin_, fake_device2_.get(),
                                            options2.get());

  {
    std::vector<std::unique_ptr<BluetoothChooserContext::Object>>
        origin_objects = context->GetGrantedObjects(foo_origin_);
    EXPECT_EQ(0u, origin_objects.size());
  }
  {
    std::vector<std::unique_ptr<BluetoothChooserContext::Object>>
        origin_objects = context->GetGrantedObjects(bar_origin_);
    EXPECT_EQ(2u, origin_objects.size());
  }

  std::vector<std::unique_ptr<BluetoothChooserContext::Object>>
      all_origin_objects = context->GetAllGrantedObjects();
  EXPECT_EQ(2u, all_origin_objects.size());
  for (const auto& object : all_origin_objects)
    EXPECT_EQ(object->origin, bar_origin_.GetURL());

  EXPECT_FALSE(context->HasDevicePermission(foo_origin_, foo_device_id1));
  EXPECT_FALSE(context->HasDevicePermission(foo_origin_, foo_device_id2));
  EXPECT_TRUE(context->HasDevicePermission(bar_origin_, bar_device_id1));
  EXPECT_TRUE(context->HasDevicePermission(bar_origin_, bar_device_id2));
}

// Check that a valid WebBluetoothDeviceId is produced for Bluetooth LE
// scanned devices. When permission is granted to one of these devices, the
// previously generated WebBluetoothDeviceId should be remembered.
TEST_F(BluetoothChooserContextTest, BluetoothLEScannedDevices) {
  BluetoothChooserContext* context = GetChooserContext(profile());

  EXPECT_CALL(mock_permission_observer_,
              OnObjectPermissionChanged(
                  absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                  ContentSettingsType::BLUETOOTH_CHOOSER_DATA))
      .Times(0);
  blink::WebBluetoothDeviceId scanned_id =
      context->AddScannedDevice(foo_origin_, fake_device1_->GetAddress());

  EXPECT_EQ(scanned_id, context->GetWebBluetoothDeviceId(
                            foo_origin_, fake_device1_->GetAddress()));
  EXPECT_EQ(fake_device1_->GetAddress(),
            context->GetDeviceAddress(foo_origin_, scanned_id));
  EXPECT_FALSE(context->HasDevicePermission(foo_origin_, scanned_id));
  EXPECT_FALSE(
      context->IsAllowedToAccessAtLeastOneService(foo_origin_, scanned_id));

  const std::vector<BluetoothUUID> services{kGlucoseUUID, kBloodPressureUUID};
  WebBluetoothRequestDeviceOptionsPtr options =
      CreateOptionsForServices(services);
  testing::Mock::VerifyAndClearExpectations(&mock_permission_observer_);
  EXPECT_CALL(mock_permission_observer_,
              OnObjectPermissionChanged(
                  absl::make_optional(ContentSettingsType::BLUETOOTH_GUARD),
                  ContentSettingsType::BLUETOOTH_CHOOSER_DATA));
  blink::WebBluetoothDeviceId granted_id =
      context->GrantServiceAccessPermission(foo_origin_, fake_device1_.get(),
                                            options.get());

  EXPECT_EQ(scanned_id, granted_id);
}

// Granted devices should return the same ID when detected via a Bluetooth LE
// scan. If the permission is revoked, then a new ID should be generated for the
// device when detected via a Bluetooth LE scan.
TEST_F(BluetoothChooserContextTest, BluetoothLEScanWithGrantedDevices) {
  const std::vector<BluetoothUUID> services{kGlucoseUUID, kBloodPressureUUID};
  WebBluetoothRequestDeviceOptionsPtr options =
      CreateOptionsForServices(services);

  BluetoothChooserContext* context = GetChooserContext(profile());

  blink::WebBluetoothDeviceId granted_id =
      context->GrantServiceAccessPermission(foo_origin_, fake_device1_.get(),
                                            options.get());
  blink::WebBluetoothDeviceId scanned_id =
      context->AddScannedDevice(foo_origin_, fake_device1_->GetAddress());
  EXPECT_EQ(granted_id, scanned_id);

  std::vector<std::unique_ptr<BluetoothChooserContext::Object>> origin_objects =
      context->GetGrantedObjects(foo_origin_);
  ASSERT_EQ(1u, origin_objects.size());
  context->RevokeObjectPermission(foo_origin_, origin_objects[0]->value);

  scanned_id =
      context->AddScannedDevice(foo_origin_, fake_device1_->GetAddress());
  EXPECT_NE(scanned_id, granted_id);
  EXPECT_FALSE(context->HasDevicePermission(foo_origin_, scanned_id));
  EXPECT_FALSE(context->HasDevicePermission(foo_origin_, granted_id));
}