text:
package org.apache.cloudstack.storage.snapshot;

import java.util.Date;

import javax.inject.Inject;

import org.apache.log4j.Logger;

import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy.SnapshotOperation;
import org.apache.cloudstack.engine.subsystem.api.storage.StorageStrategyFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
import org.apache.cloudstack.storage.command.CopyCmdAnswer;
import org.apache.cloudstack.storage.command.CreateObjectAnswer;
import org.apache.cloudstack.storage.datastore.ObjectInDataStoreManager;
import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO;
import org.apache.cloudstack.storage.to.SnapshotObjectTO;

import com.cloud.agent.api.Answer;
import com.cloud.agent.api.to.DataObjectType;
import com.cloud.agent.api.to.DataTO;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.Snapshot;
import com.cloud.storage.SnapshotVO;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.db.QueryBuilder;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.fsm.NoTransitionException;

public class SnapshotObject implements SnapshotInfo {
    private static final Logger s_logger = Logger.getLogger(SnapshotObject.class);
    private SnapshotVO snapshot;
    private DataStore store;
    private Object payload;
    private Boolean fullBackup;
    @Inject
    protected SnapshotDao snapshotDao;
    @Inject
    protected VolumeDao volumeDao;
    @Inject
    protected VolumeDataFactory volFactory;
    @Inject
    protected SnapshotStateMachineManager stateMachineMgr;
    @Inject
    SnapshotDataFactory snapshotFactory;
    @Inject
    ObjectInDataStoreManager objectInStoreMgr;
    @Inject
    SnapshotDataStoreDao snapshotStoreDao;
    @Inject
    StorageStrategyFactory storageStrategyFactory;
    private String installPath; // temporarily set installPath before passing to resource for entries with empty installPath for object store migration case

    public SnapshotObject() {

    }

    protected void configure(SnapshotVO snapshot, DataStore store) {
        this.snapshot = snapshot;
        this.store = store;
    }

    public static SnapshotObject getSnapshotObject(SnapshotVO snapshot, DataStore store) {
        SnapshotObject snapObj = ComponentContext.inject(SnapshotObject.class);
        snapObj.configure(snapshot, store);
        return snapObj;
    }

    public DataStore getStore() {
        return store;
    }

    @Override
    public SnapshotInfo getParent() {

        SnapshotDataStoreVO snapStoreVO = snapshotStoreDao.findByStoreSnapshot(store.getRole(), store.getId(), snapshot.getId());
        Long parentId = null;
        if (snapStoreVO != null) {
            parentId = snapStoreVO.getParentSnapshotId();
            if (parentId != null && parentId != 0) {
                return snapshotFactory.getSnapshot(parentId, store);
            }
        }

        return null;
    }

    @Override
    public SnapshotInfo getChild() {
        QueryBuilder<SnapshotDataStoreVO> sc = QueryBuilder.create(SnapshotDataStoreVO.class);
        sc.and(sc.entity().getDataStoreId(), Op.EQ, store.getId());
        sc.and(sc.entity().getRole(), Op.EQ, store.getRole());
        sc.and(sc.entity().getState(), Op.NIN, State.Destroying, State.Destroyed, State.Error);
        sc.and(sc.entity().getParentSnapshotId(), Op.EQ, getId());
        SnapshotDataStoreVO vo = sc.find();
        if (vo == null) {
            return null;
        }
        return snapshotFactory.getSnapshot(vo.getId(), store);
    }

    @Override
    public boolean isRevertable() {
        SnapshotStrategy snapshotStrategy = storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.REVERT);
        if (snapshotStrategy != null) {
            return true;
        }

        return false;
    }

    @Override
    public long getPhysicalSize() {
        long physicalSize = 0;
        SnapshotDataStoreVO snapshotStore = snapshotStoreDao.findBySnapshot(snapshot.getId(), DataStoreRole.Image);
        if (snapshotStore != null) {
            physicalSize = snapshotStore.getPhysicalSize();
        }
        return physicalSize;
    }

    @Override
    public VolumeInfo getBaseVolume() {
        return volFactory.getVolume(snapshot.getVolumeId());
    }

    @Override
    public long getId() {
        return snapshot.getId();
    }

    @Override
    public String getUri() {
        return snapshot.getUuid();
    }

    @Override
    public DataStore getDataStore() {
        return store;
    }

    @Override
    public Long getSize() {
        return snapshot.getSize();
    }

    @Override
    public DataObjectType getType() {
        return DataObjectType.SNAPSHOT;
    }

    @Override
    public String getUuid() {
        return snapshot.getUuid();
    }

    @Override
    public void processEvent(ObjectInDataStoreStateMachine.Event event) {
        try {
            objectInStoreMgr.update(this, event);
        } catch (Exception e) {
            s_logger.debug("Failed to update state:" + e.toString());
            throw new CloudRuntimeException("Failed to update state: " + e.toString());
        } finally {
            DataObjectInStore obj = objectInStoreMgr.findObject(this, this.getDataStore());
            if (event == ObjectInDataStoreStateMachine.Event.OperationFailed && !obj.getState().equals(ObjectInDataStoreStateMachine.State.Destroying)) {
                // Don't delete db entry if snapshot is successfully removed.
                objectInStoreMgr.deleteIfNotReady(this);
            }
        }
    }

    @Override
    public long getAccountId() {
        return snapshot.getAccountId();
    }

    @Override
    public long getVolumeId() {
        return snapshot.getVolumeId();
    }

    @Override
    public String getPath() {
        if (installPath != null)
            return installPath;

        DataObjectInStore objectInStore = objectInStoreMgr.findObject(this, getDataStore());
        if (objectInStore != null) {
            return objectInStore.getInstallPath();
        }
        return null;
    }

    public void setPath(String installPath) {
        this.installPath = installPath;
    }

    @Override
    public String getName() {
        return snapshot.getName();
    }

    @Override
    public long getSnapshotId() {
        return snapshot.getSnapshotId();
    }

    @Override
    public Date getCreated() {
        return snapshot.getCreated();
    }

    @Override
    public Type getRecurringType() {
        return snapshot.getRecurringType();
    }

    @Override
    public LocationType getLocationType() { return snapshot.getLocationType(); }

    @Override
    public State getState() {
        return snapshot.getState();
    }

    @Override
    public HypervisorType getHypervisorType() {
        return snapshot.getHypervisorType();
    }

    @Override
    public boolean isRecursive() {
        return snapshot.isRecursive();
    }

    @Override
    public short getsnapshotType() {
        return snapshot.getsnapshotType();
    }

    @Override
    public long getDomainId() {
        return snapshot.getDomainId();
    }

    @Override
    public Long getDataCenterId() {
        return snapshot.getDataCenterId();
    }

    public void processEvent(Snapshot.Event event) throws NoTransitionException {
        stateMachineMgr.processEvent(snapshot, event);
    }

    public SnapshotVO getSnapshotVO() {
        return snapshot;
    }

    @Override
    public DataTO getTO() {
        DataTO to = store.getDriver().getTO(this);
        if (to == null) {
            return new SnapshotObjectTO(this);
        }
        return to;
    }

    @Override
    public void processEvent(ObjectInDataStoreStateMachine.Event event, Answer answer) {
        try {
            SnapshotDataStoreVO snapshotStore = snapshotStoreDao.findByStoreSnapshot(getDataStore().getRole(), getDataStore().getId(), getId());
            if (answer instanceof CreateObjectAnswer) {
                SnapshotObjectTO snapshotTO = (SnapshotObjectTO)((CreateObjectAnswer)answer).getData();
                snapshotStore.setInstallPath(snapshotTO.getPath());
                snapshotStoreDao.update(snapshotStore.getId(), snapshotStore);
            } else if (answer instanceof CopyCmdAnswer) {
                SnapshotObjectTO snapshotTO = (SnapshotObjectTO)((CopyCmdAnswer)answer).getNewData();
                snapshotStore.setInstallPath(snapshotTO.getPath());
                if (snapshotTO.getPhysicalSize() != null) {
                    // For S3 delta snapshot, physical size is currently not set
                snapshotStore.setPhysicalSize(snapshotTO.getPhysicalSize());
                }
                if (snapshotTO.getParentSnapshotPath() == null) {
                    snapshotStore.setParentSnapshotId(0L);
                }
                snapshotStoreDao.update(snapshotStore.getId(), snapshotStore);

                // update side-effect of snapshot operation
                if (snapshotTO.getVolume() != null && snapshotTO.getVolume().getPath() != null) {
                    VolumeVO vol = volumeDao.findByUuid(snapshotTO.getVolume().getUuid());
                    if (vol != null) {
                        s_logger.info("Update volume path change due to snapshot operation, volume " + vol.getId() + " path: " + vol.getPath() + "->" +
                            snapshotTO.getVolume().getPath());
                        vol.setPath(snapshotTO.getVolume().getPath());
                        volumeDao.update(vol.getId(), vol);
                    } else {
                        s_logger.error("Cound't find the original volume with uuid: " + snapshotTO.getVolume().getUuid());
                    }
                }
            } else {
                throw new CloudRuntimeException("Unknown answer: " + answer.getClass());
            }
        } catch (RuntimeException ex) {
            if (event == ObjectInDataStoreStateMachine.Event.OperationFailed) {
                objectInStoreMgr.deleteIfNotReady(this);
            }
            throw ex;
        }
        this.processEvent(event);
    }

    @Override
    public void incRefCount() {
        if (store == null) {
            return;
        }

        if (store.getRole() == DataStoreRole.Image || store.getRole() == DataStoreRole.ImageCache) {
            SnapshotDataStoreVO store = snapshotStoreDao.findByStoreSnapshot(this.store.getRole(), this.store.getId(), getId());
            store.incrRefCnt();
            store.setLastUpdated(new Date());
            snapshotStoreDao.update(store.getId(), store);
        }
    }

    @Override
    public void decRefCount() {
        if (store == null) {
            return;
        }
        if (store.getRole() == DataStoreRole.Image || store.getRole() == DataStoreRole.ImageCache) {
            SnapshotDataStoreVO store = snapshotStoreDao.findByStoreSnapshot(this.store.getRole(), this.store.getId(), getId());
            store.decrRefCnt();
            store.setLastUpdated(new Date());
            snapshotStoreDao.update(store.getId(), store);
        }
    }

    @Override
    public Long getRefCount() {
        if (store == null) {
            return null;
        }
        if (store.getRole() == DataStoreRole.Image || store.getRole() == DataStoreRole.ImageCache) {
            SnapshotDataStoreVO store = snapshotStoreDao.findByStoreSnapshot(this.store.getRole(), this.store.getId(), getId());
            return store.getRefCnt();
        }
        return null;
    }

    @Override
    public ObjectInDataStoreStateMachine.State getStatus() {
        return objectInStoreMgr.findObject(this, store).getObjectInStoreState();
    }

    @Override
    public void addPayload(Object data) {
        payload = data;
    }

    @Override
    public Object getPayload() {
        return payload;
    }

    @Override
    public void setFullBackup(Boolean data) {
        fullBackup = data;
    }

    @Override
    public Boolean getFullBackup() {
        return fullBackup;
    }

    @Override
    public boolean delete() {
        if (store != null) {
            return store.delete(this);
        }
        return true;
    }

    @Override
    public Class<?> getEntityType() {
        return Snapshot.class;
    }
}


