text:
/******************************************************************************
*
* File name:   CliClient.cpp
* Subsystem:   EMS
* Description: Provides a CLI Client interface to the EMS' Client Agent
*              through CORBA.
*
* Name                 Date       Release
* -------------------- ---------- ---------------------------------------------
* Stephen Horton       01/01/2014 Initial release
*
*
******************************************************************************/

//-----------------------------------------------------------------------------
// System include files, includes 3rd party libraries.
//-----------------------------------------------------------------------------

#include <iostream>
#include <sstream>

#include <ace/Get_Opt.h>
#include <ace/Reactor.h>
#include <ace/Signal.h>
#include <ace/Sig_Adapter.h>

#include <tao/ORB_Core.h>
#include <orbsvcs/CosNamingC.h>
#include <tao/Utils/ORB_Manager.h>

//-----------------------------------------------------------------------------
// Component includes, includes elements of our system.
//-----------------------------------------------------------------------------

#include "CliClient.h"

#include "platform/logger/Logger.h"

#include "platform/threadmgr/ThreadManager.h"

//-----------------------------------------------------------------------------
// Static Declarations.
//-----------------------------------------------------------------------------

/* From the C++ FAQ, create a module-level identification string using a compile
   define - BUILD_LABEL must have NO spaces passed in from the make command
   line */
#define StrConvert(x) #x
#define XstrConvert(x) StrConvert(x)
static volatile char main_sccs_id[] __attribute__ ((unused)) = "@(#)CLI Client"
   "\n   Build Label: " XstrConvert(BUILD_LABEL)
   "\n   Compile Time: " __DATE__ " " __TIME__;

//-----------------------------------------------------------------------------
// PUBLIC methods.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Method Type: Constructor
// Description:
// Design:
//-----------------------------------------------------------------------------
CliClient::CliClient()
          : sessionImplPtr_(NULL)
{
}//end constructor

//-----------------------------------------------------------------------------
// Method Type: Virtual Destructor
// Description:
// Design:
//-----------------------------------------------------------------------------
CliClient::~CliClient()
{
}//end virtual destructor

//-----------------------------------------------------------------------------
// Method Type: STATIC
// Description: Gracefully shutdown the Application and all of its child threads
// Design:
//-----------------------------------------------------------------------------
void CliClient::shutdown()
{

}//end shutdown

//-----------------------------------------------------------------------------
// Method Type: INSTANCE
// Description: Initialization method
// Design:
//-----------------------------------------------------------------------------
int CliClient::initialize(bool dottedDecimalIORFlag, bool debugFlag, string& debugLevel,
     string& debugFilename, string& endPointString, string& initRef, string& defaultInitRef)
{
   char* exceptionMessage = NULL;

   try
   {
      exceptionMessage = "While ORB Manager init";

      // Build the Orb.init arguments. This is necessary since there is some bug that prevents
      // the Orb from initializing properly after the arguments have been run through ACE::Get_Opt.
      int numbArgs = 0;
      char** orbArgs = new char *[20];
      orbArgs[numbArgs++] = "CliClient";
      orbArgs[numbArgs++] = "-ORBDottedDecimalAddresses";
      if (dottedDecimalIORFlag == true)
      {
         TRACELOG(DEBUGLOG, CLICLIENTLOG, "Restricting IORs to use IP Addresses only",0,0,0,0,0,0);
         orbArgs[numbArgs++] = "1";
      }//end if
      else
      {
         TRACELOG(DEBUGLOG, CLICLIENTLOG, "IORs allowed to contain Hostnames for DNS resolution",0,0,0,0,0,0);
         orbArgs[numbArgs++] = "0";
      }//end else
      if (endPointString.empty() == false)
      {
         TRACELOG(DEBUGLOG, CLICLIENTLOG, "Orb instructed to use endpoints: %s",endPointString.c_str(),0,0,0,0,0);
         orbArgs[numbArgs++] = "-ORBListenEndpoints";
         orbArgs[numbArgs++] = (char*)endPointString.c_str();
      }//end if
      if (initRef.empty() == false)
      {
         TRACELOG(DEBUGLOG, CLICLIENTLOG, "Orb instructed to use initial reference: %s", initRef.c_str(),0,0,0,0,0);
         orbArgs[numbArgs++] = "-ORBInitRef";
         orbArgs[numbArgs++] = (char*)initRef.c_str();
      }//end if
      if (defaultInitRef.empty() == false)
      {
         TRACELOG(DEBUGLOG, CLICLIENTLOG, "Orb instructed to use default initial reference: %s",
            defaultInitRef.c_str(),0,0,0,0,0);
         orbArgs[numbArgs++] = "-ORBDefaultInitRef";
         orbArgs[numbArgs++] = (char*)defaultInitRef.c_str();
      }//end if
      if (debugFlag == true)
      {
         TRACELOG(DEBUGLOG, CLICLIENTLOG, "Orb internal debug logs enabled to level %s",
            debugLevel.c_str(),0,0,0,0,0);
         orbArgs[numbArgs++] = "-ORBDebug";
         orbArgs[numbArgs++] = "-ORBDebugLevel";
         orbArgs[numbArgs++] = (char*)debugLevel.c_str();
         if (debugFilename.empty() == false)
         {
            TRACELOG(DEBUGLOG, CLICLIENTLOG, "Orb internal debug logs redirected to file %s",
               debugFilename.c_str(),0,0,0,0,0);
            orbArgs[numbArgs++] = "-ORBLogFile";
            orbArgs[numbArgs++] = (char*)debugFilename.c_str();
         }//end if
      }//end if

      TRACELOG(DEBUGLOG, CLICLIENTLOG, "Calling orb init with %d arguments",numbArgs,0,0,0,0,0);

      // Initialize the Orb Manager - for GIOP 1.1, try: -ORBEndPoint iiop://1.1@<host>:<port>
      if (orbManager_.init (numbArgs, orbArgs) == ERROR)
      {
         TRACELOG(ERRORLOG, CLICLIENTLOG, "Error initializing the orb manager",0,0,0,0,0,0);
         return ERROR;
      }//end if

      // Obtain the RootPOA. It is created in holding state when the Orb is created, so
      // we need to activate it.
      CORBA::Object_var obj = orbManager_.orb()->resolve_initial_references("RootPOA");

      // Get the POA_var object from Object_var.
      exceptionMessage = "While narrowing the root poa";
      PortableServer::POA_var rootPOA = PortableServer::POA::_narrow(obj.in());

      // Get the POAManager of the RootPOA.
      exceptionMessage = "While getting the POA Manager";
      PortableServer::POAManager_var poaManager = rootPOA->the_POAManager();

      // Activate the POA Manager before activating any sub-objects
      exceptionMessage = "While activating the POA Manager";
      poaManager->activate();

      // Create the IDL-specific objects and register them with the POA
      exceptionMessage = "While creating IDL objects";
      createIDLObjects(rootPOA);

      // Perform initial resolution of the Naming Service. Then, bind our top level
      // objects into the Naming Service.
      exceptionMessage = "While initializing the Naming Service bindings";
      initNamingService();

      // Resolve client interface objects from the Naming Service
      exceptionMessage = "While resolving agent objects from the Naming Service";
      resolveAgentObjects();
   }//end try
   catch (CORBA::Exception &exception)
   {
      // See $TAO_ROOT/tao/Exception.h for additional fields and information that can be retrieved
      TRACELOG(ERRORLOG, CLICLIENTLOG, "Application Level Exception - %s. Corba Orb Level Exception - %s",
         exceptionMessage, exception._info().c_str(),0,0,0,0);
      return ERROR;
   }//end catch

   // NOTE, TBD: We have not done a good job on retry semantics. If any of the above
   // throws an exception, then we simply error-out and the Orb will not get started.
   // Suggestion to improve above: Perhaps we should not return Errors in the initNamingService
   // and resolveClientObjects methods as these depend on external components. We need
   // some mechanism to periodically retry (or at least when we need / on application demand)
   // for those methods.

   // Start the TAO Orb event loop in its own dedicated thread. From there,
   // TAO will spawn additional threads and will handle its own thread / connection
   // management. Here, returns the OS assigned unique thread Id
   ThreadManager::createThread((ACE_THR_FUNC)CliClient::runOrb, (void*) 0, "CliClientOrb", true, THR_NEW_LWP|THR_DETACHED);

   return OK;
}//end initialize

//-----------------------------------------------------------------------------
// Method Type: INSTANCE
// Description: Handle Menu Option user input
// Design:
//-----------------------------------------------------------------------------
void CliClient::processMenu()
{
   // Pass in reference to all of the interface objects FOR NOW. This so that
   // that the Menu Handlers can invoke the remote methods. This probably needs
   // to be changed so that these are given by static methods called on this
   // class -- because the references may be regenerated/replaced if the connection
   // becomes stale and objects need to be re-resolved from the Naming Service!!!

   // This call also starts the menu display loop
   TRACELOG(DEBUGLOG, CLICLIENTLOG, "Initializing Menu Controller",0,0,0,0,0,0);
   cliMenuController_.initialize(session_I_ptr_, platformConfig_I_ptr_, alarmInterface_ptr_);

}//end processMenu

//-----------------------------------------------------------------------------
// Method Type: INSTANCE
// Description: Return the String'ized form of the class contents
// Design:
//-----------------------------------------------------------------------------
string CliClient::toString()
{
   string s = "";
   return (s);
}//end toString

//-----------------------------------------------------------------------------
// PROTECTED methods.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// PRIVATE methods.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Method Type: INSTANCE
// Description: Create the IDL-specific object interfaces
// Design:
//-----------------------------------------------------------------------------
int CliClient::createIDLObjects(PortableServer::POA_var& rootPOA)
{
   char* exceptionMessage = NULL;
   try
   {
      // Create an instance of the Session interface object. This object is
      // responsible for monitoring of agent/client communication
      ACE_NEW_RETURN (sessionImplPtr_, session_Session_I_i(), 0);

      PortableServer::ObjectId_var sessionOid = PortableServer::string_to_ObjectId ("CLISession");

      exceptionMessage = "While activating CLI Client Session";
      rootPOA->activate_object_with_id (sessionOid.in(), sessionImplPtr_);

      // For debugging, here we get an Object reference for session object.
      // This verifies that the ORB is correctly managing the object.
      exceptionMessage = "While Session::_this";
      session::Session_I* sessionVar = sessionImplPtr_->_this();

      // Stringify the object reference and print it out
      exceptionMessage = "While object_to_string";
      CORBA::String_var sessionIOR = this->orbManager_.orb()->object_to_string (sessionVar);

      // Print the IOR.
      TRACELOG(DEBUGLOG, CLICLIENTLOG, "CLI Client Session IOR is <%s>", sessionIOR.in(),0,0,0,0,0);

      // Create additional IDL interface objects here...

//TODO: Need to implement a new part of the Alarms interface (register here) in order for us
// to receive Alarm notifications (async)

   }//end try
   catch (CORBA::Exception &exception)
   {
      // See $TAO_ROOT/tao/Exception.h for additional fields and information that can be retrieved
      TRACELOG(ERRORLOG, CLICLIENTLOG, "Application Level Exception - %s. Corba Orb Level Exception - %s",
         exceptionMessage, exception._info().c_str(),0,0,0,0);
      return ERROR;
   }//end catch
   return OK;
}//end createIDLObjects

