text:
#include "TcpSocketEngine.h"
#ifdef RCONNECTION
# if defined NAV2_CLIENT_SERIES60_V2 || defined NAV2_CLIENT_SERIES60_V3
#  include <apengineconsts.h>
# endif
#endif
#include "TimeOutTimer.h"
#include "TcpSocketReader.h"
#include "TcpSocketWriter.h"
#include "WFTextUtil.h"
#include "CleanupSupport.h"
#include "SocketUser.h"
#include "DNSCache.h"

#include "Log.h"
#define LOGPOINTER if(iLog)iLog
#include "LogMacros.h"

CTcpSymbianEngine::CTcpSymbianEngine(class MTcpSymbianSocketUser& aConsole) :
   CActive(EPriorityStandard), iEngineStatus(EComplete), iConsole(aConsole),
   iTimeOut(KTimeOut)
{
}

class CTcpSymbianEngine* CTcpSymbianEngine::NewL(class MTcpSymbianSocketUser& aConsole,
                                                 class isab::LogMaster* aLogMaster)
{
   class CTcpSymbianEngine* self = NewLC(aConsole, aLogMaster);
   CleanupStack::Pop(self);
   return self;
}

class CTcpSymbianEngine* CTcpSymbianEngine::NewLC(class MTcpSymbianSocketUser& aConsole,
                                                  class isab::LogMaster* aLogMaster)
{
   class CTcpSymbianEngine* self = new(ELeave) CTcpSymbianEngine(aConsole);
   CleanupStack::PushL(self);
   self->ConstructL(aLogMaster);
   return self;
}

CTcpSymbianEngine::~CTcpSymbianEngine()
{
   DBG("~CTcpSymbianEngine");
   iDNSCache.Reset();
   iDNSCache.Close();
   iEchoSocket.Close();
   CloseLinkLayer();
   delete iEchoRead;
   delete iEchoWrite;
   delete iTimer;
   iSocketServ.Close();
   iCritical.Close();
   DBG("~CTcpSymbianEngine done");
   delete iLog;
   delete iHostName;
}

void CTcpSymbianEngine::ConstructL(class isab::LogMaster* aLogMaster)
{
   if(aLogMaster){
      iLog = new (ELeave) isab::Log("TcpSymbianEngine", isab::Log::LOG_ALL, aLogMaster);
   }

   User::LeaveIfError(iCritical.CreateLocal());
   // Open channel to Socket Server
   User::LeaveIfError(iSocketServ.Connect());

   //best to have these after the socket is opened. just in case.
   iTimer = CTimeOutTimer::NewL(EPriorityHigh, *this);
   iEchoRead = CTcpSymbianRead::NewL(iEchoSocket, iConsole, *this, aLogMaster);
   iEchoWrite = CTcpSymbianWrite::NewL(iEchoSocket, iConsole, *this, aLogMaster);

   CActiveScheduler::Add(this);
   DBG("Fully constructed");
}

void CTcpSymbianEngine::OpenSocketL()
{
   User::LeaveIfError(OpenSocket());
}

TInt CTcpSymbianEngine::OpenSocket()
{
#if defined NAV2_CLIENT_SERIES60_V3 && !defined __WINS__ && !defined __WINSCW__
   TInt ret = iEchoSocket.Open(iSocketServ, KAfInet,
                               KSockStream, KProtocolInetTcp, iConnection);
#else
   TInt ret = iEchoSocket.Open(iSocketServ, KAfInet,
                               KSockStream, KProtocolInetTcp);
#endif
   DBG("OpenSocket returns %d", ret);
   return ret;
}

void CTcpSymbianEngine::DoCancel()
   // Cancel asychronous requests
{
   DBG("DoCancel");
   iTimer->Cancel();
   // Cancel appropriate request to socket
   //please handle bad opens!
   switch (EngineState()){
   case EConnecting:
      DBG("While EConnecting");
      iEchoSocket.CancelConnect();
      break;
   case ELookingUp:
      DBG("While ELookingUp");
      // Cancel look up attempt
      iResolver.Cancel();
      iResolver.Close();
      break;
   case ELinking:
      DBG("While ELinking");
      CloseLinkLayer();
      break;
   case EClosing:
      DBG("While EClosing");
      break;
   default:
      ERR("PANIC KEchoEngine, EBadCancelStatus (%d)", TInt(EBadCancelStatus));
      User::Panic(KEchoEngine, EBadCancelStatus);
      break;
   }
   DBG("DoCancel comnplete");
}

void CTcpSymbianEngine::Connect(TUint32 aAddr, TUint aPort)
   // Connect to an Echo Socket by IP address
{
   DBG("Connect(0x%"PRIx32", %u)", aAddr, aPort);
   iAddress.SetPort(aPort);
   iAddress.SetAddress(aAddr);

   iEchoSocket.Connect(iAddress, iStatus);
   SetEngineState(EConnecting);
   //beware deadlocks! notify outside critical regions.
   iConsole.ConnectionNotify(isab::Module::CONNECTING,
                              isab::Module::REQUESTED);

   SetActive();
   iTimer->After(iTimeOut);
}

void CTcpSymbianEngine::ConnectL(const TDesC8& aServerName, TUint aPort,
                                 TInt aIAP, TBool aConsiderWLAN)
{
   DBG("ConnectL(%*s, %u, %d)", aServerName.Length(), aServerName.Ptr(),
       aPort, aIAP);
   HBufC* wide = HBufC::NewLC(aServerName.Length() + 4);
   TPtr wide_p = wide->Des();
   WFTextUtil::TDesWiden(wide_p, aServerName);
   ConnectL(*wide, aPort, aIAP, aConsiderWLAN);
   CleanupStack::PopAndDestroy(wide);
}

namespace {
   /**
    * This function replaces the content of aDst with the content of
    * aSrc, reallocating if necessary. If aDst is NULL a new HBufC
    * will be allocated. Otherwise reallocation will only occur if the
    * content of aSrc will not fit in aDst.
    * @param aDst The destination HBufC. Note that this is a pointer
    *             reference.
    * @param aSrc The source descriptor.
    */
   void ReplaceL(HBufC*& aDst, const TDesC& aSrc)
   {
      if(!aDst || *aDst != aSrc){
         if(aDst && aDst->Des().MaxLength() >= aSrc.Length()){
            aDst->Des() = aSrc;
         } else {
            delete aDst;
            aDst = NULL;
            aDst = aSrc.AllocL();
         }
      }
   }
}

void CTcpSymbianEngine::SetConnectionParamsL(const TDesC& aServerName,
                                             TUint aPort, TInt aIAP,
                                             TBool aConsiderWLAN)
{
   iPort = aPort;
   iIAP = aIAP;
   iConsiderWLAN = aConsiderWLAN;
   ReplaceL(iHostName, aServerName);
}

void CTcpSymbianEngine::ConnectL(const TDesC& aServerName, TUint aPort,
                                 TInt aIAP, TBool aConsiderWLAN)
{
   DBG("ConnectL(HOST, %u, %d)", aPort, aIAP);
   //see if state is EComplete. used several times below
   const TBool stateComplete = (EngineState() == EComplete);
   //The changeServer variable indicates that we must close the
   //current connection and open a new one.
   const TBool changeServer = !stateComplete && iHostName &&
      (*iHostName != aServerName || iPort != aPort);
   DBG("stateComplete: %d, changeServer: %d", stateComplete, changeServer);
   if(changeServer){
      WARN("Switching server, danger will robinson");
      Stop(ESwitching);
      SetConnectionParamsL(aServerName, aPort, aIAP, aConsiderWLAN);
   } else {
      DBG("No need to change server");
      if(stateComplete){
         DBG("update params");
         SetConnectionParamsL(aServerName, aPort, aIAP, aConsiderWLAN);
      }
      ConnectL();
   }
}

void CTcpSymbianEngine::ConnectL()
{
   DBG("ConnectL()");
   if(EngineState() == EComplete){
      iConsole.ConnectionNotify( isab::Module::CONNECTING,
                                 isab::Module::REQUESTED );
      OpenLinkLayerL(); //setactive here
   } else {
      DBG("Do nothing, but handle the next request.");
      if(!IsActive()){ //don't think this is needed
         DBG("Signal OperationComplete");
         iConsole.OperationComplete();
      } else {
         WARN("This was unexpected!");
      }
   }
}

void CTcpSymbianEngine::StartLookupL()
{
   DBG("StartLookupL");
   SetEngineState(ELookingUp);
   // Initiate DNS
   if(KErrNone ==
#if defined NAV2_CLIENT_SERIES60_V3  && !defined __WINS__ && !defined __WINSCW__
      iResolver.Open(iSocketServ, KAfInet,
                     KProtocolInetUdp, iConnection)
#else
      iResolver.Open(iSocketServ, KAfInet, KProtocolInetUdp)
#endif
      ){

      if(KErrNone == iDNSCache.CacheHostLookup(*iHostName, iNameEntry, iPort)){
         DBG("Host found in cache");
         CompleteSelf(KErrNone);
      } else {
         DBG("Host not found in cache, looking up in DNS");
         // DNS request for name resolution
         iResolver.GetByName(*iHostName, iNameEntry, iStatus);
         SetActive();
      }
      // Request time out
      iTimer->After(iTimeOut);
      //signal state
      iConsole.ConnectionNotify(isab::Module::CONNECTING,
                                 isab::Module::REQUESTED);
      DBG("Starting asynchronous name lookup");
   } else {
      WARN("Lookup failed");
      ResetL(ELookUpFailed, isab::Module::LOOKUP_FAILED);
   }
}

void CTcpSymbianEngine::OpenLinkLayerL()
{
   DBG("OpenLinkLayerL");
   // Select IAP
   SetEngineState(ELinking);
#if defined RCONNECTION || defined RAGENT
   if(iIAP == -1){
      iConsole.ConnectionNotify(isab::Module::WAITING_FOR_USER,
                                 isab::Module::REQUESTED);
   }
#endif

#ifdef RCONNECTION
   OpenLinkLayerConnectionL(); //setactive here
#elif defined RAGENT
   OpenLinkLayerAgentL();
#else
   OpenFakeLinkLayerL();
#endif
   SetEngineState(ELinking);
   // Request time out
   iTimer->After(iTimeOut);
}

void CTcpSymbianEngine::OpenFakeLinkLayerL()
{
   DBG("Faking Link layer by async completion");
   CompleteSelf(KErrNone);
}