text: Ext.define('MyApp.Ext.require', {});

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
	<catissue_audit_event_details ELEMENT_NAME="REASON" CURRENT_VALUE="testing"/>
	<catissue_audit_event EVENT_TYPE="INSERT"/>
</dataset>


text:
#pragma once
#include <aws/iam/IAM_EXPORTS.h>
#include <aws/iam/IAMRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace IAM
{
namespace Model
{

  /*
  */
  class AWS_IAM_API DeleteRolePolicyRequest : public IAMRequest
  {
  public:
    DeleteRolePolicyRequest();
    Aws::String SerializePayload() const override;

    /*

The name (friendly name, not ARN) identifying the role that the policy is embedded in.

    */
    inline const Aws::String& GetRoleName() const{ return m_roleName; }

    /*

The name (friendly name, not ARN) identifying the role that the policy is embedded in.

    */
    inline void SetRoleName(const Aws::String& value) { m_roleNameHasBeenSet = true; m_roleName = value; }

    /*

The name (friendly name, not ARN) identifying the role that the policy is embedded in.

    */
    inline void SetRoleName(Aws::String&& value) { m_roleNameHasBeenSet = true; m_roleName = value; }

    /*

The name (friendly name, not ARN) identifying the role that the policy is embedded in.

    */
    inline void SetRoleName(const char* value) { m_roleNameHasBeenSet = true; m_roleName.assign(value); }

    /*

The name (friendly name, not ARN) identifying the role that the policy is embedded in.

    */
    inline DeleteRolePolicyRequest& WithRoleName(const Aws::String& value) { SetRoleName(value); return *this;}

    /*

The name (friendly name, not ARN) identifying the role that the policy is embedded in.

    */
    inline DeleteRolePolicyRequest& WithRoleName(Aws::String&& value) { SetRoleName(value); return *this;}

    /*

The name (friendly name, not ARN) identifying the role that the policy is embedded in.

    */
    inline DeleteRolePolicyRequest& WithRoleName(const char* value) { SetRoleName(value); return *this;}

    /*

The name identifying the policy document to delete.

    */
    inline const Aws::String& GetPolicyName() const{ return m_policyName; }

    /*

The name identifying the policy document to delete.

    */
    inline void SetPolicyName(const Aws::String& value) { m_policyNameHasBeenSet = true; m_policyName = value; }

    /*

The name identifying the policy document to delete.

    */
    inline void SetPolicyName(Aws::String&& value) { m_policyNameHasBeenSet = true; m_policyName = value; }

    /*

The name identifying the policy document to delete.

    */
    inline void SetPolicyName(const char* value) { m_policyNameHasBeenSet = true; m_policyName.assign(value); }

    /*

The name identifying the policy document to delete.

    */
    inline DeleteRolePolicyRequest& WithPolicyName(const Aws::String& value) { SetPolicyName(value); return *this;}

    /*

The name identifying the policy document to delete.

    */
    inline DeleteRolePolicyRequest& WithPolicyName(Aws::String&& value) { SetPolicyName(value); return *this;}

    /*

The name identifying the policy document to delete.

    */
    inline DeleteRolePolicyRequest& WithPolicyName(const char* value) { SetPolicyName(value); return *this;}

  private:
    Aws::String m_roleName;
    bool m_roleNameHasBeenSet;
    Aws::String m_policyName;
    bool m_policyNameHasBeenSet;
  };

} // namespace Model
} // namespace IAM
} // namespace Aws


text:
<?php

namespace Tests\Magium\Magento2\Navigation;

use Magium\Magento\AbstractMagentoTestCase;
use Magium\Magento\Navigators\Catalog\DefaultSimpleProductCategory;
use Magium\Magento\Navigators\Catalog\Product;
use Magium\Magento2\ConfigurationSwitcher;

class ProductNavigationTest extends \Tests\Magium\Magento\Navigation\ProductNavigationTest
{

    protected $productName = 'Joust Duffle Bag';

    protected function setUp()
    {
        parent::setUp();
        (new ConfigurationSwitcher($this))->configure();
    }

}


text:
import pytest
import requests

@pytest.fixture()
def jenkins_url():
    return "http://127.0.0.1/api/json"

def test_is_online(jenkins_url):
    requests.get(jenkins_url, timeout=5).raise_for_status()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

<title>Remote Method Invocation</title>

What's New in 1.1?

    Remote Method Invocation

Remote Method Invocation (RMI) enables programmers to create
distributed Java-to-Java applications, in which the methods of remote
Java objects can be invoked from other Java virtual machines, possibly
on different hosts. A Java program can make a call on a remote object
once it obtains a reference to the remote object, either by looking up
the remote object in the bootstrap naming service provided by RMI or by
receiving the reference as an argument or a return value. A client can
call a remote object in a server, and that server can also be a client
of other remote objects. RMI uses object serialization to marshal and
unmarshal parameters and does not truncate types, thereby supporting
true object-oriented polymorphism.

Where to Find Documentation

For an example that uses RMI, refer to
Putting It All Together.

You can find the Getting Started RMI tutorial
and the RMI Specification at
RMI Documentation.

RMI Enhancements
provides a preview of the enhancements planned to RMI
in the next major release of the JDK.

What's New in 1.1?


text:
go-github CHANGELOG
===================

0.6.0
-----
- Add support for the V4 Gitlab API. This means the older V3 API is no longer fully supported
  with this version. If you still need that version, please use the `f-api-v3` branch.

0.4.0
-----
- Add support to use [`sudo`](https://docs.gitlab.com/ce/api/README.html#sudo) for all API calls.
- Add support for the Notification Settings API.
- Add support for the Time Tracking API.
- Make sure that the error response correctly outputs any returned errors.
- And a reasonable number of smaller enhanchements and bugfixes.

0.3.0
-----
- Moved the tags related API calls to their own service, following the Gitlab API structure.

0.2.0
-----
- Convert all Option structs to use pointers for their fields.

0.1.0
-----
- Initial release.


text:
<?php

    namespace app\framework\Component\Validation\Validators;

    use app\framework\Component\Validation\ValidationException;
    use app\framework\Component\Validation\ValidatorInterface;

    class LessThanOrEqual implements ValidatorInterface
    {
        /**
         * Get validator name, eg: email
         *
         * @return string
         */
        public function getName()
        {
            return "less than or equal";
        }

        /**
         * Validate given value, using optional parameters and either throw an exception or return a boolean
         *
         * @param mixed     $value
         * @param array     $params
         * @param bool|true $throw
         *
         * @return boolean|string
         * @throws ValidationException
         */
        public function validate($value, $params = [], $throw = true)
        {
            $cmp = $params[0];
            if($value <= $cmp){
                return true;
            }

            $message = "Value must be less than or equal %s";
            if($throw){
                throw new ValidationException($message, $cmp);
            }

            return sprintf($message, $cmp);
        }

    }


text:
'use strict';

const utils = require('./utils.js');

const parseEmoji = function(version) {
	const source = utils.readDataFile(version, 'emoji');
	if (!source) {
		return;
	}
	const propertyMap = new Map();
	const lines = source.split('\n');
	lines.forEach(function(line) {
		if (!line || /^#/.test(line)) {
			return;
		}
		const data = line.trim().split(' ; ');
		const charRange = data[0].replace('..', '-').trim();
		const rangeParts = charRange.split('-');
		const property = data[1].split('#')[0].trim();
		if (rangeParts.length == 2) {
			utils.range(
				parseInt(rangeParts[0], 16),
				parseInt(rangeParts[1], 16)
			).forEach(function(codePoint) {
				if (propertyMap.has(property)) {
					propertyMap.get(property).add(codePoint);
				} else {
					propertyMap.set(property, new Set([codePoint]));
				}
			});
		} else {
			const codePoint = parseInt(rangeParts, 16);
			if (propertyMap.has(property)) {
				propertyMap.get(property).add(codePoint);
			} else {
				propertyMap.set(property, new Set([codePoint]));
			}
		}
	});
	const plainObject = {};
	for (const [property, codePoints] of propertyMap) {
		plainObject[property] = [...codePoints].sort((a, b) => a - b);
	}
	return plainObject;
};

module.exports = parseEmoji;


text:
tastypie-mongoengine-resource
=============================

Basic resource to integrate tastypie and mongoengine


text:
#include <pdal/pdal_internal.hpp>
#ifdef PDAL_HAVE_PYTHON

#include <pdal/plang/Script.hpp>
#include <pdal/FileUtils.hpp>

#ifdef PDAL_COMPILER_MSVC
#  pragma warning(disable: 4127) // conditional expression is constant
#endif

namespace pdal
{
namespace plang
{

Script::Script(const std::string& source, const std::string& module, const std::string& function)
    : m_source(source)
    , m_module(module)
    , m_function(function)
{
    return;
}

Script::Script(const Options& options)
{
    if (options.hasOption("source"))
    {
        const std::string& source = options.getValueOrThrow<std::string>("source");
        m_source = source;
    }
    else
    {
        const std::string& filename = options.getValueOrThrow<std::string>("filename");
        std::string source = FileUtils::readFileIntoString(filename);
        m_source = source;
    }

    const std::string& module = options.getValueOrThrow<std::string>("module");
    const std::string& function = options.getValueOrThrow<std::string>("function");

    m_module = module;
    m_function = function;

    return;
}

Script::Script(const Script& other)
    : m_source(other.m_source)
    , m_module(other.m_module)
    , m_function(other.m_function)
{
}

Script::~Script()
{
}

std::ostream& operator<<(std::ostream& os, Script const& script)
{
    int len = strlen(script.source());

    os << "source=[" << len << " bytes], ";
    os << "module=" << script.module() << ", ";
    os << "function=" << script.function();
    os << std::endl;

    return os;
}

}
} //namespaces

#endif


text:
package com.gtm.csims.dao.hibernate;

import net.sweet.dao.generic.HibernateEntityDAO;

import com.gtm.csims.dao.BsUserInfoOfZxDAO;
import com.gtm.csims.model.BsUserInfoOfZx;

public class BsUserInfoOfZxDAOImpl extends
		HibernateEntityDAO<BsUserInfoOfZx> implements
		BsUserInfoOfZxDAO {

}


text:
<?php $this->load->view('partials/header'); ?>

<?php $this->load->view('partials/sidebar'); ?>

  Tags

    <?php
    // Je récupère mon message flash grace à ma clé success
    $message = $this->session->flashdata('success');
    if(!empty($message)) { ?>

    <?php } ?>

            <a class="btn btn-sm btn-success btn-flat pull-right" href="<?php echo site_url('tag/creer'); ?>"> Ajouter un tag

                            Nom
                            Nb de films
                            Actions

                    <?php foreach($alltags as $tag){ ?>

                            <a href="<?php echo site_url('tag/voir/' . $tag->tid); ?>" class="text-bold"><?php echo $tag->tagname; ?>
                            <?php echo $tag->nbfilm; ?>

                                <a href="<?php echo site_url('tag/voir/' . $tag->tid); ?>"><button class="btn btn-xs btn-info btn-flat"> Voir</button>
                                <a href="<?php echo site_url('tag/editer/' . $tag->tid); ?>"><button class="btn btn-xs btn-warning btn-flat"> Editer</button>

                                <div id="modal<?php echo $tag->tid; ?>" class="modal fade" tabindex="-1" role="dialog" style="display: none;">

                                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Confirmer la suppression du tag "<?php echo $tag->tagname; ?>"?

                                                <button type="button" class="btn btn-xs btn-flat" data-dismiss="modal" aria-hidden="true">Annuler</button>
                                                <a href="<?php echo site_url('tag/supprimer/' . $tag->tid); ?>"><button class="btn btn-xs btn-danger btn-flat"> Supprimer</button>

                                <button class="btn btn-xs btn-danger btn-flat" data-toggle="modal" data-target="#modal<?php echo $tag->tid; ?>"> Supprimer</button>

                    <?php } ?>

<?php $this->load->view('partials/footer'); ?>


text:
require 'guard/minitest'

RSpec.describe Guard::Minitest do
  subject { Guard::Minitest }

  let(:runner) { Guard::Minitest::Runner }
  let(:guard) { subject.new }

  describe 'initialization' do
    it 'initializes runner with default options' do
      expect(runner).to receive(:new).with(all_on_start: true)

      subject.new
    end
  end

  describe 'start' do
    it 'runs all tests at start via runner' do
      expect_any_instance_of(subject).to receive(:run_all)

      subject.new.start
    end

    it 'do not run all tests if you pass run_all_on_start: false' do
      expect_any_instance_of(subject).to receive(:run_all).never

      subject.new(all_on_start: false).start
    end
  end

  describe 'stop' do
    it 'returns true' do
      expect(guard.stop).to eq true
    end
  end

  describe 'reload' do
    it 'returns true' do
      expect(guard.reload).to eq true
    end
  end

  describe 'run_on_modifications' do
    it 'is run through runner' do
      expect_any_instance_of(runner).to receive(:run_on_modifications)
        .and_return(true)

      guard.run_on_modifications
    end
  end

  describe 'run_on_additions' do
    let(:paths) { %w(path1 path2) }

    it 'is run through runner' do
      expect_any_instance_of(runner).to receive(:run_on_additions).with(paths)

      guard.run_on_additions(paths)
    end
  end

  describe 'run_on_removals' do
    let(:paths) { %w(path1 path2) }

    it 'runs run_on_removals via runner' do
      expect_any_instance_of(runner).to receive(:run_on_removals).with(paths)

      guard.run_on_removals(paths)
    end
  end

  describe 'halting and throwing on test failure' do
    it 'throws on failed test run' do
      stubbed_runner = double
      allow(stubbed_runner).to receive(:run).and_return(false)
      expect(stubbed_runner).to receive(:run_all)
      expect(stubbed_runner).to receive(:run_on_modifications)

      guard.runner = stubbed_runner

      expect { guard.run_all }.to throw_symbol :task_has_failed
      expect { guard.run_on_modifications }.to throw_symbol :task_has_failed
    end
  end
end


text:
/* Empty. Add your own CSS if you like */
.loginBackground{
  background-image: url('../img/shop.png');
}
.greenBackground{
  background-color: green;
}
.redBackground{
  background-color: red;
}
.dateDisplay{
  display: inline !important;
}


text:
Street = Struct.new(:id, :name, :latitude, :longitude) do
  def coordinates
    "#{latitude}, #{longitude}"
  end
end


text:
const libquick = require('../src/libquick');

var assert = require('assert');

const startCode = `static void BM_StringCreation(benchmark::State& state) {
  while (state.KeepRunning())
    std::string empty_string;
}
// Register the function as a benchmark
BENCHMARK(BM_StringCreation);

static void BM_StringCopy(benchmark::State& state) {
  std::string x = "hello";
  while (state.KeepRunning())
    std::string copy(x);
}
BENCHMARK(BM_StringCopy);
`;
const compiler = 'clang++-3.8';
const cppVersion = 17;
const optim = 1;

describe('id version 1', function () {
    it('should return a stable id', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: optim, cppVersion: cppVersion, protocolVersion: 1 }), '630d398cbd8e8c9d76bd3fb17ede3b77abe4302e');
    });
    it('should return different id on optim change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: "0", cppVersion: cppVersion, protocolVersion: 1 }), '1fc0b826d2aaf85cceb587ba9960638b0d36ed74');
    });
    it('should return different id on code change', function () {
        assert.equal(libquick.makeName({ code: 'hello', compiler: compiler, optim: optim, cppVersion: cppVersion, protocolVersion: 1 }), 'e7b57d1778e7b38505a3581971eb8435bced36ae');
    });
    it('should return different id on compiler change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: 'clang++-4.0', optim: optim, cppVersion: cppVersion, protocolVersion: 1 }), '5dee5060303d5a795b2154d76f87718f8aa7dbdf');
    });
    it('should return different id on cppVersion change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: optim, cppVersion: '98', protocolVersion: 1 }), '1aa1a9c43024dd01eb50f8b42832218f8d4299d9');
    });
})

