text:
typedef struct _GUID {
    unsigned int  Data1;
    unsigned short Data2;
    unsigned short Data3;
    unsigned char  Data4[ 8 ];
} GUID;
typedef GUID IID;
typedef const IID* REFIID;
typedef unsigned int HRESULT;
typedef unsigned int DWORD;
typedef DWORD ULONG;

#define STDMETHODCALLTYPE

#define S_OK                             0x0L

#define E_NOINTERFACE                    0x80004002UL
#define E_FAIL                           0x80004005L

typedef struct _IUnknown
{
    virtual HRESULT STDMETHODCALLTYPE QueryInterface(
            REFIID riid,
            void **ppvObject) = 0;

    virtual ULONG STDMETHODCALLTYPE AddRef( void) = 0;

    virtual ULONG STDMETHODCALLTYPE Release( void) = 0;

} IUnknown;

template<class TInterface, GUID const* TIID> class ComObject :  public TInterface
{

private:
    unsigned int _refCount;
public:

    virtual ULONG AddRef()
    {
        _refCount++;
        return _refCount;
    }

    virtual ULONG Release()
    {
        _refCount--;
        ULONG rv = _refCount;
        if(_refCount == 0)
            delete(this);
        return rv;
    }

    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,
            void **ppvObject)
    {
        const GUID IID_IUnknown = { 0x00, 0x0, 0x0, { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } };
        if(0 == memcmp(riid, &IID_IUnknown, sizeof(GUID)))
            *ppvObject = (IUnknown*)this;
        else if(0 == memcmp(riid, TIID, sizeof(GUID)))
        {
            TInterface* casted = this;
            *ppvObject = casted;
        }
        else
            return E_NOINTERFACE;
        _refCount++;
        return S_OK;
    }
    ComObject()
    {
        _refCount = 1;

    }
    virtual ~ComObject()
    {
    }
};

template<class TInterface>
class ComPtr
{
private:
    TInterface* _obj;
public:
    ComPtr(TInterface* pObj)
    {
        _obj = 0;

        if (pObj)
        {
            _obj = pObj;
            _obj->AddRef();
        }
    }

    ~ComPtr()
    {
        if (_obj)
        {
            _obj->Release();
            _obj = 0;
        }
    }

public:
    operator TInterface*() const
    {
        return _obj;
    }
    TInterface& operator*() const
    {
        return *_obj;
    }
    TInterface** operator&()
    {
        return &_obj;
    }
    TInterface* operator->() const
    {
        return _obj;
    }
};

#endif // COM_H_INCLUDED
#pragma clang diagnostic pop


text:
/*
 | PC-LISP (C) 1989-1992 Peter J.Ashwood-Smith
 */
#include <stdio.h>
#include <math.h>
#include "lisp.h"

/*************************************************************************
 ** (declare .....) is just ignored by the interpreter.                 **
 *************************************************************************/
struct conscell *budeclare(form)
struct conscell *form;
{      return(LIST(thold));
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef UAVCAN_PROTOCOL_DYNAMIC_NODE_ID_CLIENT_HPP_INCLUDED
#define UAVCAN_PROTOCOL_DYNAMIC_NODE_ID_CLIENT_HPP_INCLUDED

#include <uavcan/node/subscriber.hpp>
#include <uavcan/node/publisher.hpp>
#include <uavcan/node/timer.hpp>
#include <uavcan/util/method_binder.hpp>
#include <uavcan/build_config.hpp>
#include <uavcan/protocol/dynamic_node_id/Allocation.hpp>
#include <uavcan/protocol/HardwareVersion.hpp>

namespace uavcan
{
/**
 * This class implements client-side logic of dynamic node ID allocation procedure.
 *
 * Once started, the object will be publishing dynamic node ID allocation requests at the default frequency defined
 * by the specification, until a Node ID is granted by the allocator.
 *
 * If the local node is equipped with redundant CAN interfaces, all of them will be used for publishing requests
 * and listening for responses.
 *
 * Once dynamic allocation is complete (or not needed anymore), the object can be deleted.
 *
 * Note that this class uses std::rand(), which must be correctly seeded before use.
 */
class UAVCAN_EXPORT DynamicNodeIDClient : private TimerBase
{
    typedef MethodBinder<DynamicNodeIDClient*,
                         void (DynamicNodeIDClient::*)
                             (const ReceivedDataStructure<protocol::dynamic_node_id::Allocation>&)>
        AllocationCallback;

    enum Mode
    {
        ModeWaitingForTimeSlot,
        ModeDelayBeforeFollowup,
        NumModes
    };

    Publisher<protocol::dynamic_node_id::Allocation> dnida_pub_;
    Subscriber<protocol::dynamic_node_id::Allocation, AllocationCallback> dnida_sub_;

    uint8_t unique_id_[protocol::HardwareVersion::FieldTypes::unique_id::MaxSize];
    uint8_t size_of_received_unique_id_;

    NodeID preferred_node_id_;
    NodeID allocated_node_id_;
    NodeID allocator_node_id_;

    void terminate();

    static MonotonicDuration getRandomDuration(uint32_t lower_bound_msec, uint32_t upper_bound_msec);

    void restartTimer(const Mode mode);

    virtual void handleTimerEvent(const TimerEvent&) override;

    void handleAllocation(const ReceivedDataStructure<protocol::dynamic_node_id::Allocation>& msg);

public:
    typedef protocol::HardwareVersion::FieldTypes::unique_id UniqueID;

    DynamicNodeIDClient(INode& node)
        : TimerBase(node)
        , dnida_pub_(node)   // never use can fd for DNIDA
        , dnida_sub_(node)
        , size_of_received_unique_id_(0)
    { }

    /**
     * @param unique_id         Unique ID of the local node. Must be the same as in the hardware version struct.
     * @param preferred_node_id Node ID that the application would like to take; set to broadcast (zero) if
     *                          the application doesn't have any preference (this is default).
     * @param transfer_priority Transfer priority, Normal by default.
     * @return                  Zero on success
     *                          Negative error code on failure
     *                          -ErrLogic if 1. the node is not in passive mode or 2. the client is already started
     */
    int start(const UniqueID& unique_id,
              const NodeID preferred_node_id = NodeID::Broadcast,
              const TransferPriority transfer_priority = TransferPriority::OneHigherThanLowest);

    /**
     * Use this method to determine when allocation is complete.
     */
    bool isAllocationComplete() const { return getAllocatedNodeID().isUnicast(); }

    /**
     * This method allows to retrieve the node ID that was allocated to the local node.
     * If no node ID was allocated yet, the returned node ID will be invalid (non-unicast).
     * @return          If allocation is complete, a valid unicast node ID will be returned.
     *                  If allocation is not complete yet, a non-unicast node ID will be returned.
     */
    NodeID getAllocatedNodeID() const { return allocated_node_id_; }

    /**
     * This method allows to retrieve node ID of the allocator that granted our Node ID.
     * If no node ID was allocated yet, the returned node ID will be invalid (non-unicast).
     * @return          If allocation is complete, a valid unicast node ID will be returned.
     *                  If allocation is not complete yet, an non-unicast node ID will be returned.
     */
    NodeID getAllocatorNodeID() const { return allocator_node_id_; }
};

}

#endif // UAVCAN_PROTOCOL_DYNAMIC_NODE_ID_CLIENT_HPP_INCLUDED


text:
package edu.clemson.cs.r2jt.typeandpopulate;

import edu.clemson.cs.r2jt.typeandpopulate.searchers.TableSearcher;
import edu.clemson.cs.r2jt.typeandpopulate.entry.SymbolTableEntry;
import java.util.List;

import edu.clemson.cs.r2jt.data.PosSymbol;
import edu.clemson.cs.r2jt.typeandpopulate.MathSymbolTable.FacilityStrategy;
import edu.clemson.cs.r2jt.typeandpopulate.MathSymbolTable.ImportStrategy;

public class PossiblyQualifiedPath implements ScopeSearchPath {

    private final ScopeSearchPath myActualSearchPath;

    public PossiblyQualifiedPath(PosSymbol qualifier,
            ImportStrategy importStrategy, FacilityStrategy facilityStrategy,
            boolean localPriority) {

        myActualSearchPath =
                getAppropriatePath(qualifier, importStrategy, facilityStrategy,
                        localPriority);
    }

    public PossiblyQualifiedPath(PosSymbol qualifier) {
        this(qualifier, ImportStrategy.IMPORT_NONE,
                FacilityStrategy.FACILITY_IGNORE, false);
    }

    @Override
    public <E extends SymbolTableEntry> List<E> searchFromContext(
            TableSearcher<E> searcher, Scope source, ScopeRepository repo)
            throws DuplicateSymbolException {

        return myActualSearchPath.searchFromContext(searcher, source, repo);
    }