void CTcpSymbianEngine::OpenLinkLayerConnectionL()
{
#ifdef RCONNECTION
   DBG("OpenLinkLayerConnectionL");
# if defined __WINS__ || defined __WINSCW__
   OpenFakeLinkLayerL();
# else
   User::LeaveIfError(iConnection.Open(iSocketServ));

   iPrefs = TCommDbConnPref();

   DBG("iIAP == %d", iIAP);
   if (iIAP >= 0) {
      iPrefs.SetIapId(iIAP);
      iPrefs.SetDialogPreference(ECommDbDialogPrefDoNotPrompt);
      iConnection.Start(iPrefs, iStatus);
   } else if (iIAP == -2) {
      // Debug mode - use system default
      iConnection.Start(iStatus);
   } else { //iIAP == -1
      // Use Always ask
      iPrefs.SetDialogPreference(ECommDbDialogPrefPrompt);
      iPrefs.SetDirection(ECommDbConnectionDirectionOutgoing);
#  if   defined NAV2_CLIENT_SERIES60_V2
      iPrefs.SetBearerSet( EApBearerTypeGPRS | EApBearerTypeHSCSD );
#  elif defined NAV2_CLIENT_SERIES60_V3
      iPrefs.SetBearerSet( EApBearerTypeGPRS | EApBearerTypeHSCSD |
                           EApBearerTypeCDMA );
#  elif defined NAV2_CLIENT_UIQ3
      iPrefs.SetBearerSet( ECommDbBearerCSD | ECommDbBearerWcdma |
                           ECommDbBearerCdma2000 | ECommDbBearerPSD |
                           (iConsiderWLAN ? (ECommDbBearerWLAN | ECommDbBearerLAN) : 0) );
#  else //s80, s90
      iPrefs.SetBearerSet( ECommDbBearerCSD | ECommDbBearerWcdma |
                           ECommDbBearerCdma2000 | ECommDbBearerPSD );

#  endif
      iConnection.Start(iPrefs, iStatus);
   }
   SetActive();
   DBG("Starting asynchronous link layer setup");
# endif
#else
   ERR("OpenLinkLayerConnectionL");
#endif
}

void CTcpSymbianEngine::OpenLinkLayerAgentL()
{
#ifdef RAGENT
   DBG("OpenLinkLayerAgentL");
   iAgent = new (ELeave) RGenericAgent;
   User::LeaveIfError(iAgent->Open());
   // Series60 release 1 (eg. Nokia 7650/3650)
   //
   TBool isUp=EFalse;
   iAgent->NetworkActive(isUp);
   if (!isUp) {
      // Attempt to open a connection using the selected IAP
      delete iCommsOverrides;
      iCommsOverrides = NULL;
# ifdef NAV2_CLIENT_UIQ
      iCommsOverrides =
         CStoreableOverrideSettings::NewL(
            CStoreableOverrideSettings::EParamListPartial );
# else //s60v1
      iCommsOverrides =
         CStoreableOverrideSettings::NewL(
            CStoreableOverrideSettings::EParamListPartial,
            EDatabaseTypeIAP);
# endif
      iPrefs = CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref();
      iPrefs.iRanking = 1;
      iPrefs.iDirection = ECommDbConnectionDirectionOutgoing;
      iPrefs.iBearer.iBearerSet = ECommDbBearerUnknown;
      if(iIAP != -2){
         if (iIAP >= 0) {
            iPrefs.iDialogPref = ECommDbDialogPrefDoNotPrompt;
            iPrefs.iBearer.iIapId = iIAP;
         } else {
            // Use Always ask
            iPrefs.iDialogPref = ECommDbDialogPrefPrompt;
            iPrefs.iBearer.iIapId = 0;
         }
         iCommsOverrides->SetConnectionPreferenceOverride(iPrefs);
         iAgent->StartOutgoing(*iCommsOverrides, iStatus);
         SetActive();
         DBG("Starting async link layer connection");
      }
   }
   if(!IsActive()){
      //if IsActive returns EFalse the network is either already up or
      //we should use system default (iap = -2), in either case
      //complete immediately
      DBG("Link layer already active, complete immediately. ");
      CompleteSelf(KErrNone);
   }
#else
   ERR("OpenLinkLayerAgentL");
#endif
}

void CTcpSymbianEngine::CloseLinkLayer()
{
   DBG("CloseLinkLayer");
#ifdef RCONNECTION
   iConnection.Close();
#elif defined RAGENT
   if(iAgent){
      iAgent->Close();
      delete iAgent;
      iAgent = NULL;
   }
#else
   //do nothing
#endif
   DBG("CloseLinkLayer complete");
}

TBool CTcpSymbianEngine::IsConnected()
{
   return EngineState() == EConnected;
}

void CTcpSymbianEngine::Query()
{
   DBG("Query");
   //TODO: keep the disconnect reasons somewhere, we can give better
   //indication that way.
   enum isab::Module::ConnectionNotify state = isab::Module::CLEAR;
   enum isab::Module::ConnectionNotifyReason reason = isab::Module::REQUESTED;
   switch(EngineState()){
   case EComplete:                                               break;
   case EConnecting:    state  = isab::Module::CONNECTING;       break;
   case EConnected:     state  = isab::Module::CONNECTED;        break;
   case ETimedOut:      state  = isab::Module::DISCONNECTING;
                        reason = isab::Module::UNSPECIFIED;      break;
   case ELinking:       state  = isab::Module::CONNECTING;       break;
   case ELinkFailed:    state  = isab::Module::DISCONNECTING;
                        reason = isab::Module::TRANSPORT_FAILED; break;
   case ELookingUp:     state  = isab::Module::CONNECTING;       break;
   case ELookUpFailed:  state  = isab::Module::DISCONNECTING;
                        reason = isab::Module::LOOKUP_FAILED;    break;
   case EConnectFailed: state  = isab::Module::DISCONNECTING;
                        reason = isab::Module::NO_RESPONSE;      break;
   case EClosing:       state  = isab::Module::DISCONNECTING;
                        reason = isab::Module::REQUESTED;        break;
   case EBroken:        state  = isab::Module::DISCONNECTING;
                        reason = isab::Module::CHANNEL_FAILED;   break;
   case ESwitching:     state  = isab::Module::CONNECTING;
                        reason = isab::Module::REQUESTED;        break;
   case EClosed:        state  = isab::Module::DISCONNECTING;
                        reason = isab::Module::BY_PEER;   break;
   }
   iConsole.ConnectionNotify(state, reason);
}

void CTcpSymbianEngine::Write(HBufC8* aData)
{
   if(EngineState() != EConnected || iEchoWrite->IsActive()){
      ERR("EngineState: %d, Echowrite is %sactive", EngineState(), iEchoWrite->IsActive() ? "": "not");
   }
   __ASSERT_ALWAYS(EngineState() == EConnected,
                   User::Panic(KEchoEngine, EWriteNotConnected));
   __ASSERT_ALWAYS(!iEchoWrite->IsActive(),
                   User::Panic(KEchoEngine, EWriteActive));
   //we should never get here unless CTcpSymbianEngine is ready for
   //another write.  See assertations above.
   if ((EngineState() == EConnected) && !iEchoWrite->IsActive()){
      iEchoWrite->IssueWrite(aData);
   } else {
      ERR("Write issued while not connected or echowrite is active");
   }
}

void CTcpSymbianEngine::Read()
{
   __ASSERT_ALWAYS(EngineState() == EConnected,
                   User::Panic(KEchoEngine, EReadNotConnected));
   ///if we are already active, that's not a problem.
   if ((EngineState() == EConnected) && (!iEchoRead->IsActive())) {
      iEchoRead->IssueRead();
   } else {
      ERR("Read issued while not connected ot echoread is active");
   }
}

void CTcpSymbianEngine::CompleteSelf(TInt aCompleteStatus)
{
   iStatus = KRequestPending;
   SetActive();
   class TRequestStatus* p = &iStatus;
   User::RequestComplete(p, aCompleteStatus);
}

void CTcpSymbianEngine::RunL()
{
   DBG("RunL, EngineState: %d, iStatus: %d", EngineState(), iStatus.Int());
   iTimer->Cancel(); // Cancel TimeOut timer before handling completion
   switch(EngineState()){
   case EConnecting:
      // IP connection request
      if (iStatus == KErrNone){
         DBG("Connection completed Ok");
         // Connection completed sucessfully
         iConsole.ConnectionNotify(isab::Module::CONNECTED,
                                    isab::Module::REQUESTED);
         SetEngineState(EConnected);
         Read(); //Start CTcpSymbianRead Active object
      } else {
         WARN("Unable to connect, removing host from cache.");
         iDNSCache.Remove(*iHostName);
         if (iStatus == KErrCouldNotConnect){
            ResetL(EConnectFailed, isab::Module::NO_RESPONSE);
         } else if (iStatus == KErrTimedOut) {
            ResetL(ETimedOut, isab::Module::NO_RESPONSE);
         } else{
            WARN("EConnectFailed, INTERNAL_ERROR");
            ResetL(EConnectFailed, isab::Module::INTERNAL_ERROR);
            //handle the different cases here
         }
      }
      break;
   case ELookingUp:
      iResolver.Close();
      if (iStatus == KErrNone) {
         DBG("Name lookup ok");
         // DNS look up successful
         // Extract domain name and IP address from name record
         class TInetAddr addr = TInetAddr::Cast(iNameEntry().iAddr);
         //cache the ip for later.
         TInt cacheStat = iDNSCache.CacheHost(*iHostName, addr.Address());
         DBG("Host cached with result %d", cacheStat);
         cacheStat = cacheStat;
         // And connect to the IP address
         Connect(addr.Address(), iPort); //setactive here
      } else { //includes KErrTimedOut
         WARN("Lookup failed");
         ResetL(ELookUpFailed, isab::Module::LOOKUP_FAILED);
      }
      break;
   case ELinking:
      if(iStatus == KErrNone){
         DBG("Link layer setup ok");
         OpenSocketL();  //cannot open socket until here. We need RConnection.
         StartLookupL(); //setactive here
      } else { //includes KErrCanceled and KErrTimedOut
         WARN("Link layer setup failed");
         ResetL(ELinkFailed, isab::Module::TRANSPORT_FAILED);
      }
      break;
   case EBroken:
      DBG("Broken");
      ResetL( EngineState(), isab::Module::CHANNEL_FAILED );
      break;
   case EClosing:
      if(iStatus == KErrNone){
         DBG("Closing ok");
         ResetL(EComplete, isab::Module::REQUESTED);
      } else if(iStatus == KErrTimedOut){
         ResetL(ETimedOut);
      } else {
         ResetL(EngineState());
      }
      break;
   case ESwitching:
      if(iStatus == KErrNone){
         //the connection has been closed, start a new connection
         //using the values in iHostName, iPort, and iIAP.
         SetEngineState(EComplete);
         ConnectL();
      } else if(iStatus == KErrTimedOut){
         ResetL(ETimedOut);
      } else {
         ResetL(EngineState());
      }
      break;
   case EClosed:
      DBG("Closed");
      ResetL( EngineState(), isab::Module::BY_PEER );
      break;
   default:
      ERR("PANIC KEchoEngine EBadEngineState (%d)", TInt(EBadEngineState));
      User::Panic(KEchoEngine, EBadEngineState);
      break;
   };
   if(!IsActive()){
      DBG("Signal OperationComplete");
      iConsole.OperationComplete();
      DBG("Signaled OperationComplete");
   }
}

TInt CTcpSymbianEngine::RunError(TInt aError)
{
   //RunL contains two functions that may leave: ResetL and StartLookupL.
   //ResetL will leave if RSocket::Open fails.
   //StartLookupL will leave if ResetL leaves.
   //Hey, I see a pattern here!

   //In other words, any time we end up here it's because a call to
   //RSocket::Open has failed. This is very, very bad. It's very
   //probable that we will not be able to recover from this. We might
   //as well give up and start farming chipmunks.

   ERR("RunError %d", aError);
   iConsole.Panic(aError);

   //Return KErrNone here to placate the active scheduler.
   return KErrNone;
}

void CTcpSymbianEngine::TimerExpired()
{
   DBG("TimerExpired");
   Cancel();
   CompleteSelf(KErrTimedOut);
}