describe('id version 2', function () {
    it('should return different id on protocolVersion change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: optim, cppVersion: cppVersion, isAnnotated: true, protocolVersion: 2 }), '79521ea600940e871ab08a602b355849706871de');
    });
    it('should return different id on optim change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: "0", cppVersion: cppVersion, isAnnotated: true, protocolVersion: 2 }), 'a60edbed043f9271eb8f2ac33e48ba836d33f6eb');
    });
    it('should return different id on code change', function () {
        assert.equal(libquick.makeName({ code: 'hello', compiler: compiler, optim: optim, cppVersion: cppVersion, isAnnotated: true, protocolVersion: 2 }), '878de5d52c012f1c6469af9273510412a3607ab8');
    });
    it('should return different id on compiler change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: 'clang++-4.0', optim: optim, cppVersion: cppVersion, isAnnotated: true, protocolVersion: 2 }), '02da5f0e209d2370f0546b5919c754d577a67af9');
    });
    it('should return different id on cppVersion change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: optim, cppVersion: '98', isAnnotated: true, protocolVersion: 2 }), 'c2c8ca7553725f561c05120804638d44318825f6');
    });
    it('should return different id on annotation change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: optim, cppVersion: cppVersion, isAnnotated: false, protocolVersion: 2 }), '5ccde87699ed42859925307950ec7ce2c2197ddc');
    });
})

describe('id version 3', function () {
    it('should return different id on protocolVersion change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: optim, cppVersion: cppVersion, isAnnotated: true, lib: 'gnu', protocolVersion: 3 }), 'a53c5b14856c39c55439218c10320bef4a49257c');
    });
    it('should return different id on optim change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: "0", cppVersion: cppVersion, isAnnotated: true, lib: 'gnu', protocolVersion: 3 }), '6b208fee183ba8884aa62a025f9e07308c6aa757');
    });
    it('should return different id on code change', function () {
        assert.equal(libquick.makeName({ code: 'hello', compiler: compiler, optim: optim, cppVersion: cppVersion, isAnnotated: true, lib: 'gnu', protocolVersion: 3 }), 'b1a20c68ed6ccf1f68c5cae88ca96b559d260dc4');
    });
    it('should return different id on compiler change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: 'clang++-4.0', optim: optim, cppVersion: cppVersion, isAnnotated: true, lib: 'gnu', protocolVersion: 3 }), '0b17798be35cd859202da65dee74301ae048cf2f');
    });
    it('should return different id on cppVersion change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: optim, cppVersion: '98', isAnnotated: true, lib: 'gnu', protocolVersion: 3 }), '77aff1de87af423078b44330ce0e002b53a8ae24');
    });
    it('should return different id on annotation change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: optim, cppVersion: cppVersion, isAnnotated: false, lib: 'gnu', protocolVersion: 3 }), '390203c96b49407964a8973bb51f5ee87156b045');
    });
    it('should return different id on lib change', function () {
        assert.equal(libquick.makeName({ code: startCode, compiler: compiler, optim: optim, cppVersion: cppVersion, isAnnotated: true, lib: 'llvm', protocolVersion: 3 }), '4bd647bcab41dd4b40022af2c88a86e0529611b0');
    });
})


text:
package io.machinecode.chainlink.rt.glassfish.command.config;

import com.sun.enterprise.config.serverbeans.Config;
import com.sun.enterprise.config.serverbeans.Domain;
import io.machinecode.chainlink.core.schema.xml.subsystem.XmlChainlinkSubSystem;
import io.machinecode.chainlink.rt.glassfish.command.BaseCommand;
import io.machinecode.chainlink.rt.glassfish.command.Code;
import io.machinecode.chainlink.rt.glassfish.schema.GlassfishDeployment;
import io.machinecode.chainlink.rt.glassfish.schema.GlassfishJobOperator;
import io.machinecode.chainlink.rt.glassfish.schema.GlassfishSubSystem;
import io.machinecode.chainlink.core.schema.xml.XmlSchema;
import org.glassfish.api.admin.AdminCommandContext;
import org.glassfish.api.admin.CommandLock;
import org.glassfish.api.admin.ExecuteOn;
import org.glassfish.api.admin.RestEndpoint;
import org.glassfish.api.admin.RestEndpoints;
import org.glassfish.api.admin.RuntimeType;
import org.glassfish.config.support.CommandTarget;
import org.glassfish.config.support.TargetType;
import org.glassfish.hk2.api.PerLookup;
import org.jvnet.hk2.annotations.Service;

import java.util.Collections;

/**
 * @author Brent Douglas
 * @since 1.0
 */
@Service(name="delete-chainlink")
@PerLookup
@CommandLock(CommandLock.LockType.NONE)
@ExecuteOn(value = {RuntimeType.DAS})
@TargetType(value = {CommandTarget.DAS, CommandTarget.STANDALONE_INSTANCE, CommandTarget.CLUSTER})
@RestEndpoints({
        @RestEndpoint(configBean = Domain.class,
                opType = RestEndpoint.OpType.DELETE,
                path = "delete-chainlink",
                description = "Delete Chainlink SubSystem"),
})
public class DeleteSubSystemCommand extends BaseCommand {

    @Override
    public void exec(final Config config, final AdminCommandContext context) throws Exception {
        final GlassfishSubSystem subSystem = config.getExtensionByType(GlassfishSubSystem.class);
        if (subSystem == null) {
            throw new Exception("Chainlink not configured."); //TODO Message
        }
        locked(subSystem, new DeleteSubSystem(context));
    }

    private static class DeleteSubSystem extends Code<GlassfishSubSystem> {

        final AdminCommandContext context;

        private DeleteSubSystem(final AdminCommandContext context) {
            this.context = context;
        }