//-----------------------------------------------------------------------------
// Method Type: INSTANCE
// Description: Perform initial resolution of the Naming Service. Then, bind
//   our top level objects into the Naming Service.
// Design:
//-----------------------------------------------------------------------------
int CliClient::initNamingService()
{
   const char *exceptionMessage = NULL;
   try
   {
      TRACELOG(DEBUGLOG, CLICLIENTLOG, "Attempting to resolve the Naming Service",0,0,0,0,0,0);

      // Resolve the Naming Service generic reference - Success here depends on the value of
      // -ORBInitRef (or ORBDefaultInitRef) passed in to Orb.init from the argc/argv options to
      // specify the corbaloc/iiop target for Interoperable Naming Service lookup. The only
      // alternative to doing it this way is to actually have the root IOR of the Naming
      // Service (possibly exchanged via a URL or via database replication, file exchange, or whatever)
      exceptionMessage = "While resolving Naming Service";
      CORBA::ORB_ptr orbPtr = TAO_ORB_Core_instance()->orb();
      CORBA::Object_var namingObj = orbPtr->resolve_initial_references ("NameService");

      // Check to see if the Naming Service reference is null
      if (CORBA::is_nil (namingObj.in ()))
      {
         TRACELOG(ERRORLOG, CLICLIENTLOG, "Unable to resolve Naming Service",0,0,0,0,0,0);
         // Need to implement retry semantics here!!

         return ERROR;
      }//end if

      exceptionMessage = "While narrowing Naming Service context";
      namingContextVar_ = CosNaming::NamingContext::_narrow (namingObj.in());

      // Check to see if there was a problem performing narrow
      if (CORBA::is_nil (namingContextVar_.in()))
      {
         TRACELOG(ERRORLOG, CLICLIENTLOG, "Naming Service Context reference is null",0,0,0,0,0,0);
         // Implement retry semantics here (if necessary)!!

         return ERROR;
      }//end if

      // Bind the Session IDL object into the naming service. This is the top level
      // interface from which all other interfaces should be retrieved. So, we should not
      // need to bind other interface objects to the Naming Service later.
      CosNaming::Name sessionName (1);
      sessionName.length (1);
      // TBD: This should be replaced with a unique identifier that distinguishes this
      // CLI Client from other possible CLI client. Needs discussion.
      sessionName[0].id = CORBA::string_dup ("ClientSession");
      sessionName[0].kind = CORBA::string_dup ("client");
      TRACELOG(DEBUGLOG, CLICLIENTLOG, "CLI Client Naming Service Bind Name is ClientSession", 0,0,0,0,0,0);

      exceptionMessage = "While using Session _this";
      session::Session_I* sessionVar = sessionImplPtr_->_this();

      exceptionMessage = "While rebinding Session";
      namingContextVar_->rebind (sessionName, sessionVar);
   }//end try
   catch (CORBA::Exception &exception)
   {
      // See $TAO_ROOT/tao/Exception.h for additional fields and information that can be retrieved
      TRACELOG(ERRORLOG, CLICLIENTLOG, "Application Level Exception - %s. Corba Orb Level Exception - %s",
         exceptionMessage, exception._info().c_str(),0,0,0,0);
      return ERROR;
   }//end catch
   return OK;
}//end initNamingService

//-----------------------------------------------------------------------------
// Method Type: INSTANCE
// Description: Resolve/retrieve our Agent's top level interface objects from
//   the Naming Service
// Design:
//-----------------------------------------------------------------------------
int CliClient::resolveAgentObjects()
{
   const char* exceptionMessage = NULL;
   try
   {
      // Resolve the Agent's Session reference which is the top level object reference. From
      // there we can get references to all of the other remote interfaces
      CosNaming::Name agentSessionContextName (1);
      agentSessionContextName.length (1);
      // NOTE, TBD: This needs to be replaced with a unique distinguishing string for
      // each Agent (redundant). For now, we only support 1 agent!!!!
      agentSessionContextName[0].id = CORBA::string_dup ("AgentSession");
      agentSessionContextName[0].kind = CORBA::string_dup ("server");

      if (CORBA::is_nil (namingContextVar_.in()))
      {
         TRACELOG(ERRORLOG, CLICLIENTLOG, "Naming Service Context reference is NULL",0,0,0,0,0,0);
         return ERROR;
      }//end if

      TRACELOG(DEBUGLOG, CLICLIENTLOG, "Resolving Agent's Session Interfaces",0,0,0,0,0,0);
      exceptionMessage = "While resolving Agent's session interfaces";
      CORBA::Object_var agentSessionVar = namingContextVar_->resolve(agentSessionContextName);

      exceptionMessage = "While narrowing the Agent's Session Interface";
      session_I_ptr_ = session::Session_I::_narrow (agentSessionVar.in());

      if (CORBA::is_nil (session_I_ptr_) || session_I_ptr_->_non_existent())
      {
         TRACELOG(ERRORLOG, CLICLIENTLOG, "Failed to resolve Agent's Session Interfaces in Naming Service",0,0,0,0,0,0);
         return ERROR;
      }//end if

      // Display list of Clients and their IORs
      TRACELOG(DEBUGLOG, CLICLIENTLOG, "IOR of the Agent Session object is %s",
         this->orbManager_.orb()->object_to_string(session_I_ptr_),0,0,0,0,0);

      // Set the reference of the Agent Session object into our own Session object
      // as the 'Associated Session'
      sessionImplPtr_->setAssociatedSession(session_I_ptr_);

      // Resolve the Agent's PlatformConfig reference for now. Later, we may need to use
      // an interface method to retrieve this object from the session top-level object
      CosNaming::Name agentPlatformConfigContextName(1);
      agentPlatformConfigContextName.length(1);

      agentPlatformConfigContextName[0].id = CORBA::string_dup("PlatformConfig");
      agentPlatformConfigContextName[0].kind = CORBA::string_dup("server");

      TRACELOG(DEBUGLOG, CLICLIENTLOG, "Resolving Agent's Platform Config Interface",0,0,0,0,0,0);
      exceptionMessage = "While resolving Agent's Platform Config interface";
      CORBA::Object_var agentPlatformConfigVar = namingContextVar_->resolve(agentPlatformConfigContextName);

      exceptionMessage = "While narrowing the Agent's Platform Config Interface";
      platformConfig_I_ptr_ = platformConfig::platformConfig_I::_narrow(agentPlatformConfigVar.in());

      if (CORBA::is_nil (platformConfig_I_ptr_) || (platformConfig_I_ptr_->_non_existent()))
      {
         TRACELOG(ERRORLOG, CLICLIENTLOG, "Failed to resolve Agent's Platform Config Interface in Naming Service",0,0,0,0,0,0);
         return ERROR;
      }//end if

      // Display the IOR
      TRACELOG(DEBUGLOG, CLICLIENTLOG, "IOR of the Agent Platform Config object is %s",
         this->orbManager_.orb()->object_to_string(platformConfig_I_ptr_),0,0,0,0,0);

      // Resolve the Agent's Alarm reference for now. Later, we may need to use
      // an interface method to retrieve this object from the session top-level object
      CosNaming::Name agentAlarmContextName(1);
      agentAlarmContextName.length(1);

      agentAlarmContextName[0].id = CORBA::string_dup("Alarms");
      agentAlarmContextName[0].kind = CORBA::string_dup("server");

      TRACELOG(DEBUGLOG, CLICLIENTLOG, "Resolving Agent's Alarms Interface",0,0,0,0,0,0);
      exceptionMessage = "While resolving Agent's Alarms interface";
      CORBA::Object_var alarmInterface_var = namingContextVar_->resolve(agentAlarmContextName);

      exceptionMessage = "While narrowing the Agent's Alarms Interface";
      alarmInterface_ptr_ = alarms::alarmInterface::_narrow(alarmInterface_var.in());

      if (CORBA::is_nil (alarmInterface_ptr_) || (alarmInterface_ptr_->_non_existent()))
      {
         TRACELOG(ERRORLOG, CLICLIENTLOG, "Failed to resolve Agent's Alarms Interface in Naming Service",0,0,0,0,0,0);
         return ERROR;
      }//end if

      // Display the IOR
      TRACELOG(DEBUGLOG, CLICLIENTLOG, "IOR of the Agent Alarms object is %s",
         this->orbManager_.orb()->object_to_string(alarmInterface_ptr_),0,0,0,0,0);

   }//end try
   //catch NamingContext error
   catch (CosNaming::NamingContext::NotFound notFoundException)
   {
      TRACELOG(ERRORLOG, CLICLIENTLOG, "CosNaming Naming Service Context not found %s: %s",
         exceptionMessage, notFoundException._info().c_str(),0,0,0,0);
      return ERROR;
   }//end catch
   catch (CosNaming::NamingContext::CannotProceed cannotProceed)
   {
      TRACELOG(ERRORLOG, CLICLIENTLOG, "CosNaming Cannot proceed user exception %s: %s",
         exceptionMessage, cannotProceed._info().c_str(),0,0,0,0);
      return ERROR;
   }//end catch
   catch (CORBA::Exception &exception)
   {
      // See $TAO_ROOT/tao/Exception.h for additional fields and information that can be retrieved
      TRACELOG(ERRORLOG, CLICLIENTLOG, "Application Level Exception - %s. Corba Orb Level Exception - %s",
         exceptionMessage, exception._info().c_str(),0,0,0,0);
      return ERROR;
   }//end catch
   return OK;
}//end resolveAgentObjects

//-----------------------------------------------------------------------------
// Method Type: STATIC
// Description: Method used to start the TAO Orb in its own dedicated thread
// Design:
//-----------------------------------------------------------------------------
void CliClient::runOrb()
{
   // Start the orb main event loop - THIS IS AN INFINITE BLOCKING CALL
   TAO_ORB_Core_instance()->orb()->run();
}//end runOrb