void CTcpSymbianEngine::Stop()
   // Shutdown connection request
{
   Stop(EClosing);
}

void CTcpSymbianEngine::Stop(enum TEchoEngineState aState)
{
   enum TEchoEngineState state = EngineState();
   DBG("Stop, Enginestate: %d, aState: %d", state, aState);
   if(state != EComplete){
      iConsole.BlockEvents();
   }
   switch (state){
   case EConnected:
      // Stop live connection
      iEchoRead->Cancel();
      iEchoWrite->Cancel();
      SetEngineState(aState);
      iEchoSocket.Shutdown(RSocket::EImmediate, iStatus);
      SetActive();
      iTimer->After(iTimeOut);
      break;
   case EConnecting:
   case ELookingUp:
   case ELinking:
      // if request to CTcpSymbianEngine, then stop it
      Cancel();
      break;
   case ESwitching:
      SetEngineState(EClosing);
      break;
   case EClosing:
      ///already closing.
      break;
   case EComplete:
      //all set.
      if(!IsActive()){
         DBG("Signal OperationComplete");
         iConsole.OperationComplete();
         DBG("Signaled OperationComplete");
      }
      break;
   default:
      ERR("PANIC KEchoEngine EBadEngineStopState (%d)", EBadEngineStopState);
      User::Panic(KEchoEngine, EBadEngineStopState);
      break;
   }
}

void CTcpSymbianEngine::ResetL(enum TEchoEngineState aDuring)
{
   DBG("ResetL(%d)", aDuring);
   SetEngineState(aDuring);   //temporary state
   iEchoSocket.Close();       //close the socket..
   CloseLinkLayer();          //..and the link layer
   SetEngineState(EComplete); //ready for new connection attempts
}

void CTcpSymbianEngine::ResetL(enum TEchoEngineState aDuring,
                         enum isab::Module::ConnectionNotifyReason aReason)
{
   SetEngineState(aDuring);
   iConsole.ConnectionNotify(isab::Module::DISCONNECTING, aReason);
   ResetL(aDuring);
}

enum CTcpSymbianEngine::TEchoEngineState CTcpSymbianEngine::EngineState()
{
   iCritical.Wait();
   enum TEchoEngineState state = iEngineStatus;
   iCritical.Signal();
   return state;
}