    private static ScopeSearchPath getAppropriatePath(PosSymbol qualifier,
            ImportStrategy importStrategy, FacilityStrategy facilityStrategy,
            boolean localPriority) {
        ScopeSearchPath result;

        if (qualifier == null) {
            result =
                    new UnqualifiedPath(importStrategy, facilityStrategy,
                            localPriority);
        }
        else {
            result = new QualifiedPath(qualifier, facilityStrategy);
        }

        return result;
    }
}


text:
namespace proximity_auth {

namespace {

// The number of days that an enrollment is valid. Note that we try to refresh
// the enrollment well before this time elapses.
const int kValidEnrollmentPeriodDays = 45;

// The normal period between successful enrollments in days.
const int kEnrollmentRefreshPeriodDays = 30;

// A more aggressive period between enrollments to recover when the last
// enrollment fails, in minutes. This is a base time that increases for each
// subsequent failure.
const int kEnrollmentBaseRecoveryPeriodMinutes = 10;

// The bound on the amount to jitter the period between enrollments.
const double kEnrollmentMaxJitterRatio = 0.2;

// The value of the device_software_package field in the device info uploaded
// during enrollment. This value must be the same as the app id used for GCM
// registration.
const char kDeviceSoftwarePackage[] = "com.google.chrome.cryptauth";

}  // namespace

CryptAuthEnrollmentManager::CryptAuthEnrollmentManager(
    scoped_ptr<base::Clock> clock,
    scoped_ptr<CryptAuthEnrollerFactory> enroller_factory,
    const std::string& user_public_key,
    const std::string& user_private_key,
    const cryptauth::GcmDeviceInfo& device_info,
    CryptAuthGCMManager* gcm_manager,
    PrefService* pref_service)
    : clock_(clock.Pass()),
      enroller_factory_(enroller_factory.Pass()),
      user_public_key_(user_public_key),
      user_private_key_(user_private_key),
      device_info_(device_info),
      gcm_manager_(gcm_manager),
      pref_service_(pref_service),
      weak_ptr_factory_(this) {}

CryptAuthEnrollmentManager::~CryptAuthEnrollmentManager() {
  gcm_manager_->RemoveObserver(this);
}

// static
void CryptAuthEnrollmentManager::RegisterPrefs(PrefRegistrySimple* registry) {
  registry->RegisterBooleanPref(
      prefs::kCryptAuthEnrollmentIsRecoveringFromFailure, false);
  registry->RegisterDoublePref(
      prefs::kCryptAuthEnrollmentLastEnrollmentTimeSeconds, 0.0);
  registry->RegisterIntegerPref(prefs::kCryptAuthEnrollmentReason,
                                cryptauth::INVOCATION_REASON_UNKNOWN);
}

void CryptAuthEnrollmentManager::Start() {
  gcm_manager_->AddObserver(this);

  bool is_recovering_from_failure =
      pref_service_->GetBoolean(
          prefs::kCryptAuthEnrollmentIsRecoveringFromFailure) ||
      !IsEnrollmentValid();

  base::Time last_successful_enrollment = GetLastEnrollmentTime();
  base::TimeDelta elapsed_time_since_last_sync =
      clock_->Now() - last_successful_enrollment;

  scheduler_ = CreateSyncScheduler();
  scheduler_->Start(elapsed_time_since_last_sync,
                    is_recovering_from_failure
                        ? SyncScheduler::Strategy::AGGRESSIVE_RECOVERY
                        : SyncScheduler::Strategy::PERIODIC_REFRESH);
}

void CryptAuthEnrollmentManager::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void CryptAuthEnrollmentManager::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

void CryptAuthEnrollmentManager::ForceEnrollmentNow(
    cryptauth::InvocationReason invocation_reason) {
  // We store the invocation reason in a preference so that it can persist
  // across browser restarts. If the sync fails, the next retry should still use
  // this original reason instead of INVOCATION_REASON_FAILURE_RECOVERY.
  pref_service_->SetInteger(prefs::kCryptAuthEnrollmentReason,
                            invocation_reason);
  scheduler_->ForceSync();
}

bool CryptAuthEnrollmentManager::IsEnrollmentValid() const {
  base::Time last_enrollment_time = GetLastEnrollmentTime();
  return !last_enrollment_time.is_null() &&
         (clock_->Now() - last_enrollment_time) <
             base::TimeDelta::FromDays(kValidEnrollmentPeriodDays);
}

base::Time CryptAuthEnrollmentManager::GetLastEnrollmentTime() const {
  return base::Time::FromDoubleT(pref_service_->GetDouble(
      prefs::kCryptAuthEnrollmentLastEnrollmentTimeSeconds));
}

base::TimeDelta CryptAuthEnrollmentManager::GetTimeToNextAttempt() const {
  return scheduler_->GetTimeToNextSync();
}

bool CryptAuthEnrollmentManager::IsEnrollmentInProgress() const {
  return scheduler_->GetSyncState() ==
         SyncScheduler::SyncState::SYNC_IN_PROGRESS;
}

bool CryptAuthEnrollmentManager::IsRecoveringFromFailure() const {
  return scheduler_->GetStrategy() ==
         SyncScheduler::Strategy::AGGRESSIVE_RECOVERY;
}

void CryptAuthEnrollmentManager::OnEnrollmentFinished(bool success) {
  if (success) {
    pref_service_->SetDouble(
        prefs::kCryptAuthEnrollmentLastEnrollmentTimeSeconds,
        clock_->Now().ToDoubleT());
    pref_service_->SetInteger(prefs::kCryptAuthEnrollmentReason,
                              cryptauth::INVOCATION_REASON_UNKNOWN);
  }

  pref_service_->SetBoolean(prefs::kCryptAuthEnrollmentIsRecoveringFromFailure,
                            !success);

  sync_request_->OnDidComplete(success);
  cryptauth_enroller_.reset();
  sync_request_.reset();
  FOR_EACH_OBSERVER(Observer, observers_, OnEnrollmentFinished(success));
}

scoped_ptr<SyncScheduler> CryptAuthEnrollmentManager::CreateSyncScheduler() {
  return make_scoped_ptr(new SyncSchedulerImpl(
      this, base::TimeDelta::FromDays(kEnrollmentRefreshPeriodDays),
      base::TimeDelta::FromMinutes(kEnrollmentBaseRecoveryPeriodMinutes),
      kEnrollmentMaxJitterRatio, "CryptAuth Enrollment"));
}

void CryptAuthEnrollmentManager::OnGCMRegistrationResult(bool success) {
  if (!sync_request_)
    return;

  PA_LOG(INFO) << "GCM registration for CryptAuth Enrollment completed: "
               << success;
  if (success)
    DoCryptAuthEnrollment();
  else
    OnEnrollmentFinished(false);
}

void CryptAuthEnrollmentManager::OnReenrollMessage() {
  ForceEnrollmentNow(cryptauth::INVOCATION_REASON_SERVER_INITIATED);
}

void CryptAuthEnrollmentManager::OnSyncRequested(
    scoped_ptr<SyncScheduler::SyncRequest> sync_request) {
  FOR_EACH_OBSERVER(Observer, observers_, OnEnrollmentStarted());

  sync_request_ = sync_request.Pass();

  if (gcm_manager_->GetRegistrationId().empty() ||
      pref_service_->GetInteger(prefs::kCryptAuthEnrollmentReason) ==
          cryptauth::INVOCATION_REASON_MANUAL) {
    gcm_manager_->RegisterWithGCM();
  } else {
    DoCryptAuthEnrollment();
  }
}

void CryptAuthEnrollmentManager::DoCryptAuthEnrollment() {
  DCHECK(sync_request_);
  cryptauth::InvocationReason invocation_reason =
      cryptauth::INVOCATION_REASON_UNKNOWN;

  int reason_stored_in_prefs =
      pref_service_->GetInteger(prefs::kCryptAuthEnrollmentReason);

  if (cryptauth::InvocationReason_IsValid(reason_stored_in_prefs) &&
      reason_stored_in_prefs != cryptauth::INVOCATION_REASON_UNKNOWN) {
    invocation_reason =
        static_cast<cryptauth::InvocationReason>(reason_stored_in_prefs);
  } else if (GetLastEnrollmentTime().is_null()) {
    invocation_reason = cryptauth::INVOCATION_REASON_INITIALIZATION;
  } else if (!IsEnrollmentValid()) {
    invocation_reason = cryptauth::INVOCATION_REASON_EXPIRATION;
  } else if (scheduler_->GetStrategy() ==
             SyncScheduler::Strategy::PERIODIC_REFRESH) {
    invocation_reason = cryptauth::INVOCATION_REASON_PERIODIC;
  } else if (scheduler_->GetStrategy() ==
             SyncScheduler::Strategy::AGGRESSIVE_RECOVERY) {
    invocation_reason = cryptauth::INVOCATION_REASON_FAILURE_RECOVERY;
  }

  // Fill in the current GCM registration id before enrolling, and explicitly
  // make sure that the software package is the same as the GCM app id.
  cryptauth::GcmDeviceInfo device_info(device_info_);
  device_info.set_gcm_registration_id(gcm_manager_->GetRegistrationId());
  device_info.set_device_software_package(kDeviceSoftwarePackage);

  std::string public_key_b64;
  Base64UrlEncode(user_public_key_, &public_key_b64);
  PA_LOG(INFO) << "Making enrollment:\n"
               << "  public_key: " << public_key_b64 << "\n"
               << "  invocation_reason: " << invocation_reason << "\n"
               << "  gcm_registration_id: "
               << device_info.gcm_registration_id();

  cryptauth_enroller_ = enroller_factory_->CreateInstance();
  cryptauth_enroller_->Enroll(
      user_public_key_, user_private_key_, device_info, invocation_reason,
      base::Bind(&CryptAuthEnrollmentManager::OnEnrollmentFinished,
                 weak_ptr_factory_.GetWeakPtr()));
}

}  // namespace proximity_auth


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC  "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/>
      <meta name="description" content="W3C SVG 1.1 2nd Edition Object Mini Test Suite"/>
      <title>
SVG 1.1 2nd Edition Test (<object>): filters-composite-03-f.svg
      </title>
      <link href="harness_mini.css" rel="stylesheet" type="text/css" />
      <link rel="prev" href="filters-composite-02-b.html" />
      <link rel="index" href="index.html" />
      <link rel="next" href="filters-composite-04-f.html" />