//-----------------------------------------------------------------------------
// Nested Class Definitions:
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Function Type: main function for CliClient binary
// Description:
// Design:
//-----------------------------------------------------------------------------
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
   // Turn of OS limits and enable core file generation
   struct rlimit resourceLimit;
   resourceLimit.rlim_cur = RLIM_INFINITY;
   resourceLimit.rlim_max = RLIM_INFINITY;
   setrlimit(RLIMIT_CORE, &resourceLimit);

   // If this application does NOT need command line arguments, then uncomment (to
   // prevent compiler warning for unused variables):
   //int tmpInt __attribute__ ((unused)) = argc;
   //char** tmpChar __attribute__ ((unused)) = argv;

   // Create usage string
   ostringstream usageString;
   string str4spaces = "    ";
   usageString << "Usage:\n  CliClient\n" << str4spaces
               /* command line options */
               << "-h Restrict the use of hostnames in IORs. Invokes -ORBDottedDecimalAddresses=1 on the Orb\n" << str4spaces
               << "-d Enable debug messages from within the Orb\n" << str4spaces
               << "-l <Debug Level> Controls the level of debug messages from within the Orb (Max is 10)\n" << str4spaces
               << "-f <log filename> Redirect Orb logs to a file instead of the default stdout\n" << str4spaces
               << "-e <Endpoint> Direct the Orb to listen for connections on the interface specified by the endpoint URL\n" << str4spaces
               << "-i <Initial Reference> URL the Orb uses for initial resolution of the NameService. Invokes -ORBInitRef\n" << str4spaces
               << "-r <Default Init Ref> URL the Orb uses for default initial resolution of the NameService. Invokes -ORBDefaultInitRef\n"
               << str4spaces;
   usageString << ends;

   // Validate that the user passed some arguments
   if (argc < 1)
   {
      cout << "Minimum argument requirements not met." << endl
           << usageString << endl;
      exit(ERROR);
   }//end if

   // Perform our own arguments parsing -before- we pass args to the class
   ACE_Get_Opt get_opt (argc, argv, "hdl:f:e:i:r:");
   bool dottedDecimalIORFlag = false;
   bool debugFlag = false;
   string debugLevel = "0";
   string debugFilename;
   string endPointString;
   string initRef;
   string defaultInitRef;
   int c;
   while ((c = get_opt ()) != ERROR)
   {
      switch (c)
      {
         case 'h':
         {
            // Set flag for enabling Dotted Decimal Addresses inside IORs
            dottedDecimalIORFlag = true;
            break;
         }//end case
         case 'd':
         {
            // Set flag for enabling Debug logs within the Orb
            debugFlag = true;
            break;
         }//end case
         case 'l':
         {
            // Get the argument for setting the Debug Level within the Orb
            debugLevel = get_opt.optarg;
            break;
         }//end case
         case 'f':
         {
            // Get the argument for the file to redirect Orb Debug logs to
            debugFilename = get_opt.optarg;
            break;
         }//end case
         case 'e':
         {
            // Get the argument for setting the Orb Listener Endpoint
            endPointString = get_opt.optarg;
            break;
         }//end case
         case 'i':
         {
            // Get the argument for the Initial Reference String url
            initRef = get_opt.optarg;
            break;
         }//end case
         case 'r':
         {
            // Get the argument for the Default Initial Reference String url
            defaultInitRef = get_opt.optarg;
            break;
         }//end case
         default:
         {
            cout << "Misunderstood option: " << c << endl;
            cout << usageString.str() << endl;
            exit(ERROR);
         }//end default
      }//end switch
   }//end while

   // Initialize the Logger with local-only output since we probably don't want to log
   // these logs for the CLI through the shared memory queue (MAYBE ??)
   Logger::getInstance()->initialize(true);

   // Turn on All relevant Subsystem logging levels -- NOTE, for CliClient, this line
   // should match whatever the default datafill is in the platform.LogLevels table. We
   // need this to be true so that the user experience is consistent
   Logger::setSubsystemLogLevel(CLICLIENTLOG, DEVELOPERLOG);

   // Create an adapter to shutdown this application
   ACE_Sig_Adapter signalAdapter ((ACE_Sig_Handler_Ex) CliClient::shutdown);

   // Specify which types of signals we want to trap
   ACE_Sig_Set signalSet;
   signalSet.sig_add (SIGINT);
   signalSet.sig_add (SIGQUIT);

   // Register ourselves to receive signals so we can shut down gracefully.
   if (ACE_Reactor::instance()->register_handler (signalSet, &signalAdapter) == ERROR)
   {
      TRACELOG(ERRORLOG, CLICLIENTLOG, "Error registering for OS signals",0,0,0,0,0,0);
   }//end if

   // Initialize the OPM
   //OPM::initialize();

   // Create the CliClient instance
   CliClient* cliClient = new CliClient();
   if (!cliClient)
   {
      TRACELOG(ERRORLOG, CLICLIENTLOG, "Could not create CliClient instance",0,0,0,0,0,0);
      return ERROR;
   }//end if

   // Initialize the CliClient instance
   if (cliClient->initialize(dottedDecimalIORFlag, debugFlag, debugLevel, debugFilename,
       endPointString, initRef, defaultInitRef) == ERROR)
   {
      TRACELOG(DEBUGLOG, CLICLIENTLOG, "CliClient failed initialization",0,0,0,0,0,0);
      exit(ERROR);
   }//end if
   else
   {
      TRACELOG(DEBUGLOG, CLICLIENTLOG, "CliClient successfully started with PID=%d", ACE_OS::getpid(),0,0,0,0,0);
   }//end else

   // Start CliClient's menu processing loop to handle user input. Here we block
   // and run forever until we are shutdown by the SIGINT/SIGQUIT signal
   cliClient->processMenu();
}//end main


text:
class Organisation
  attr_accessor :title, :abbreviation, :content_id, :web_url

  def initialize(attributes = {})
    @title = attributes[:title]
    @abbreviation = attributes[:abbreviation]
    @content_id = attributes[:content_id]
    @web_url = attributes[:web_url]
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace gmock_sample
{

notification_manager::notification_manager(std::shared_ptr<notifier> _notifier)
	: notifier_(_notifier)
{
}

bool
notification_manager::has_notifications() const
{
	return this->notification_count_ > 0;
}

void
notification_manager::add(const std::string& notification)
{
	(void)notification;
	++this->notification_count_;
}

std::size_t
notification_manager::notification_count() const
{
	return this->notification_count_;
}

void
notification_manager::notify()
{
	this->notifier_->exec("stub");
	this->notification_count_ = 0;
}

} // gmock_sample.


text:
module Ebay # :nodoc:
  module Types # :nodoc:
    class FeatureIDCode
      extend Enumerable
      extend Enumeration
      ListingDurations = 'ListingDurations'
      BestOfferEnabled = 'BestOfferEnabled'
      DutchBINEnabled = 'DutchBINEnabled'
      ShippingTermsRequired = 'ShippingTermsRequired'
      UserConsentRequired = 'UserConsentRequired'
      HomePageFeaturedEnabled = 'HomePageFeaturedEnabled'
      AdFormatEnabled = 'AdFormatEnabled'
      DigitalDeliveryEnabled = 'DigitalDeliveryEnabled'
      BestOfferCounterEnabled = 'BestOfferCounterEnabled'
      BestOfferAutoDeclineEnabled = 'BestOfferAutoDeclineEnabled'
      ProPack = 'ProPack'
      BasicUpgradePack = 'BasicUpgradePack'
      ValuePack = 'ValuePack'
      ProPackPlus = 'ProPackPlus'
      LocalMarketSpecialitySubscription = 'LocalMarketSpecialitySubscription'
      LocalMarketRegularSubscription = 'LocalMarketRegularSubscription'
      LocalMarketPremiumSubscription = 'LocalMarketPremiumSubscription'
      LocalMarketNonSubscription = 'LocalMarketNonSubscription'
      ExpressEnabled = 'ExpressEnabled'
      ExpressPicturesRequired = 'ExpressPicturesRequired'
      ExpressConditionRequired = 'ExpressConditionRequired'
      SellerContactDetailsEnabled = 'SellerContactDetailsEnabled'
      MinimumReservePrice = 'MinimumReservePrice'
      TransactionConfirmationRequestEnabled = 'TransactionConfirmationRequestEnabled'
      StoreInventoryEnabled = 'StoreInventoryEnabled'
      LocalListingDistances = 'LocalListingDistances'
      SkypeMeTransactionalEnabled = 'SkypeMeTransactionalEnabled'
      SkypeMeNonTransactionalEnabled = 'SkypeMeNonTransactionalEnabled'
      ClassifiedAdPaymentMethodEnabled = 'ClassifiedAdPaymentMethodEnabled'
      ClassifiedAdShippingMethodEnabled = 'ClassifiedAdShippingMethodEnabled'
      ClassifiedAdBestOfferEnabled = 'ClassifiedAdBestOfferEnabled'
      ClassifiedAdCounterOfferEnabled = 'ClassifiedAdCounterOfferEnabled'
      ClassifiedAdAutoDeclineEnabled = 'ClassifiedAdAutoDeclineEnabled'
      ClassifiedAdContactByEmailEnabled = 'ClassifiedAdContactByEmailEnabled'
      ClassifiedAdContactByPhoneEnabled = 'ClassifiedAdContactByPhoneEnabled'
      SafePaymentRequired = 'SafePaymentRequired'
      MaximumBestOffersAllowed = 'MaximumBestOffersAllowed'
      ClassifiedAdMaximumBestOffersAllowed = 'ClassifiedAdMaximumBestOffersAllowed'
      ClassifiedAdContactByEmailAvailable = 'ClassifiedAdContactByEmailAvailable'
      ClassifiedAdPayPerLeadEnabled = 'ClassifiedAdPayPerLeadEnabled'
      ItemSpecificsEnabled = 'ItemSpecificsEnabled'
    end
  end
end


text:
using System.Data;

namespace bulky
{
    public class Util
    {
        public static object AdHoc(IDbConnection connection, IDbTransaction transaction, int timeout, string sql)
        {
            if (connection.State == ConnectionState.Closed) connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = sql;
            command.CommandTimeout = timeout;
            command.Transaction = transaction;
            return command.ExecuteScalar();
        }
    }
}