void CTcpSymbianEngine::SetEngineState(enum TEchoEngineState aState)
{
   iCritical.Wait();
   iEngineStatus = aState;
   iCritical.Signal();
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Xerocomus lenticolor E.A. Dick & Snell

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Shop\CatalogBundle\Controller;

use Shop\CatalogBundle\Entity\Category;
use Shop\CatalogBundle\Entity\CategoryParameterGroup;
use Shop\CatalogBundle\Form\Type\CategoryParameterGroupType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class AdminCategoryController
 * @package Shop\CatalogBundle\Controller
 */
class AdminCategoryController extends Controller
{

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function categoriesAction()
    {

        $categories = $this->get('shop_catalog.category.repository')->findBy(array(), array(
            'name' => 'ASC',
        ));

        return $this->render('ShopCatalogBundle:AdminCategory:categories.html.twig', array(
            'categories' => $categories,
        ));

    }

    /**
     * @param $id
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function categoryAction($id, Request $request)
    {

        $repository = $this->get('shop_catalog.category.repository');
        $category = $repository->findOneBy(array(
            'id' => $id
        ));

        if(!$category instanceof Category){
            $category = new Category;
        }

        $isNew = !$category->getId();
        $form = $this->createForm('shop_catalog_category', $category);

        $form->handleRequest($request);

        if($request->getMethod() == 'POST' && $form->isValid()){

            $em = $this->getDoctrine()->getManager();

            if($isNew){
                $em->persist($category);
            }

            $em->flush();

            return $this->redirect($this->generateUrl('category', array(
                'id' => $category->getId(),
            )));

        } else {

            return $this->render('ShopCatalogBundle:AdminCategory:category.html.twig', array(
                'title' => $isNew ? 'Добавление категории' : 'Изменение категории',
                'form' => $form->createView(),
                'category' => $category,
            ));

        }

    }

    /**
     * @param $id
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteCategoryAction($id)
    {

        $entity = $this->getDoctrine()->getManager()->getRepository('ShopCatalogBundle:Category')->findOneBy(array(
            'id' => $id
        ));

        if($entity){

            $em = $this->getDoctrine()->getManager();
            $em->remove($entity);
            $em->flush();

        }

        return $this->redirect($this->generateUrl('admin_catalog_categories'));

    }

    /**
     * @param $categoryId
     * @param $id
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function categoryParameterGroupAction($categoryId, $id, Request $request){

        $category = $this->get('shop_catalog.category.repository')->findOneBy(array(
            'id' => $categoryId,
        ));

        if(!$category instanceof Category){
            return $this->redirect($this->generateUrl('admin_catalog_categories'));
        }

        $categoryParameterGroupRepository = $this->getDoctrine()->getRepository('ShopCatalogBundle:CategoryParameterGroup');
        $categoryParameterGroup = $categoryParameterGroupRepository->findOneBy(array(
            'id' => $id,
        ));

        if(!$categoryParameterGroup instanceof CategoryParameterGroup){
            $categoryParameterGroup = new CategoryParameterGroup();
        }

        $isNew = !$categoryParameterGroup->getId();

        $form = $this->createForm(new CategoryParameterGroupType($category), $categoryParameterGroup);

        $form->handleRequest($request);

        if($request->getMethod() == 'POST' && $form->isValid()){

            $em = $this->getDoctrine()->getManager();

            if($isNew){
                $category->addParameterGroup($categoryParameterGroup);
            }

            $em->flush();

            return $this->redirect($this->generateUrl('category_parameters', array(
                'categoryId' => $category->getId(),
            )));

        } else {

            return $this->render('ShopCatalogBundle:AdminCategory:categoryParameterGroup.html.twig', array(
                'title' => $isNew ? 'Добавление группы параметров' : 'Изменение группы параметров',
                'form' => $form->createView(),
                'category' => $category,
                'category_parameter_group' => $categoryParameterGroup,
            ));

        }

    }

    /**
     * @param $id
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteCategoryParameterGroupAction($id)
    {

        $categoryParameterGroup = $this->getDoctrine()->getManager()->getRepository('ShopCatalogBundle:CategoryParameterGroup')->findOneBy(array(
            'id' => $id
        ));

        if($categoryParameterGroup instanceof CategoryParameterGroup){

            $categoryId = $categoryParameterGroup->getCategoryId();

            $em = $this->getDoctrine()->getManager();
            $em->remove($categoryParameterGroup);
            $em->flush();

            return $this->redirect($this->generateUrl('category_parameters', array('categoryId' => $categoryId)));

        }

        return $this->redirect($this->generateUrl('admin_catalog_categories'));

    }

}


text:
define("dojox/mobile/ProgressIndicator",["dojo/_base/config","dojo/_base/declare","dojo/_base/lang","dojo/dom-class","dojo/dom-construct","dojo/dom-geometry","dojo/dom-style","dojo/has","dijit/_Contained","dijit/_WidgetBase"],function(_1,_2,_3,_4,_5,_6,_7,_8,_9,_a){
var _b=_2("dojox.mobile.ProgressIndicator",[_a,_9],{interval:100,size:40,removeOnStop:true,startSpinning:false,center:true,colors:null,baseClass:"mblProgressIndicator",constructor:function(){
this.colors=[];
this._bars=[];
},buildRendering:function(){
this.inherited(arguments);
if(this.center){
_4.add(this.domNode,"mblProgressIndicatorCenter");
}
this.containerNode=_5.create("div",{className:"mblProgContainer"},this.domNode);
this.spinnerNode=_5.create("div",null,this.containerNode);
for(var i=0;i<12;i++){
var _c=_5.create("div",{className:"mblProg mblProg"+i},this.spinnerNode);
this._bars.push(_c);
}
this.scale(this.size);
if(this.startSpinning){
this.start();
}
},scale:function(_d){
var _e=_d/40;
_7.set(this.containerNode,{webkitTransform:"scale("+_e+")",webkitTransformOrigin:"0 0"});
_6.setMarginBox(this.domNode,{w:_d,h:_d});
_6.setMarginBox(this.containerNode,{w:_d/_e,h:_d/_e});
},start:function(){
if(this.imageNode){
var _f=this.imageNode;
var l=Math.round((this.containerNode.offsetWidth-_f.offsetWidth)/2);
var t=Math.round((this.containerNode.offsetHeight-_f.offsetHeight)/2);
_f.style.margin=t+"px "+l+"px";
return;
}
var _10=0;
var _11=this;
var n=12;
this.timer=setInterval(function(){
_10--;
_10=_10<0?n-1:_10;
var c=_11.colors;
for(var i=0;i<n;i++){
var idx=(_10+i)%n;
if(c[idx]){
_11._bars[i].style.backgroundColor=c[idx];
}else{
_4.replace(_11._bars[i],"mblProg"+idx+"Color","mblProg"+(idx===n-1?0:idx+1)+"Color");
}
}
},this.interval);
},stop:function(){
if(this.timer){
clearInterval(this.timer);
}
this.timer=null;
if(this.removeOnStop&&this.domNode&&this.domNode.parentNode){
this.domNode.parentNode.removeChild(this.domNode);
}
},setImage:function(_12){
if(_12){
this.imageNode=_5.create("img",{src:_12},this.containerNode);
this.spinnerNode.style.display="none";
}else{
if(this.imageNode){
this.containerNode.removeChild(this.imageNode);
this.imageNode=null;
}
this.spinnerNode.style.display="";
}
},destroy:function(){
this.inherited(arguments);
if(this===_b._instance){
_b._instance=null;
}
}});
_b._instance=null;
_b.getInstance=function(_13){
if(!_b._instance){
_b._instance=new _b(_13);
}
return _b._instance;
};
return _b;
});


text:
'use strict';

module.exports = function(app) {
	// Root routing
	var core = require('../../server/controllers/core');
	app.route('/').get(core.index);
};


text:
<?php

if ( !function_exists( 'shoestrap_branding' ) ) :
/*
 * The Header template
 */
function shoestrap_branding() { ?>
	<?php if ( shoestrap_getVariable( 'header_toggle' ) == 1 ) : ?>
		<?php if ( shoestrap_getVariable( 'site_style' ) == 'boxed' ) : ?>

		<?php endif; ?>

			<?php if ( shoestrap_getVariable( 'site_style' ) == 'wide' ) : ?>

			<?php endif; ?>

			<?php if ( shoestrap_getVariable( 'header_branding' ) == 1 ) : ?>
				<a class="brand-logo" href="<?php echo home_url(); ?>/">

						<?php if ( function_exists( 'shoestrap_logo' ) ) : ?>
							<?php shoestrap_logo(); ?>
						<?php endif; ?>

			<?php endif; ?>

			<?php if ( shoestrap_getVariable( 'header_branding' ) == 1 ) : ?>

			<?php else : ?>

			<?php endif; ?>

			<?php dynamic_sidebar( 'header-area' ); ?>

		<?php if ( shoestrap_getVariable( 'site_style' ) != 'fluid' ) : ?>

		<?php endif; ?>

	<?php endif;
}
endif;
add_action( 'shoestrap_below_top_navbar', 'shoestrap_branding', 5 );

if ( !function_exists( 'shoestrap_header_css' ) ) :
/*
 * Any necessary extra CSS is generated here
 */
function shoestrap_header_css() {
	$bg = shoestrap_getVariable( 'header_bg' );
	$cl = shoestrap_getVariable( 'header_color' );

	$header_margin_top    = shoestrap_getVariable( 'header_margin_top' );
	$header_margin_bottom = shoestrap_getVariable( 'header_margin_bottom' );

	$opacity  = (intval(shoestrap_getVariable( 'header_bg_opacity' )))/100;
	$rgb      = shoestrap_get_rgb($bg, true);

	if ( shoestrap_getVariable( 'header_toggle' ) == 1 ) {
		$style = '.header-wrapper{ color: '.$cl.';';

		$style .= ( $opacity != 1 && $opacity != '' ) ? 'background: rgb('.$rgb.'); background: rgba('.$rgb.', '.$opacity.');' : 'background: '.$bg.';';
		$style .= 'margin-top:'.$header_margin_top.'px; margin-bottom:'.$header_margin_bottom.'px; }';

		wp_add_inline_style( 'shoestrap_css', $style );
	}
}
endif;
add_action( 'wp_enqueue_scripts', 'shoestrap_header_css', 101 );


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Aspergillus pyri W.H. English

### Remarks
null


text:
package com.payler.paylergateapi.lib.model;

public class TransactionStatus {

    public static final String CREATED = "Created";

    public static final String PREAUTHORIZED3DS = "PreAuthorized3DS";

    public static final String AUTHORIZED = "Authorized";

    public static final String RETRIEVED = "Retrieved";

    public static final String REVERSED = "Reversed";

    public static final String CHARGED = "Charged";

    public static final String REFUNDED = "Refunded";

    public static final String REJECTED = "Rejected";

    public static final String ERROR = "Error";

}


text:
<?php
namespace CIP;
require_once 'plugins/IValueTransformer.php';

class EnumTransformer implements IValueTransformer {
  public function transform($array) {
    if (isset($array['id']) && isset($array['displaystring'])) {
      return $array['id'];
    } else {
      error_log('EnumTransformer expects an array with "id" and "displaystring" fields');
      error_log(var_dump($array));
      error_log(var_export($array));
      return null;
    }
  }
  public function getType() { return 'int'; }
}


text:
class AddColorToLocationSection < ActiveRecord::Migration
  def self.up
    add_column :offering_location_sections, :color, :string
  end

  def self.down
    remove_column :offering_location_sections, :color
  end
end


text:
package cn.xz.study.design.pattern.singleton;

public class LazySingleton {
	/**
	 * volatile 确保线程改变了变量的值时 会立刻同步改变量的值  以保证改变量的值是最新的
	 */
	private volatile static LazySingleton singleton = null;
	private LazySingleton(){

	}

	public static LazySingleton getInstance(){
		if(singleton == null){
			synchronized (LazySingleton.class){
				singleton = new LazySingleton();
			}
		}
		return singleton;
	}

	private int count = 0;
	public synchronized int add(){
		return count++;
	}

	public int getCount() {
		return count;
	}

}


text:
require_relative "../lib/ruboty/todoist"
require "pp"
require 'dotenv'
Dotenv.load

# items = Ruboty::Todoist::Resorces::Item.fetch
# items.each { |_| pp _.due_date }

projects = Ruboty::Todoist::Resorces::Project.fetch
pp projects


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using MEFSample.Business.Repository;

namespace MEFSample.Respository.DAL
{

  [Export(typeof(IRootDataAccess))]
  public class MyRootDataAccess : IRootDataAccess
  {
    public RootData Get(int id)
    {
      return new RootData() { Id = id, Name = "Ole Olsen" };
    }
  }
}


text:
BEGIN_CONTRACT (M2Grid)

        INVARIANTS (
            FACT (self.dimension > 0);
            FACT (self.scene != nil);
        )
+ (void) allocCellsOnGrid:(NSMutableArray *)_grid withSize:(NSInteger)dimension VERIFY_PROC (

        REQUIRE(
                FACT(_grid != nil)
                FACT(dimension >0)
            )
        int gridSize = [_grid count];
        MODIFY(gridSize)
        [super allocCellsOnGrid:_grid withSize:dimension];
        gridSize = [_grid count];
        ENSURE(
                FACT((int)OLD(gridSize) + dimension == gridSize)
              )
)
- (void)forEach:(IteratorBlock)block reverseOrder:(BOOL)reverse VERIFY_PROC (

     REQUIRE(
             FACT(self.dimension >0)
             )
     [super forEach:block reverseOrder:reverse];

)
- (M2Cell *)cellAtPosition:(M2Position)position VERIFY (

     REQUIRE(
            )
     M2Cell *Result = [super cellAtPosition:position];

     ENSURE(
            FACT(Result != nil)
            )
)

- (M2Tile *)tileAtPosition:(M2Position)position VERIFY (

        REQUIRE(
               )
        M2Tile *Result = [super tileAtPosition:position];

        ENSURE(
           FACT(Result != nil || (
                position.x < 0 ||
                position.y < 0 ||
                position.x >= self.dimension ||
                position.y >= self.dimension ) ||
                (position.x == 0 ||
                 position.y == 0
                 ))
           FACT(Result == [super cellAtPosition:position].tile );
        )
)
- (BOOL)hasAvailableCells; VERIFY(
REQUIRE(
        FACT(self.dimension > 0)
        )
      BOOL Result = [super hasAvailableCells];
)

- (void)insertTileAtRandomAvailablePositionWithDelay:(BOOL)delay VERIFY_PROC (
    REQUIRE(FACT(self.scene != nil))
      M2Scene *theScene = self.scene;

  [super insertTileAtRandomAvailablePositionWithDelay:delay];
      M2Scene *newScene = self.scene;
      ENSURE(
             FACT(theScene == newScene);
             )
)
END_CONTRACT

#endif


text:
{% comment %} {% endcomment %}{% comment %}
Some parts Copyright (c) 2009 The IETF Trust, all rights reserved.
{% endcomment %}<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>IESG Agenda - Scribe Template</title>

{% load ietf_filters %}{% filter compress_empty_lines %}

Scribe template for IESG Narrative Minutes, {{date}}

{% with "iesg/scribe_doc.html" as doc_template %}
{% with "iesg/scribe_conflict_doc.html" as doc_conflict_template %}
{% include "iesg/agenda_outline_23.html" %}
{% endwith %}
{% endwith %}

Appendix: Snapshot of discusses/comments

(at {% now "Y-m-d H:i:s T" %})

{% for doc in docs.s211 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s212 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s213 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s221 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s222 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s223 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s231 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s232 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s233 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s311 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s312 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s313 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s321 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s322 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s323 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s331 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s332 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s333 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s341 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s342 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}
{% for doc in docs.s343 %}{% include "iesg/scribe_doc2.html" %}{%endfor%}

{% endfilter %}


text:
This is a spinoff of astropys NDData object. Testing some stuff here...

[![Coverage Status](https://coveralls.io/repos/github/MSeifert04/nddata/badge.svg?branch=master)](https://coveralls.io/github/MSeifert04/nddata?branch=master)
[![AppVeyor status](https://ci.appveyor.com/api/projects/status/avdmbjmrehgln1dh/branch/master?svg=true)](https://ci.appveyor.com/project/MSeifert04/nddata/branch/master)
[![Travis CI Status](https://travis-ci.org/MSeifert04/nddata.svg?branch=master)](https://travis-ci.org/MSeifert04/nddata)

[![Documentation Status](https://readthedocs.org/projects/nddata/badge/?version=latest)](http://nddata.readthedocs.io/en/latest/?badge=latest)


text:
from django.contrib import admin

from snippets.models import Snippet

class SnippetAdmin(admin.ModelAdmin):
    pass

admin.site.register(Snippet, SnippetAdmin)


text:
#import "BaseTableViewController.h"

@interface PayCompanyChooseController : BaseTableViewController

@property (nonatomic) CPPayType type;

@end


text:
#!/usr/bin/env node

var fs = require('fs');
var webclient = require('../modules/webclient');
var async = require('async');
var projectormodel = require('../modules/projectormodel');
var kanbanModel = require('../db/kanbanModel');
var tfsdecorator = require('../modules/tfsdecorator');
var _ = require('underscore');
var http = require('http');

var args = process.argv.slice(2);
var config = JSON.parse(fs.readFileSync(args[0], 'utf8'));

var db = require('../db');
var connectDb = function(callback) {
    db.connect(config.mongoConnection, function (err) {
        if (err) {
            console.log('failed to connect to database: ' + JSON.stringify(err));
            process.exit(0);
        }
        console.log('mongodb connected');
        callback();
    })
}
var ClassOfService = require('../db/classOfService');

console.log("reading credentials from " + config.credentialsFile);
config.credentials = JSON.parse(fs.readFileSync(config.credentialsFile, 'utf8'));

http.globalAgent.maxSockets = config.maxConcurrentRequests;

var model = {};

if(args[1] == 'skipdownload')
    model = load();
else
    model = new projectormodel.Model();

// in series, get classes and then run queries

var serialOps = [
    connectDb,
    getClassesOfService.bind(null, model),
    getItemsForClasses.bind(null, model),
    getHistoryForItems.bind(null, model),
    getInfoForItems.bind(null, model),
    addColumnsToClasses.bind(null, model),
    computeRawCycleTimes.bind(null, model),
    persist.bind(null, model),
    tfsdecorator.decorateTFS.bind(null, model, config)
];

if(args[1] == 'skipdownload')
    serialOps = serialOps.slice(5);

async.series(
    serialOps,
    function (err) {
        if(err) {
            log("error with series");
            log(err.message);
        }

        db.disconnect(function() {
            log("all done");
        })

    }

);

function computeRawCycleTimes(model, callbackWhenDone) {

    model.rawCycleTimes = {};

    async.forEachOf(model.itemHistory, function(historyRecord, id, callbackWhenItemDone) {
        model.rawCycleTimes[id] = computeColumnTimes(historyRecord);
        callbackWhenItemDone();
    }, callbackWhenDone);

    //_.each(model.itemHistory, function(historyRecord, id) {
    //        model.rawCycleTimes[id] = computeColumnTimes(historyRecord);
    //        log(model.rawCycleTimes[id]);
    //})
    //callbackWhenDone();

}

function computeColumnTimes(itemHistory) {
    // itemHistory is an array of revisions
    // each revision is of the form {
    //  changedDate: datetime
    //  board1: {
    //      oldValue: (optional)
    //      newValue: (optional)
    //  }
    // }

    // returns dictionary by board ID: {
    //  array of columns: [ {columnName:, bizDays: }]
    // }

    var columnTimes = {};

    if(itemHistory.length <= 1)
        return null;

    for(var revNdx = 1; revNdx < itemHistory.length; revNdx++) {
        _.each(itemHistory[revNdx], function(value, key) {
            if(key != 'changedDate') {
                var board = key;
                var prevColumn = value.oldValue;
                // find the previous record with the same board and prev.newValue = cur.oldValue
                var searchNdx = revNdx-1;
                while(searchNdx >= 0 && !(
                  itemHistory[searchNdx].hasOwnProperty(board) && itemHistory[searchNdx][board].newValue == prevColumn))
                    searchNdx--;
                if(searchNdx >=0)
                    addColumnTimesRecord(columnTimes, board, prevColumn, bizDaysBetween(itemHistory[searchNdx].changedDate, itemHistory[revNdx].changedDate));
                // if this is the last revision, then add cycle time to current date
                if(revNdx == itemHistory.length-1)
                    addColumnTimesRecord(columnTimes, board, value.newValue, bizDaysBetween(itemHistory[revNdx].changedDate, new Date()));
            }
        })
    }

    return columnTimes;
}

function addColumnTimesRecord(columnTimes, board, column, days) {
    if(!columnTimes.hasOwnProperty(board))
        columnTimes[board] = [];
    var columnNdx = _.findIndex(columnTimes[board], function(element) {
        return element.columnName == board;
    })
    if(columnNdx == -1) {
        columnTimes[board].push({
            columnName: column,
            bizDays: 0
        });
        columnNdx = columnTimes[board].length - 1;
    }
    columnTimes[board][columnNdx].bizDays += days;
}

Date.prototype.addDays = function(days)
{
    // http://stackoverflow.com/questions/563406/add-days-to-datetime
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
}

function bizDaysBetween(beforedate, afterdate) {
    before = new Date(beforedate);
    after = new Date(afterdate);

    before = new Date(before.getFullYear(), before.getMonth(), before.getDate());
    after = new Date(after.getFullYear(), after.getMonth(), after.getDate());

    if(after < before)
        return bizdaysdiff(afterdate, beforedate);

    var cur = before;
    var numDays = 0;
    while(cur <= after) {
        var dow = new Date(cur).getDay();
        if(dow != 0 && dow != 6)
            numDays++;
        cur = cur.addDays(1);
    }

    if(numDays < 1)
        return 0;
    return numDays-1;

}

function getInfoForItems(model, callbackWhenDone) {

    model.itemInfo = {};

    async.eachLimit(model.allItems, config.maxConcurrentRequests, function(id, callbackWhenItemDone) {
        getItemInfo(id, model, function(err, info) {

            if(err) {
                log("error getting info for item " + id);
                return callbackWhenItemDone(err);
            }
            log("got info for item " + id);
            model.itemInfo[id] = info;
            callbackWhenItemDone(null);
        })
    }, function(err) {
        log("done downloading info for all items");
        callbackWhenDone(err);
    });
}

function getItemInfo(id, model, callbackWithInfo) {

    var boards = model.allBoards;

    var additionalInfoFields = [];
    if(model.additionalInfoFields != null)
        additionalInfoFields = model.additionalInfoFields;

    var baseurl = config.url + "/_apis/wit/workitems?ids=" + id + "&api-version=1.0";

    var options = {
        'url': baseurl,
        'method': "GET",
        'json': true,
        'headers': {
          'Content-Type': 'application/json',
        },
        'credentials': config.credentials

    }

    webclient.rawRequest(options, function(error, response) {
        if (!error && response.statusCode == 200) {

            var responseObj = JSON.parse(response.body);

            var infoObj = {};

            var fields = {
                "System.WorkItemType": "type",
                "System.Title": "title",
                "Microsoft.VSTS.Common.ClosedDate": "closedDate"
            };
            _(additionalInfoFields).each(function(field) {
                fields[field] = field;
            });

            _.each(fields, function(internalField, externalField) {
                if(responseObj.value[0].fields.hasOwnProperty(externalField))
                    infoObj[internalField] = responseObj.value[0].fields[externalField];
            });

            infoObj.boards = [];

            _.each(boards, function(board) {
                if(responseObj.value[0].fields.hasOwnProperty("WEF_" + board + "_Kanban.Column"))
                    infoObj.boards.push({
                        board: board,
                        column: responseObj.value[0].fields["WEF_" + board + "_Kanban.Column"]
                    })
            })

            callbackWithInfo(null, infoObj);

        }
        else {
            if(response)
                logRequestError("getItemInfo", response);
            else
                log("request error, but no response data: " + JSON.stringify(error))
            callbackWithInfo(true);
        }
    })

}

function addColumnsToClasses(model, callbackWhenDone) {
    model.columnsForBoard = {};

    _.each(model.allBoards, function(board) {
        model.columnsForBoard[board] = [];
    })

    _.each(model.itemHistory, function(itemRevisions) {
        _.each(itemRevisions, function(revision) {
            _.each(revision, function(value, key) {
                if(value.hasOwnProperty('oldValue'))
                    model.columnsForBoard[key] = _.union(model.columnsForBoard[key], [value.oldValue]);
                if(value.hasOwnProperty('newValue'))
                    model.columnsForBoard[key] = _.union(model.columnsForBoard[key], [value.newValue]);
            })
        })

    })

    _.each(model.classesOfService, function(classOfService) {
        classOfService.columnNames = model.columnsForBoard[classOfService.board].sort();

        var closedDates = _.map(classOfService.itemsClosed, function(itemId) {
            return(model.itemInfo[itemId]['closedDate']);
        });
        classOfService.minDate = _.reduce(closedDates, function(memo, closedDate) {
            if(closedDate === undefined || closedDate == null)
                return memo;
            if(closedDate < memo)
                return closedDate;
            return memo;
        });
        classOfService.maxDate = _.reduce(closedDates, function(memo, closedDate) {
            if(closedDate === undefined || closedDate == null)
                return memo;
            if(closedDate > memo)
                return closedDate;
            return memo;
        });

    })

    callbackWhenDone(null);
}

function persist(model, callbackWhenDone) {

    async.parallel([
        function(cbWhenFileSaved) {
            fs.writeFile(config.modelStorageFile, JSON.stringify(model), cbWhenFileSaved);
        },
        function(cbWhenDatabaseUpdated) {
            kanbanModel.replace(model, cbWhenDatabaseUpdated);
        }
    ], callbackWhenDone);

}

function load() {
    return JSON.parse(fs.readFileSync(config.modelStorageFile, 'utf8'));
}

function getHistoryForItems(model, callbackWhenDone) {
    model.computeAllItemsAndBoards();

    async.eachLimit(model.allItems, config.maxConcurrentRequests, function(id, callback) {
        getItemHistory(id, model.allBoards, function(err, history) {
            if(!err)
                model.itemHistory[id] = history;
            callback(err);
        })
    }, callbackWhenDone);
}

function getItemHistory(id, boards, callbackWithHistory) {
    // callback arguments: err, history

    var baseurl = config.url + "/_apis/wit/workitems/" + id + "/updates?api-version=1.0";
    // &$top=200&$skip=300

    var sizeOfLastPage = config.revisionsStep;
    var skip = 0;
    var fullHistory = [];

    async.whilst(function() {return sizeOfLastPage == config.revisionsStep},
    function(callback) {
        var options = {
            'url': baseurl + "&$top=" + config.revisionsStep + "&$skip=" + skip,
            'method': "GET",
            'json': true,
            'headers': {
                'Content-Type': 'application/json',
            },
            'credentials': config.credentials

        }

        fetchHistoryPage(options, boards, function(err, pageSize, history) {

            if(err) {
                log("error fetching history page " + skip + " for id " + id + ", " + options.url);
                return callback(err);
            }
            log("got history for " + id + ", page " + (skip / config.revisionsStep) + " with " + pageSize + " events " + " of which " + history.length + " were interesting")
            sizeOfLastPage = pageSize;
            skip += config.revisionsStep;
            fullHistory = fullHistory.concat(history);
            callback();
        })
    }, function(err) {
            if(err) {
                log("error fetching history for id " + id);
                return callbackWithHistory(true);
            }

            callbackWithHistory(null, fullHistory);
        });

}

function fetchHistoryPage(options, boards, callback) {
    webclient.rawRequest(options, function(error, response) {
        if (!error && response.statusCode == 200) {

            var responseObj = JSON.parse(response.body);
            var newRevisions = _.filter(responseObj.value, function(element) {
                if(!element.hasOwnProperty("fields"))
                    return false;
                for(var i=0; i<boards.length; i++)
                    if(element.fields.hasOwnProperty("WEF_" + boards[i] + "_Kanban.Column"))
                        return true;
                return false;
            }, this);

            var history = _.map(newRevisions, function(rev) {

                var revRecord = { };

                _.each(rev.fields, function(value, key) {
                    if(key == 'System.ChangedDate')
                        revRecord.changedDate = value.newValue;
                    else {
                        _.each(boards, function(board) {
                            if(key == "WEF_" + board + "_Kanban.Column") {
                                revRecord[board] = value;
                            }
                        }, this);
                    }
                }, this);

                return revRecord;
            }, this);

            callback(null, responseObj.value.length, history);
        }
        else {
            if(response)
                logRequestError("getItemHistory", response);
            else
                log("request error, but no response data: " + JSON.stringify(error))
            callback(true);
        }
    })
}

function getClassesOfService(model, callback) {
    log("getting classes of service...")

    ClassOfService.find().lean().exec(function(err, classesOfService) {
        if(err) return callback(err);
        model.classesOfService = classesOfService;
        model.additionalInfoFields = _.chain(model.classesOfService)
            .pluck('decoratorConfig')
            .pluck('fieldToUpdate')
            .uniq()
            .filter(function(val) {
                return val != null;
            })
            .value();
        return callback();
    })

    //fs.readFile(config.classesOfServiceFile, 'utf8', function(err, data) {
    //    if(err)
    //        return callback(err);
    //    var classesConfig = JSON.parse(data);
    //    model.classesOfService = classesConfig.classes;
    //    model.additionalInfoFields = classesConfig.additionalInfoFields;
    //    return callback(null);
    //
    //});

}

function getItemsForClasses(model, callbackWhenDone) {

    async.each(model.classesOfService, (function (classOfService, callbackCoS) {
        log("getting items for class " + classOfService.name);
        async.parallel([
          function(callback) {
              getItemsFromWIQL(classOfService.queryForAll, function(items, err) {
                  if(err) {
                      log("error getting all items for class: " + classOfService.name);
                      return callback(err);
                  }
                  classOfService.itemsAll = _.pluck(items, 'id');
                  callback();
              })
          },
          function(callback) {
              getItemsFromWIQL(classOfService.queryForClosed, function(items, err) {
                  if(err) {
                      log("error getting closed items for class: " + classOfService.name);
                      return callback(err);
                  }
                  classOfService.itemsClosed = _.pluck(items, 'id');
                  callback();
              })
          }
        ], callbackCoS);

    }), function(err) {
        if(err) {
            log("error getting items for classes");
            return callbackWhenDone(err);
        }
        callbackWhenDone();
    })
}

function getItemsFromWIQL(wiql, callback) {

    var body = {
        'query': wiql
    }

    var options = {
        'url': config.url + "/_apis/wit/wiql?api-version=1.0",
        'method': "POST",
        'body': JSON.stringify(body),
        'json': true,
        'headers': {
            'Content-Type': 'application/json',
        },
        'credentials': config.credentials

    }

    webclient.rawRequest(options, function(error, response) {
        if (!error && response.statusCode == 200) {
            callback(JSON.parse(response.body).workItems);
        }
        else {
            logRequestError("getItemsFromWIQL", response);
            callback(null, error);
        }
    })

}

function log(str) {
    console.log(str);
}

function logRequestError(message, response) {
    if(response != null && response.statusCode != null)
        log("Error calling API (" + message + "). Response code " + response.statusCode);
    else
        log("Error calling API (" + message + "). Response: " + JSON.stringify(response));
}


text:
//package fromslides.S09;
import java.util.Scanner;
/**
 *
 * This class illustrates exercises from the slide deck for the course
 * 360-420-DW Intro to Java
 *
 * @author PMCampbell
 * @version today
 *
 **/

public class SimpleMethods {

    public static void main(String[] args) {
            int num1, num2, minNum, maxNum;

            Scanner keyboard = new Scanner(System.in);
            System.out.print("Enter an integer: ");
            num1 = keyboard.nextInt();
            System.out.print("Enter an integer: ");
            num2 = keyboard.nextInt();

            minNum = min(num1, num2);
            maxNum = max(num1, num2);

            System.out.printf("Minimum %d Maximum %d\n", minNum, maxNum);

        } // main()

    /**
     * Compares the two parameters
     * returns the smallest of the two
     *
     * @param a integer
     * @param b integer
     * @return smallest of a and b integer
     * @author PMCampbell
     * @version today
     * */

    public static int min(int a, int b) {
        int small;
        if ( a > b)
           small = b;
        else
           small = a;

        return small;
    }  // min()

    /**
     * Compares the two parameters
     * returns the largest of the two
     *
     * @param a integer
     * @param b integer
     * @return largest of a and b
     * @author PMCampbell
     * @version today
     * */

    public static int max(int a, int b) {
        int big;
        if ( a > b)
           big = a;
        else
           big = b;

        return big;
    }  // max()

} // SimpleMethods


text:
layout: archive
lang: en
ref: c_windows
read_time: true
share: true
author_profile: false
permalink: /docs/en/software/dynamixel/dynamixel_sdk/library_setup/c_windows/
sidebar:
  title: DYNAMIXEL SDK
  nav: "dynamixel_sdk"
---

# [Library Setup](#library-setup)

## [C Windows](#c-windows)

### [Compiler and Builder](#compiler-and-builder)

* [Download Visual Express for Windows Desktop](https://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx)

  ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/vs.png)

### [Building the Library](#building-the-library)

* Run the project solution file (.sln) located in the `[DynamixelSDK folder]/c/build/win32` directory OR `[DynamixelSDK folder]/c/build/win64` directory).

  ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/library_file/1.png)

* Under Solution Explorer, right click on the project and select Properties.

  ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/library_file/2.png)

* Under General Configuration Properties, confirm that the paths and file extensions are set as follows:

  * Output Directory: `$(SolutionDir)output\`
  * Intermediate Directory: `$(Configuration)\`
  * Target Extension: `.dll`
  * Platform Toolset: `Visual Studio 20XX (v000)`
  * Configuration Type: `Dynamic Library (.dll)`.

{% capture notice_01 %}
**WARNING**:
If the library file should be built in lower or higher version Visual Studio, change the `Platform Toolset` into the needed value. (ex: To use the DynamixelSDK c ver. library file in the MATLAB 2010 or LabVIEW 2010, the `Platform Toolset` should be changed into `Visual Studio 2009` or lower one.)
{% endcapture %}

{{ notice_01 | markdownify }}

![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/library_file/3.png)

* Confirm that the Additional Include Directories path under the General C/C++ Configuration Properties tree is as follows:

  `..\..\..\include\dynamixel_sdk`

  ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/library_file/4.png)

* Right click on the project and select Build to build the library.

  ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/library_file/5.png)

* The built library file is located in `[DynamixelSDK folder]/c/build/[winXX]/output/dxl_xYY_c.dll`.

### [Building and Running the Sample Code](#building-and-running-the-sample-code)

The DYNAMIXEL SDK sample code for C uses the library files(.dll for Windows) built in C language.

By doing above, each released DYNAMIXEL SDK have latest library files in `[DynamixelSDK folder]/c/build/[winXX]/output/dxl_xYY_c.dll` which were built by its own source code.

* Run the .sln file located in the `[DynamixelSDK folder]/c/example/protocol2.0/read_write/win32` folder if you have a 32-bit platform OR the `[DynamixelSDK folder]/c/example/protocol2.0/read_write/win64` folder if you have a 64-bit platform.

  ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/sample_code/1.png)

* Right click on the project and select Properties.

  ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/sample_code/2.png)

* In the resulting Property Pages window, under Configuration Properties --> General, check that the directories and file extensions are set as follows:

  * Output Directory: `$(SolutionDir)$(Configuration)\`
  * Intermediate Directory: `$(Configuration)\`
  * Target Extension: `.exe`
  * Configuration Type: `Application (.exe)`

    ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/sample_code/3.png)

* Under Configuration Properties --> Debugging add the following path to Environment:
  - win32: `PATH=%PATH%;..\..\..\..\..\build\win32\output;`
  - win64: `PATH=%PATH%;..\..\..\..\..\build\win64\output;`

    ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/sample_code/4.png)

* Under Configuration Properties --> VC++ Directories, add the following path to Library Directories:
  - win32: `..\..\..\..\..\build\win32\output;`
  - win64: `..\..\..\..\..\build\win64\output;`

    ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/sample_code/5.png)

* Under Configuration Properties --> C/C++ --> General, add the following path to Additional Include Directories:

  `..\..\..\..\..\include\dynamixel_sdk`

    ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/sample_code/6.png)

* Under Configuration Properties --> Linker --> Input, add the following file to Additional Dependencies:

  - win32: `dxl_x86_c.lib;`
  - win64: `dxl_x64_c.lib;`

    ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/sample_code/7.png)

* Click on the Local Windows Debugger button to run the program.

  ![](/assets/images/sw/sdk/dynamixel_sdk/library_setup/c/windows/sample_code/8.png)


text:
namespace media {

class VideoFrame;

class MEDIA_GPU_EXPORT V4L2MjpegDecodeAccelerator
    : public chromeos_camera::MjpegDecodeAccelerator {
 public:
  // Job record. Jobs are processed in a FIFO order. This is separate from
  // BufferRecord of input, because a BufferRecord of input may be returned
  // before we dequeue the corresponding output buffer. It can't always be
  // associated with a BufferRecord of output immediately either, because at
  // the time of submission we may not have one available (and don't need one
  // to submit input to the device).
  class JobRecord;

  V4L2MjpegDecodeAccelerator(
      const scoped_refptr<V4L2Device>& device,
      const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner);
  ~V4L2MjpegDecodeAccelerator() override;

  // MjpegDecodeAccelerator implementation.
  bool Initialize(
      chromeos_camera::MjpegDecodeAccelerator::Client* client) override;
  void Decode(BitstreamBuffer bitstream_buffer,
              scoped_refptr<VideoFrame> video_frame) override;
  void Decode(int32_t task_id,
              base::ScopedFD src_dmabuf_fd,
              size_t src_size,
              off_t src_offset,
              scoped_refptr<media::VideoFrame> dst_frame) override;
  bool IsSupported() override;

 private:
  // Record for input/output buffers.
  struct BufferRecord {
    BufferRecord();
    ~BufferRecord();
    void* address[VIDEO_MAX_PLANES];  // mmap() address.
    size_t length[VIDEO_MAX_PLANES];  // mmap() length.

    // Set true during QBUF and DQBUF. |address| will be accessed by hardware.
    bool at_device;
  };

  void EnqueueInput();
  void EnqueueOutput();
  void Dequeue();
  bool EnqueueInputRecord();
  bool EnqueueOutputRecord();
  bool CreateInputBuffers();
  bool CreateOutputBuffers();
  void DestroyInputBuffers();
  void DestroyOutputBuffers();

  // Convert |output_buffer| to |dst_frame|. The function supports the following
  // formats:
  //   - All formats that libyuv::ConvertToI420 can handle.
  //   - V4L2_PIX_FMT_YUV_420M, V4L2_PIX_FMT_YUV_422M to I420, YV12, and NV12.
  bool ConvertOutputImage(const BufferRecord& output_buffer,
                          scoped_refptr<VideoFrame> dst_frame);

  // Return the number of input/output buffers enqueued to the device.
  size_t InputBufferQueuedCount();
  size_t OutputBufferQueuedCount();

  // Return true if input buffer size is not enough.
  bool ShouldRecreateInputBuffers();
  // Destroy and create input buffers. Return false on error.
  bool RecreateInputBuffers();
  // Destroy and create output buffers. Return false on error.
  bool RecreateOutputBuffers();

  void VideoFrameReady(int32_t task_id);
  void NotifyError(int32_t task_id, Error error);
  void PostNotifyError(int32_t task_id, Error error);

  // Run on |decoder_thread_| to enqueue the coming frame.
  void DecodeTask(std::unique_ptr<JobRecord> job_record);

  // Run on |decoder_thread_| to dequeue last frame and enqueue next frame.
  // This task is triggered by DevicePollTask. |event_pending| means that device
  // has resolution change event or pixelformat change event.
  void ServiceDeviceTask(bool event_pending);

  // Dequeue source change event. Return false on error.
  bool DequeueSourceChangeEvent();

  // Start/Stop |device_poll_thread_|.
  void StartDevicePoll();
  bool StopDevicePoll();

  // Run on |device_poll_thread_| to wait for device events.
  void DevicePollTask();

  // Run on |decoder_thread_| to destroy input and output buffers.
  void DestroyTask();

  // The number of input buffers and output buffers.
  const size_t kBufferCount = 2;

  // Coded size of output buffer.
  gfx::Size output_buffer_coded_size_;

  // Pixel format of output buffer.
  uint32_t output_buffer_pixelformat_;

  // Number of physical planes the output buffers have.
  size_t output_buffer_num_planes_;

  // Strides of the output buffers.
  size_t output_strides_[VIDEO_MAX_PLANES];

  // ChildThread's task runner.
  scoped_refptr<base::SingleThreadTaskRunner> child_task_runner_;

  // GPU IO task runner.
  scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;

  // The client of this class.
  chromeos_camera::MjpegDecodeAccelerator::Client* client_;

  // The V4L2Device this class is operating upon.
  scoped_refptr<V4L2Device> device_;

  // Thread to communicate with the device.
  base::Thread decoder_thread_;
  // Decode task runner.
  scoped_refptr<base::SingleThreadTaskRunner> decoder_task_runner_;
  // Thread used to poll the V4L2 for events only.
  base::Thread device_poll_thread_;
  // Device poll task runner.
  scoped_refptr<base::SingleThreadTaskRunner> device_poll_task_runner_;

  // All the below members except |weak_factory_| are accessed from
  // |decoder_thread_| only (if it's running).
  base::queue<std::unique_ptr<JobRecord>> input_jobs_;
  base::queue<std::unique_ptr<JobRecord>> running_jobs_;

  // Input queue state.
  bool input_streamon_;
  // Mapping of int index to an input buffer record.
  std::vector<BufferRecord> input_buffer_map_;
  // Indices of input buffers ready to use; LIFO since we don't care about
  // ordering.
  std::vector<int> free_input_buffers_;

  // Output queue state.
  bool output_streamon_;
  // Mapping of int index to an output buffer record.
  std::vector<BufferRecord> output_buffer_map_;
  // Indices of output buffers ready to use; LIFO since we don't care about
  // ordering.
  std::vector<int> free_output_buffers_;

  // Point to |this| for use in posting tasks from the decoder thread back to
  // the ChildThread.
  base::WeakPtr<V4L2MjpegDecodeAccelerator> weak_ptr_;
  // Weak factory for producing weak pointers on the child thread.
  base::WeakPtrFactory<V4L2MjpegDecodeAccelerator> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(V4L2MjpegDecodeAccelerator);
};

}  // namespace media

#endif  // MEDIA_GPU_V4L2_V4L2_MJPEG_DECODE_ACCELERATOR_H_


text:
Puppet::Type.newtype(:oneview_server_profile) do
  desc "Oneview's Server Profile"

  #:nocov:
  ensurable do
    defaultvalues

    # PUTs
    newvalue(:update_from_template) do
      provider.update_from_template
    end

    # GETs
    newvalue(:found) do
      provider.found
    end

    newvalue(:get_available_networks) do
      provider.get_available_networks
    end

    newvalue(:get_available_servers) do
      provider.get_available_servers
    end

    newvalue(:get_available_storage_systems) do
      provider.get_available_storage_systems
    end

    newvalue(:get_available_storage_system) do
      provider.get_available_storage_system
    end

    newvalue(:get_available_targets) do
      provider.get_available_targets
    end

    newvalue(:get_profile_ports) do
      provider.get_profile_ports
    end

    newvalue(:get_compliance_preview) do
      provider.get_compliance_preview
    end

    newvalue(:get_messages) do
      provider.get_messages
    end

    newvalue(:get_transformation) do
      provider.get_transformation
    end

    newvalue(:get_sas_logical_jbods) do
      provider.get_sas_logical_jbods
    end

    newvalue(:get_sas_logical_jbod_drives) do
      provider.get_sas_logical_jbod_drives
    end

    newvalue(:get_sas_logical_jbod_attachments) do
      provider.get_sas_logical_jbod_attachments
    end
  end
  #:nocov:

  newparam(:name, namevar: true) do
    desc 'Server Profile name'
  end

  newparam(:data) do
    desc 'Server Profile data hash containing all specifications for the system'
    validate do |value|
      raise('Inserted value for data is not valid') unless value.class == Hash
    end
  end
end


text:
package cleo.search.test.store;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;

import cleo.search.store.ConnectionsStore;
import cleo.search.store.StoreFactory;
import cleo.search.test.util.FileUtils;

import junit.framework.TestCase;
import krati.core.segment.MemorySegmentFactory;
import krati.core.segment.SegmentFactory;
import krati.core.segment.WriteBufferSegmentFactory;

/**
 * TestConnectionsStore
 *
 * @author jwu
 * @since 02/12, 2011
 */
public class TestConnectionsStore extends TestCase {
  protected Random rand = new Random();
  protected File storeHome;
  protected ConnectionsStore<String> store;

  protected int getInitialCapacity() {
    return 100000;
  }

  protected ConnectionsStore<String> createConnectionsStore() throws Exception {
    int indexSegmentFileSizeMB = 8;
    SegmentFactory indexSegmentFactory = new MemorySegmentFactory();
    int storeSegmentFileSizeMB = 32;
    SegmentFactory storeSegmentFactory = new WriteBufferSegmentFactory(storeSegmentFileSizeMB);

    return StoreFactory.createConnectionsStore(storeHome, getInitialCapacity(), indexSegmentFileSizeMB, indexSegmentFactory, storeSegmentFileSizeMB, storeSegmentFactory);
  }

  @Override
  protected void setUp() {
    String storeName = getClass().getSimpleName();
    storeHome = FileUtils.getTestDir(storeName);

    try {
      store = createConnectionsStore();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void tearDown() {
    if(storeHome != null) {
      try {
        store.close();
        FileUtils.deleteDirectory(storeHome);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  public void testApiBasics() throws Exception {
    String source = "key" + rand.nextInt();
    int[] connections;
    int newConnection;

    connections = new int[] { 1, 2, 3, 7, 19 };
    newConnection = 23;
    runApiBasics(source, connections, newConnection);

    connections = new int[] {};
    newConnection = rand.nextInt();
    runApiBasics(source, connections, newConnection);

    connections = null;
    newConnection = rand.nextInt();
    runApiBasics(source, connections, newConnection);
  }

  private void runApiBasics(String source, int[] connections, int newConnection) throws Exception {
    int[] connectionsRead;
    int cnt = connections == null ? 0 : connections.length;

    store.putConnections(source, connections, System.currentTimeMillis());
    connectionsRead = store.getConnections(source);
    assertTrue(Arrays.equals(connections, connectionsRead));

    store.addConnection(source, newConnection, System.currentTimeMillis());
    connectionsRead = store.getConnections(source);
    assertEquals(cnt + 1, connectionsRead.length);

    assertTrue(store.getLWMark() <= store.getHWMark());
    store.persist();
    assertTrue(store.getLWMark() == store.getHWMark());

    store.removeConnection(source, newConnection, System.currentTimeMillis());
    connectionsRead = store.getConnections(source);
    assertEquals(cnt, connectionsRead.length);

    store.deleteConnections(source, System.currentTimeMillis());
    connectionsRead = store.getConnections(source);
    assertEquals(null, connectionsRead);

    assertTrue(store.getLWMark() <= store.getHWMark());
    store.sync();
    assertTrue(store.getLWMark() == store.getHWMark());
  }
}


text:
@interface CDOUserImportOperation ()
@property (nonatomic, strong) CDOGithubAPIClient *APIClient;
@end

@implementation CDOUserImportOperation

- (instancetype)initWithContextManager:(SQKContextManager *)contextManager APIClient:(CDOGithubAPIClient *)APIClient
{
    self = [super initWithContextManager:contextManager];
    if (self)
    {
        self.APIClient = APIClient;
    }
    return self;
}

- (void)performWorkWithPrivateContext:(NSManagedObjectContext *)context
{
    NSLog(@"Executing %@", NSStringFromClass([self class]));

    NSMutableArray *usersJSON = [NSMutableArray array];

    NSFetchRequest *fetchRequest = [User sqk_fetchRequest];
    NSArray *users = [context executeFetchRequest:fetchRequest error:NULL];

    if (users.count > 0)
    {
        for (User *user in users)
        {
            id JSON = [self.APIClient getUser:user.username error:NULL];
            [usersJSON addObject:JSON];
        }
        CDOUserImporter *importer = [[CDOUserImporter alloc] initWithManagedObjectContext:context];
        [importer importJSON:usersJSON];
        [self completeOperationBySavingContext:context];
    }
    else
    {
        [self completeOperationBySavingContext:context];
    }
}

@end


text:
hello-sdj
=========

Hello SDJournal.org

Get Started with Django
=======================

Follow the docs at https://docs.djangoproject.com/en/dev/intro/tutorial01/

The Django docs walk you through something of a Minimum Viable Server, complete with error handlers and forward-thinking practices. I'll walk you through setting up a Minimum Functioning Program that just barely gets off the ground and has a feature.

%> django-admin.py startproject django_sdj
%> cd django_sdj
%> python manage.py runserver
Go to http://localhost:8000 in your browser

Add sqlite3 database for simplicity in settings.py:

        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'django_sdj.sqlite3',

%> python manage.py syncdb      # run through the prompts
Go to http://localhost:8000 in your browser to check it's not broken

%> python manage.py startapp hello    # generates hello directory
You edit settings.py according to django instructions to add your app
See: https://github.com/mdagosta/hello-sdj/commit/c8970ded6fc015f57278ad128f5b9195eeaa2a4e

%> python manage.py sql hello  # sample output. if it looks ok...
%> python manage.py syncdb

Django's docs for part 2 on the Admin Interface are great so I don't have much to add... for what it's worth here's what I needed to enable Admin:

https://github.com/mdagosta/hello-sdj/commit/7e4744e7c92be1e3430a147b4965ae0b7172dd03

Creating a view:
----------------

Start by editing urls and views: https://github.com/mdagosta/hello-sdj/commit/a1882138363ff684c11b427a37a067a75166cff1

Create a feature:
-----------------

Commits are worth a thousand words each:

https://github.com/mdagosta/hello-sdj/commit/3e5b0c5a4fb4beb3e2e968ee1a0e9ecb35bc0fc7

https://github.com/mdagosta/hello-sdj/commit/866c88b3d51724f5e1a8177ce56d66565dc3e8bb

https://github.com/mdagosta/hello-sdj/commit/b97230fbc08ea85c8c8730609f32c3befc097314

Get Started with Tornado
========================

We're going to modify the tornado webchat to store messages in the database, which will touch on the ioloop and async requests. This uses Google Oauth so if you aren't already Google Borg you'll need to sign up to Gmail for this demo.

Start by installing tornado using pip or clone it from github:

%> pip install tornado torndb
OR
%> git clone https://github.com/facebook/tornado.git

Then copy the contents of the tornado/demos/chat directory to yours:

https://github.com/facebook/tornado/tree/master/demos/chat

Then run the chatdemo:

%> cd chat
%> ./chatdemo.py

Use two separate browsers or profiles and visit http://localhost:8888, and sign into Google. Out of the box you should be able to type messages that appear in the other browser.

Try the same thing using websockets. Copy the contents of the tornado/demos/websocket directory to yours:

https://github.com/facebook/tornado/tree/master/demos/websocket

%> cd websocket
%> ./chatdemo.py

Do the same in both browsers. If you got it to work, the first step is to do some studying - chatdemo.py is the code sample.


text:
<?xml version='1.0' encoding='UTF-8'?>
<vehicle_configs>
    <vehicle class="multirotor" rotors="4" geometry="x" propeller_diameter="8" weight="1.0" id="4010">
        <title>Standard 8" Prop Quadrotor (x)</title>
        <short_desc>Standard quadrotor configuration in x configuration for 8-" propellers</short_desc>
        <mixer>/etc/mixers/quad_x.main.mix</mixer>
    </vehicle>
    <vehicle class="multirotor" rotors="4" geometry="+" propeller_diameter="8" weight="1.0" id="5001">
        <title>Standard 8" Prop Quadrotor (+)</title>
        <short_desc>Standard quadrotor configuration in + configuration for 8-" propellers</short_desc>
        <mixer>/etc/mixers/quad_+.main.mix</mixer>
    </vehicle>
    <vehicle class="multirotor" rotors="4" geometry="x" propeller_diameter="10" weight="1.5" id="4011">
        <title>Standard 8" Prop Quadrotor (x)</title>
        <short_desc>Standard quadrotor configuration in x configuration for 8-" propellers</short_desc>
        <mixer>/etc/mixers/quad_x.main.mix</mixer>
    </vehicle>
    <vehicle class="fixed_wing" wingspan="0.85" elevons="yes" ailerons="no" rudder="no" weight="1.5" id="3033">
        <title>Zeta Science Wing Wing Z-84</title>
        <short_desc>Configuration for a small flying wing.</short_desc>
        <mixer>/etc/mixers/wingwing.main.mix</mixer>
    </vehicle>
</vehicle_configs>


text:
var fs = require('fs');

if (process.argv.length == 3) {
	var fileName = process.argv[2];

	fs.readFile(fileName, function (err, data) {
		if (err) {
			console.log('An error occurred.');
			throw err;
		}

		var fileContents = data.toString();

		var lines = fileContents.split('\n');
		if (lines.length > 0) {
			console.log(lines.length - 1);
			return;
		}
	});
}
else {
	console.log(0);
}


text:
package ogame.objects.game;

import com.google.gson.Gson;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Created by jarndt on 5/10/17.
 */
public class BuildTask implements Comparable<BuildTask>{
    public static void main(String[] args) {
        List<BuildTask> buildTasks = new ArrayList<>(Arrays.asList(
                new BuildTask().setBuildable(Buildable.getBuildableByID(0)).setBuildPriority(100).setCompleteTime(LocalDateTime.now().minusSeconds(1)),
                new BuildTask().setBuildable(Buildable.getBuildableByID(1)).setQueuedTime(LocalDateTime.now().plusSeconds(100)),
                new BuildTask().setBuildable(Buildable.getBuildableByID(2)).setQueuedTime(LocalDateTime.now().plusSeconds(10)),
                new BuildTask().setBuildable(Buildable.getBuildableByID(3)).setBuildPriority(0),
                new BuildTask().setBuildable(Buildable.getBuildableByID(4)).setBuildPriority(1000)
        ));
//        buildTasks.forEach(System.out::println);
//        System.out.println("\n\n\n");
//        Collections.sort(buildTasks);
//        buildTasks.forEach(System.out::println);

        System.out.println(new Gson().toJson(buildTasks));
    }

    private Buildable buildable;
    private String line, botPlanetID;
    private LocalDateTime queuedTime, startTime, completeTime;
    private int countOrLevel, buildPriority;
    private boolean done = false;
    private Coordinates coordinates;

    public BuildTask(Map<String, Object> databaseMap) {
        if(databaseMap.containsKey("bot_planets_id"))
            botPlanetID = databaseMap.get("bot_planets_id").toString();
        if(databaseMap.containsKey("buildable_id"))
            buildable = Buildable.getBuildableByID((int)databaseMap.get("buildable_id"));
        if(databaseMap.containsKey("build_level")) {
            countOrLevel = (int) databaseMap.get("build_level");
            if(buildable!=null)
                buildable.setCurrentLevel(countOrLevel);
        }if(databaseMap.containsKey("build_priority"))
            buildPriority = (int) databaseMap.get("build_priority");
        if(databaseMap.containsKey("build_timestamp")) {
            Timestamp o = ((Timestamp) databaseMap.get("build_timestamp"));
            if(o != null)
                queuedTime = o.toLocalDateTime();
            else
                queuedTime = LocalDateTime.now();
        }if(databaseMap.containsKey("done")) {
            String d = databaseMap.get("done").toString();
            done = d.equals("Y");
        }
    }

    public BuildTask(Buildable buildable, LocalDateTime completeTime) {
        this.buildable = buildable;
        this.startTime = LocalDateTime.now();
        this.completeTime = completeTime;
    }
    public BuildTask(Buildable buildable, LocalDateTime completeTime, int countOrLevel) {
        this.buildable = buildable;
        this.startTime = LocalDateTime.now();
        this.completeTime = completeTime;
        this.countOrLevel = countOrLevel;
    }
    public BuildTask(Buildable buildable, int countOrLevel, String nextProfileBuild){
        this.buildable = buildable;
        this.countOrLevel = countOrLevel;
        this.line = nextProfileBuild;
    }

    public BuildTask() {    }

    public Coordinates getCoordinates() {
        return coordinates;
    }

    public void setCoordinates(Coordinates coordinates) {
        this.coordinates = coordinates;
    }

    public String getBotPlanetID() {
        return botPlanetID;
    }

    public BuildTask setBotPlanetID(String botPlanetID) {
        this.botPlanetID = botPlanetID;
        return this;
    }

    public LocalDateTime getQueuedTime() {
        return queuedTime;
    }

    public BuildTask setQueuedTime(LocalDateTime queuedTime) {
        this.queuedTime = queuedTime;
        return this;
    }

    public int getBuildPriority() {
        return buildPriority;
    }

    public BuildTask setBuildPriority(int buildPriority) {
        this.buildPriority = buildPriority;
        return this;
    }

    public LocalDateTime getStartTime() {
        return startTime;
    }

    public BuildTask setStartTime(LocalDateTime startTime) {
        this.startTime = startTime;
        return this;
    }

    public LocalDateTime getCompleteTime() {
        return completeTime;
    }

    public BuildTask setCompleteTime(LocalDateTime completeTime) {
        this.completeTime = completeTime;
        return this;
    }

    public String getLine() {
        return line;
    }

    public BuildTask setLine(String line) {
        this.line = line;
        return this;
    }

    public Buildable getBuildable() {
        return buildable;
    }

    public BuildTask setBuildable(Buildable buildable) {
        this.buildable = buildable;
        return this;
    }

    public int getCountOrLevel() {
        return countOrLevel;
    }

    public BuildTask setCountOrLevel(int countOrLevel) {
        this.countOrLevel = countOrLevel;
        return this;
    }

    public boolean isDone() {
        return done;
    }

    public BuildTask setDone(boolean done) {
        this.done = done;
        return this;
    }
    public boolean isInProgress() {
        if(startTime == null || completeTime == null)
            return false;
        return startTime.isBefore(completeTime);
    }

    public boolean isComplete() {
        if(completeTime == null)
            return false;
        boolean b = LocalDateTime.now().isAfter(completeTime);
        if(b) done = true;
        return b;
    }

    @Override
    public String toString() {
        return "BuildTask{" +
                "buildable=" + buildable +
                ", line='" + line + '\'' +
                ", botPlanetID='" + botPlanetID + '\'' +
                ", queuedTime=" + queuedTime +
                ", startTime=" + startTime +
                ", completeTime=" + completeTime +
                ", countOrLevel=" + countOrLevel +
                ", buildPriority=" + buildPriority +
                ", done=" + done +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        BuildTask buildTask = (BuildTask) o;

        if (countOrLevel != buildTask.countOrLevel) return false;
        if (buildPriority != buildTask.buildPriority) return false;
        if (done != buildTask.done) return false;
        if (buildable != null ? !buildable.equals(buildTask.buildable) : buildTask.buildable != null) return false;
        if (line != null ? !line.equals(buildTask.line) : buildTask.line != null) return false;
        if (botPlanetID != null ? !botPlanetID.equals(buildTask.botPlanetID) : buildTask.botPlanetID != null)
            return false;
        if (queuedTime != null ? !queuedTime.equals(buildTask.queuedTime) : buildTask.queuedTime != null) return false;
        if (startTime != null ? !startTime.equals(buildTask.startTime) : buildTask.startTime != null) return false;
        return completeTime != null ? completeTime.equals(buildTask.completeTime) : buildTask.completeTime == null;
    }

    @Override
    public int hashCode() {
        int result = buildable != null ? buildable.hashCode() : 0;
        result = 31 * result + (line != null ? line.hashCode() : 0);
        result = 31 * result + (botPlanetID != null ? botPlanetID.hashCode() : 0);
        result = 31 * result + (queuedTime != null ? queuedTime.hashCode() : 0);
        result = 31 * result + (startTime != null ? startTime.hashCode() : 0);
        result = 31 * result + (completeTime != null ? completeTime.hashCode() : 0);
        result = 31 * result + countOrLevel;
        result = 31 * result + buildPriority;
        result = 31 * result + (done ? 1 : 0);
        return result;
    }

    @Override
    public int compareTo(BuildTask o) {
        int score = 0;
        if(isComplete()||isDone())
            return Integer.MAX_VALUE;
        if(queuedTime != null)
            score = o.getQueuedTime().compareTo(queuedTime);
        score+=new Integer(o.getBuildPriority()).compareTo(buildPriority);
        return score;
    }
}


text:
package eu.celarcloud.cloud_is.controller.services.restful;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;

/**
 * The Class ResponseCorsFilter.
 */
public class ResponseCorsFilter implements ContainerResponseFilter {

    /* (non-Javadoc)
     * @see com.sun.jersey.spi.container.ContainerResponseFilter#filter(com.sun.jersey.spi.container.ContainerRequest, com.sun.jersey.spi.container.ContainerResponse)
     */
	@Override
    public ContainerResponse filter(ContainerRequest req, ContainerResponse contResp) {

        ResponseBuilder resp = Response.fromResponse(contResp.getResponse());
        resp.header("Access-Control-Allow-Origin", "*");
        resp.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

        String reqHead = req.getHeaderValue("Access-Control-Request-Headers");

        if(null != reqHead && !reqHead.equals("")){
            resp.header("Access-Control-Allow-Headers", reqHead);
        }

        contResp.setResponse(resp.build());
        return contResp;
    }

}


text:
describe('The Log Utility ', function() {
	var global = (function() {return this;})();
	var Util =  global.fell ? global.fell.Utils : require("..").Utils;

	it('provides an interpolation function.', function() {
		expect(Util.interpolate(""))
				.toBe("");

		expect(Util.interpolate("{0}", 23, 49))
				.toBe("23");

		expect(Util.interpolate('hello {1} fred is {0} again, {1}, {2}', "sleepy", "world"))
				.toBe("hello world fred is sleepy again, world, undefined");
	});

	it('provides a format function for dates.', function() {

		var date = new Date(2013, 5, 4, 3, 2, 1, 23);

		expect(Util.format("", date))
				.toBe("");

		expect(Util.format("EEE MMM dd yyyy HH:mm:ss", date))
				.toBe("Tue Jun 04 2013 03:02:01");

		expect(Util.format("EEEE MMMM d yy H:m:s.SSS", date))
				.toBe("Tuesday June 4 13 3:2:1.023");

		expect(Util.format("MM", date))
				.toBe("06");
	});

});


text:
FROM drupal:latest

RUN apt-get update && apt-get install -y openssh-server

RUN curl -fSL https://github.com/drush-ops/drush/releases/download/8.0.0-rc4/drush.phar -o drush.phar \
	&& php drush.phar core-status \
	&& chmod +x drush.phar \
	&& mv drush.phar /usr/local/bin/drush \
	&& php /usr/local/bin/drush init


text:
package org.unique.web.exception;

import org.unique.common.tools.StringUtils;
import org.unique.web.render.Render;
import org.unique.web.render.RenderFactory;

public class ActionException extends RuntimeException{

	private static final long serialVersionUID = 1998063243843477017L;
	private int errorCode;
	private Render errorRender;

	public ActionException(int errorCode, Render errorRender) {
		if (errorRender == null)
			throw new IllegalArgumentException("The parameter errorRender can not be null.");

		this.errorCode = errorCode;
		this.errorRender = errorRender;
	}

	public ActionException(int errorCode, String errorView) {
		if (StringUtils.isBlank(errorView)){
			throw new IllegalArgumentException("The parameter errorView can not be blank.");
		}
		this.errorCode = errorCode;
		this.errorRender = RenderFactory.single().getErrorRender(errorCode, errorView);
	}

	public int getErrorCode() {
		return errorCode;
	}

	public Render getErrorRender() {
		return errorRender;
	}
}


text:
import chan from '../../src'
import {p, sleep} from '../utils'

async function producer(ch, items) {
  for (let item of items) {
    p(` -> sending item: ${ item }...`)
    await ch.send(item)
  }
  p(` -> closing channel...`)
  await ch.close()
  p(` -> done closing channel`)
}

async function consumer(ch) {
  while (true) {
    let item = await ch.take()
    if (item == ch.CLOSED) break
    p(`<-  got item: ${ item }`)
  }
  p(`<-  channel closed`)
}

async function run() {
  // allow buffering up to 3 items without blocking
  let ch = chan(3)
  let items = [ 1, 2, 3, 4, 5 ]
  producer(ch, items).catch(p)
  await sleep(500)
  consumer(ch).catch(p)
}

run().catch(p)