        @Override
        public Object code(final GlassfishSubSystem subSystem) throws Exception {
            final XmlChainlinkSubSystem xml = XmlSchema.xmlSubSystem(subSystem);
            context.getActionReport().setMessage(XmlSchema.writeSubSystem(xml));
            subSystem.setRef(null);
            subSystem.setDeployments(Collections.<GlassfishDeployment>emptyList());
            subSystem.setConfigurationLoaders(Collections.<String>emptyList());
            subSystem.setJobOperators(Collections.<GlassfishJobOperator>emptyList());
            return null;
        }
    }
}


text:
class NameData
  attr_accessor :name
  def initialize
    @name = "Sabrina"
  end
end

class Greetings

  def initialize
    @my_name =  NameData.new.name
  end

  def hello
    puts "Hello " + @my_name + "! How wonderful to see you today."
  end
end

greet = Greetings.new
greet.hello

# Reflection

#Release 1
# What are these methods doing?

# Some of these methods are acting as storage for the information name, age, and occupation. In a lot of ways, this reminds me of hashes, more specifically, the storage of a key and a value. Here, we are using instance variables to do something very similar. The other methods serve as ways to alter the data.

# How are they modifying or returning the value of instance variables?

# The methods are returning or reassinging the values of the instance variables. We initialize with a specific set of data, but we are able to modify the data using methods that change what the variables ultimately return.

#Release 2

# What changed between the last release and this release?

# The biggest change between release one and release two is the introduction of attr_reader :age. This returns the value age without having the ability to change it, which is why we still have the method change_my_name=. Also, because of the inclusion of attr_reader :age, there is no longer a need for the what_is_age method. age is a method we can call in our profile maker because we have the attr_reader.

# What was replaced?

# attr_reader :age replaced the what_is_age method.

# Is this code simpler than the last?

# Yes, I would say that this code is simpler, if for no other reason than it has fewer lines of code. The age method is doing in one line of code what the what_is_age method was doing in three lines of code.

#Release 3

# What changed between the last release and this release?

# Much like in release 2, the biggest change here is the inclusion of attr_writer.

# What was replaced?

# attr_writer replaces the change_my_age method. We no longer need this method because we can rewrite the age by using the age method we have implemented here. It accepts arguments just like a normal method would.

# Is this code simpler than the last?

# Yes, this code is simpler. We have condensed two several line methods into two lines of code, the attr_writer and the attr_reader, which can store, return, and replace the age.

# Release 6

# What is a reader method?

# A reader method accepts an element (like a name, age, or occupation), and stores that information in a method. This way, say if you had a attr_reader :name, you could call the method .name and it would return the value that was assigned to name.

# What is a writer method?

# A writer method can change the value stored in the method of the same name. Much like you can call the value of attr_reader :name with .name, you can also change the value of .name if you have attr_writer :name

# What do the attr methods do for you?

# This cleans up the code, elminiating the need to include methods that return or change values.

# Should you always use an accessor to cover your bases? Why or why not?

# No. In the case of the challenge here, I used just attr_reader because there was no need to ever change the name, or at least that was not specified in the challenge. You should think about what you want attr to do, and then use it accordingly.

# What is confusing to you about these methods?

# I am still not entirely sure how classes work. Once I have completed a challenge, everything makes sense, but sometimes getting there can be a bit of a hassle. For instance, it took awhile to synthesize what the earlier releases of the challenges had to do with this challenge, when the provided examples didn't use attr at all. It was very confusing. I probably just need more practice.


text:
namespace display {

// PlatformScreenOzone provides the necessary functionality to configure all
// attached physical displays on the ozone platform.
class PlatformScreenOzone
    : public PlatformScreen,
      public ui::DisplayConfigurator::Observer,
      public ui::DisplayConfigurator::StateController,
      public service_manager::InterfaceFactory<mojom::DisplayController>,
      public service_manager::InterfaceFactory<mojom::TestDisplayController>,
      public mojom::DisplayController,
      public mojom::TestDisplayController {
 public:
  PlatformScreenOzone();
  ~PlatformScreenOzone() override;

  // PlatformScreen:
  void AddInterfaces(service_manager::InterfaceRegistry* registry) override;
  void Init(PlatformScreenDelegate* delegate) override;
  void RequestCloseDisplay(int64_t display_id) override;
  int64_t GetPrimaryDisplayId() const override;

  // mojom::TestDisplayController:
  void ToggleAddRemoveDisplay() override;
  void ToggleDisplayResolution() override;

  // mojom::DisplayController:
  void SwapPrimaryDisplay() override;
  void SetDisplayWorkArea(int64_t display_id,
                          const gfx::Size& size,
                          const gfx::Insets& insets) override;

 private:
  // TODO(kylechar): This struct is just temporary until we migrate
  // DisplayManager code out of ash so it can be used here.
  struct DisplayInfo {
    DisplayInfo();
    DisplayInfo(const DisplayInfo& other);
    ~DisplayInfo();

    int64_t id = Display::kInvalidDisplayID;
    // Information about display viewport.
    ViewportMetrics metrics;
    // Last insets received from WM.
    gfx::Insets last_work_area_insets;

    // Temporary hack to allow changing display resolution.
    std::vector<gfx::Size> supported_sizes;
    gfx::Size requested_size;

    // The display bounds have been modified and delegate should be updated.
    bool modified = false;
    // The display has been removed and delegate should be updated.
    bool removed = false;
  };
  using CachedDisplayIterator = std::vector<DisplayInfo>::iterator;

  // Processes list of display snapshots and sets |removed| on any displays that
  // have been removed. Updates |primary_display_id_| if the primary display was
  // removed. Does not remove displays from |cached_displays_| or send updates
  // to delegate.
  void ProcessRemovedDisplays(
      const ui::DisplayConfigurator::DisplayStateList& snapshots);

  // Processes list of display snapshots and updates the bounds of any displays
  // in |cached_displays_| that have changed size. Does not send updates to
  // delegate.
  void ProcessModifiedDisplays(
      const ui::DisplayConfigurator::DisplayStateList& snapshots);

  // Looks at |cached_displays_| for modified or removed displays. Also updates
  // display bounds in response to modified or removed displays. Sends updates
  // to the delegate when appropriate by calling OnDisplayModified() or
  // OnDisplayRemoved(). Makes at most one call to delegate per display.
  //
  // Usually used after ProcessRemovedDisplays() and ProcessModifiedDisplays().
  void UpdateCachedDisplays();

  // Processes list of display snapshots and adds any new displays to
  // |cached_displays_|. Updates delegate by calling OnDisplayAdded().
  void AddNewDisplays(
      const ui::DisplayConfigurator::DisplayStateList& snapshots);

  // Returns an iterator to the cached display with |display_id| or an end
  // iterator if there is no display with that id.
  CachedDisplayIterator GetCachedDisplayIterator(int64_t display_id);

  // Converts |snapshot| into ViewportMetrics.
  ViewportMetrics MetricsFromSnapshot(const ui::DisplaySnapshot& snapshot,
                                      const gfx::Point& origin);

  // ui::DisplayConfigurator::Observer:
  void OnDisplayModeChanged(
      const ui::DisplayConfigurator::DisplayStateList& displays) override;
  void OnDisplayModeChangeFailed(
      const ui::DisplayConfigurator::DisplayStateList& displays,
      ui::MultipleDisplayState failed_new_state) override;

  // ui::DisplayConfigurator::StateController:
  ui::MultipleDisplayState GetStateForDisplayIds(
      const ui::DisplayConfigurator::DisplayStateList& display_states)
      const override;
  bool GetResolutionForDisplayId(int64_t display_id,
                                 gfx::Size* size) const override;

  // mojo::InterfaceFactory<mojom::DisplayController>:
  void Create(const service_manager::Identity& remote_identity,
              mojom::DisplayControllerRequest request) override;

  // mojo::InterfaceFactory<mojom::TestDisplayController>:
  void Create(const service_manager::Identity& remote_identity,
              mojom::TestDisplayControllerRequest request) override;

  ui::DisplayConfigurator display_configurator_;
  PlatformScreenDelegate* delegate_ = nullptr;

  // If not null it provides a way to modify the display state when running off
  // device (eg. running mustash on Linux).
  FakeDisplayController* fake_display_controller_ = nullptr;

  // Tracks if we've made a display configuration change and want to wait for
  // the display configuration to update before making further changes.
  bool wait_for_display_config_update_ = false;

  // TODO(kylechar): These values can/should be replaced by DisplayLayout.
  int64_t primary_display_id_ = display::Display::kInvalidDisplayID;
  std::vector<DisplayInfo> cached_displays_;
  gfx::Point next_display_origin_;

  mojo::BindingSet<mojom::DisplayController> controller_bindings_;
  mojo::BindingSet<mojom::TestDisplayController> test_bindings_;

  DISALLOW_COPY_AND_ASSIGN(PlatformScreenOzone);
};

}  // namespace display

#endif  // SERVICES_UI_DISPLAY_PLATFORM_SCREEN_OZONE_H_


text:
package com.example.tests;

import static org.junit.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

public class AddressBookBaseMethods {

	protected static WebDriver driver;
	private static String baseUrl;
	private static boolean acceptNextAlert = true;
	private static StringBuffer verificationErrors = new StringBuffer();

	@BeforeTest
	public void setUp() throws Exception {
		driver = new FirefoxDriver();
	    baseUrl = "http://localhost/";
	    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	  }

	@AfterTest
	public void tearDown() throws Exception {
	    driver.quit();
	    String verificationErrorString = verificationErrors.toString();
	    if (!"".equals(verificationErrorString))
	    {
	      fail(verificationErrorString);
	    }
	  }

	protected void openHomePage() {
		driver.get(baseUrl + "/addressbookv4.1.4/");
	  }

	protected void gotoHomePage() {
		driver.findElement(By.linkText("home page")).click();
	  }

}


text:
import ray
from ray._private import test_utils

@test_utils.wait_for_stdout(
    strings_to_match=["Adding 1 node(s) of type small-group."], timeout_s=15
)
def main():
    """Submits CPU request.
    Wait 15 sec for autoscaler scale-up event to get emitted to stdout.

    The autoscaler update interval is 5 sec, so it should be enough to wait 5 seconds.
    An extra ten seconds are added to the timeout as a generous buffer against
    flakiness.
    """
    ray.autoscaler.sdk.request_resources(num_cpus=2)

if __name__ == "__main__":
    ray.init("auto")
    main()


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<link href="https://fonts.googleapis.com/css?family=Roboto|Montserrat" rel="stylesheet">
<title>Phoneme Classifier Demo</title>

Phoneme Classifier Demo

Pascal Getreuer, 2020-08-07

Select input

Test sound

<audio id="test_audio" src="test_audio.wav" controls="controls"
onplay="SelectInputSource(0)" style="width:300px; height:50px">
 </audio>

Microphone

<button type="button" onclick="SelectInputSource(1)" style="padding:0 0.3em 0 0.3em; width:50px;
height:50px; border-radius:2em; background: #f3f3f3 url('microphone.svg') no-repeat center center">
</button>