        filters-composite-02-b ←
        index
        → filters-composite-04-f

            SVG Image

            PNG Image

            <object data="../../svg/filters-composite-03-f.svg" width="480" height="360" type="image/svg+xml">
FAIL
</object>

      Operator script (click here to toggle)

        Run the test. No interaction required.

      Pass Criteria

        The test is passed if there are four filled squares visible, and the
        fill color matches the respective reference stroke exactly.

        filters-composite-02-b ←
        index
        → filters-composite-04-f


text:
package com.typeahead.server.beacon.core;

import java.io.IOException;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

import com.yammer.dropwizard.json.Json;
import com.yammer.dropwizard.json.JsonSnakeCase;
import com.yammer.dropwizard.logging.Log;

/***
  Object example

 {
    "status": "ACTIVE",
    "website": "somewebsite.com",
    "_state": "<django.db.models.base.ModelState object at 0x10ee0a4d0>",
    "creation_time": "2012-08-23T21:51:16.143Z",
    "modified_time": "2012-08-23T21:51:16.143Z",
    "package_id": null,
    "api_key": "N369vOR2klR01IouQhJp",
    "client_key": "N369vOR2klR01IouQhJp",
    "id": 1
}

****/

@JsonIgnoreProperties(ignoreUnknown=true)
@JsonSnakeCase
public class Account {
	private String status;
	private String website;
	private Date creationTime;
	private Date modifiedTime;
	private String apiKey;
	private String clientKey;
	private long id;

	private static Log LOG = Log.forClass(Account.class);

	public Account() {

	}

	public Account(long id, String status, String website, String apiKey, String clientKey, Date creationTime, Date modifiedTime) {
		this.id = id;
		this.status = status;
		this.website = website;
		this.apiKey = apiKey;
		this.clientKey = clientKey;
		this.creationTime = creationTime;
		this.modifiedTime = modifiedTime;
	}

	public String getStatus() {
		return status;
	}

	public String getWebsite() {
		return website;
	}

	public Date getCreationTime() {
		return creationTime;
	}

	public Date getModifiedTime() {
		return modifiedTime;
	}

	public String getApiKey() {
		return apiKey;
	}

	public String getClientKey() {
		return clientKey;
	}

	public long getId() {
		return id;
	}

	public static final Account getInstance(String json) {
		if (StringUtils.isBlank(json)) {
			return null;
		}

		Json parser = new Json();
		try {
			return parser.readValue(json, Account.class);
		}
		catch (IOException ex) {
			LOG.warn(ex, "error parsing value");
		}
		return null;
	}

	@Override
	public String toString() {
		Json parser = new Json();
		return parser.writeValueAsString(this);
	}

}


text:
#ifndef MXNET_NDARRAY_AUTOGRAD_H_
#define MXNET_NDARRAY_AUTOGRAD_H_

#include <dmlc/logging.h>
#include <mxnet/base.h>
#include <mxnet/ndarray.h>
#include <mxnet/op_attr_types.h>
#include <mxnet/c_api.h>
#include <nnvm/symbolic.h>
#include <nnvm/op.h>
#include <nnvm/graph.h>
#include <vector>
#include <atomic>
#include <unordered_map>

namespace mxnet {
namespace autograd {

class AGNode {
 public:
  OpReqType grad_req;
  nnvm::NodePtr nn_node;
  OpStatePtr state;
  std::vector<AGNodeEntry> inputs;
  std::vector<NDArray> outputs;
  std::vector<NDArray> out_grads;
  bool fresh_out_grad;

  explicit AGNode(const nnvm::NodePtr& nn_node_) :
    grad_req(kNullOp), nn_node(nn_node_), fresh_out_grad(false) {}

  static AGNodePtr Create(const nnvm::NodePtr& nn_node_) {
    return std::make_shared<AGNode>(nn_node_);
  }

  void clear_history() {
    if (out_grads.size()) return;
    state.reset();
    outputs.clear();
    nn_node.reset();
    for (auto& i : inputs) i.ag_node->clear_history();
    inputs.clear();
  }
};

/*!
 * \brief AutogradRuntime Interface
 */
class AutogradRuntime {
 public:
  /*! \brief turn on or turn off operator recording for autograd. */
  bool SetIsTraining(bool is_train) {
      bool old = is_train_;
      is_train_ = is_train;
      return old;
  }
  /*! \brief whether operator recording is on. */
  bool IsTraining() const {
    return is_train_;
  }
  /*! \brief mark variables for computing gradients. */
  void MarkVariables(const std::vector<NDArray*>& variables,
                     const std::vector<mx_uint>& grad_reqs,
                     const std::vector<NDArray*>& gradients);
  /*! \brief record imperative operator which is executed by fcompute. */
  void RecordImperativeFCompute(const nnvm::Op* op,
                                const nnvm::NodeAttrs& attrs,
                                std::vector<NDArray>* p_inputs,
                                std::vector<NDArray>* p_outputs);
  /*! \brief record imperative operator which is executed by operator. */
  void RecordImperativeOperator(const OpStatePtr& state,
                                const nnvm::Op* op,
                                const nnvm::NodeAttrs& attrs,
                                std::vector<NDArray>* p_inputs,
                                std::vector<NDArray>* p_outputs);
  /*! \brief compute the gradient of outputs w.r.t variables. */
  void ComputeGradient(const std::vector<NDArray>& outputs,
                       const std::vector<NDArray>& ograds,
                       bool retain_graph);
  /*! \return AutogradRuntime singleton */
  static AutogradRuntime* Get();
  /*! \brief Get shared pointer reference to AutogradRuntime singleton.
   *   Most user should not call this function.
   *   This function is called by another singleton X who requires
   *   AutogradRuntime to be destructed after X.
   *
   *  \return A shared pointer to AutogradRuntime singleton.
   */
  static std::shared_ptr<AutogradRuntime> _GetSharedRef();

 protected:
  /*! \brief make constructor protected. */
  AutogradRuntime();