text:
Lütfen kullandığınız dokümanın Electron versiyonunuzla aynı olduğundan emin olun.
Versiyon numarası okuduğunuz dokümanın URL'sindekiyle aynı olmalı. Eğer aynı değilse, muhtemelen geliştirme aşamasındaki API değişikliklerini içerebilecek dokümantasyonudur.
Eğer öyleyse, atom.io üzerinden [mevcut sürümler](https://electron.atom.io/docs/)e göz atabilirsiniz ya da eğer GitHub arayüzünü kullanıyorsanız "Switch branches/tags" açılır menüsünden versiyonunuza uygun olanı seçebilirsiniz.

## SSS(Sıkça Sorulan Sorular)

Bir problem(issue) bildirmeden önce sıkça sorulan sorulara göz atın:
* [Electron SSS](https://github.com/electron/electron/tree/master/docs/faq/electron-faq.md)

## Klavuzlar

* [Desteklenen Platformlar ](https://github.com/electron/electron/tree/master/docs/tutorial/supported-platforms.md)
* [Uygulama Dağıtımı](https://github.com/electron/electron/tree/master/docs/tutorial/application-distribution.md)
* [Mac Uygulama Mağazası Başvuru Klavuzu](https://github.com/electron/electron/tree/master/docs/tutorial/mac-app-store-submission-guide.md)
* [Uygulama Paketleme](https://github.com/electron/electron/tree/master/docs/tutorial/application-packaging.md)
* [Native Node Modüllerini Kullanma](https://github.com/electron/electron/tree/master/docs/tutorial/using-native-node-modules.md)
* [Ana Süreç(Main Process) Hata ayıklama](https://github.com/electron/electron/tree/master/docs/tutorial/debugging-main-process.md)
* [Selenium ve WebDriver kullanımı](https://github.com/electron/electron/tree/master/docs/tutorial/using-selenium-and-webdriver.md)
* [DevTools Eklentisi](https://github.com/electron/electron/tree/master/docs/tutorial/devtools-extension.md)
* [Pepper Flash Kullanımı](https://github.com/electron/electron/tree/master/docs/tutorial/using-pepper-flash-plugin.md)
* [Widevine CDM Kullanımı](https://github.com/electron/electron/tree/master/docs/tutorial/using-widevine-cdm-plugin.md)
* [CI Sistem Testleri (Travis, Jenkins)](https://github.com/electron/electron/tree/master/docs/tutorial/testing-on-headless-ci.md)

## Eğitimler

* [Quick Start](https://github.com/electron/electron/tree/master/docs/tutorial/quick-start.md)
* [Desktop Environment Integration](https://github.com/electron/electron/tree/master/docs/tutorial/desktop-environment-integration.md)
* [Online/Offline Event Detection](https://github.com/electron/electron/tree/master/docs/tutorial/online-offline-events.md)

## API Kaynakları

* [Synopsis](https://github.com/electron/electron/tree/master/docs/api/synopsis.md)
* [Process Object](https://github.com/electron/electron/tree/master/docs/api/process.md)
* [Desteklenen Chrome Komut Satırı Anahtarları](https://github.com/electron/electron/tree/master/docs/api/chrome-command-line-switches.md)
* [Environment Değişkenleri](https://github.com/electron/electron/tree/master/docs/api/environment-variables.md)

### Özel DOM Elementleri:

* [`File` Nesnesi](api/file-object.md)
* [`<webview>` Etiketi](https://github.com/electron/electron/tree/master/docs/api/webview-tag.md)
* [`window.open` Fonksiyonu](https://github.com/electron/electron/tree/master/docs/api/window-open.md)

### Ana Süreç(Main Process) Modülleri:

* [app](https://github.com/electron/electron/tree/master/docs/api/app.md)
* [autoUpdater](https://github.com/electron/electron/tree/master/docs/api/auto-updater.md)
* [BrowserWindow](https://github.com/electron/electron/tree/master/docs/api/browser-window.md)
* [contentTracing](https://github.com/electron/electron/tree/master/docs/api/content-tracing.md)
* [dialog](https://github.com/electron/electron/tree/master/docs/api/dialog.md)
* [globalShortcut](https://github.com/electron/electron/tree/master/docs/api/global-shortcut.md)
* [ipcMain](https://github.com/electron/electron/tree/master/docs/api/ipc-main.md)
* [Menu](https://github.com/electron/electron/tree/master/docs/api/menu.md)
* [MenuItem](https://github.com/electron/electron/tree/master/docs/api/menu-item.md)
* [powerMonitor](https://github.com/electron/electron/tree/master/docs/api/power-monitor.md)
* [powerSaveBlocker](https://github.com/electron/electron/tree/master/docs/api/power-save-blocker.md)
* [protocol](https://github.com/electron/electron/tree/master/docs/api/protocol.md)
* [session](https://github.com/electron/electron/tree/master/docs/api/session.md)
* [webContents](https://github.com/electron/electron/tree/master/docs/api/web-contents.md)
* [Tray](https://github.com/electron/electron/tree/master/docs/api/tray.md)

### Renderer Process Modülelri (Web Page):

* [desktopCapturer](https://github.com/electron/electron/tree/master/docs/api/desktop-capturer.md)
* [ipcRenderer](https://github.com/electron/electron/tree/master/docs/api/ipc-renderer.md)
* [remote](https://github.com/electron/electron/tree/master/docs/api/remote.md)
* [webFrame](https://github.com/electron/electron/tree/master/docs/api/web-frame.md)

### Her İki Süreç İçin Geçerli Modüller:

* [clipboard](https://github.com/electron/electron/tree/master/docs/api/clipboard.md)
* [crashReporter](https://github.com/electron/electron/tree/master/docs/api/crash-reporter.md)
* [nativeImage](https://github.com/electron/electron/tree/master/docs/api/native-image.md)
* [screen](https://github.com/electron/electron/tree/master/docs/api/screen.md)
* [shell](https://github.com/electron/electron/tree/master/docs/api/shell.md)

## Geliştirme

* [Kodlama Stili](https://github.com/electron/electron/tree/master/docs/development/coding-style.md)
* [Kaynak Kod Dizin Yapısı](https://github.com/electron/electron/tree/master/docs/development/source-code-directory-structure.md)
* [NW.js(node-webkit adıyla bilinen) İle Arasındaki Teknik Farklılıklar](https://github.com/electron/electron/tree/master/docs/development/atom-shell-vs-node-webkit.md)
* [Build Sisyem Genel Bakış](https://github.com/electron/electron/tree/master/docs/development/build-system-overview.md)
* [(macOS) Build Komutları](https://github.com/electron/electron/tree/master/docs/development/build-instructions-osx.md)
* [(Windows) Build Komutları](https://github.com/electron/electron/tree/master/docs/development/build-instructions-windows.md)
* [(Linux) Build Komutları](https://github.com/electron/electron/tree/master/docs/development/build-instructions-linux.md)
* [(Windows) Hata Ayıklama Komutları](https://github.com/electron/electron/tree/master/docs/development/debug-instructions-windows.md)
* [Simge Sunucusu(Symbol Server) Hata Ayıklama Kurulumu](https://github.com/electron/electron/tree/master/docs/development/setting-up-symbol-server.md)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="Jumph" default="build">
 <property name="toolsdir" value="bin/" />
 <target name="build"
         depends="prepare,copy-parameters,bower,composer,lint,phploc-ci,pdepend,phpmd-ci,phpcs-ci,phpcpd-ci,phpunit,phpdox,csslint,jshint"
         description=""/>

 <target name="build-parallel"
         depends="prepare,lint,tools-parallel,phpunit,phpdox"
         description=""/>

 <target name="tools-parallel" description="Run tools in parallel">
  <parallel threadCount="2">
   <sequential>
    <antcall target="pdepend"/>
    <antcall target="phpmd-ci"/>
   </sequential>
   <antcall target="phpcpd-ci"/>
   <antcall target="phpcs-ci"/>
   <antcall target="phploc-ci"/>
  </parallel>
 </target>

 <target name="clean"
         unless="clean.done"
         description="Cleanup build artifacts">
  <delete dir="${basedir}/build/api"/>
  <delete dir="${basedir}/build/coverage"/>
  <delete dir="${basedir}/build/logs"/>
  <delete dir="${basedir}/build/pdepend"/>
  <delete dir="${basedir}/build/phpdox"/>
  <property name="clean.done" value="true"/>
 </target>

 <target name="prepare"
         unless="prepare.done"
         depends="clean"
         description="Prepare for build">
  <mkdir dir="${basedir}/build/api"/>
  <mkdir dir="${basedir}/build/coverage"/>
  <mkdir dir="${basedir}/build/logs"/>
  <mkdir dir="${basedir}/build/pdepend"/>
  <mkdir dir="${basedir}/build/phpdox"/>
  <property name="prepare.done" value="true"/>
 </target>

 <target name="copy-parameters" description="Copy parameters.yml file">
  <exec executable="cp" failonerror="true">
   <arg path="app/config/parameters.yml.dist" />
   <arg path="app/config/parameters.yml" />
  </exec>
 </target>

 <target name="composer" description="Installing composer dependencies">
  <exec executable="composer" failonerror="true">
   <arg value="install" />
   <arg value="--dev" />
   <arg value="--prefer-dist" />
   <arg value="--no-progress" />

   <env key="SYMFONY_ENV" value="test"/>
  </exec>
 </target>

 <target name="bower" description="Installing bower dependencies">
  <exec executable="bower" failonerror="true">
   <arg value="install" />
  </exec>
 </target>

 <target name="lint" description="Perform syntax check of sourcecode files">
  <apply executable="php" failonerror="true">
   <arg value="-l" />

   <fileset dir="${basedir}/src">
    <include name="**/*.php" />
    <modified />
   </fileset>

  </apply>
 </target>

 <target name="phploc"
         description="Measure project size using PHPLOC and print human readable output. Intended for usage on the command line.">
  <exec executable="${toolsdir}phploc">
   <arg value="--count-tests" />
   <arg path="${basedir}/src" />
  </exec>
 </target>

 <target name="phploc-ci"
         depends="prepare"
         description="Measure project size using PHPLOC and log result in CSV and XML format. Intended for usage within a continuous integration environment.">
  <exec executable="${toolsdir}phploc">
   <arg value="--count-tests" />
   <arg value="--log-csv" />
   <arg path="${basedir}/build/logs/phploc.csv" />
   <arg value="--log-xml" />
   <arg path="${basedir}/build/logs/phploc.xml" />
   <arg path="${basedir}/src" />
  </exec>
 </target>

 <target name="pdepend"
         depends="prepare"
         description="Calculate software metrics using PHP_Depend and log result in XML format. Intended for usage within a continuous integration environment.">
  <exec executable="${toolsdir}pdepend">
   <arg value="--jdepend-xml=${basedir}/build/logs/jdepend.xml" />
   <arg value="--jdepend-chart=${basedir}/build/pdepend/dependencies.svg" />
   <arg value="--overview-pyramid=${basedir}/build/pdepend/overview-pyramid.svg" />
   <arg path="${basedir}/src" />
  </exec>
 </target>

 <target name="phpmd"
         description="Perform project mess detection using PHPMD and print human readable output. Intended for usage on the command line before committing.">
  <exec executable="${toolsdir}phpmd">
   <arg path="${basedir}/src" />
   <arg value="text" />
   <arg path="${basedir}/build/phpmd.xml" />
  </exec>
 </target>

 <target name="phpmd-ci"
         depends="prepare"
         description="Perform project mess detection using PHPMD and log result in XML format. Intended for usage within a continuous integration environment.">
  <exec executable="${toolsdir}phpmd">
   <arg path="${basedir}/src" />
   <arg value="xml" />
   <arg path="${basedir}/build/phpmd.xml" />
   <arg value="--reportfile" />
   <arg path="${basedir}/build/logs/pmd.xml" />
  </exec>
 </target>

 <target name="phpcs"
         description="Find coding standard violations using PHP_CodeSniffer and print human readable output. Intended for usage on the command line before committing.">
  <exec executable="${toolsdir}phpcs">
   <arg value="--standard=PSR2" />
   <arg value="--extensions=php" />
   <arg value="--ignore=autoload.php" />
   <arg path="${basedir}/src" />
  </exec>
 </target>

 <target name="phpcs-ci"
         depends="prepare"
         description="Find coding standard violations using PHP_CodeSniffer and log result in XML format. Intended for usage within a continuous integration environment.">
  <exec executable="${toolsdir}phpcs" output="/dev/null">
   <arg value="--report=checkstyle" />
   <arg value="--report-file=${basedir}/build/logs/checkstyle.xml" />
   <arg value="--standard=PSR2" />
   <arg value="--extensions=php" />
   <arg value="--ignore=autoload.php" />
   <arg path="${basedir}/src" />
  </exec>
 </target>

 <target name="phpcpd"
         description="Find duplicate code using PHPCPD and print human readable output. Intended for usage on the command line before committing.">
  <exec executable="${toolsdir}phpcpd">
   <arg path="${basedir}/src" />
  </exec>
 </target>

 <target name="phpcpd-ci"
         depends="prepare"
         description="Find duplicate code using PHPCPD and log result in XML format. Intended for usage within a continuous integration environment.">
  <exec executable="${toolsdir}phpcpd">
   <arg value="--log-pmd" />
   <arg path="${basedir}/build/logs/pmd-cpd.xml" />
   <arg path="${basedir}/src" />
  </exec>
 </target>

 <target name="phpunit"
         depends="prepare"
         description="Run unit tests with PHPUnit">
  <exec executable="${toolsdir}phpunit" failonerror="true">
   <arg value="--configuration"/>
   <arg path="${basedir}/build/phpunit.xml"/>
  </exec>
 </target>

 <target name="phpdox"
         depends="phploc-ci,phpcs-ci,phpmd-ci"
         description="Generate project documentation using phpDox">
  <exec executable="${toolsdir}phpdox">
   <arg value="--file" />
   <arg value="${basedir}/build/phpdox.xml" />
  </exec>
 </target>

 <target name="csslint" description="Run the CSSLint tool on CSS files">
   <fileset dir="${basedir}/src" id="cssfiles.raw">
     <include name="**/*.css" />
   </fileset>
   <pathconvert pathsep=" " property="cssfiles.clean" refid="cssfiles.raw" />
   <exec executable="csslint" output="${basedir}/build/logs/csslint.xml">
     <arg line="--warnings=box-model,floats --errors=ids,important --format=lint-xml ${cssfiles.clean}" />
   </exec>
 </target>

 <target name="jshint" description="Run the JSHint tool on JavaScript files">
	<fileset dir="${basedir}/src" id="jsfiles.raw">
	  <include name="**/*.js" />
	</fileset>
	<pathconvert pathsep=" " property="jsfiles.clean" refid="jsfiles.raw" />
	<exec executable="jshint" output="${basedir}/build/logs/jshint.xml">
	  <arg line="--reporter=jslint ${jsfiles.clean}" />
	</exec>
 </target>

</project>


text:
import React from 'react';
import { signOut } from '../firebase';
import Spike from './Spike';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';

const Header = ({ admins, user, createSpike, showForm, toggleForm }) => {
  return (

Turing Fridays

        <button className="SignOut" onClick={() => signOut()}>Sign Out</button>

{user.email}

      <ReactCSSTransitionGroup
        transitionName='AnimateForm'
        transitionEnterTimeout={500}
        transitionLeaveTimeout={500}
      >
        {!showForm &&
          <button
            className="AddSpikeButton"
            onClick={() => toggleForm()}>
            Add Spike
          </button>}
          {showForm &&
          <Spike
            createSpike={createSpike}
            toggleForm={toggleForm}
          />}
      </ReactCSSTransitionGroup>

  )
}

export default Header;


text:
namespace Sc
{
	const std::string &GetPublicKey(EUniverse universe);
}

#endif


text:
module FunIn3 where

--Default parameters can be added to definition of functions and simple constants.

--In this example: add parameter 'y' to 'foo'

main::Int
main =let foo :: a -> Int -> Int
          foo y  x= h + t
               where (h,t) = head $ zip [1..x] [3..15]

          foo_y = undefined  in (let a=10
                                     b=10
                                 in (foo foo_y) 5+a+b)


text:
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["day", "today", "selected", "onChange", "hidden", "disabled", "active", "selectionStart", "selectionEnd", "focused", "onEnter", "onLeave", "hinted", "hintedSelectionStart", "hintedSelectionEnd", "sameMonth", "size", "className"];
import * as React from "react";
import { classNamesString } from "../../lib/classNames";
import { Tappable } from "../Tappable/Tappable";
import { ENABLE_KEYBOARD_INPUT_EVENT_NAME } from "../../hooks/useKeyboardInputTracker";
import { LocaleProviderContext } from "../LocaleProviderContext/LocaleProviderContext";
export var CalendarDay = /*#__PURE__*/React.memo(function (_ref) {
  var day = _ref.day,
      today = _ref.today,
      selected = _ref.selected,
      onChange = _ref.onChange,
      hidden = _ref.hidden,
      disabled = _ref.disabled,
      active = _ref.active,
      selectionStart = _ref.selectionStart,
      selectionEnd = _ref.selectionEnd,
      focused = _ref.focused,
      onEnter = _ref.onEnter,
      onLeave = _ref.onLeave,
      hinted = _ref.hinted,
      hintedSelectionStart = _ref.hintedSelectionStart,
      hintedSelectionEnd = _ref.hintedSelectionEnd,
      sameMonth = _ref.sameMonth,
      size = _ref.size,
      className = _ref.className,
      props = _objectWithoutProperties(_ref, _excluded);

  var locale = React.useContext(LocaleProviderContext);
  var ref = React.useRef(null);
  var onClick = React.useCallback(function () {
    return onChange(day);
  }, [day, onChange]);
  var handleEnter = React.useCallback(function () {
    return onEnter === null || onEnter === void 0 ? void 0 : onEnter(day);
  }, [day, onEnter]);
  var handleLeave = React.useCallback(function () {
    return onLeave === null || onLeave === void 0 ? void 0 : onLeave(day);
  }, [day, onLeave]);
  React.useEffect(function () {
    if (focused && ref.current) {
      ref.current.dispatchEvent(new Event(ENABLE_KEYBOARD_INPUT_EVENT_NAME, {
        bubbles: true
      }));
      ref.current.focus();
    }
  }, [focused]);

  if (hidden) {
    return /*#__PURE__*/React.createElement("div", {
      className: "vkuiCalendarDay__hidden"
    });
  }

  return /*#__PURE__*/React.createElement(Tappable, _extends({
    className: classNamesString("vkuiCalendarDay", size && styles["CalendarDay--size-".concat(size)], today && "vkuiCalendarDay--today", selected && !disabled && "vkuiCalendarDay--selected", active && !disabled && "vkuiCalendarDay--active", selectionStart && "vkuiCalendarDay--selection-start", selectionEnd && "vkuiCalendarDay--selection-end", disabled && "vkuiCalendarDay--disabled", !sameMonth && "vkuiCalendarDay--not-same-month", className),
    hoverMode: active ? "vkuiCalendarDay--active-hover" : "vkuiCalendarDay--hover",
    hasActive: false,
    onClick: onClick,
    disabled: disabled,
    "aria-label": new Intl.DateTimeFormat(locale, {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric"
    }).format(day),
    tabIndex: -1,
    getRootRef: ref,
    focusVisibleMode: active ? "outside" : "inside",
    onEnter: handleEnter,
    onLeave: handleLeave
  }, props), /*#__PURE__*/React.createElement("div", {
    className: classNamesString("vkuiCalendarDay__hinted", hinted && "vkuiCalendarDay__hinted--active", hintedSelectionStart && "vkuiCalendarDay__hinted--selection-start", hintedSelectionEnd && "vkuiCalendarDay__hinted--selection-end")
  }, /*#__PURE__*/React.createElement("div", {
    className: classNamesString("vkuiCalendarDay__inner", active && !disabled && "vkuiCalendarDay__inner--active")
  }, /*#__PURE__*/React.createElement("div", {
    className: "vkuiCalendarDay__day-number"
  }, day.getDate()))));
});
CalendarDay.displayName = "CalendarDay";
var styles = {
  "CalendarDay--size-s": "vkuiCalendarDay--size-s",
  "CalendarDay--size-m": "vkuiCalendarDay--size-m"
};
//# sourceMappingURL=CalendarDay.js.map


text:
=begin

	- i will take the sentence and split it by the space, to create an array with each word as a separate element
	- i will iterate over each element of the array to reverse using the reverse method.
	- i will then join the words back together using a space.
=end

# Initial Solution

def reverse_words(string)
	split = string.split(" ")
	split.map! do |x|
		x = x.reverse
	end
	new_string = split.join(" ")
	return new_string
end

# Refactored Solution

def reverse_words(string)
	split_array = string.split(" ").map! do |x|
			x = x.reverse
	end
	return split_array.join(" ")
end

# Reflection


text:
//
//  ZFTopicLabel.m
//  ZFDropDownDemo
//
//  Created by apple on 2017/1/5.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "ZFView.h"

@implementation ZFView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
#pragma once
#include <aws/drs/Drs_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/drs/model/ExtensionStatus.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace drs
{
namespace Model
{

  /**
   *
Staging information related to source server.

See Also:
   AWS API
   * Reference

   */
  class AWS_DRS_API StagingArea
  {
  public:
    StagingArea();
    StagingArea(Aws::Utils::Json::JsonView jsonValue);
    StagingArea& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
Shows an error message that occurred when DRS tried to access the staging
     * source server. In this case StagingArea$status will have value
     * EXTENSION_ERROR

     */
    inline const Aws::String& GetErrorMessage() const{ return m_errorMessage; }

    /**
     *
Shows an error message that occurred when DRS tried to access the staging
     * source server. In this case StagingArea$status will have value
     * EXTENSION_ERROR

     */
    inline bool ErrorMessageHasBeenSet() const { return m_errorMessageHasBeenSet; }

    /**
     *
Shows an error message that occurred when DRS tried to access the staging
     * source server. In this case StagingArea$status will have value
     * EXTENSION_ERROR

     */
    inline void SetErrorMessage(const Aws::String& value) { m_errorMessageHasBeenSet = true; m_errorMessage = value; }

    /**
     *
Shows an error message that occurred when DRS tried to access the staging
     * source server. In this case StagingArea$status will have value
     * EXTENSION_ERROR

     */
    inline void SetErrorMessage(Aws::String&& value) { m_errorMessageHasBeenSet = true; m_errorMessage = std::move(value); }

    /**
     *
Shows an error message that occurred when DRS tried to access the staging
     * source server. In this case StagingArea$status will have value
     * EXTENSION_ERROR

     */
    inline void SetErrorMessage(const char* value) { m_errorMessageHasBeenSet = true; m_errorMessage.assign(value); }

    /**
     *
Shows an error message that occurred when DRS tried to access the staging
     * source server. In this case StagingArea$status will have value
     * EXTENSION_ERROR

     */
    inline StagingArea& WithErrorMessage(const Aws::String& value) { SetErrorMessage(value); return *this;}

    /**
     *
Shows an error message that occurred when DRS tried to access the staging
     * source server. In this case StagingArea$status will have value
     * EXTENSION_ERROR

     */
    inline StagingArea& WithErrorMessage(Aws::String&& value) { SetErrorMessage(std::move(value)); return *this;}

    /**
     *
Shows an error message that occurred when DRS tried to access the staging
     * source server. In this case StagingArea$status will have value
     * EXTENSION_ERROR

     */
    inline StagingArea& WithErrorMessage(const char* value) { SetErrorMessage(value); return *this;}

    /**
     *
Account ID of the account to which source server belongs. If this source
     * server is extended - shows Account ID of staging source server.

     */
    inline const Aws::String& GetStagingAccountID() const{ return m_stagingAccountID; }

    /**
     *
Account ID of the account to which source server belongs. If this source
     * server is extended - shows Account ID of staging source server.

     */
    inline bool StagingAccountIDHasBeenSet() const { return m_stagingAccountIDHasBeenSet; }

    /**
     *
Account ID of the account to which source server belongs. If this source
     * server is extended - shows Account ID of staging source server.

     */
    inline void SetStagingAccountID(const Aws::String& value) { m_stagingAccountIDHasBeenSet = true; m_stagingAccountID = value; }

    /**
     *
Account ID of the account to which source server belongs. If this source
     * server is extended - shows Account ID of staging source server.

     */
    inline void SetStagingAccountID(Aws::String&& value) { m_stagingAccountIDHasBeenSet = true; m_stagingAccountID = std::move(value); }

    /**
     *
Account ID of the account to which source server belongs. If this source
     * server is extended - shows Account ID of staging source server.

     */
    inline void SetStagingAccountID(const char* value) { m_stagingAccountIDHasBeenSet = true; m_stagingAccountID.assign(value); }

    /**
     *
Account ID of the account to which source server belongs. If this source
     * server is extended - shows Account ID of staging source server.

     */
    inline StagingArea& WithStagingAccountID(const Aws::String& value) { SetStagingAccountID(value); return *this;}

    /**
     *
Account ID of the account to which source server belongs. If this source
     * server is extended - shows Account ID of staging source server.

     */
    inline StagingArea& WithStagingAccountID(Aws::String&& value) { SetStagingAccountID(std::move(value)); return *this;}

    /**
     *
Account ID of the account to which source server belongs. If this source
     * server is extended - shows Account ID of staging source server.

     */
    inline StagingArea& WithStagingAccountID(const char* value) { SetStagingAccountID(value); return *this;}

    /**
     *
Arn of the staging source server if this source server is extended

     */
    inline const Aws::String& GetStagingSourceServerArn() const{ return m_stagingSourceServerArn; }

    /**
     *
Arn of the staging source server if this source server is extended

     */
    inline bool StagingSourceServerArnHasBeenSet() const { return m_stagingSourceServerArnHasBeenSet; }

    /**
     *
Arn of the staging source server if this source server is extended

     */
    inline void SetStagingSourceServerArn(const Aws::String& value) { m_stagingSourceServerArnHasBeenSet = true; m_stagingSourceServerArn = value; }

    /**
     *
Arn of the staging source server if this source server is extended

     */
    inline void SetStagingSourceServerArn(Aws::String&& value) { m_stagingSourceServerArnHasBeenSet = true; m_stagingSourceServerArn = std::move(value); }

    /**
     *
Arn of the staging source server if this source server is extended

     */
    inline void SetStagingSourceServerArn(const char* value) { m_stagingSourceServerArnHasBeenSet = true; m_stagingSourceServerArn.assign(value); }

    /**
     *
Arn of the staging source server if this source server is extended

     */
    inline StagingArea& WithStagingSourceServerArn(const Aws::String& value) { SetStagingSourceServerArn(value); return *this;}

    /**
     *
Arn of the staging source server if this source server is extended

     */
    inline StagingArea& WithStagingSourceServerArn(Aws::String&& value) { SetStagingSourceServerArn(std::move(value)); return *this;}

    /**
     *
Arn of the staging source server if this source server is extended

     */
    inline StagingArea& WithStagingSourceServerArn(const char* value) { SetStagingSourceServerArn(value); return *this;}

    /**
     *
Status of Source server extension. Possible values: (a) NOT_EXTENDED - This
     * is a source server that is replicating in the current account. (b) EXTENDED -
     * Source server is extended from a staging source server. In this case, the value
     * of stagingSourceServerArn is pointing to the Arn of the source server in the
     * staging account. (c) EXTENSION_ERROR - Some issue occurred when accessing
     * staging source server. In this case, errorMessage field will contain an error
     * message that explains what happened.

     */
    inline const ExtensionStatus& GetStatus() const{ return m_status; }

    /**
     *
Status of Source server extension. Possible values: (a) NOT_EXTENDED - This
     * is a source server that is replicating in the current account. (b) EXTENDED -
     * Source server is extended from a staging source server. In this case, the value
     * of stagingSourceServerArn is pointing to the Arn of the source server in the
     * staging account. (c) EXTENSION_ERROR - Some issue occurred when accessing
     * staging source server. In this case, errorMessage field will contain an error
     * message that explains what happened.

     */
    inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }

    /**
     *
Status of Source server extension. Possible values: (a) NOT_EXTENDED - This
     * is a source server that is replicating in the current account. (b) EXTENDED -
     * Source server is extended from a staging source server. In this case, the value
     * of stagingSourceServerArn is pointing to the Arn of the source server in the
     * staging account. (c) EXTENSION_ERROR - Some issue occurred when accessing
     * staging source server. In this case, errorMessage field will contain an error
     * message that explains what happened.

     */
    inline void SetStatus(const ExtensionStatus& value) { m_statusHasBeenSet = true; m_status = value; }

    /**
     *
Status of Source server extension. Possible values: (a) NOT_EXTENDED - This
     * is a source server that is replicating in the current account. (b) EXTENDED -
     * Source server is extended from a staging source server. In this case, the value
     * of stagingSourceServerArn is pointing to the Arn of the source server in the
     * staging account. (c) EXTENSION_ERROR - Some issue occurred when accessing
     * staging source server. In this case, errorMessage field will contain an error
     * message that explains what happened.

     */
    inline void SetStatus(ExtensionStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }

    /**
     *
Status of Source server extension. Possible values: (a) NOT_EXTENDED - This
     * is a source server that is replicating in the current account. (b) EXTENDED -
     * Source server is extended from a staging source server. In this case, the value
     * of stagingSourceServerArn is pointing to the Arn of the source server in the
     * staging account. (c) EXTENSION_ERROR - Some issue occurred when accessing
     * staging source server. In this case, errorMessage field will contain an error
     * message that explains what happened.

     */
    inline StagingArea& WithStatus(const ExtensionStatus& value) { SetStatus(value); return *this;}

    /**
     *
Status of Source server extension. Possible values: (a) NOT_EXTENDED - This
     * is a source server that is replicating in the current account. (b) EXTENDED -
     * Source server is extended from a staging source server. In this case, the value
     * of stagingSourceServerArn is pointing to the Arn of the source server in the
     * staging account. (c) EXTENSION_ERROR - Some issue occurred when accessing
     * staging source server. In this case, errorMessage field will contain an error
     * message that explains what happened.

     */
    inline StagingArea& WithStatus(ExtensionStatus&& value) { SetStatus(std::move(value)); return *this;}

  private:

    Aws::String m_errorMessage;
    bool m_errorMessageHasBeenSet = false;

    Aws::String m_stagingAccountID;
    bool m_stagingAccountIDHasBeenSet = false;

    Aws::String m_stagingSourceServerArn;
    bool m_stagingSourceServerArnHasBeenSet = false;

    ExtensionStatus m_status;
    bool m_statusHasBeenSet = false;
  };

} // namespace Model
} // namespace drs
} // namespace Aws


text:
import urllib2

OPENER = urllib2.build_opener(urllib2.ProxyHandler({}))

def forward():
    return OPENER.open("http://localhost:8000/RoMIE/movements/forward").read()

def turn_left():
    return OPENER.open("http://localhost:8000/RoMIE/movements/turn_left").read()

def turn_right():
    return OPENER.open("http://localhost:8000/RoMIE/movements/turn_right").read()

def sensor_wall():
    response = OPENER.open("http://localhost:8000/RoMIE/movements/sensor_wall").read()
    print "response second: ",response
    if "1" in response:
        return True
    else:
        return False
    #return response
    #return OPENER.open("http://localhost:8000/RoMIE/movements/sensor_wall").read()

for count in range(100):
  if sensor_wall():
    turn_left()
  else:
    forward()
    turn_right()
    if sensor_wall():
      turn_left()


text:
import axios from 'axios';
import { push } from 'react-router-redux';

import { dispatchRequest } from './fetch'

export const TOGGLE_GHOSTS = "TOGGLE_GHOSTS";

export function toggleGhosts() {
  return {
    type: TOGGLE_GHOSTS
  };
}

export const TOGGLE_ADDGHOST = "TOGGLE_ADDGHOST";

export function toggleAddGhost() {
  return (dispatch, getState) => {
    const state = getState();
    if (!state.ghosts.riderId && state.riders && state.riders.length) {
      dispatch(selectRider(state.riders[0].id))
    }

    dispatch({
      type: TOGGLE_ADDGHOST
    });
  }
}

export const CHANGED_RIDER = "CHANGED_RIDER";

function changedRider(riderId) {
  return {
    type: CHANGED_RIDER,
    riderId
  }
}

export function selectRider(riderId) {
  return dispatch => {
    dispatch(changedRider(riderId));
    dispatch(fetchActivities(riderId));
  }
}

function fetchActivities(riderId) {
  return dispatchRequest(`/activities/${riderId}`, receiveActivities);
}

export const RECEIVE_ACTIVITIES = "RECEIVE_ACTIVITIES";

export function receiveActivities(data) {
  return {
    type: RECEIVE_ACTIVITIES,
    data
  };
}

export function fetchGhosts(riderId) {
  return dispatchRequest(`/ghosts`, receiveGhosts);
}

export const RECEIVE_GHOSTS = "RECEIVE_GHOSTS";

export function receiveGhosts(data) {
  const isArray = Array.isArray(data);
  return {
    type: RECEIVE_GHOSTS,
    data: isArray ? data : [],
    showButton: isArray
  };
}

export const CHANGED_ACTIVITY = "CHANGED_ACTIVITY";

export function changedActivity(activityId) {
  return {
    type: CHANGED_ACTIVITY,
    activityId
  }
}

export const ADDING_GHOST = "ADDING_GHOST";
export const ADDED_GHOST = "ADDED_GHOST";

export function addGhost(riderId, activityId) {
  return dispatch => {
    dispatch({
      type: ADDING_GHOST
    });

    axios.put('/ghosts', { riderId, activityId })
      .then(() => {
        dispatch({
          type: ADDED_GHOST
        });
        dispatch(fetchGhosts());
     })
      .catch(error => {
        dispatch({
          type: ADDED_GHOST
        });
        if (error.response) {
          const { status, statusMessage } = error.response;
          console.error(`Error adding ghost : ${status} - ${statusMessage}`);
        } else {
          console.error(error);
        }
      });
  }
}

export const CHANGED_GHOST = "CHANGED_GHOST";

export function changedGhost(ghostId) {
  return {
    type: CHANGED_GHOST,
    ghostId
  }
}

export function removeGhost(ghostId) {
  return dispatch => {
    axios.delete(`/ghosts/${ghostId}`)
      .then(() => {
        dispatch(fetchGhosts());
      })
      .catch(error => {
        if (error.response) {
          const { status, statusMessage } = error.response;
          console.error(`Error removing ghost : ${status} - ${statusMessage}`);
        } else {
          console.error(error);
        }
      })
  }
}

export const REQUESTING_REGROUP = "REQUESTING_REGROUP";
export const RECEIVE_REGROUP = "RECEIVE_REGROUP";

export function requestRegroup() {
  return dispatch => {
    dispatch({
      type: REQUESTING_REGROUP
    });

    axios.post(`/ghosts/regroup`)
      .then(() => {
        dispatch({
					type: RECEIVE_REGROUP
        });
      })
      .catch(error => {
        if (error.response) {
          const { status, statusMessage } = error.response;
          console.error(`Error removing ghost : ${status} - ${statusMessage}`);
        } else {
          console.error(error);
        }

        dispatch({
          type: RECEIVE_REGROUP
        });
      })
  }
}

export function fetchActivity(riderId, activityId) {
  return dispatchRequest(`/rider/${riderId}/activity/${activityId}`, receiveActivity);
}

export const RECEIVE_ACTIVITY = "RECEIVE_ACTIVITY";

function receiveActivity(data) {
  return {
    type: RECEIVE_ACTIVITY,
    data
  };
}

export const RESET_GHOSTS = "RESET_GHOSTS";

export function resetGhosts() {
  return dispatch => {
     dispatch({
      type: RESET_GHOSTS
    });

    axios.delete(`/ghosts`)
      .then(() => {
        dispatch({ type: RESET_GHOSTS });
      })
      .catch(error => {
        if (error.response) {
          const { status, statusMessage } = error.response;
          console.error(`Error removing ghosts : ${status} - ${statusMessage}`);
        } else {
          console.error(error);
        }
      })
  }
}


text:
/**
 * 飞船的创建,销毁,飞行
 * 动力系统
 * 指令接受
 */
var SpaceShip = function(id){

    var ship = this;
    var dom;
    var position = 0;

    //能源系统
    var power = (function(){
        var amount = 100;
        var showPower = function(){
            dom.childNodes[1].innerText = Math.ceil(amount)+"%";
        }
        //showPower();

        return new function (){
            var charge = function(num){
                amount = Math.min(amount+num, 100);
                showPower();
            }

            //消耗能量,能量不够时返回false
            this.use = function(num){
                if(amount < num) return false;
                amount = Math.max(amount - num, 0);
                showPower();
                return true;
            }

            //每秒钟增加2%
            setInterval(function(){
                charge(2);
            }, 1000)
        }
    })();

    //动力系统
    var engine = (function(power){
        var interval;
        var speed = 50;
        var isStart = false;

        return new function (){
            var eg = this;
            this.start = function(){
                if(isStart) return;
                isStart = true;
                interval = setInterval(function(){
                    if(!power.use(0.1)) {
                        eg.stop();
                        return;
                    }
                    dom.style.transform = "rotate("+(position++ % 360)+"deg)";
                }, 1000 / speed);
            }

            this.stop = function(){
                if(!isStart) return;
                isStart = false;
                clearInterval(interval);
            }
        }
    })(power);

    //销毁飞船
    var destory = function(){
        writelog("自毁程序已启动");

        for(var index=0; index< document.getElementById("planet").childNodes.length; index++){
            if(document.getElementById("planet").childNodes[index].id === 'spaceship'+id){
                document.getElementById("planet").removeChild(document.getElementById("planet").childNodes[index])
            }
        }
    }

    //开始
    var start = function(){
        engine.start();
        writelog("进入飞行状态");
    }

    //停止
    var stop = function(){
        engine.stop();
        writelog("停止飞行");
    }

    //接收消息
    var onReceiveMessage = function(cmd){
        if(cmd.receiver !== id) return;

        switch (cmd.message){
            case 'startSpaceShip' :
                start();
                break;

            case "stopSpaceShip" :
                stop();
                break;

            case "destorySpaceShip" :
                destory();
                break;
        }
    }

    var create = function(){
        Mediator.addListener(onReceiveMessage);

        dom = document.createElement("div");
        dom.setAttribute("id", "spaceship"+id);
        dom.setAttribute("class", "spaceship");
        dom.innerHTML = id + "号100%";
        document.getElementById("planet").appendChild(dom);
        writelog("新的飞船已经进入轨道");
    }

    var writelog = function(message){
        log("Ship"+id, message);
    }
    create();
}


text:
import shutil
import logging
import os
import io

try:
    from urllib.request import urlopen
except ImportError:
    from urllib import urlopen

from django.template.defaultfilters import slugify
from django.db import transaction

import networkx as nx
import unicodecsv

from .models import Entity, EntityType, Relationship, RelationshipType
from .utils import get_raw_sources, get_absolute_media_path, mkdir_p

logger = logging.getLogger(__name__)

class YolodexImportError(Exception):
    def __init__(self, kind, lineno, data, exc):
        self.kind = kind
        self.lineno = lineno
        self.exc = exc
        self.data = data

    def __str__(self):
        return '%s:%s - (%s) %s' % (self.kind, self.lineno, self.data, self.exc)

def get_from_cache_or_create(type_slug, klass, cache, realm):
    if type_slug in cache:
        typ = cache[type_slug]
    else:
        typ = klass.objects.filter(realms=realm, translations__slug=slugify(type_slug))
        if typ:
            typ = typ[0]
        else:
            typ = klass()
            typ.set_current_language('en')
            typ.name = type_slug
            typ.slug = slugify(type_slug)
            typ.settings = {}
            typ.save()
            typ.realms.add(realm)
        cache[type_slug] = typ
    return typ

def update_object(obj, dic):
    changed = False
    for k, v in dic.items():
        if getattr(obj, k) != v:
            setattr(obj, k, v)
            changed = True
    return changed

STAT_VALUES = {
    None: 'unchanged',
    False: 'updated',
    True: 'created'
}

def update_or_create(klass, search_dict, attr_dict):
    created = True
    try:
        obj = klass.objects.get(**search_dict)
        created = None
        if update_object(obj, attr_dict):
            created = False
            obj.save()
    except klass.DoesNotExist:
        attr_dict.update(search_dict)
        obj = klass.objects.create(**attr_dict)
    return obj, created

class YolodexImporter(object):
    def __init__(self, realm):
        self.entity_type_cache = {}
        self.rel_typ_cache = {}
        self.entity_cache = {}

        self.realm = realm
        self.stats = {
            'entity_created': 0,
            'entity_updated': 0,
            'entity_deleted': 0,
            'entity_unchanged': 0,
            'relationship_created': 0,
            'relationship_updated': 0,
            'relationship_deleted': 0,
            'relationship_unchanged': 0,
        }

    def import_graph_from_urls(self, node_url, edge_url, consume=True, **kwargs):
        node_file = urlopen(node_url)
        edge_file = urlopen(edge_url)
        if consume:
            node_file = io.BytesIO(node_file.read())
            edge_file = io.BytesIO(edge_file.read())
        self.import_graph_from_files(node_file, edge_file, **kwargs)

    def import_graph_from_files(self, node_file, edge_file, **kwargs):
        nodes = unicodecsv.DictReader(node_file)
        edges = unicodecsv.DictReader(edge_file)
        self.import_graph(nodes, edges, **kwargs)

    def import_graph(self, nodes, edges, media_dir=None, clear=False, update=False):
        if clear:
            self.clear()

        self.version = self.realm.version
        self.old_version = None
        if update:
            self.old_version = self.version
            self.version = self.version + 1
        with transaction.atomic():
            self.create_nodes(nodes, media_dir=media_dir)
            self.create_relationships(edges, media_dir=media_dir)

            if update:
                self.realm.version = self.version
                self.realm.save()
                self.clear_old_versions()

    def assign_degree(self):
        mg = nx.MultiDiGraph()
        mg.add_nodes_from(Entity.objects.filter(realm=self.realm))
        mg.add_edges_from((r.source, r.target) for r in Relationship.objects.filter(realm=self.realm))
        for entity, deg in mg.in_degree_iter():
            entity.in_degree = deg
        for entity, deg in mg.out_degree_iter():
            entity.out_degree = deg
        for entity, deg in mg.degree_iter():
            entity.degree = deg
        for entity in mg.nodes_iter():
            entity.save()

    def create_nodes(self, nodes, media_dir=None):
        for i, node in enumerate(nodes):
            try:
                entity = self.create_entity(node)
            except Exception as e:
                raise YolodexImportError('nodes', i, node, e)
            if entity is not None and media_dir is not None:
                raw_sources = get_raw_sources(self.realm, entity.sources)
                self.import_sources([s[1] for s in raw_sources if s[0] == 'file'], media_dir)

    def create_relationships(self, edges, media_dir=None):
        for i, edge in enumerate(edges):
            try:
                rel = self.create_relationship(edge)
            except Exception as e:
                raise YolodexImportError('edges', i, edge, e)
            if rel is not None and media_dir is not None:
                raw_sources = get_raw_sources(self.realm, rel.sources)
                self.import_sources([s[1] for s in raw_sources if s[0] == 'file'], media_dir)

    def import_sources(self, sources, media_dir):
        for source in sources:
            src = os.path.join(media_dir, source).encode('utf-8')
            target = get_absolute_media_path(self.realm, source).encode('utf-8')
            target_dir = os.path.dirname(target)
            mkdir_p(target_dir)
            if not os.path.exists(target):
                shutil.copyfile(src, target)

    def clear(self):
        logger.info("Deleting all entities/relationships of realm %s", self.realm)
        self.delete_entities(Entity.objects.filter(realm=self.realm))
        self.delete_relationships(Relationship.objects.filter(realm=self.realm).delete())

    def clear_old_versions(self):
        logger.info("Deleting entities/relationships of realm %s with old version %s", self.realm, self.old_version)
        e_qs = Entity.objects.filter(realm=self.realm, version=self.old_version)
        self.delete_entities(e_qs)

        r_qs = Relationship.objects.filter(realm=self.realm, version=self.old_version)
        self.delete_relationships(r_qs)

    def create_entity(self, node):
        name = node.pop('name')
        slug = slugify(node.pop('id', name))
        if not slug:
            return
        type_slug = node.pop('type', None)
        typ = None
        if type_slug is not None:
            typ = self.get_entitytype(type_slug)

        sources = node.pop('sources', '')
        data = {k: v for k, v in node.items() if v}

        search_dict = {
            'slug': slug,
            'realm': self.realm
        }
        attr_dict = dict(
            name=name,
            sources=sources,
            type=typ,
            data=data,
            version=self.version
        )
        entity, created = update_or_create(Entity, search_dict, attr_dict)
        logger.info("Entity %s %s", entity, STAT_VALUES[created])
        self.record_entity_stat(created)
        self.entity_cache[slug] = entity
        return entity

    def create_relationship(self, edge):
        source_slug = slugify(edge.pop('source'))
        if not source_slug:
            return
        source = self.entity_cache[source_slug]
        target_slug = slugify(edge.pop('target'))
        if not target_slug:
            return
        target = self.entity_cache[target_slug]
        sources = edge.pop('sources', '')
        reltype_slug = edge.pop('relationtype', None)
        reltype = None
        if reltype_slug:
            reltype = self.get_relationshiptype(reltype_slug)
        edge_type = edge.pop('type', 'directed')
        data = {k: v for k, v in edge.items() if v}

        search_dict = dict(
            realm=self.realm,
            source=source,
            target=target,
            type=reltype,
            data=data,
        )
        attr_dict = dict(
            directed=edge_type == 'directed',
            sources=sources,
            version=self.version
        )
        rel, created = update_or_create(Relationship, search_dict, attr_dict)
        logger.info("Relationship %s %s", rel, STAT_VALUES[created])
        self.record_relationship_stat(created)
        return rel

    def delete_entities(self, e_qs):
        self.stats['entity_deleted'] = e_qs.count()
        e_qs.delete()

    def delete_relationships(self, r_qs):
        self.stats['relationsip_deleted'] = r_qs.count()
        r_qs.delete()

    def get_entitytype(self, type_slug):
        return get_from_cache_or_create(type_slug, EntityType, self.entity_type_cache, self.realm)

    def get_relationshiptype(self, reltype_slug):
        return get_from_cache_or_create(reltype_slug, RelationshipType, self.rel_typ_cache, self.realm)

    def record_stat(self, typ, created):
        self.stats['%s_%s' % (typ, STAT_VALUES[created])] += 1

    def record_entity_stat(self, created):
        self.record_stat('entity', created)

    def record_relationship_stat(self, created):
        self.record_stat('relationship', created)


text:
// Copyright 2005-2009 Daniel James.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !defined(BOOST_UNORDERED_TEST_HELPERS_STRONG_HEADER)
#define BOOST_UNORDERED_TEST_HELPERS_STRONG_HEADER

#include <boost/config.hpp>
#include <iterator>
#include "./equivalent.hpp"
#include "./list.hpp"
#include "./exception_test.hpp"

namespace test
{
    template <class X>
    class strong
    {
        typedef test::list<BOOST_DEDUCED_TYPENAME X::value_type> values_type;
        values_type values_;
        unsigned int allocations_;
    public:
        void store(X const& x, unsigned int allocations = 0) {
            DISABLE_EXCEPTIONS;
            values_.clear();
            values_.insert(x.cbegin(), x.cend());
            allocations_ = allocations;
        }

        void test(X const& x, unsigned int allocations = 0) const {
            if(!(x.size() == values_.size() &&
                    test::equal(x.cbegin(), x.cend(), values_.begin(),
                        test::equivalent)))
                BOOST_ERROR("Strong exception safety failure.");
            if(allocations != allocations_)
                BOOST_ERROR("Strong exception failure: extra allocations.");
        }
    };
}

#endif


text:
var app = ZendeskApps.defineApp(null)
  .reopenClass({"experiments":{"hashParams":true},"location":{"support":{"top_bar":{"url":"assets/support/index.html"},"nav_bar":{"url":"assets/support/index.html"}},"chat":{"chat_sidebar":{"url":"assets/chat/index.html"}}},"noTemplate":[],"singleInstall":false,"signedUrls":false})
  .reopen({
    appName: "ABC",
    appVersion: "1.0.0",
    locationIcons: {"support":{"top_bar":{"inactive":"support/icon_top_bar_inactive.png","active":"support/icon_top_bar_active.png","hover":"support/icon_top_bar_hover.png"},"nav_bar":{"svg":"support/icon_nav_bar.svg"}}},
    assetUrlPrefix: "http://localhost:4567/0/",
    logoAssetHash: {"support":"support/logo-small.png","chat":"chat/logo-small.png"},
    appClassName: "app-0",
    author: {
      name: "John Smith",
      email: "john@example.com"
    },
    frameworkVersion: "2.0"
  });

ZendeskApps["ABC"] = app;


text:
/**
 * @author May
 * @version 1.0.0
 */
import React from "react";
import PropTypes from 'prop-types';

import {connect} from "react-redux";
import {Link} from "react-router";
import SignInForm from "../../components/signInForm";
import {authActions, isSignInRejected, isSignInFulfilled} from "userApp/core/auth";

export function SignIn({signIn, signInRejected, signInFulfilled}) {
  if (signInFulfilled) {
    window.location.href = '/';
  }

  return (

登录 May's sit

      <SignInForm
        signIn={signIn}
        signInRejected={signInRejected}
      />

        忘记密码?
        ·
        <Link to="/sign-up" className="form-link register-link">注册帐户</Link>

        第三方账号登录

)
}

SignIn.propTypes = {
  signIn: PropTypes.func.isRequired
};

const mapStateToProps = (state) => ({
  signInRejected: isSignInRejected(state),
  signInFulfilled: isSignInFulfilled(state)
});

const mapDispatchToProps = {
  signIn: authActions.signIn
};
export default connect(mapStateToProps, mapDispatchToProps)(SignIn);


text:
package v1beta1

import (
	enmassev1beta1 "github.com/enmasseproject/enmasse/pkg/apis/enmasse/v1beta1"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

type AuthenticationService struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`

	Spec   AuthenticationServiceSpec   `json:"spec"`
	Status AuthenticationServiceStatus `json:"status"`
}

type AuthenticationServiceSpec struct {
	Type     AuthenticationServiceType          `json:"type"`
	Realm    *string                            `json:"realm,omitempty"`
	None     *AuthenticationServiceSpecNone     `json:"none,omitempty"`
	Standard *AuthenticationServiceSpecStandard `json:"standard,omitempty"`
	External *AuthenticationServiceSpecExternal `json:"external,omitempty"`
}

type AuthenticationServiceType string

const (
	None     AuthenticationServiceType = "none"
	Standard AuthenticationServiceType = "standard"
	External AuthenticationServiceType = "external"
)

type AuthenticationServiceSpecNone struct {
	Replicas          *int32                        `json:"replicas,omitempty"`
	CertificateSecret *corev1.SecretReference       `json:"certificateSecret,omitempty"`
	Image             *enmassev1beta1.ImageOverride `json:"image,omitempty"`
	Resources         *corev1.ResourceRequirements  `json:"resources,omitempty"`
}

type AuthenticationServiceSpecStandard struct {
	Replicas           *int32                                       `json:"replicas,omitempty"`
	CredentialsSecret  *corev1.SecretReference                      `json:"credentialsSecret,omitempty"`
	CertificateSecret  *corev1.SecretReference                      `json:"certificateSecret,omitempty"`
	ServiceAccountName *string                                      `json:"serviceAccountName,omitempty"`
	DeploymentName     *string                                      `json:"deploymentName,omitempty"`
	ServiceName        *string                                      `json:"serviceName,omitempty"`
	RouteName          *string                                      `json:"routeName,omitempty"`
	Image              *enmassev1beta1.ImageOverride                `json:"image,omitempty"`
	InitImage          *enmassev1beta1.ImageOverride                `json:"initImage,omitempty"`
	JvmOptions         *string                                      `json:"jvmOptions,omitempty"`
	Resources          *corev1.ResourceRequirements                 `json:"resources,omitempty"`
	Storage            *AuthenticationServiceSpecStandardStorage    `json:"storage,omitempty"`
	Datasource         *AuthenticationServiceSpecStandardDatasource `json:"datasource,omitempty"`
	SecurityContext    *corev1.PodSecurityContext                   `json:"securityContext,omitempty"`
}

type StorageType string

const (
	Ephemeral       StorageType = "ephemeral"
	PersistentClaim StorageType = "persistent-claim"
)

type AuthenticationServiceSpecStandardStorage struct {
	Type        StorageType           `json:"type"`
	Class       *string               `json:"class,omitempty"`
	ClaimName   *string               `json:"claimName,omitempty"`
	Selector    *metav1.LabelSelector `json:"selector,omitempty"`
	DeleteClaim *bool                 `json:"deleteClaim,omitempty"`
	Size        resource.Quantity     `json:"size,omitempty"`
}

type AuthenticationServiceSpecStandardDatasource struct {
	Type              DatasourceType         `json:"type"`
	Host              string                 `json:"host,omitempty"`
	Port              int                    `json:"port,omitempty"`
	Database          string                 `json:"database,omitempty"`
	CredentialsSecret corev1.SecretReference `json:"credentialsSecret,omitempty"`
}

type DatasourceType string

const (
	H2Datasource         DatasourceType = "h2"
	PostgresqlDatasource DatasourceType = "postgresql"
)

type AuthenticationServiceSpecExternal struct {
	Host             string                  `json:"host"`
	Port             int                     `json:"port"`
	CaCertSecret     *corev1.SecretReference `json:"caCertSecret,omitempty"`
	ClientCertSecret *corev1.SecretReference `json:"clientCertSecret,omitempty"`
	AllowOverride    bool                    `json:"allowOverride,omitempty"`
}

type AuthenticationServicePhase string

const (
	AuthenticationServicePending     AuthenticationServicePhase = "Pending"
	AuthenticationServiceConfiguring AuthenticationServicePhase = "Configuring"
	AuthenticationServiceActive      AuthenticationServicePhase = "Active"
)

type AuthenticationServiceStatus struct {
	Phase            AuthenticationServicePhase `json:"phase,omitempty"`
	Message          string                     `json:"message,omitempty"`
	Host             string                     `json:"host,omitempty"`
	Port             int                        `json:"port,omitempty"`
	CaCertSecret     *corev1.SecretReference    `json:"caCertSecret,omitempty"`
	ClientCertSecret *corev1.SecretReference    `json:"clientCertSecret,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

type AuthenticationServiceList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata,omitempty"`

	Items []AuthenticationService `json:"items"`
}

// ** ConsoleService

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

type ConsoleService struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`
	Spec              ConsoleServiceSpec   `json:"spec"`
	Status            ConsoleServiceStatus `json:"status"`
}

type ConsoleServiceSpec struct {
	Replicas             *int32                           `json:"replicas,omitempty"`
	DiscoveryMetadataURL *string                          `json:"discoveryMetadataURL,omitempty"`
	Scope                *string                          `json:"scope,omitempty"`
	Impersonation        *ConsoleServiceImpersonationSpec `json:"impersonation,omitempty"`
	OauthClientSecret    *corev1.SecretReference          `json:"oauthClientSecret,omitempty"`
	CertificateSecret    *corev1.SecretReference          `json:"certificateSecret,omitempty"`
	SsoCookieSecret      *corev1.SecretReference          `json:"ssoCookieSecret,omitempty"`
	SsoCookieDomain      *string                          `json:"ssoCookieDomain,omitempty"`
	Host                 *string                          `json:"host,omitempty"`
	OauthProxy           *ConsoleServiceOauthProxySpec    `json:"oauthProxy,omitempty"`
	ConsoleServer        *ConsoleServiceConsoleServerSpec `json:"consoleServer,omitempty"`
}

type ConsoleServiceImpersonationSpec struct {
	UserHeader string `json:"userHeader"`
}

type ConsoleServiceOauthProxySpec struct {
	ExtraArgs []string                     `json:"extraArgs,omitempty"`
	Resources *corev1.ResourceRequirements `json:"resources,omitempty"`
}

type ConsoleServiceConsoleServerSpec struct {
	Resources      *corev1.ResourceRequirements            `json:"resources,omitempty"`
	Session        *ConsoleServiceConsoleServerSessionSpec `json:"session,omitempty"`
	LivenessProbe  *corev1.Probe                           `json:"livenessProbe,omitempty"`
	ReadinessProbe *corev1.Probe                           `json:"readinessProbe,omitempty"`
}

type ConsoleServiceConsoleServerSessionSpec struct {
	Lifetime    *string `json:"lifetime,omitempty"`
	IdleTimeout *string `json:"idleTimeout,omitempty"`
}

type ConsoleServiceStatus struct {
	Host         string                  `json:"host,omitempty"`
	Port         int                     `json:"port,omitempty"`
	CaCertSecret *corev1.SecretReference `json:"caCertSecret,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

type ConsoleServiceList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata,omitempty"`

	Items []ConsoleService `json:"items"`
}


text:
package life.utahairquality.model.twitter;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 *
 * @author cbrown
 */
@JsonIgnoreProperties
public class Mention {
    private long id;
    private long start;
    private String name;
    private String screenName;
    private long end;

    @JsonProperty("id")
    public long getId() {
        return id;
    }

    @JsonProperty("id")
    public void setId(long id) {
        this.id = id;
    }

    @JsonProperty("start")
    public long getStart() {
        return start;
    }

    @JsonProperty("start")
    public void setStart(long start) {
        this.start = start;
    }

    @JsonProperty("name")
    public String getName() {
        return name;
    }

    @JsonProperty("name")
    public void setName(String name) {
        this.name = name;
    }

    @JsonProperty("screen_name")
    public String getScreenName() {
        return screenName;
    }

    @JsonProperty("screen_name")
    public void setScreenName(String screenName) {
        this.screenName = screenName;
    }

    @JsonProperty("end")
    public long getEnd() {
        return end;
    }

    @JsonProperty("end")
    public void setEnd(long end) {
        this.end = end;
    }
}