<canvas id="canvas" width="800" height="640" style="z-index:-1">
  Your browser does not support the canvas element.
</canvas>

silence

ɑ

æ

ʌ

ɔ

aʊ

aI

ɛ

ɜ˞

eI

I

i

oʊ

ɔI

ʊ

u

j

ɹ

l

w

h

m

n

ŋ

v

f

ð

θ

b

p

g

k

d

t

dʒ

tʃ

z

s

ʒ

ʃ

Vowel

Semivowel

Nasal

Stop

Sibilant

This is a demo of the
audio-to-tactile
project. It visualizes the scores from a simple phoneme classifier network, a
network with low latency in order to synchronize with vision. This network is
potentially useful to drive tactile cues to complement lip reading.

In the visualization above, each row displays scores for one phoneme,
labeled in IPA.
The network runs on an input window of 40ms with a hop size of 8ms.


text:
package com.tle.web.qti.viewer.questions.renderer.interaction.unsupported;

import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import com.tle.web.qti.viewer.QtiViewerContext;
import com.tle.web.qti.viewer.questions.renderer.base.BlockInteractionRenderer;
import com.tle.web.qti.viewer.questions.renderer.unsupported.UnsupportedQuestionException;
import com.tle.web.sections.render.SectionRenderable;
import uk.ac.ed.ph.jqtiplus.node.item.interaction.MatchInteraction;

/** NOT SUPPORTED */
public class MatchInteractionRenderer extends BlockInteractionRenderer {
  @AssistedInject
  protected MatchInteractionRenderer(
      @Assisted MatchInteraction model, @Assisted QtiViewerContext context) {
    super(model, context);
  }

  @Override
  protected SectionRenderable createTopRenderable() {
    throw new UnsupportedQuestionException("matchInteraction");
  }
}


text:
<Alloy>
	<Collection src="Fugitives"></Collection>
	<Tab title="Captured" id="tabCaptured">
		<Window title="Captured">
			<TableView id="table" dataCollection="Fugitives" dataFilter="filtrar">
				<Require src="FugitiveRow" />
			</TableView>
		</Window>
	</Tab>
</Alloy>


text:
from atomic import *

__all__ = filter(lambda s:not s.startswith('_'),dir())


text: Cheapo Hardware IR tracker system


text:
    module.exports = header: 'Kafka Client Check', handler: ({options}) ->

## Register

      @registry.register 'ranger_policy', '@rybajs/metal/ranger/actions/ranger_policy'

## Wait

      @call once: true, 'masson/core/krb5_client/wait', options.wait_krb5_client
      @call once: true, '@rybajs/metal/zookeeper/server/wait', options.wait_zookeeper_server
      @call once: true, '@rybajs/metal/kafka/broker/wait', options.wait_kafka_broker

## Add Ranger Policy

      @call
        header: 'Ranger'
        if: !!options.ranger_admin
      , ->
        @call '@rybajs/metal/ranger/admin/wait', once: true, options.wait_ranger_admin
        topics = options.protocols.map (prot) =>
          "check-#{options.hostname}-client-#{prot.toLowerCase().split('_').join('-')}-topic"
        users = ["#{options.test.user.name}", options.superusers...]
        users.push 'ANONYMOUS' if ('PLAINTEXT' in options.protocols) or ('SSL' in options.protocols)
        @wait.execute
          header: 'Wait Service'
          cmd: """
          curl --fail -H "Content-Type: application/json" -k -X GET \
            -u #{options.ranger_admin.username}:#{options.ranger_admin.password} \
            "#{options.ranger_install['POLICY_MGR_URL']}/service/public/v2/api/service/name/#{options.ranger_install['REPOSITORY_NAME']}"
          """
          code_skipped: [1,7,22] #22 is for 404 not found,7 is for not connected to host
        @ranger_policy
          header: 'Create Policy'
          username: options.ranger_admin.username
          password: options.ranger_admin.password
          url: options.ranger_install['POLICY_MGR_URL']
          policy:
            service: "#{options.ranger_install['REPOSITORY_NAME']}"
            name: "test-ryba-client-#{options.hostname}"
            description: "Policy for ryba kafka Client test"
            isAuditEnabled: true
            resources:
              topic:
                values: topics
                isExcludes: false
                isRecursive: false
            policyItems: [
                "accesses": [
                  'type': 'publish'
                  'isAllowed': true
                ,
                  'type': 'consume'
                  'isAllowed': true
                ,
                  'type': 'configure'
                  'isAllowed': true
                ,
                  'type': 'describe'
                  'isAllowed': true
                ,
                  'type': 'create'
                  'isAllowed': true
                ,
                  'type': 'delete'
                  'isAllowed': true
                ,
                  'type': 'kafka_admin'
                  'isAllowed': true
                ],
                'users': users
                'groups': []
                'conditions': []
                'delegateAdmin': false
              ]
        @wait
          time: 10000
          if: -> @status -1

## PLAINTEXT Protocol

Check Message by writing to a test topic on the PLAINTEXT channel.
Since new API (0.8-0.9) and security features, kafka broker are able to deal with
multiple channel with different protocols. For its internal functionment, it associates
an not authenticated user to ANONYMOUS name when client communicates on PLAINTEXT-SSL
protocols.

      @call
        header: 'PLAINTEXT'
        if: 'PLAINTEXT' in options.protocols
        retry: 3
      , ->
        test_topic = "check-#{options.hostname}-client-plaintext-topic"
        @system.execute
          if: options.env['KAFKA_KERBEROS_PARAMS']?
          cmd: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-topics.sh --create \
            --zookeeper #{options.consumer.config['zookeeper.connect']} \
            --partitions #{Math.min(options.brokers['PLAINTEXT'].length-1,1)} \
            --replication-factor #{Math.min(options.brokers['PLAINTEXT'].length-1,0)} \
            --topic #{test_topic}
          """
          unless_exec: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-topics.sh --list \
            --zookeeper #{options.consumer.config['zookeeper.connect']} \
          | grep #{test_topic}
          """
        @system.execute
          unless: options.env['KAFKA_KERBEROS_PARAMS']? or !!options.ranger_admin
          cmd: """
          /usr/hdp/current/kafka-broker/bin/kafka-topics.sh --create \
            --zookeeper #{options.consumer.config['zookeeper.connect']} \
            --partitions #{Math.min(options.brokers['PLAINTEXT'].length-1,1)} \
            --replication-factor #{Math.min(options.brokers['PLAINTEXT'].length-1,0)} \
            --topic #{test_topic}
          """
          unless_exec: """
          /usr/hdp/current/kafka-broker/bin/kafka-topics.sh --list \
            --zookeeper #{options.consumer.config['zookeeper.connect']} \
          | grep #{test_topic}
          """
        @system.execute
          if:  options.env['KAFKA_KERBEROS_PARAMS']?
          cmd: mkcmd.kafka options.admin, """
          (
            sleep 1
            /usr/hdp/current/kafka-broker/bin/kafka-acls.sh \
              --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
              --add \
              --allow-principal User:ANONYMOUS \
              --operation Read \
              --operation Write \
              --topic #{test_topic}
          )&
          (
          /usr/hdp/current/kafka-broker/bin/kafka-acls.sh \
            --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
            --add \
            --allow-principal User:ANONYMOUS \
            --consumer \
            --producer \
            --group #{options.consumer.config['group.id']} \
            --topic #{test_topic}
          )
          """
          unless_exec: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-acls.sh --list \
            --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
            --topic #{test_topic} \
          | grep 'User:ANONYMOUS has Allow permission for operations: Write from hosts: *'
          """
        @system.execute
          unless:  options.env['KAFKA_KERBEROS_PARAMS']? or !!options.ranger_admin
          cmd: """
          (
            sleep 1
            /usr/hdp/current/kafka-broker/bin/kafka-acls.sh \
              --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
              --add --allow-principal User:ANONYMOUS \
              --operation Read \
              --operation Write \
              --topic #{test_topic}
          )&
          (
          /usr/hdp/current/kafka-broker/bin/kafka-acls.sh \
            --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
            --add \
            --allow-principal User:ANONYMOUS \
            --consumer \
            --producer \
            --group #{options.consumer.config['group.id']} \
            --topic #{test_topic}
          )
          """
          unless_exec: """
          /usr/hdp/current/kafka-broker/bin/kafka-acls.sh --list \
            --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
            --topic #{test_topic} \
          | grep 'User:ANONYMOUS has Allow permission for operations: Write from hosts: *'
          """
        @system.execute
          cmd: """
          (
            sleep 5
            echo 'hello #{options.hostname}' | /usr/hdp/current/kafka-broker/bin/kafka-console-producer.sh \
              --producer-property security.protocol=PLAINTEXT \
              --broker-list #{options.brokers['PLAINTEXT'].join ','} \
              --security-protocol PLAINTEXT \
              --producer.config #{options.conf_dir}/producer.properties \
              --topic #{test_topic}
          )&
          /usr/hdp/current/kafka-broker/bin/kafka-console-consumer.sh \
            --delete-consumer-offsets \
            --bootstrap-server #{options.brokers['PLAINTEXT'].join ','} \
            --topic #{test_topic} \
            --security-protocol PLAINTEXT \
            --property security.protocol=PLAINTEXT \
            --consumer.config #{options.conf_dir}/consumer.properties \
            --from-beginning \
            --max-messages 1 \
          | grep 'hello #{options.hostname}'
          """

## SSL Protocol

Check Message by writing to a test topic on the SSL channel. Truststore location
and password given to line command because if executed before producer install
'/etc/kafka/conf/producer.properties' might be empty.

      @call
        header: 'SSL'
        retry: 3
        if: 'SSL' in options.protocols
      , ->
        test_topic = "check-#{options.hostname}-client-ssl-topic"
        @system.execute
          cmd: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-topics.sh --create \
            --zookeeper #{options.consumer.config['zookeeper.connect']} \
            --partitions #{Math.min(options.brokers['SSL'].length-1,1)} \
            --replication-factor #{Math.min(options.brokers['SSL'].length-1,0)} \
            --topic #{test_topic}
          """
          unless_exec: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-topics.sh --list \
            --zookeeper #{options.consumer.config['zookeeper.connect']} \
          | grep #{test_topic}
          """
        @system.execute
          unless: !!options.ranger_admin
          cmd: mkcmd.kafka options.admin, """
          (
            sleep 1
            /usr/hdp/current/kafka-broker/bin/kafka-acls.sh \
              --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
              --add --allow-principal User:ANONYMOUS \
              --operation Read \
              --operation Write \
              --topic #{test_topic}
          )&
          (
          /usr/hdp/current/kafka-broker/bin/kafka-acls.sh \
            --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
            --add \
            --allow-principal User:ANONYMOUS \
            --consumer \
            --producer \
            --group #{options.consumer.config['group.id']} \
            --topic #{test_topic}
          )
          """
          unless_exec: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-acls.sh --list \
            --authorizer-properties \
            zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
            --topic #{test_topic} \
          | grep 'User:ANONYMOUS has Allow permission for operations: Write from hosts: *'
          """
        @system.execute
          cmd: """
          (
            sleep 5
            echo 'hello #{options.hostname}' | /usr/hdp/current/kafka-broker/bin/kafka-console-producer.sh \
              --producer-property security.protocol=SSL \
              --broker-list #{options.brokers['SSL'].join ','} \
              --security-protocol SSL \
              --producer-property ssl.truststore.location=#{options.config['ssl.truststore.location']} \
              --producer-property ssl.truststore.password=#{options.config['ssl.truststore.password']} \
              --producer.config #{options.conf_dir}/producer.properties \
              --topic #{test_topic}
          )&
          /usr/hdp/current/kafka-broker/bin/kafka-console-consumer.sh \
            --delete-consumer-offsets \
            --bootstrap-server #{options.brokers['SSL'].join ','} \
            --topic #{test_topic} \
            --security-protocol SSL \
            --property security.protocol=SSL \
            --property ssl.truststore.location=#{options.config['ssl.truststore.location']} \
            --property ssl.truststore.password=#{options.config['ssl.truststore.password']} \
            --consumer.config #{options.conf_dir}/consumer.properties \
            --from-beginning \
            --max-messages 1 \
          | grep 'hello #{options.hostname}'
          """