 private:
  /*! \brief to record operator, return corresponding node. */
  AGNodePtr RecordOp(const nnvm::Op* op,
                     const nnvm::NodeAttrs& attrs,
                     std::vector<NDArray>* p_inputs,
                     std::vector<NDArray>* p_outputs,
                     const OpStatePtr& state);
  /*! \brief AutogradRuntime singleton. */
  static AutogradRuntime* instance_;
  /*! \brief indicate whether is training. */
#if DMLC_CXX11_THREAD_LOCAL
  static thread_local bool is_train_;
#else
  static MX_THREAD_LOCAL bool is_train_;
#endif
  /*! \brief node count used for naming */
  std::atomic<uint64_t> node_count_{0};
  /*! \brief variable count used for naming */
  std::atomic<uint64_t> variable_count_{0};
};

}  // namespace autograd
}  // namespace mxnet
#endif  // MXNET_NDARRAY_AUTOGRAD_H_


text:
{-# LANGUAGE ExistentialQuantification, MultiParamTypeClasses, FlexibleContexts, FlexibleInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  Xmobar.Runnable
-- Copyright   :  (c) Andrea Rossato
-- License     :  BSD-style (see LICENSE)
--
-- Maintainer  :  Andrea Rossato <andrea.rossato@unibz.it>
-- Stability   :  unstable
-- Portability :  unportable
--
-- The existential type to store the list of commands to be executed.
-- I must thank Claus Reinke for the help in understanding the mysteries of
-- reading existential types. The Read instance of Runnable must be credited to
-- him.
--
-- See here:
-- http:\/\/www.haskell.org\/pipermail\/haskell-cafe\/2007-July\/028227.html
--
-----------------------------------------------------------------------------

module Runnable where

import Control.Monad
import Text.Read
import Text.ParserCombinators.ReadPrec
import Config (runnableTypes)
import Commands

data Runnable = forall r . (Exec r, Read r, Show r) => Run r

instance Exec Runnable where
     start (Run a) = start a
     alias (Run a) = alias a

instance Show Runnable where
    show (Run x) = show x

instance Read Runnable where
    readPrec = readRunnable

class ReadAsAnyOf ts ex where
    -- | Reads an existential type as any of hidden types ts
    readAsAnyOf :: ts -> ReadPrec ex

instance ReadAsAnyOf () ex where
    readAsAnyOf ~() = mzero

instance (Show t, Read t, Exec t, ReadAsAnyOf ts Runnable) => ReadAsAnyOf (t,ts) Runnable where
    readAsAnyOf ~(t,ts) = r t `mplus` readAsAnyOf ts
              where r ty = do { m <- readPrec; return (Run (m `asTypeOf` ty)) }

-- | The 'Prelude.Read' parser for the 'Runnable' existential type. It
-- needs an 'Prelude.undefined' with a type signature containing the
-- list of all possible types hidden within 'Runnable'. See 'Config.runnableTypes'.
-- Each hidden type must have a 'Prelude.Read' instance.
readRunnable :: ReadPrec Runnable
readRunnable = prec 10 $ do
                 Ident "Run" <- lexP
                 parens $ readAsAnyOf runnableTypes


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Otd. Izd. Obshch. Izuch. Man'chzhur. Kraya, A 22:8, fig. 6-11. 1927 (Landw. Mandschurei 76. 1922, nom. inval. )

#### Original name
null

### Remarks
null


text:
#ifndef ALINOUS_DB_TABLE_TABLEINDEX_H_
#define ALINOUS_DB_TABLE_TABLEINDEX_H_
namespace alinous{namespace annotation{
class OneSource;
}}
namespace alinous {namespace db {namespace table {
class TableColumnMetadata;}}}

namespace alinous {namespace system {
class AlinousCore;}}

namespace alinous {namespace btree {
class BTreeGlobalCache;}}

namespace java {namespace io {
class File;}}

namespace alinous {namespace btree {
class BTree;}}

namespace alinous {namespace compile {namespace sql {namespace analyze {
class ScanTableColumnIdentifier;}}}}

namespace alinous {namespace db {namespace table {
class IDatabaseRecord;}}}

namespace alinous {namespace db {namespace table {
class BTreeIndexKey;}}}

namespace alinous {namespace db {namespace table {
class TableIndexValue;}}}

namespace alinous {namespace db {
class AlinousDbException;}}

namespace java {namespace io {
class IOException;}}

namespace java {namespace lang {
class InterruptedException;}}

namespace alinous {namespace btree {
class BTreeException;}}

namespace java {namespace lang {
class StringBuilder;}}

namespace alinous {namespace db {namespace table {
class TableIndex;}}}

namespace alinous {namespace buffer {namespace storage {
class FileStorageEntryFetcher;}}}

namespace alinous {namespace buffer {namespace storage {
class FileStorageEntryBuilder;}}}

namespace alinous {namespace db {namespace table {
class IBtreeTableIndex;}}}

namespace alinous {namespace db {namespace table {
class IScannableIndex;}}}

namespace alinous {namespace btree {
class IBTreeValue;}}

namespace alinous {namespace runtime {namespace dom {
class VariableException;}}}

namespace alinous {namespace system {
class AlinousException;}}

namespace java {namespace lang {
class IObject;
}}

namespace alinous {
class ThreadContext;
}

namespace alinous {namespace db {namespace table {

using namespace ::alinous;
using namespace ::java::lang;
using ::java::util::Iterator;
using ::java::io::File;
using ::java::io::IOException;
using ::java::util::ArrayList;
using ::alinous::btree::BTree;
using ::alinous::btree::BTreeException;
using ::alinous::btree::BTreeGlobalCache;
using ::alinous::btree::IBTreeValue;
using ::alinous::buffer::storage::FileStorageEntryBuilder;
using ::alinous::buffer::storage::FileStorageEntryFetcher;
using ::alinous::compile::sql::analyze::ScanTableColumnIdentifier;
using ::alinous::db::AlinousDbException;
using ::alinous::runtime::dom::VariableException;
using ::alinous::system::AlinousCore;
using ::alinous::system::AlinousException;

class TableIndex final : public IBtreeTableIndex, public IScannableIndex, public virtual IObject {
public:
	TableIndex(const TableIndex& base) = default;
public:
	TableIndex(String* name, String* baseDir, bool primary, ArrayList<TableColumnMetadata>* metadata, ThreadContext* ctx) throw() ;
	void __construct_impl(String* name, String* baseDir, bool primary, ArrayList<TableColumnMetadata>* metadata, ThreadContext* ctx) throw() ;
	virtual ~TableIndex() throw();
	virtual void __releaseRegerences(bool prepare, ThreadContext* ctx) throw();
private:
	String* name;
	String* baseDir;
	bool primary;
	ArrayList<TableColumnMetadata>* columns;
	String* filePath;
	BTree* storage;
public:
	constexpr static const int capacity{1024};
	constexpr static const int BLOCK_SIZE{128};
	constexpr static const int maxCache{256};
public:
	bool isOpened(ThreadContext* ctx) throw()  final;
	void open(AlinousCore* core, BTreeGlobalCache* cache, ThreadContext* ctx) final;
	void close(ThreadContext* ctx) final;
	bool isAvailable(ArrayList<String>* columnsStr, ThreadContext* ctx) throw()  final;
	bool isAvailableByScanId(ArrayList<ScanTableColumnIdentifier>* columnIds, ThreadContext* ctx) throw()  final;
	void addIndexValue(IDatabaseRecord* record, ThreadContext* ctx) final;
	void createIndex(AlinousCore* core, BTreeGlobalCache* cache, ThreadContext* ctx) final;
	int archiveSize(ThreadContext* ctx) final;
	void appendToEntry(FileStorageEntryBuilder* builder, ThreadContext* ctx) final;
	BTree* getStorage(ThreadContext* ctx) throw()  final;
	String* getName(ThreadContext* ctx) throw()  final;
	bool isPrimary(ThreadContext* ctx) throw()  final;
	ArrayList<TableColumnMetadata>* getColumns(ThreadContext* ctx) throw()  final;
private:
	void setPath(ThreadContext* ctx) throw() ;
public:
	static TableIndex* valueFromFetcher(FileStorageEntryFetcher* fetcher, String* baseDir, ThreadContext* ctx) throw() ;
public:
	static bool __init_done;
	static bool __init_static_variables();
public:
	static void __cleanUp(ThreadContext* ctx);
};

}}}

#endif /* end of ALINOUS_DB_TABLE_TABLEINDEX_H_ */


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.fifesoft</groupId>
		<artifactId>rtext-root-pom</artifactId>
		<version>3</version>
		<relativePath>../../pom.xml</relativePath>
	</parent>

	<artifactId>rstaui</artifactId>
	<version>@VERSION@</version>
	<packaging>jar</packaging>
	<name>RSyntaxTextArea UI</name>
	<description>
		RSTAUI is an add-on library for RSyntaxTextArea that provides pre-built dialog boxes commonly
		needed in text editing applications.
  	</description>
	<inceptionYear>2003</inceptionYear>
	<url>http://www.fifesoft.com/rsyntaxtextarea/</url>
	<licenses>
		<license>
			<name>Modified BSD License</name>
			<url>http://fifesoft.com/rsyntaxtextarea/RSyntaxTextArea.License.txt</url>
			<distribution>repo</distribution>
		</license>
	</licenses>
	<scm>
		<url>http://svn.fifesoft.com/viewvc-1.0.5/bin/cgi/viewvc.cgi/RSTAUI/trunk/?root=RSyntaxTextArea</url>
		<connection>http://svn.fifesoft.com/svn/RSyntaxTextArea/RSTAUI</connection>
	</scm>
	<developers>
		<developer>
			<name>Robert Futrell</name>
			<url>http://www.fifesoft.com</url>
		</developer>
	</developers>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit-version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.fifesoft</groupId>
			<artifactId>rsyntaxtextarea</artifactId>
			<version>@RSYNTAXTEXTAREAVERSION@</version>
		</dependency>
		<dependency>
			<groupId>com.fifesoft</groupId>
			<artifactId>autocomplete</artifactId>
			<version>@AUTOCOMPLETEVERSION@</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${compiler-plugin-version}</version>
				<executions>
					<execution>
						<id>default-compile</id>
						<configuration>
							<fork>true</fork>
							<executable>${javac15-compiler-executable}</executable>
							<compilerVersion>1.5</compilerVersion>
							<source>1.5</source>
							<target>1.5</target>
						</configuration>
						<goals>
							<goal>compile</goal>
						</goals>

					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


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

    <title>TestSuiteBinarySpec (Gradle API 2.1)</title>
    <meta name="date" content="2014-09-08">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
    <link href="../../../../../groovy.ico" type="image/x-icon" rel="icon">
    <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Summary:

            Nested   Field      Method

 | Detail:

            Field      Method

Package: org.gradle.runtime.base.test

[Java] Interface TestSuiteBinarySpec

Named

All Superinterfaces:

BinarySpec, BuildableModelElement, Named

 A binary which runs a suite of tests.

Inherited Methods Summary

Inherited Methods

                            Methods inherited from class
                            Name

                            interface BinarySpec
                            getDisplayName, getSource, getTasks, isBuildable, source

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Summary:

            Nested   Field      Method

 | Detail:

            Field      Method

Gradle API 2.1


text:
root = "/focusd"
working_directory root
pid "#{root}/tmp/pids/unicorn.pid"
stderr_path "#{root}/log/unicorn.log"
stdout_path "#{root}/log/unicorn.log"

listen "/tmp/unicorn.focusd.sock"
worker_processes 2
timeout 30

# Force the bundler gemfile environment variable to
# reference the capistrano "current" symlink
before_exec do |_|
  ENV["BUNDLE_GEMFILE"] = File.join(root, 'Gemfile')
end


text:
<?php

// Include the essential config-file which also creates the $pucko variable with its defaults.
include(__DIR__.'/config.php');

// Create the object to display sourcecode
//$source = new CSource();
$source = new CSource(array('secure_dir' => '..', 'base_dir' => '..'));

// Do it and store it all in variables in the Pucko container.
$pucko['header'] = '';
$pucko['title'] = "Visa källkod";
$pucko['main'] = "
Visa källkod
\n" . $source->View();
$pucko['footer'] = <<<EOD
Copyright (c) Sebastian Jonasson | Pucko on GitHub | Unicorn
EOD;

// Finally, leave it all to the rendering phase of Pucko.
include(PUCKO_THEME_PATH);


text:
using System;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Logging;
using osu.Framework.Timing;
using osu.Game.Beatmaps;

namespace osu.Game.Screens.Play
{
    /// <summary>
    /// Encapsulates gameplay timing logic and provides a <see cref="IGameplayClock"/> via DI for gameplay components to use.
    /// </summary>
    [Cached(typeof(IGameplayClock))]
    public class GameplayClockContainer : Container, IAdjustableClock, IGameplayClock
    {
        /// <summary>
        /// Whether gameplay is paused.
        /// </summary>
        public IBindable<bool> IsPaused => isPaused;

        /// <summary>
        /// The source clock. Should generally not be used for any timekeeping purposes.
        /// </summary>
        public IClock SourceClock { get; private set; }

        /// <summary>
        /// Invoked when a seek has been performed via <see cref="Seek"/>
        /// </summary>
        public event Action? OnSeek;

        /// <summary>
        /// The time from which the clock should start. Will be seeked to on calling <see cref="Reset"/>.
        /// Can be adjusted by calling <see cref="Reset"/> with a time value.
        /// </summary>
        /// <remarks>
        /// By default, a value of zero will be used.
        /// Importantly, the value will be inferred from the current beatmap in <see cref="MasterGameplayClockContainer"/> by default.
        /// </remarks>
        public double StartTime { get; protected set; }

        public IAdjustableAudioComponent AdjustmentsFromMods { get; } = new AudioAdjustments();

        private readonly BindableBool isPaused = new BindableBool(true);

        /// <summary>
        /// The adjustable source clock used for gameplay. Should be used for seeks and clock control.
        /// This is the final source exposed to gameplay components <see cref="IGameplayClock"/> via delegation in this class.
        /// </summary>
        protected readonly FramedBeatmapClock GameplayClock;

        protected override Container<Drawable> Content { get; } = new Container { RelativeSizeAxes = Axes.Both };

        /// <summary>
        /// Creates a new <see cref="GameplayClockContainer"/>.
        /// </summary>
        /// <param name="sourceClock">The source <see cref="IClock"/> used for timing.</param>
        /// <param name="applyOffsets">Whether to apply platform, user and beatmap offsets to the mix.</param>
        public GameplayClockContainer(IClock sourceClock, bool applyOffsets = false)
        {
            SourceClock = sourceClock;

            RelativeSizeAxes = Axes.Both;

            InternalChildren = new Drawable[]
            {
                GameplayClock = new FramedBeatmapClock(applyOffsets) { IsCoupled = false },
                Content
            };
        }

        /// <summary>
        /// Starts gameplay and marks un-paused state.
        /// </summary>
        public void Start()
        {
            if (!isPaused.Value)
                return;

            isPaused.Value = false;

            ensureSourceClockSet();

            PrepareStart();

            // The case which caused this to be added is FrameStabilityContainer, which manages its own current and elapsed time.
            // Because we generally update our own current time quicker than children can query it (via Start/Seek/Update),
            // this means that the first frame ever exposed to children may have a non-zero current time.
            //
            // If the child component is not aware of the parent ElapsedFrameTime (which is the case for FrameStabilityContainer)
            // they will take on the new CurrentTime with a zero elapsed time. This can in turn cause components to behave incorrectly
            // if they are intending to trigger events at the precise StartTime (ie. DrawableStoryboardSample).
            //
            // By scheduling the start call, children are guaranteed to receive one frame at the original start time, allowing
            // then to progress with a correct locally calculated elapsed time.
            SchedulerAfterChildren.Add(() =>
            {
                if (isPaused.Value)
                    return;

                StartGameplayClock();
            });
        }

        /// <summary>
        /// When <see cref="Start"/> is called, this will be run to give an opportunity to prepare the clock at the correct
        /// start location.
        /// </summary>
        protected virtual void PrepareStart()
        {
        }

        /// <summary>
        /// Seek to a specific time in gameplay.
        /// </summary>
        /// <param name="time">The destination time to seek to.</param>
        public virtual void Seek(double time)
        {
            Logger.Log($"{nameof(GameplayClockContainer)} seeking to {time}");

            GameplayClock.Seek(time);

            OnSeek?.Invoke();
        }

        /// <summary>
        /// Stops gameplay and marks paused state.
        /// </summary>
        public void Stop()
        {
            if (isPaused.Value)
                return;

            isPaused.Value = true;
            StopGameplayClock();
        }

        protected virtual void StartGameplayClock() => GameplayClock.Start();
        protected virtual void StopGameplayClock() => GameplayClock.Stop();

        /// <summary>
        /// Resets this <see cref="GameplayClockContainer"/> and the source to an initial state ready for gameplay.
        /// </summary>
        /// <param name="time">The time to seek to on resetting. If <c>null</c>, the existing <see cref="StartTime"/> will be used.</param>
        /// <param name="startClock">Whether to start the clock immediately, if not already started.</param>
        public void Reset(double? time = null, bool startClock = false)
        {
            bool wasPaused = isPaused.Value;

            Stop();

            ensureSourceClockSet();

            if (time != null)
                StartTime = time.Value;

            Seek(StartTime);

            if (!wasPaused || startClock)
                Start();
        }

        /// <summary>
        /// Changes the source clock.
        /// </summary>
        /// <param name="sourceClock">The new source.</param>
        protected void ChangeSource(IClock sourceClock) => GameplayClock.ChangeSource(SourceClock = sourceClock);

        /// <summary>
        /// Ensures that the <see cref="GameplayClock"/> is set to <see cref="SourceClock"/>, if it hasn't been given a source yet.
        /// This is usually done before a seek to avoid accidentally seeking only the adjustable source in decoupled mode,
        /// but not the actual source clock.
        /// That will pretty much only happen on the very first call of this method, as the source clock is passed in the constructor,
        /// but it is not yet set on the adjustable source there.
        /// </summary>
        private void ensureSourceClockSet()
        {
            if (GameplayClock.Source == null)
                ChangeSource(SourceClock);
        }

        #region IAdjustableClock

        bool IAdjustableClock.Seek(double position)
        {
            Seek(position);
            return true;
        }

        void IAdjustableClock.Reset() => Reset();

        public virtual void ResetSpeedAdjustments()
        {
        }

        double IAdjustableClock.Rate
        {
            get => GameplayClock.Rate;
            set => throw new NotSupportedException();
        }

        public double Rate => GameplayClock.Rate;

        public double CurrentTime => GameplayClock.CurrentTime;

        public bool IsRunning => GameplayClock.IsRunning;

        #endregion

        public void ProcessFrame()
        {
            // Handled via update. Don't process here to safeguard from external usages potentially processing frames additional times.
        }

        public double ElapsedFrameTime => GameplayClock.ElapsedFrameTime;

        public double FramesPerSecond => GameplayClock.FramesPerSecond;

        public FrameTimeInfo TimeInfo => GameplayClock.TimeInfo;
    }
}


text:
package it.backbox;

import java.io.File;
import java.sql.SQLException;
import java.util.List;

import it.backbox.bean.Chunk;
import it.backbox.exception.BackBoxException;

public interface IDBManager {

	/**
	 * Open the jdbc connection
	 *
	 * @throws BackBoxException
	 * @throws SQLException
	 */
	public void openDB() throws BackBoxException, SQLException;

	/**
	 * Close the jdbc connection
	 *
	 * @throws SQLException
	 */
	public void closeDB() throws SQLException;

	/**
	 * Delete file informations from database
	 *
	 * @param folder
	 *            Folder alias where the file is
	 * @param filename
	 *            Name of the file to delete
	 * @param hash
	 *            File hash to delete
	 * @return Row count deleted
	 * @throws BackBoxException
	 * @throws SQLException
	 */
	public int delete(String folder, String filename, String hash) throws BackBoxException, SQLException;

	/**
	 * Insert new file information in database
	 *
	 * @param file
	 *            New file
	 * @param filename
	 *            File relative path
	 * @param folder
	 *            Folder where the file is
	 * @param hash
	 *            New file hash
	 * @param chunks
	 *            List of new file chunks
	 * @param encrypted
	 * @param compressed
	 * @param splitted
	 *
	 * @return Row count added
	 * @throws SQLException
	 */
	public int insert(File file, String filename, String folder, String hash, List<Chunk> chunks, short encrypted,
			short compressed, short splitted) throws SQLException;

	/**
	 * Edit file information in database
	 *
	 * @param hash
	 *            Hash of the file to edit
	 * @param folder
	 *            Folder of the file to edit
	 * @param filename
	 *            Filename of the file to edit
	 * @param newFolder
	 *            New folder name
	 * @param newFilename
	 *            New filename
	 * @param fileLastModified
	 *            New file last modified time
	 * @param fileSize
	 *            New file size
	 * @param encrypted
	 * @param compressed
	 * @param splitted
	 * @returnRow count added
	 * @throws BackBoxException
	 * @throws SQLException
	 */
	public int update(String hash, String folder, String filename, String newFolder, String newFilename,
			long fileLastModified, long fileSize, short encrypted, short compressed, short splitted)
					throws BackBoxException, SQLException;

	/**
	 * Get the record of a file
	 *
	 * @param folder
	 *            Folder alias where the file is
	 * @param filename
	 *            Name of the file
	 * @param hash
	 *            Hash of the file
	 *
	 * @return The file record
	 * @throws SQLException
	 */
	public it.backbox.bean.File getFileRecord(String folder, String filename, String hash) throws SQLException;

	/**
	 * Get the chunks of the file with the hash in input
	 *
	 * @param filehash
	 *            File hash
	 * @return File chunks
	 * @throws SQLException
	 */
	public List<it.backbox.bean.Chunk> getFileChunks(String filehash) throws SQLException;

	/**
	 * Get all the files with the hash in input
	 *
	 * @param filehash
	 *            File hash
	 * @return File list
	 * @throws SQLException
	 */
	public List<it.backbox.bean.File> getFiles(String filehash) throws SQLException;

	/**
	 * Get all the files in a folder
	 *
	 * @param folder
	 *            Folder to list
	 * @return File list
	 * @throws SQLException
	 */
	public List<it.backbox.bean.File> getFilesInFolder(String folder) throws SQLException;

	/**
	 * Reset or create the database and open the connection
	 *
	 * @throws BackBoxException
	 * @throws SQLException
	 */
	public void createDB() throws BackBoxException, SQLException;

	/**
	 * Get all files in the database
	 *
	 * @return List of all files
	 * @throws SQLException
	 */
	public List<it.backbox.bean.File> getAllFiles() throws SQLException;

	/**
	 * Get all chunks in the database
	 *
	 * @return List of all chunks
	 * @throws SQLException
	 */
	public List<it.backbox.bean.Chunk> getAllChunks() throws SQLException;

	/**
	 * Check if the db has been modified
	 *
	 * @return True if the db has been modified, false otherwise
	 */
	public boolean isModified();

}


text:
var helpers = require("../helpers");
var KEY_FILE = "key.json";

var task =  function(request, callback){
	var keyConfig = helpers.readJSONFile(KEY_FILE).key;
	var key = request.query.key;
	console.log(keyConfig);
	console.log(key);
	if(key !== keyConfig) {
		callback("wrong access key");
	}
	else {
		callback(null, {binary:true, filePath:__dirname + "\\zad.zip"});
	}

}

exports.action = task


text:
require "bundler/setup"
require 'minitest/assertions'
require "minitest/autorun"
require "minitest/mock"
require "xmlsimple"
require "json"
require "pathname"

$: << File.expand_path('../../lib', __FILE__)
require "sablon"
require "sablon/test/assertions"

class Sablon::TestCase < MiniTest::Test
  include Sablon::Test::Assertions

  def teardown
    super
  end

  class MockTemplate
    attr_reader :document

    def initialize
      @path = nil
      @document = MockDomModel.new
    end
  end

  # catch all for method stubs that are needed during testing
  class MockDomModel
    attr_accessor :current_entry
    attr_reader :current_rid, :zip_contents

    # Simple class to reload mock document components from fixtures on demand
    class ZipContents
      def [](entry_name)
        load_mock_content(entry_name)
      end

      private

      # Loads and parses individual files to build the mock document
      def load_mock_content(entry_name)
        root = Pathname.new(File.dirname(__FILE__))
        xml_path = root.join('fixtures', 'xml', 'mock_document', entry_name)
        Nokogiri::XML(File.read(xml_path))
      end
    end

    def initialize
      @current_entry = nil
      @current_rid = 1234
      @current_rid_start = @current_rid
      @current_numid = 0
      @current_numid_start = @current_numid
      @zip_contents = ZipContents.new
    end

    # Returns the corresponding DOM handled file
    def [](entry_name)
      Sablon::DOM.wrap_with_handler(entry_name, @zip_contents[entry_name])
    end

    def add_relationship(*)
      "rId#{@current_rid += 1}"
    end

    def add_list_definition(style)
      @current_numid += 1
      Struct.new(:style, :numid).new(style, @current_numid)
    end

    def reset
      @current_rid = @current_rid_start
      @current_numid = @current_numid_start
    end

    alias add_media add_relationship
  end
end


text:
title: "Thai Pale Ale"
date: "2009-08-04"
layout: "post"
categories: "brewing"
tags:
  - "thai"
---

Amber has been on Andrew and I for some time to make a beer involving ginger, lemongrass and Thai chilies. Needless to say, it sounded a bit too experimental at first.

Then last year at the [Oregon Brewers Festival](http://oregonbrewfest.com/), there was a brew that leaned heavy on the ginger. Spicy, but still definitely beer (not just strong ginger-ale). We sampled it, and our minds were changed.

It took a while before we got to it, but the basic recipe was a pale ale with these added to the boil:

- 20 stalks of lemongrass (45 minutes)
- 2 packs of Kafir lime leaves (45 minutes, approximately 30 leaves per pack)
- 4 large hands of ginger, coined (30 minutes)
- 10 hot Thai peppers (15 minutes)

The result has been well received. It is very gingery and next go around I think we'll do something to up the citrus content, as the lemongrass is pretty subtle. It was also a little foamy, which is about the only downside. I'm voting to increase the peppers, but as the [hot food fiend](/brewing/2007/07/14/is-it-getting-chile-in-here) I might be the outlier there. We'll also probably use an amber ale base instead, as the pale ale almost disappears behind the potent ginger in this batch.

In any case, an interesting experiment with great promise for the future.


text: import 'antd-mobile/lib/notice-bar/style/css';


text:
<?php

class Ramybrook_Hpb_Model_Resource_Homepageblock
    extends Mage_Core_Model_Resource_Db_Abstract
{
    protected function _construct()
    {
        $this->_init('ramybrook_hpb/ramybrook_hpb', 'block_id');
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Copyright 2016 Red Hat Inc. and/or its affiliates and other contributors.
-
- Licensed under the Apache License, Version 2.0 (the "License")
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <groupId>org.switchyard</groupId>
    <artifactId>switchyard-build</artifactId>
    <name>SwitchYard: Build</name>
    <version>3.0.0-SNAPSHOT</version>
    <description>The SwitchYard Build Module</description>
    <url>http://switchyard.org</url>
    <organization>
        <name>JBoss by Red Hat</name>
        <url>http://jboss.org</url>
    </organization>
    <issueManagement>
        <system>jira</system>
        <url>http://jira.jboss.org/browse/SWITCHYARD</url>
    </issueManagement>
    <developers>
        <developer>
            <name>SwitchYard committers</name>
        </developer>
    </developers>
    <licenses>
        <license>
            <name>GNU Lesser General Public License</name>
            <url>http://www.gnu.org/copyleft/lesser.html</url>
            <distribution>repo</distribution>
        </license>
    </licenses>
    <scm>
        <url>http://github.com/switchyard/core</url>
    </scm>
    <distributionManagement>
        <repository>
            <id>jboss-releases-repository</id>
            <name>JBoss Releases Repository</name>
            <url>https://repository.jboss.org/nexus/service/local/staging/deploy/maven2/</url>
        </repository>
        <snapshotRepository>
            <id>jboss-snapshots-repository</id>
            <name>JBoss Snapshots Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/snapshots/</url>
        </snapshotRepository>
    </distributionManagement>
</project>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title></title>

    <link href="css/bootstrap.css" rel="stylesheet">

    <link href="css/freelancer.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href="css/awesome-bootstrap-checkbox.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Michael Ross

                        Portfolio

                        About

                        Contact

                        Software Developer

                        Web Development - Mobile Development - Application Development

Resume

                                 Resume

Portfolio

                                 School Work

                                 Outside Projects

About

Freelancer is a free bootstrap theme created by Start Bootstrap. The download includes the complete source files including HTML, CSS, and JavaScript as well as optional LESS stylesheets for easy customization.

Whether you're a student looking to showcase your work, a professional looking to attract clients, or a graphic artist looking to share your projects, this template is the perfect starting point!

                         Download Theme

Contact Me

                    <form name="sentMessage" id="contactForm" novalidate>

                                Name
                                <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">

                                Email Address
                                <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">

                                Phone Number
                                <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">

                                Message
                                <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-success btn-lg">Send</button>

                    </form>

Location

3481 Melrose Place
Beverly Hills, CA 90210

Around the Web

About Freelancer

Freelance is a free to use, open source Bootstrap theme created by Start Bootstrap.

                        Copyright © Your Website 2014

Resume

                                                    timeline

                                                    <form id="checkbox_form" role="form">

                                                        <input type="checkbox" id="checkbox_education" class="styled">

                                                            Education

                                                        <input type="checkbox" id="checkbox_employment" class="styled">

                                                            Employment

                                                        <input type="checkbox" id="checkbox_activities" class="styled">

                                                            Activities

                                                    </form>

The Pennsylvania State University

State College, Pennsylvania

Class of 2016

                                                                                Bachelor of Science in Computer Science

                                                                                Minor: Mathematics (already completed)

                                                                                GPA (last semester): 4.0

                                                                                GPA within Computer Science: 3.77

                                                                                Cumulative GPA: 3.56

IBM - Software Development Internship

May 2015 - Present

Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.

Workplace Dynamics - Software Development Internship

May 2014 - August 2014

Maintained and built on web applications written in C#, ASP.Net, HTML, Javascript, and SQL. Day-to-day, I fixed bugs and added new features to a website that receives traffic from around 2 million people a year.

Hack PSU

March 2014

Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.

Wagshal's Gourmet Deli

May 2013 - August 2013

Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.

Hack NY

April 2013

Maintained and built on web applications written in C#, ASP.Net, HTML, Javascript, and SQL. Day-to-day, I fixed bugs and added new features to a website that receives traffic from around 2 million people a year.

Hack PSU

March 2013

Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.

Gonzaga College High School

Washington D.C.

Class of 2012

                                                                                Cumulative GPA: 3.7

                                                                                Senior Year GPA: 4.4

                                                                                ACT Score: 33

                                                    skills

                                                        programming skills

                                                                95% Complete (success)

C# 95%

                                                                95% Complete

C++ 95%

                                                                90% Complete (warning)

C 90%

                                                                95% Complete (danger)

SQL 95%

                                                                95% Complete (success)

Java 95%

                                                                85% Complete (warning)

Javascript 85%

                                                                95% Complete

HTML 95%

Download CV

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

School Work

Project Title

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project Title

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project Title

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project Title

Use this area of the page to describe your project. The icon above is part of a free icon set by Flat Icons. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>


text:
from pygecko.multiprocessing import geckopy
import cv2
# from pygecko import image2msg
from pygecko.messages import image_st
from pygecko.transport import MsgPack
# import platform
# from imutils.video import VideoStream

def image2msg(img, compressed=False, handler=MsgPack):
    if compressed:
        jpg = cv2.imencode('.jpg', img)[1]
        # m = handler.dumps(img.tobytes())
        msg = image_st(img.shape, jpg, True)
    else:
        msg = image_st(img.shape, img.tobytes(), False)
    return msg

def publisher(**kwargs):
    geckopy.init_node(**kwargs)
    rate = geckopy.Rate(10)  # 10 Hz

    # p = geckopy.Publisher(['camera'])

    p = geckopy.pubBinderTCP(
        kwargs.get('key'),
        kwargs.get('topic')
    )
    if p is None:
        raise Exception("publisher is None")

    # determine if we should use picamera or standard usb camera
    # if platform.system() == 'Linux':
    #     picam = True
    # else:
    #     picam = False
    #
    # camera = VideoStream(usePiCamera=picam)
    # camera.start()

    while not geckopy.is_shutdown():
        img = camera.read()
        # img = cv2.resize(img, (320, 240))
        # img = cv2.resize(img, (640, 480))
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        msg = image2msg(img)
        p.publish('camera', msg)
        rate.sleep()

    print('pub bye ...')

if __name__ == '__main__':
    args = {"host": "localhost"}
    publisher(**args)


text:
import {MongoModel} from '../classes/MongoModel.ts';
import {PersonBE} from '../classes/PersonBE.ts';
import {IPerson} from '../interfaces/IPerson.ts';
import {IPersonWithCredentials} from '../interfaces/IPersonWithCredentials.ts';
import {Error} from '../interfaces/Error.ts';
import {Person as PersonModel} from '../db-models/Person.ts';
import {updateOrCreateCredential} from './Credential.ts';
import * as Q from 'q';
import {validate} from '../services/validate.ts';
import {returnServerError} from '../services/returnServerError.ts';

/**
 * Create Indexes for Person model
 */
    export function createPersonIndexes () {
        var model = new MongoModel('person');
        model.createIndex({email: 1}, {unique: true});
    }

/**
 * Register a new Person
 */
    export function registerPerson (personData: IPersonWithCredentials): Promise<IPerson> {
        var model = new MongoModel('person');
        var deferred = Q.defer();
        // Validate
        var validationResults = validate(personData, require('../schemas/PersonWithCredentials.json'));
        if (validationResults.errors.length) {
            var error: Error = {
                httpStatus: 400,
                description: 'Invalid parameters',
                error: validationResults.errors
            };
            deferred.reject(error);
            return deferred.promise;
        }
        getPersonDataFromEmail(personData.email).then(function (registeredPerson?: PersonModel) {
            // Verify if already registered
            if (registeredPerson) {
                var error: Error = {
                    httpStatus: 409,
                    description: 'Already registered'
                };
                deferred.reject(error);
                return;
            }
            // Register
            model.insert(personData).then(function (respData: PersonModel) {
                updateOrCreateCredential(personData.email, personData.password).then(function () {
                    deferred.resolve(respData);
                })
                // Error on register credentials
                .catch(function (err) {
                    model.remove({
                        email: personData.email
                    });
                    returnServerError(deferred)(err);
                });
            }).catch(returnServerError(deferred));
        }).catch(returnServerError(deferred));
        return deferred.promise;
    }

/**
 * Update or Create a Person
 */
    export function updateOrCreatePerson (personData: PersonModel): Promise<any> {
        var model = new MongoModel('person');
        var deferred = Q.defer();
        model.updateOrCreate({email: personData.email}, personData).then(function () {
            deferred.resolve();
        }).catch(deferred.reject);
        return deferred.promise;
    }

/**
 * Get Person Data
 */
    export function getPersonDataFromId (id: string): Promise<IPerson> {
        var model = new MongoModel('person');
        var deferred = Q.defer();
        model.findOne({ _id: id }).then(function (personData?: PersonModel) {
            deferred.resolve(personData);
        }).catch(deferred.reject);
        return deferred.promise;
    }
    export function getPersonDataFromEmail (email: string): Promise<IPerson> {
        var model = new MongoModel('person');
        var deferred = Q.defer();
        model.findOne({ email: email }).then(function (personData?: PersonModel) {
            deferred.resolve(personData);
        }).catch(deferred.reject);
        return deferred.promise;
    }


text:
package org.abins.platform.core.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.abins.platform.core.dao.IAPermissionDao;
import org.abins.platform.core.entity.ADictType;
import org.abins.platform.core.entity.APermission;
import org.abins.platform.core.service.IADictService;
import org.abins.platform.core.service.IAPermissionService;
import org.abins.platform.utils.MD5Util;
import org.abins.platform.utils.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 功能描述:登录控制器
 *
 * @author : yaobin 2016-9-28
 * @modify : yaobin 2016-9-28 <描述修改内容>
 */
@RequestMapping("/platform/main")
@Controller
public class ALoginController {

    /**
     * logger 日志
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public static final String LOGIN_TOKEN_ID = "tokenId";

    public static final String FAIL_STR = "fail";

    @Autowired
    private IAPermissionService permissionService;
    @Autowired
    private IADictService dictService;

    /**
     * <一句话功能简述> 进入登录页面
     *
     * @modefy : yaobin 2016-9-28
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/toLogin", method = RequestMethod.GET)
    public String platToLogin(@ModelAttribute(FAIL_STR) String failMsg, HttpServletRequest request, Model model, RedirectAttributes attr) {
        String tokenId = MD5Util.getInstance().getMD5ofStr(String.valueOf(System.currentTimeMillis()));
        request.getSession().setAttribute(LOGIN_TOKEN_ID, tokenId);
        model.addAttribute(LOGIN_TOKEN_ID, tokenId);
        model.addAttribute(FAIL_STR, failMsg);
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            model.addAttribute("currentUsername", currentUser.getPrincipal());
            return "platform/home";
        } else {
            return "platform/login";
        }
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String platGetLogin() {
        return "redirect:/platform/main/toLogin";
    }

    /**
     * <一句话功能简述> 登录验证
     *
     * @modefy : yaobin 2016-9-28
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String platLogin(HttpServletRequest request, Model model, RedirectAttributes attr) {
        HttpSession session = request.getSession();
        Object sessionTokenId = session.getAttribute(LOGIN_TOKEN_ID);
        String tokenId = request.getParameter(LOGIN_TOKEN_ID);
        if (sessionTokenId == null || StringUtil.isEmpty(tokenId)) {
            attr.addFlashAttribute(FAIL_STR, "请刷新页面,重新登录");
            return "redirect:/platform/main/toLogin";
        }
        String login_account = request.getParameter("login");
        String password = request.getParameter("password");
        if (StringUtil.isEmpty(login_account) || StringUtil.isEmpty(password)) {
            attr.addFlashAttribute(FAIL_STR, "账号或密码不能为空 ");
            return "redirect:/platform/main/toLogin";
        } else {
            session.removeAttribute(LOGIN_TOKEN_ID);
            // Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:config/shiro.ini");
            // // step2 解析shiro.ini 返回配置的 SecutiryManager 实例
            // SecurityManager securityManager = factory.getInstance();
            // // step3
            // SecurityUtils.setSecurityManager(securityManager);

            Subject currentUser = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(login_account, MD5Util.encryptMD5(password));
            token.setRememberMe(true);
            try {
                currentUser.login(token);
                logger.info("用户:[" + token.getUsername() + "]登录成功");
                model.addAttribute("currentUsername", currentUser.getPrincipal());
            } catch (UnknownAccountException uae) {
                attr.addFlashAttribute(FAIL_STR, "账号或密码不正确");
                return "redirect:/platform/main/toLogin";
            } catch (AuthenticationException e) {
                e.printStackTrace();
                attr.addFlashAttribute(FAIL_STR, "账号或密码不正确");
                return "redirect:/platform/main/toLogin";
            } catch (Exception e) {
                attr.addFlashAttribute(FAIL_STR, "系统异常,请重试");
                return "redirect:/platform/main/toLogin";
            }

//            APermission permission = permissionService.findById("4028b29557ad1da40157ad1da45d0000");
//            logger.info("permission={}", permission);
            List<ADictType> dictList = dictService.getAllType("cs");
            System.out.println(dictList);
            return "platform/home";
        }
    }

    /**
     * <一句话功能简述> 退出登录
     *
     * @modefy : yaobin 2016-10-9
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout() {
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.logout();
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return "redirect:/platform/main/toLogin";
    }

}


text:
import struct
from StringIO import StringIO

import vstruct.primitives as vs_prims

def isVstructType(x):
    return isinstance(x, vs_prims.v_base)

class VStruct(vs_prims.v_base):

    def __init__(self, bigend=False):
        # A tiny bit of evil...
        object.__setattr__(self, "_vs_values", {})
        vs_prims.v_base.__init__(self)
        self._vs_name = self.__class__.__name__
        self._vs_fields = []
        self._vs_field_align = False # To toggle visual studio style packing
        self._vs_padnum = 0
        self._vs_fmtbase = '<'
        if bigend:
            self._vs_fmtbase = '>'

    def vsGetClassPath(self):
        '''
        Return the entire class name (including module path).
        '''
        return '%s.%s' % (self.__module__, self._vs_name)

    def vsParse(self, bytes, offset=0):
        """
        For all the primitives contained within, allow them
        an opportunity to parse the given data and return the
        total offset...
        """
        plist = self.vsGetPrims()
        fmt = self.vsGetFormat()
        size = struct.calcsize(fmt)
        vals = struct.unpack(fmt, bytes[offset:offset+size])
        for i in range(len(plist)):
            plist[i].vsSetParsedValue(vals[i])

    def vsEmit(self):
        """
        Get back the byte sequence associated with this structure.
        """
        fmt = self.vsGetFormat()
        r = []
        for p in self.vsGetPrims():
            r.append(p.vsGetFmtValue())
        return struct.pack(fmt, *r)

    def vsGetFormat(self):
        """
        Return the format specifier which would then be used
        """
        # Unpack everything little endian, let vsParseValue deal...
        ret = self._vs_fmtbase
        for p in self.vsGetPrims():
            ret += p.vsGetFormat()
        return ret

    def vsIsPrim(self):
        return False

    def vsGetFields(self):
        ret = []
        for fname in self._vs_fields:
            fobj = self._vs_values.get(fname)
            ret.append((fname,fobj))
        return ret

    def vsGetField(self, name):
        x = self._vs_values.get(name)
        if x == None:
            raise Exception("Invalid field: %s" % name)
        return x

    def vsHasField(self, name):
        return self._vs_values.get(name) != None

    def vsSetField(self, name, value):
        if isVstructType(value):
            self._vs_values[name] = value
            return
        x = self._vs_values.get(name)
        return x.vsSetValue(value)

    # FIXME implement more arithmetic for structs...
    def __ixor__(self, other):
        for name,value in other._vs_values.items():
            self._vs_values[name] ^= value
        return self

    def vsAddField(self, name, value):
        if not isVstructType(value):
            raise Exception("Added fields MUST be vstruct types!")

        # Do optional field alignment...
        if self._vs_field_align:

            # If it's a primitive, all is well, if not, pad to size of
            # the first element of the VStruct/VArray...
            if value.vsIsPrim():
                align = len(value)
            else:
                fname = value._vs_fields[0]
                align = len(value._vs_values.get(fname))

            delta = len(self) % align
            if delta != 0:
                print "PADDING %s by %d" % (name,align-delta)
                pname = "_pad%d" % self._vs_padnum
                self._vs_padnum += 1
                self._vs_fields.append(pname)
                self._vs_values[pname] = vs_prims.v_bytes(align-delta)

        self._vs_fields.append(name)
        self._vs_values[name] = value

    def vsGetPrims(self):
        """
        return an order'd list of the primitive fields in this
        structure definition.  This is recursive and will return
        the sub fields of all nested structures.
        """
        ret = []
        for name, field in self.vsGetFields():
            if field.vsIsPrim():
                ret.append(field)
            else:
                ret.extend(field.vsGetPrims())

        return ret

    def vsGetTypeName(self):
        return self._vs_name

    def vsGetOffset(self, name):
        """
        Return the offset of a member.
        """
        offset = 0
        for fname in self._vs_fields:
            if name == fname:
                return offset
            x = self._vs_values.get(fname)
            offset += len(x)
        raise Exception("Invalid Field Specified!")

    def vsGetPrintInfo(self, offset=0, indent=0, top=True):
        ret = []
        if top:
            ret.append((offset, indent, self._vs_name, self))
        indent += 1
        for fname in self._vs_fields:
            x = self._vs_values.get(fname)
            off = offset + self.vsGetOffset(fname)
            if isinstance(x, VStruct):
                ret.append((off, indent, fname, x))
                ret.extend(x.vsGetPrintInfo(offset=off, indent=indent, top=False))
            else:
                ret.append((off, indent, fname, x))
        return ret

    def __len__(self):
        fmt = self.vsGetFormat()
        return struct.calcsize(fmt)

    def __getattr__(self, name):
        # Gotta do this for pickle issues...
        vsvals = self.__dict__.get("_vs_values")
        if vsvals == None:
            vsvals = {}
            self.__dict__["_vs_values"] = vsvals
        r = vsvals.get(name)
        if r is None:
            raise AttributeError(name)
        if isinstance(r, vs_prims.v_prim):
            return r.vsGetValue()
        return r

    def __setattr__(self, name, value):
        # If we have this field, asign to it
        x = self._vs_values.get(name, None)
        if x != None:
            return self.vsSetField(name, value)

        # If it's a vstruct type, create a new field
        if isVstructType(value):
            return self.vsAddField(name, value)

        # Fail over to standard object attribute behavior
        return object.__setattr__(self, name, value)

    def __iter__(self):
        # Our iteration returns name,field pairs
        ret = []
        for name in self._vs_fields:
            ret.append((name, self._vs_values.get(name)))
        return iter(ret)

    def __repr__(self):
        return self._vs_name

    def tree(self, va=0, reprmax=None):
        ret = ""
        for off, indent, name, field in self.vsGetPrintInfo():
            rstr = field.vsGetTypeName()
            if isinstance(field, vs_prims.v_number):
                val = field.vsGetValue()
                rstr = '0x%.8x (%d)' % (val,val)
            elif isinstance(field, vs_prims.v_prim):
                rstr = repr(field)
            if reprmax != None and len(rstr) > reprmax:
                rstr = rstr[:reprmax] + '...'
            ret += "%.8x (%.2d)%s %s: %s\n" % (va+off, len(field), " "*(indent*2),name,rstr)
        return ret

class VArray(VStruct):

    def __init__(self, elems=()):
        VStruct.__init__(self)
        for e in elems:
            self.vsAddElement(e)

    def vsAddElement(self, elem):
        """
        Used to add elements to an array
        """
        idx = len(self._vs_fields)
        self.vsAddField("%d" % idx, elem)

    def __getitem__(self, index):
        return self.vsGetField("%d" % index)

    #FIXME slice asignment

def resolve(impmod, nameparts):
    """
    Resolve the given (potentially nested) object
    from within a module.
    """
    if not nameparts:
        return None

    m = impmod
    for nname in nameparts:
        m = getattr(m, nname, None)
        if m == None:
            break

    return m

# NOTE: Gotta import this *after* VStruct/VSArray defined
import vstruct.defs as vs_defs

def getStructure(sname):
    """
    Return an instance of the specified structure.  The
    structure name may be a definition that was added with
    addStructure() or a python path (ie. win32.TEB) of a
    definition from within vstruct.defs.
    """
    x = resolve(vs_defs, sname.split("."))
    if x != None:
        return x()

    return None

def getModuleNames():
    return [x for x in dir(vs_defs) if not x.startswith("__")]

def getStructNames(modname):
    ret = []
    mod = resolve(vs_defs, modname)
    if mod == None:
        return ret

    for n in dir(mod):
        x = getattr(mod, n)
        if issubclass(x, VStruct):
            ret.append(n)

    return ret


text:
Resourceful more standardized controllers. Uses inherited resources. Geared towards api driven apps.

### Standards

More soon.

``` ruby
class Admin::Api::WidgetsController < ::Admin::Api::BaseController
  include ::Trax::Controller

  defaults :resource_class => ::Widget

  def resource_serializer
    ::Admin::Api::WidgetSerializer
  end

  #normally same as above unless overridden
  def collection_serializer
    ::Admin::Api::WidgetSerializer
  end
end
```

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'trax_controller'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install trax_controller

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it ( https://github.com/[my-github-username]/trax_controller/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request