## SASL_PLAINTEXT Protocol

Check Message by writing to a test topic on the SASL_PLAINTEXT channel.

      @call
        header: 'SASL_PLAINTEXT'
        retry: 3
        if: 'SASL_PLAINTEXT' in options.protocols
      , ->
        test_topic = "check-#{options.hostname}-client-sasl-plaintext-topic"
        @system.execute
          cmd: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-topics.sh --create \
            --zookeeper #{options.consumer.config['zookeeper.connect']} \
            --partitions #{Math.min(options.brokers['SASL_PLAINTEXT'].length-1,1)} \
            --replication-factor #{Math.min(options.brokers['SASL_PLAINTEXT'].length-1,0)} \
            --topic #{test_topic}
          """
          unless_exec: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-topics.sh --list \
            --zookeeper #{options.consumer.config['zookeeper.connect']} \
          | grep #{test_topic}
          """
        @system.execute
          unless: !!options.ranger_admin
          cmd: mkcmd.kafka options.admin, """
          (
            sleep 1
            /usr/hdp/current/kafka-broker/bin/kafka-acls.sh \
              --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
              --add \
              --allow-principal User:#{options.test.user.name} \
              --operation Read \
              --operation Write \
              --topic #{test_topic}
          )&
          (
          /usr/hdp/current/kafka-broker/bin/kafka-acls.sh \
            --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
            --add \
            --allow-principal User:#{options.test.user.name} \
            --consumer --group #{options.config['group.id']} \
            --topic #{test_topic}
          )
          """
          unless_exec: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-acls.sh  --list \
            --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
            --topic #{test_topic} \
          | grep 'User:#{options.test.user.name} has Allow permission for operations: Write from hosts: *'
          """
        @system.execute
          cmd:  mkcmd.test options.test_krb5_user, """
          (
            sleep 5
            echo 'hello #{options.hostname}' | /usr/hdp/current/kafka-broker/bin/kafka-console-producer.sh \
              --producer-property security.protocol=SASL_PLAINTEXT \
              --broker-list #{options.brokers['SASL_PLAINTEXT'].join ','} \
              --security-protocol SASL_PLAINTEXT \
              --producer.config #{options.conf_dir}/producer.properties \
              --topic #{test_topic}
          )&
          /usr/hdp/current/kafka-broker/bin/kafka-console-consumer.sh \
            --delete-consumer-offsets \
            --bootstrap-server #{options.brokers['SASL_PLAINTEXT'].join ','} \
            --topic #{test_topic} \
            --security-protocol SASL_PLAINTEXT \
            --consumer.config #{options.conf_dir}/consumer.properties \
            --from-beginning \
            --max-messages 1 \
          | grep 'hello #{options.hostname}'
          """

## SASL_SSL Protocol

Check Message by writing to a test topic on the SASL_SSL channel.
Trustore location and password given to line command because if executed before producer install
'/etc/kafka/conf/producer.properties' might be empty.

      @call
        header: 'SASL_SSL'
        retry: 3
        if: 'SASL_SSL' in options.protocols
      , ->
        test_topic = "check-#{options.hostname}-client-sasl-ssl-topic"
        @system.execute
          cmd: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-topics.sh --create \
            --zookeeper #{options.consumer.config['zookeeper.connect']} \
            --partitions #{Math.min(options.brokers['SASL_SSL'].length-1,1)} \
            --replication-factor #{Math.min(options.brokers['SASL_SSL'].length-1,0)} \
            --topic #{test_topic}
          """
          unless_exec: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-topics.sh \
            --list \
            --zookeeper #{options.consumer.config['zookeeper.connect']} \
          | grep #{test_topic}
          """
        @system.execute
          unless: !!options.ranger_admin
          cmd: mkcmd.kafka options.admin, """
          (
            sleep 1
            /usr/hdp/current/kafka-broker/bin/kafka-acls.sh \
              --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
              --add \
              --allow-principal User:#{options.test.user.name} \
              --operation Read \
              --operation Write \
              --topic #{test_topic}
          )&
          (
          /usr/hdp/current/kafka-broker/bin/kafka-acls.sh \
            --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
            --add \
            --allow-principal User:#{options.test.user.name} \
            --consumer \
            --producer \
            --group #{options.consumer.config['group.id']} \
            --topic #{test_topic}
          )
          """
          unless_exec: mkcmd.kafka options.admin, """
          /usr/hdp/current/kafka-broker/bin/kafka-acls.sh  --list \
            --authorizer-properties zookeeper.connect=#{options.consumer.config['zookeeper.connect']} \
            --topic #{test_topic} \
          | grep 'User:#{options.test.user.name} has Allow permission for operations: Write from hosts: *'
          """
        @system.execute
          cmd:  mkcmd.test options.test_krb5_user, """
          (
            sleep 5
            echo 'hello #{options.hostname}' | /usr/hdp/current/kafka-broker/bin/kafka-console-producer.sh \
              --producer-property security.protocol=SASL_SSL \
              --broker-list #{options.brokers['SASL_SSL'].join ','} \
              --security-protocol SASL_SSL \
              --producer-property ssl.truststore.location=#{options.config['ssl.truststore.location']} \
              --producer-property ssl.truststore.password=#{options.config['ssl.truststore.password']} \
              --producer.config #{options.conf_dir}/producer.properties \
              --topic #{test_topic}
          )&
          /usr/hdp/current/kafka-broker/bin/kafka-console-consumer.sh \
            --delete-consumer-offsets \
            --bootstrap-server #{options.brokers['SASL_SSL'].join ','} \
            --topic #{test_topic} \
            --security-protocol SASL_SSL \
            --property security.protocol=SASL_SSL \
            --property ssl.truststore.location=#{options.config['ssl.truststore.location']} \
            --property ssl.truststore.password=#{options.config['ssl.truststore.password']} \
            --consumer.config #{options.conf_dir}/consumer.properties \
            --from-beginning \
            --max-messages 1 \
          | grep 'hello #{options.hostname}'
          """

## Dependencies

    mkcmd = require '../../lib/mkcmd'


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

<title>ExpenseRepeiptTest</title>
<meta name="date" content="2015-04-07">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

ca.ualberta.cmput301w15t13.test

Class ExpenseRepeiptTest

java.lang.Object

<any>

ca.ualberta.cmput301w15t13.test.ExpenseRepeiptTest

public class ExpenseRepeiptTest
extends <any>

This test suite tests the functionality of the applications
 photographic receipt functionality

 User Stories Tested:
 US06.01.01, US06.04.01, US06.03.01

 General use case can be found on the wiki at
 https://github.com/CMPUT301W15T13/TravelPlanner/wiki/User-Stories-and-Requirements

 Not implemented for Project Part 4, should fail

Constructor Summary

Constructors

Constructor and Description

ExpenseRepeiptTest()

Method Summary

Methods

Modifier and Type
Method and Description

void
testAddBitmap()

Part of use case F1
 Test that you can add a bitmap to a claim
 Tests US06.01.01
 https://github.com/CMPUT301W15T13/TravelPlanner/issues/61

void
testLargeBitmap()

Part of Use Case F1
 Test that you bitmaps are compressed before they're stored
 Tests US06.04.01
 https://github.com/CMPUT301W15T13/TravelPlanner/issues/64

void
testRemoveBitmap()

Use case F3
 Test that you can delete a bitmap from a claim
 Tests US06.03.01
 https://github.com/CMPUT301W15T13/TravelPlanner/issues/63

void
testViewPhoto()

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ExpenseRepeiptTest

public ExpenseRepeiptTest()

Method Detail

testAddBitmap

public void testAddBitmap()
                   throws InvalidDateException,
                          EmptyFieldException,
                          InvalidUserPermissionException

Part of use case F1
 Test that you can add a bitmap to a claim
 Tests US06.01.01
 https://github.com/CMPUT301W15T13/TravelPlanner/issues/61

Throws:

EmptyFieldException

InvalidNameException

InvalidDateException

InvalidUserPermissionException

testLargeBitmap

public void testLargeBitmap()
                     throws InvalidDateException,
                            EmptyFieldException,
                            InvalidUserPermissionException

Part of Use Case F1
 Test that you bitmaps are compressed before they're stored
 Tests US06.04.01
 https://github.com/CMPUT301W15T13/TravelPlanner/issues/64

Throws:

EmptyFieldException

InvalidNameException

InvalidDateException

InvalidUserPermissionException

testRemoveBitmap

public void testRemoveBitmap()
                      throws InvalidDateException,
                             EmptyFieldException,
                             InvalidUserPermissionException

Use case F3
 Test that you can delete a bitmap from a claim
 Tests US06.03.01
 https://github.com/CMPUT301W15T13/TravelPlanner/issues/63

Throws:

EmptyFieldException

InvalidNameException

InvalidDateException

InvalidUserPermissionException

testViewPhoto

public void testViewPhoto()
                   throws EmptyFieldException,
                          InvalidDateException

Throws:

EmptyFieldException

InvalidDateException

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD


text:
package testCases.http;

/**
 * @author v.chibrikov
 */
public class HttpAnswer {
    private final String page;
    private final int code;

    public HttpAnswer(String page, int code) {
        this.page = page;
        this.code = code;
    }

    public String getPage() {
        return page;
    }

    public int getCode() {
        return code;
    }
}


text:
<?php
namespace MockObject;

use Ginger\Model\Source\SourceLoaderInterface;

class SourceLoader implements SourceLoaderInterface
{
    protected $registeredSources = array();

    public function getSource($sourceId)
    {
        if ($sourceId == 1) {
            return new Source(1, "testsource", "/testsource", "MockObject");
        }
    }

    public function registerSource($moduleName, $sourceName, $sourceClass, $sourceLink)
    {
        $this->registeredSources[] = array(
            'module' => $moduleName,
            'name' => $sourceName,
            'class' => $sourceClass,
            'link' => $sourceLink
        );
    }

    public function getSources()
    {
        return $this->registeredSources;
    }

    public function unregisterSource($sourceId)
    {

    }

    public function listSources()
    {
        return array($this->getSource(1));
    }
}


text:
/*
 * xtiff.c
 *
 * Extended TIFF Directory GEO Tag Support.
 *
 *  You may use this file as a template to add your own
 *  extended tags to the library. Only the parts of the code
 *  marked with "XXX" require modification.
 *
 *  Author: Niles D. Ritter
 *
 *  Revisions:
 *    18 Sep 1995   -- Deprecated Integraph Matrix tag with new one.
 *                     Backward compatible support provided.  --NDR.
 */

#include "xtiffio.h"
#include <stdio.h>
#include "cpl_serv.h"

/*  Tiff info structure.
 *
 *     Entry format:
 *        { TAGNUMBER, ReadCount, WriteCount, DataType, FIELDNUM,
 *          OkToChange, PassDirCountOnSet, AsciiName }
 *
 *     For ReadCount, WriteCount, -1 = unknown.
 */

static const TIFFFieldInfo xtiffFieldInfo[] = {

  /* XXX Insert Your tags here */
    { TIFFTAG_GEOPIXELSCALE,	-1,-1, TIFF_DOUBLE,	FIELD_CUSTOM,
      TRUE,	TRUE,	"GeoPixelScale" },
    { TIFFTAG_INTERGRAPH_MATRIX,-1,-1, TIFF_DOUBLE,	FIELD_CUSTOM,
      TRUE,	TRUE,	"Intergraph TransformationMatrix" },
    { TIFFTAG_GEOTRANSMATRIX,	-1,-1, TIFF_DOUBLE,	FIELD_CUSTOM,
      TRUE,	TRUE,	"GeoTransformationMatrix" },
    { TIFFTAG_GEOTIEPOINTS,	-1,-1, TIFF_DOUBLE,	FIELD_CUSTOM,
      TRUE,	TRUE,	"GeoTiePoints" },
    { TIFFTAG_GEOKEYDIRECTORY,-1,-1, TIFF_SHORT,	FIELD_CUSTOM,
      TRUE,	TRUE,	"GeoKeyDirectory" },
    { TIFFTAG_GEODOUBLEPARAMS,	-1,-1, TIFF_DOUBLE,	FIELD_CUSTOM,
      TRUE,	TRUE,	"GeoDoubleParams" },
    { TIFFTAG_GEOASCIIPARAMS,	-1,-1, TIFF_ASCII,	FIELD_CUSTOM,
      TRUE,	FALSE,	"GeoASCIIParams" },
#ifdef JPL_TAG_SUPPORT
    { TIFFTAG_JPL_CARTO_IFD,	 1, 1, TIFF_LONG,	FIELD_CUSTOM,
      TRUE,	TRUE,	"JPL Carto IFD offset" },  /** Don't use this! **/
#endif
};

#define	N(a)	(sizeof (a) / sizeof (a[0]))
static void _XTIFFLocalDefaultDirectory(TIFF *tif)
{
    /* Install the extended Tag field info */
    TIFFMergeFieldInfo(tif, xtiffFieldInfo, N(xtiffFieldInfo));
}

/**********************************************************************
 *    Nothing below this line should need to be changed.
 **********************************************************************/

static TIFFExtendProc _ParentExtender;

/*
 *  This is the callback procedure, and is
 *  called by the DefaultDirectory method
 *  every time a new TIFF directory is opened.
 */

static void
_XTIFFDefaultDirectory(TIFF *tif)
{
    /* set up our own defaults */
    _XTIFFLocalDefaultDirectory(tif);

    /* Since an XTIFF client module may have overridden
     * the default directory method, we call it now to
     * allow it to set up the rest of its own methods.
     */

    if (_ParentExtender)
        (*_ParentExtender)(tif);
}

/**
Registers an extension with libtiff for adding GeoTIFF tags.
After this one-time intialization, any TIFF open function may be called in
the usual manner to create a TIFF file that compatible with libgeotiff.
The XTIFF open functions are simply for convenience: they call this
and then pass their parameters on to the appropriate TIFF open function.

This function may be called any number of times safely, since it will
only register the extension the first time it is called.
**/

void XTIFFInitialize(void)
{
    static int first_time=1;

    if (! first_time) return; /* Been there. Done that. */
    first_time = 0;

    /* Grab the inherited method and install */
    _ParentExtender = TIFFSetTagExtender(_XTIFFDefaultDirectory);
}

/**
 * GeoTIFF compatible TIFF file open function.
 *
 * @param name The filename of a TIFF file to open.
 * @param mode The open mode ("r", "w" or "a").
 *
 * @return a TIFF * for the file, or NULL if the open failed.
 *
This function is used to open GeoTIFF files instead of TIFFOpen() from
libtiff.  Internally it calls TIFFOpen(), but sets up some extra hooks
so that GeoTIFF tags can be extracted from the file.  If XTIFFOpen() isn't
used, GTIFNew() won't work properly.  Files opened
with XTIFFOpen() should be closed with XTIFFClose().

The name of the file to be opened should be passed as name, and an
opening mode ("r", "w" or "a") acceptable to TIFFOpen() should be passed as the
mode.

If XTIFFOpen() fails it will return NULL.  Otherwise, normal TIFFOpen()
error reporting steps will have already taken place.

 */

TIFF*
XTIFFOpen(const char* name, const char* mode)
{
    TIFF *tif;

    /* Set up the callback */
    XTIFFInitialize();

    /* Open the file; the callback will set everything up
     */
    tif = TIFFOpen(name, mode);
    if (!tif) return tif;

    return tif;
}

TIFF*
XTIFFFdOpen(int fd, const char* name, const char* mode)
{
    TIFF *tif;

    /* Set up the callback */
    XTIFFInitialize();

    /* Open the file; the callback will set everything up
     */
    tif = TIFFFdOpen(fd, name, mode);
    if (!tif) return tif;

    return tif;
}

TIFF*
XTIFFClientOpen(const char* name, const char* mode, thandle_t thehandle,
	    TIFFReadWriteProc RWProc, TIFFReadWriteProc RWProc2,
	    TIFFSeekProc SProc, TIFFCloseProc CProc,
	    TIFFSizeProc SzProc,
	    TIFFMapFileProc MFProvc, TIFFUnmapFileProc UMFProc )
{
    TIFF *tif;

    /* Set up the callback */
    XTIFFInitialize();

    /* Open the file; the callback will set everything up
     */
    tif = TIFFClientOpen(name, mode, thehandle,
                         RWProc, RWProc2,
                         SProc, CProc,
                         SzProc,
                         MFProvc, UMFProc);

    if (!tif) return tif;

    return tif;
}

/**
 * Close a file opened with XTIFFOpen().
 *
 * @param tif The file handle returned by XTIFFOpen().
 *
 * If a GTIF structure was created with GTIFNew()
 * for this file, it should be freed with GTIFFree()
 * before calling XTIFFClose().
*/

void
XTIFFClose(TIFF *tif)
{
    TIFFClose(tif);
}


text:
namespace AnimalHope.Web.Controllers
{
    using AnimalHope.Data;
    using System.Web.Mvc;

    public abstract class BaseController : Controller
    {
        protected IApplicationData data;

        protected BaseController(IApplicationData data)
        {
            this.data = data;
        }
    }
}


text:
package com.prince.snmp.tool.util;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestDataUtil {
	public static int randomInt(int start, int end){
		return new Random().nextInt(end - start) + start;
	}

	public static String randomString(int length){
		String result = "";
		for (int i = 0; i < length; i++) {
			char a = (char) (new Random().nextInt(24) + 98);
			result = result + a;
		}
		return result;
	}

	public static String nowTime(String dateFormat){
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat(dateFormat);
		return format.format(date);
	}

	public static File getResourceFile(String fileName){
		File resource = null;
		String path = TestDataUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		File parent = new File(path);
		if(parent.isDirectory()){
			resource = new File(parent, fileName);
		}else{
			resource = new File(parent.getParent(), fileName);
		}

		return resource;
	}

	public static String parseInnerMethod(String src) {
		Pattern p = Pattern.compile(".*\\$\\{(.*)\\}.*");
		Matcher m = p.matcher(src);
		String matInStr = "";
		if(m.find()){
			matInStr = m.group(1);
		}

		String replaced = getReplaced(matInStr);

		return src.replaceAll("\\$\\{.*\\}", replaced);
	}

	private static String getReplaced(String matInStr) {
		String methodName = null;
		String parameter = null;
		Pattern p = Pattern.compile("(.*)\\((.*)\\)");
		Matcher m = p.matcher(matInStr);
		if(m.find()){
			methodName = m.group(1);
			parameter = m.group(2);
		}

		return executeMethod(methodName, parameter);
	}

	private static String executeMethod(String methodName, String parameter) {
		String result = null;
		if("randomInt".equals(methodName)){
			result = Integer.toString(randomInt(Integer.parseInt(parameter.split(", *")[0]), Integer.parseInt(parameter.split(", *")[1])));
		}
		if("randomString".equals(methodName)){
			result = randomString(Integer.parseInt(parameter));
		}
		if("nowTime".equals(methodName)){
			result = nowTime(parameter);
		}
		return result;
	}

	public static void main(String[] args) throws ParseException {
		String aa = "Wed Jul 17 11:50:28 2013";
		String bb = "Wed Jul 17 15:50:28 2013";
		System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(new SimpleDateFormat("E MMM d HH:mm:ss yyyy", Locale.ENGLISH).parse(aa)));
		System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(new SimpleDateFormat("E MMM d HH:mm:ss yyyy", Locale.ENGLISH).parse(bb)));
	}
}


text:
// Generated by CoffeeScript 2.0.0-beta5
void function () {
  var $cache, axilla, cacheTemplate, fs, getTemplateReference, glob, Handlebars, isAbsolutePath, isPartial, Path, readAndCompileSync, readFileSync, removeBasePath, removeExtensions, removeUnderscore, render, renderPartial, utils;
  fs = require('fs');
  Path = require('path');
  glob = require('glob');
  Handlebars = require('handlebars');
  $cache = {
    layouts: {},
    partials: {},
    templates: {}
  };
  module.exports = axilla = function (basePath, defaults) {
    if (utils.isObject(basePath)) {
      defaults = basePath;
      basePath = null;
    }
    return function (path, viewObject, options) {
      if (!utils.isEmpty(basePath))
        path = Path.normalize('' + basePath + Path.sep + path);
      return render(path, viewObject, utils.defaults(options, defaults));
    };
  };
  axilla.configure = function (path, options) {
    if (null == options)
      options = {};
    if (!isAbsolutePath(path))
      throw new Error('Path argument must be an absolute path');
    if (!fs.existsSync(path))
      throw new Error('' + path + ' does not exist');
    return glob.sync(Path.normalize('' + path + '/**/*.mustache')).forEach(function (file) {
      var opts, relativePath;
      relativePath = getTemplateReference(file, path);
      opts = utils.clone(options);
      if (opts.layouts === true)
        opts.cacheType = 'layouts';
      if (isPartial(Path.basename(file))) {
        opts.cacheType = 'partials';
        relativePath = removeUnderscore(relativePath);
      }
      return cacheTemplate(file, utils.extend(opts, { as: relativePath }));
    });
  };
  axilla.render = render = function (path, viewObject, options) {
    var layout, template;
    if (null == options)
      options = {};
    if (!(null != (template = $cache.templates[path])))
      throw new Error('Unable to resolve template at ' + path);
    if (options.layout === false)
      return template.render(viewObject);
    layout = null != options.layout ? options.layout : axilla._defaultLayout;
    if (!(null != (layout = $cache.layouts[layout])))
      throw new Error('Unable to resolve layout at ' + layout);
    viewObject['yield'] = new Handlebars.SafeString(template.render(viewObject));
    return layout.render(viewObject);
  };
  axilla._defaultLayout = null;
  axilla.setDefaultLayout = function (layout) {
    return axilla._defaultLayout = layout;
  };
  axilla.clearCache = function () {
    $cache = {
      layouts: {},
      partials: {},
      templates: {}
    };
  };
  axilla.handlebars = function () {
    return Handlebars;
  };
  axilla.templates = function () {
    var cache, key, value;
    cache = {};
    for (key in $cache) {
      if (!isOwn$($cache, key))
        continue;
      value = $cache[key];
      cache[key] = utils.clone(value);
    }
    return cache;
  };
  renderPartial = function (path, viewObject) {
    var partial;
    if (!(null != (partial = $cache.partials[path])))
      throw new Error('Unable to resolve partial at ' + path);
    return partial.render(viewObject);
  };
  getTemplateReference = function (file, dirname) {
    return removeBasePath(dirname, removeExtensions(file));
  };
  cacheTemplate = function (path, options) {
    $cache[null != options.cacheType ? options.cacheType : 'templates'][options.as] = {
      render: function () {
        if (!(options.cache === false))
          return readAndCompileSync(path);
        return function (viewObject) {
          return readAndCompileSync(path)(viewObject);
        };
      }()
    };
  };
  readAndCompileSync = function (absolutePath) {
    var template;
    template = readFileSync(absolutePath);
    return Handlebars.compile(template);
  };
  removeBasePath = function (dirname, path) {
    return path.split(new RegExp('^' + dirname + Path.sep))[1];
  };
  removeExtensions = function (path) {
    var base, filename;
    filename = Path.basename(path);
    base = filename.split('.')[0];
    return '' + path.split(filename)[0] + base;
  };
  removeUnderscore = function (path) {
    var base, filename;
    filename = Path.basename(path);
    base = filename.split(/^_/)[1];
    return '' + path.split(filename)[0] + base;
  };
  isPartial = function (filename) {
    return null != filename.match(/^_/);
  };
  isAbsolutePath = function (path) {
    return null != path.match(new RegExp('^' + Path.sep));
  };
  readFileSync = function (path, options) {
    if (null == options)
      options = {};
    return fs.readFileSync(path, utils.defaults(options, { encoding: 'utf8' }));
  };
  utils = function () {
    var slice, toString;
    slice = Array.prototype.slice;
    toString = Object.prototype.toString;
    return {
      extend: function (obj) {
        slice.call(arguments, 1).forEach(function (source) {
          var key;
          for (key in source) {
            if (!isOwn$(source, key))
              continue;
            obj[key] = source[key];
          }
        });
        return obj;
      },
      defaults: function (obj) {
        slice.call(arguments, 1).forEach(function (source) {
          var key;
          for (key in source) {
            if (!isOwn$(source, key))
              continue;
            if (!(null != obj[key]))
              obj[key] = source[key];
          }
        });
        return obj;
      },
      clone: function (obj) {
        return utils.extend({}, obj);
      },
      isArray: Array.isArray,
      isObject: function (obj) {
        return obj === Object(obj);
      },
      isString: function (obj) {
        return toString.call(obj) === '[object String]';
      },
      isEmpty: function (obj) {
        var key;
        if (!(null != obj))
          return true;
        if (utils.isArray(obj) || utils.isString(obj))
          return obj.length === 0;
        for (key in obj) {
          if (!isOwn$(obj, key))
            continue;
          return false;
        }
        return true;
      }
    };
  }();
  Handlebars.registerHelper('partial', function (path) {
    return new Handlebars.SafeString(renderPartial(path, this));
  });
  function isOwn$(o, p) {
    return {}.hasOwnProperty.call(o, p);
  }
}.call(this);


text:
import math
import time
from hashlib import md5
from itertools import cycle

import random
import numpy as np

from spring.states import STATES, NUM_STATES

from fastdocgen import build_achievements

class Iterator(object):

    def __init__(self):
        self.prefix = None

    def __iter__(self):
        return self

    def add_prefix(self, key):
        if self.prefix:
            return '%s-%s' % (self.prefix, key)
        else:
            return key

class ExistingKey(Iterator):

    def __init__(self, working_set, working_set_access, prefix):
        self.working_set = working_set
        self.working_set_access = working_set_access
        self.prefix = prefix

    def next(self, curr_items, curr_deletes):
        num_existing_items = curr_items - curr_deletes
        num_hot_items = int(num_existing_items * self.working_set / 100.0)
        num_cold_items = num_existing_items - num_hot_items

        left_limit = 1 + curr_deletes
        if self.working_set_access == 100 or \
                random.randint(0, 100) <= self.working_set_access:
            left_limit += num_cold_items
            right_limit = curr_items
        else:
            right_limit = left_limit + num_cold_items
        key = np.random.random_integers(left_limit, right_limit)
        key = '%012d' % key
        return self.add_prefix(key)

class SequentialHotKey(Iterator):

    def __init__(self, sid, ws, prefix):
        self.sid = sid
        self.ws = ws
        self.prefix = prefix

    def __iter__(self):
        num_hot_keys = int(self.ws.items * self.ws.working_set / 100.0)
        num_cold_items = self.ws.items - num_hot_keys

        for seq_id in xrange(1 + num_cold_items + self.sid,
                             1 + self.ws.items,
                             self.ws.workers):
            key = '%012d' % seq_id
            key = self.add_prefix(key)
            yield key

class NewKey(Iterator):

    def __init__(self, prefix, expiration):
        self.prefix = prefix
        self.expiration = expiration
        self.ttls = cycle(range(150, 450, 30))

    def next(self, curr_items):
        key = '%012d' % curr_items
        key = self.add_prefix(key)
        ttl = None
        if self.expiration and random.randint(1, 100) <= self.expiration:
            ttl = self.ttls.next()
        return key, ttl

class KeyForRemoval(Iterator):

    def __init__(self, prefix):
        self.prefix = prefix

    def next(self, curr_deletes):
        key = '%012d' % curr_deletes
        return self.add_prefix(key)

class NewDocument(Iterator):

    SIZE_VARIATION = 0.25  # 25%
    KEY_LENGTH = 10

    def __init__(self, avg_size):
        self.avg_size = avg_size

    @classmethod
    def _get_variation_coeff(cls):
        return np.random.uniform(1 - cls.SIZE_VARIATION, 1 + cls.SIZE_VARIATION)

    @staticmethod
    def _build_alphabet(key):
        return md5(key).hexdigest() + md5(key[::-1]).hexdigest()

    @staticmethod
    def _build_name(alphabet):
        return '%s %s' % (alphabet[:6], alphabet[6:12])

    @staticmethod
    def _build_email(alphabet):
        return '%s@%s.com' % (alphabet[12:18], alphabet[18:24])

    @staticmethod
    def _build_city(alphabet):
        return alphabet[24:30]

    @staticmethod
    def _build_realm(alphabet):
        return alphabet[30:36]

    @staticmethod
    def _build_country(alphabet):
        return alphabet[42:48]

    @staticmethod
    def _build_county(alphabet):
        return alphabet[48:54]

    @staticmethod
    def _build_street(alphabet):
        return alphabet[54:62]

    @staticmethod
    def _build_coins(alphabet):
        return max(0.1, int(alphabet[36:40], 16) / 100.0)

    @staticmethod
    def _build_gmtime(alphabet):
        seconds = 396 * 24 * 3600 * (int(alphabet[63], 16) % 12)
        return tuple(time.gmtime(seconds))

    @staticmethod
    def _build_year(alphabet):
        return 1985 + int(alphabet[62], 16)

    @staticmethod
    def _build_state(alphabet):
        idx = alphabet.find('7') % NUM_STATES
        return STATES[idx][0]

    @staticmethod
    def _build_full_state(alphabet):
        idx = alphabet.find('8') % NUM_STATES
        return STATES[idx][1]

    @staticmethod
    def _build_category(alphabet):
        return int(alphabet[41], 16) % 3

    @staticmethod
    def _build_achievements(alphabet):
        return build_achievements(alphabet) or [0]

    @staticmethod
    def _build_body(alphabet, length):
        length_int = int(length)
        num_slices = int(math.ceil(length / 64))  # 64 == len(alphabet)
        body = num_slices * alphabet
        return body[:length_int]

    def next(self, key):
        next_length = self._get_variation_coeff() * self.avg_size
        alphabet = self._build_alphabet(key)
        return {
            'name': self._build_name(alphabet),
            'email': self._build_email(alphabet),
            'city': self._build_city(alphabet),
            'realm': self._build_realm(alphabet),
            'coins': self._build_coins(alphabet),
            'category': self._build_category(alphabet),
            'achievements': self._build_achievements(alphabet),
            'body': self._build_body(alphabet, next_length)
        }

class NewNestedDocument(NewDocument):

    OVERHEAD = 450  # Minimum size due to fixed fields, body size is variable

    def _size(self):
        if self.avg_size <= self.OVERHEAD:
            return 0
        if random.random() < 0.975:
            # Normal distribution with mean=self.avg_size
            normal = np.random.normal(loc=1.0, scale=0.17)
            return (self.avg_size - self.OVERHEAD) * normal
        else:
            # Beta distribution, 2KB-2MB range
            return 2048 / np.random.beta(a=2.2, b=1.0)

    def next(self, key):
        alphabet = self._build_alphabet(key)
        size = self._size()
        return {
            'name': {'f': {'f': {'f': self._build_name(alphabet)}}},
            'email': {'f': {'f': self._build_email(alphabet)}},
            'street': {'f': {'f': self._build_street(alphabet)}},
            'city': {'f': {'f': self._build_city(alphabet)}},
            'county': {'f': {'f': self._build_county(alphabet)}},
            'state': {'f': self._build_state(alphabet)},
            'full_state': {'f': self._build_full_state(alphabet)},
            'country': {'f': self._build_country(alphabet)},
            'realm': {'f': self._build_realm(alphabet)},
            'coins': {'f': self._build_coins(alphabet)},
            'category': self._build_category(alphabet),
            'achievements': self._build_achievements(alphabet),
            'gmtime': self._build_gmtime(alphabet),
            'year': self._build_year(alphabet),
            'body': self._build_body(alphabet, size),
        }