text:
import java.io.*;
import java.util.*;
import java.lang.reflect.*;

import java.security.*;
import java.security.cert.*;
import java.security.spec.*;
import java.security.interfaces.*;
import java.math.BigInteger;

import javax.crypto.*;
import javax.crypto.spec.*;

public class SecretKeysBasic extends PKCS11Test {

    private static final char SEP = File.separatorChar;
    private static char[] tokenPwd;
    private static final char[] nssPwd =
            new char[]{'t', 'e', 's', 't', '1', '2'};
    private static final char[] solarisPwd =
            new char[]{'p', 'i', 'n'};
    private static SecretKey sk1;
    private static SecretKey sk2;
    private static SecretKey softkey;
    private static KeyStore ks;
    private static final String KS_TYPE = "PKCS11";
    private static Provider provider;

    public static void main(String[] args) throws Exception {
        main(new SecretKeysBasic());
    }

    public void main(Provider p) throws Exception {
        this.provider = p;

        // create secret key
        byte[] keyVal = new byte[16];
        (new SecureRandom()).nextBytes(keyVal);
        // NSS will throw CKR_HOST_MEMORY if calling C_DecryptInit w/
        // (keyVal[0] == 0)
        if (keyVal[0] == 0) {
            keyVal[0] = 1;
        }
        softkey = new SecretKeySpec(keyVal, "AES");
        dumpKey("softkey", softkey);

        KeyGenerator kg = KeyGenerator.getInstance("DESede", provider);
        sk1 = kg.generateKey();
        dumpKey("skey1", sk1);
        sk2 = kg.generateKey();
        dumpKey("skey2", sk2);

        String token = System.getProperty("TOKEN");

        if (token == null || token.length() == 0) {
            System.out.println("Error: missing TOKEN system property");
            throw new Exception("token arg required");
        }

        if ("nss".equals(token)) {
            tokenPwd = nssPwd;
        } else if ("solaris".equals(token)) {
            tokenPwd = solarisPwd;
        }

        int testnum = 1;
        doTest();
    }

    private static boolean checkSecretKeyEntry(String alias,
            SecretKey expected,
            boolean saveBeforeCheck)
            throws Exception {
        if (saveBeforeCheck) {
            ks.setKeyEntry(alias, expected, null, null);
        }
        SecretKey result = (SecretKey) (ks.getKey(alias, null));
        String keyEncFormat = result.getFormat();
        if (keyEncFormat == null) {
            // sensitive or un-extractable keys - verify by encrypt/decrypt
            byte[] data = new byte[64];
            Cipher c =
                    Cipher.getInstance(result.getAlgorithm() + "/CBC/NoPadding",
                    provider);
            c.init(Cipher.ENCRYPT_MODE, expected);
            byte[] encOut = c.doFinal(data);
            c.init(Cipher.DECRYPT_MODE, result, c.getParameters());
            byte[] decOut = c.doFinal(encOut);
            if (!Arrays.equals(data, decOut)) {
                return false;
            }
        } else if (keyEncFormat.toUpperCase().equals("RAW")) {
            if (!Arrays.equals(result.getEncoded(), expected.getEncoded())) {
                dumpKey("\texpected:", expected);
                dumpKey("\treturns:", result);
                return false;
            }
        }
        return true;
    }

    private static void dumpKey(String info, SecretKey key) {
        System.out.println(info + "> " + key);
        System.out.println("\tALGO=" + key.getAlgorithm());
        if (key.getFormat() != null) {
            System.out.println("\t[" + key.getFormat() + "] VALUE=" +
                    new BigInteger(key.getEncoded()));
        } else {
            System.out.println("\tVALUE=n/a");
        }
    }

    private static void doTest() throws Exception {
        if (ks == null) {
            ks = KeyStore.getInstance(KS_TYPE, provider);
            ks.load(null, tokenPwd);
        }

        System.out.println("Number of entries: " + ks.size());
        if (ks.size() != 0) {
            System.out.println("Deleting entries under aliases: ");
            for (Enumeration<String> aliases = ks.aliases();
                    aliases.hasMoreElements();) {
                String alias = aliases.nextElement();
                System.out.println("\t" + alias);
                ks.deleteEntry(alias);
            }
        }

        String alias = "testSKey";

        boolean testResult = checkSecretKeyEntry(alias, softkey, true);
        if (!testResult) {
            System.out.println("FAILURE: setKey() w/ softSecretKey failed");
        }

        if (!checkSecretKeyEntry(alias, sk1, true)) {
            testResult = false;
            System.out.println("FAILURE: setKey() w/ skey1 failed");
        }
        if (!checkSecretKeyEntry(alias, sk2, true)) {
            testResult = false;
            System.out.println("FAILURE: setKey() w/ skey2 failed");
        }

        ks.store(null);
        System.out.println("Reloading keystore...");

        ks.load(null, "whatever".toCharArray());
        if (ks.size() != 1) {
            System.out.println("FAILURE: reload#1 ks.size() != 1");
        }
        if (!checkSecretKeyEntry(alias, sk2, false)) {
            testResult = false;
            System.out.println("FAILURE: reload#1 ks entry check failed");
        }

        ks.deleteEntry(alias);
        ks.store(null);

        System.out.println("Reloading keystore...");
        ks.load(null, "whatever".toCharArray());
        if (ks.size() != 0) {
            testResult = false;
            System.out.println("FAILURE: reload#2 ks.size() != 0");
        }
        if (!testResult) {
            throw new Exception("One or more test failed!");
        }
    }
}


text:
/*****************************************************************************/
/* Sockets.h                              Copyright (c) Ladislav Zezula 2021 */
/*---------------------------------------------------------------------------*/
/* MIME parsing functions for CascLib                                        */
/*---------------------------------------------------------------------------*/
/*   Date    Ver   Who  Comment                                              */
/* --------  ----  ---  -------                                              */
/* 13.02.21  1.00  Lad  Created                                              */
/*****************************************************************************/

#ifndef __SOCKET_H__
#define __SOCKET_H__

//-----------------------------------------------------------------------------
// Defines

#ifndef INVALID_SOCKET
#define INVALID_SOCKET (SOCKET)(-1)
#endif

#ifndef SOCKET_ERROR
#define SOCKET_ERROR   (-1)
#endif

#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif

#ifndef WSAECONNRESET
#define WSAECONNRESET       10054L
#endif

#ifndef EPIPE
#define EPIPE               32
#endif

#define CASC_PORT_HTTP      80
#define CASC_PORT_RIBBIT    1119

//-----------------------------------------------------------------------------
// The CASC_SOCKET class

typedef class CASC_SOCKET_CACHE * PCASC_SOCKET_CACHE;
typedef class CASC_SOCKET * PCASC_SOCKET;
typedef struct addrinfo * PADDRINFO;

class CASC_SOCKET
{
    public:

    char * ReadResponse(const char * request, size_t request_length = 0, size_t * PtrLength = NULL);
    DWORD AddRef();
    void Release();

    private:

    // Constructor and destructor
    static int GetSockError();
    static DWORD GetAddrInfoWrapper(const char * hostName, unsigned portNum, PADDRINFO hints, PADDRINFO * ppResult);
    static SOCKET CreateAndConnect(addrinfo * remoteItem);
    static SOCKET ReconnectAfterShutdown(SOCKET & sock, addrinfo * remoteItem);
    static PCASC_SOCKET New(addrinfo * remoteList, addrinfo * remoteItem, const char * hostName, unsigned portNum, SOCKET sock);
    static PCASC_SOCKET Connect(const char * hostName, unsigned portNum);

    // Frees all resources and deletes the socket
    void Delete();

    // Entities allowed to manipulate with the class
    friend CASC_SOCKET * sockets_connect(const char * hostName, unsigned portNum);
    friend char * sockets_read_response(PCASC_SOCKET pSocket, const char * request, size_t request_length, size_t * PtrLength);
    friend class CASC_SOCKET_CACHE;

    PCASC_SOCKET_CACHE pCache;          // Pointer to the cache. If NULL, the socket is not cached
    PCASC_SOCKET pPrev;                 // Pointer to the prev socket in the list
    PCASC_SOCKET pNext;                 // Pointer to the next socket in the list
    PADDRINFO remoteList;               // List of the remote host informations
    PADDRINFO remoteItem;               // The particular host picked during the last connection attempt
    CASC_LOCK Lock;                     // Lock for single threaded access
    SOCKET sock;                        // Opened and connected socket
    DWORD dwRefCount;                   // Number of references
    DWORD portNum;                      // Port number
    char hostName[1];                   // Buffer for storing remote host (variable length)
};

//-----------------------------------------------------------------------------
// Socket cache class

class CASC_SOCKET_CACHE
{
    public:

    CASC_SOCKET_CACHE();
    ~CASC_SOCKET_CACHE();

    PCASC_SOCKET Find(const char * hostName, unsigned portNum);
    PCASC_SOCKET InsertSocket(PCASC_SOCKET pSocket);
    void UnlinkSocket(PCASC_SOCKET pSocket);

    void SetCaching(bool bAddRef);
    void PurgeAll();

    private:

    PCASC_SOCKET pFirst;
    PCASC_SOCKET pLast;
    DWORD dwRefCount;
};

//-----------------------------------------------------------------------------
// Public functions

PCASC_SOCKET sockets_connect(const char * hostName, unsigned portNum);
void sockets_set_caching(bool caching);

#endif  // __SOCKET_H__

redpajama_set_name: RedPajamaGithub


text:
#include "BasicFileSystem.hpp"

#include <algorithm>
#include <cstring>

#include "DebugUtilities.hpp"

namespace Diligent
{

String BasicFileSystem::m_strWorkingDirectory;

BasicFile::BasicFile(const FileOpenAttribs& OpenAttribs) :
    m_Path //
    {
        [](const Char* strPath) //
        {
            String Path = strPath != nullptr ? strPath : "";
            BasicFileSystem::CorrectSlashes(Path);
            return Path;
        }(OpenAttribs.strFilePath) //
    },
    m_OpenAttribs{m_Path.c_str(), OpenAttribs.AccessMode}
{
}

BasicFile::~BasicFile()
{
}

String BasicFile::GetOpenModeStr()
{
    std::string OpenModeStr;
    switch (m_OpenAttribs.AccessMode)
    {
        // clang-format off
        case EFileAccessMode::Read:            OpenModeStr += 'r'; break;
        case EFileAccessMode::Overwrite:       OpenModeStr += 'w'; break;
        case EFileAccessMode::Append:          OpenModeStr += 'a'; break;
        case EFileAccessMode::ReadUpdate:      OpenModeStr += "r+"; break;
        case EFileAccessMode::OverwriteUpdate: OpenModeStr += "w+"; break;
        case EFileAccessMode::AppendUpdate:    OpenModeStr += "a+"; break;
        // clang-format on
        default: break;
    }

    // Always open file in binary mode. Text mode is platform-specific
    OpenModeStr += 'b';

    return OpenModeStr;
}

BasicFile* BasicFileSystem::OpenFile(FileOpenAttribs& OpenAttribs)
{
    return nullptr;
}

void BasicFileSystem::ReleaseFile(BasicFile* pFile)
{
    if (pFile)
        delete pFile;
}

bool BasicFileSystem::FileExists(const Char* strFilePath)
{
    return false;
}

void BasicFileSystem::CorrectSlashes(String& Path, Char Slash)
{
    if (Slash != 0)
        DEV_CHECK_ERR(IsSlash(Slash), "Incorrect slash symbol");
    else
        Slash = SlashSymbol;
    Char RevSlashSym = (Slash == '\\') ? '/' : '\\';
    std::replace(Path.begin(), Path.end(), RevSlashSym, Slash);
}

void BasicFileSystem::GetPathComponents(const String& Path,
                                        String*       Directory,
                                        String*       FileName)
{
    auto LastSlashPos = Path.find_last_of("/\\");
    if (Directory)
    {
        if (LastSlashPos != String::npos)
            *Directory = Path.substr(0, LastSlashPos);
        else
            *Directory = "";
    }

    if (FileName)
    {
        if (LastSlashPos != String::npos)
            *FileName = Path.substr(LastSlashPos + 1);
        else
            *FileName = Path;
    }
}

bool BasicFileSystem::IsPathAbsolute(const Char* strPath)
{
    if (strPath == nullptr || strPath[0] == 0)
        return false;

#if PLATFORM_WIN32 || PLATFORM_UNIVERSAL_WINDOWS
    return ((strPath[1] == ':' && (strPath[2] == '\\' || strPath[2] == '/')) || // c:\Path or c:/Path
            (strPath[0] == '\\' && strPath[1] == '\\'));                        // \\?\Path
#elif PLATFORM_LINUX || PLATFORM_MACOS || PLATFORM_IOS || PLATFORM_TVOS || PLATFORM_ANDROID || PLATFORM_EMSCRIPTEN
    return strPath[0] == '/';
#else
#    error Unknown platform.
#endif
}

template <typename StringType>
std::vector<StringType> SplitPath(const Char* Path, bool Simplify)
{
    std::vector<StringType> Components;

    // BasicFileSystem::IsSlash() does not get inlined by at least MSVC
    auto IsSlash = [](Char c) {
        return c == '/' || c == '\\';
    };

    // Estimate the number of components and reserve space in the vector
    {
        size_t CompnentCount = 1;
        for (const auto* c = Path; *c != '\0'; ++c)
        {
            if (IsSlash(c[0]) && !IsSlash(c[1]))
                ++CompnentCount;
        }
        Components.reserve(CompnentCount);
    }

    const auto* c = Path;
    while (*c != '\0')
    {
        while (IsSlash(*c))
            ++c;

        if (*c == '\0')
        {
            // a/
            break;
        }

        const auto* const CmpStart = c;
        while (*c != '\0' && !IsSlash(*c))
            ++c;

        if (Simplify)
        {
            if ((c - CmpStart) == 1 && CmpStart[0] == '.') // "."
            {
                // Skip /.
                continue;
            }
            else if ((c - CmpStart) == 2 && CmpStart[0] == '.' && CmpStart[1] == '.') // ".."
            {
                // Pop previous subdirectory if "/.." is found, but only if there is
                // no ".." already (e.g "../..")
                if (!Components.empty() && Components.back() != "..")
                {
                    Components.pop_back();
                    continue;
                }
            }
        }

        Components.emplace_back(CmpStart, c);
    }

    return Components;
}

std::vector<String> BasicFileSystem::SplitPath(const Char* Path, bool Simplify)
{
    return Diligent::SplitPath<String>(Path, Simplify);
}

std::string BasicFileSystem::SimplifyPath(const Char* Path, Char Slash)
{
    if (Path == nullptr)
        return "";

    if (Slash != 0)
        DEV_CHECK_ERR(IsSlash(Slash), "Incorrect slash symbol");
    else
        Slash = SlashSymbol;

    struct MiniStringView
    {
        MiniStringView(const char* _Start,
                       const char* _End) :
            Start{_Start},
            End{_End}
        {}

        bool operator==(const char* Str) const noexcept
        {
            const auto Len = End - Start;
            return strncmp(Str, Start, Len) == 0 && Str[Len] == '\0';
        }

        bool operator!=(const char* str) const noexcept
        {
            return !(*this == str);
        }

        const char* const Start;
        const char* const End;
    };

    const auto PathComponents  = Diligent::SplitPath<MiniStringView>(Path, true);
    const auto NumComponents   = PathComponents.size();
    const auto UseLeadingSlash = Slash == '/' && IsSlash(Path[0]);

    size_t Len = UseLeadingSlash ? 1 : 0;
    for (const auto& Cmp : PathComponents)
        Len += Cmp.End - Cmp.Start;
    if (NumComponents > 0)
        Len += NumComponents - 1;

    std::string SimplifiedPath;
    SimplifiedPath.reserve(Len);
    if (UseLeadingSlash)
        SimplifiedPath.push_back(Slash);

    for (size_t i = 0; i < NumComponents; ++i)
    {
        if (i > 0)
            SimplifiedPath.push_back(Slash);
        const auto& Cmp = PathComponents[i];
        SimplifiedPath.append(Cmp.Start, Cmp.End);
    }
    VERIFY_EXPR(SimplifiedPath.length() == Len);

    return SimplifiedPath;
}

std::string BasicFileSystem::GetRelativePath(const Char* PathFrom,
                                             bool        IsFromDirectory,
                                             const Char* PathTo,
                                             bool /*IsToDirectory*/)
{
    DEV_CHECK_ERR(PathFrom != nullptr, "Source path must not be null");
    DEV_CHECK_ERR(PathTo != nullptr, "Destination path must not be null");

    const auto FromPathComps = SplitPath(PathFrom, true);
    const auto ToPathComps   = SplitPath(PathTo, true);

    auto from_it = FromPathComps.begin();
    auto to_it   = ToPathComps.begin();
    while (from_it != FromPathComps.end() && to_it != ToPathComps.end() && *from_it == *to_it)
    {
        ++from_it;
        ++to_it;
    }
    if (from_it == FromPathComps.begin())
        return PathFrom; // No common prefix

    String RelPath;
    for (; from_it != FromPathComps.end(); ++from_it)
    {
        if (!IsFromDirectory && from_it + 1 == FromPathComps.end())
        {
            //                    from_it
            //                       V
            // from:    "common/from/file"
            // to:      "common/to"
            // RelPath: ".."
            break;
        }

        if (!RelPath.empty())
            RelPath.push_back(SlashSymbol);
        RelPath.append("..");
    }

    for (; to_it != ToPathComps.end(); ++to_it)
    {
        // IsToDirectory is in fact irrelevant
        if (!RelPath.empty())
            RelPath.push_back(SlashSymbol);
        RelPath.append(*to_it);
    }

    return RelPath;
}

std::string BasicFileSystem::FileDialog(const FileDialogAttribs& DialogAttribs)
{
    LOG_WARNING_MESSAGE("File dialog is not implemented on this platform");
    return "";
}

} // namespace Diligent


text:
ruby_block 'set private key' do
  block do
    node.run_state[:jenkins_private_key] = chef_vault_item("master", "scala-jenkins-keypair")['private_key']
  end
end

credentialsMap = {
  'jenkins'  => '954dd564-ce8c-43d1-bcc5-97abffc81c57'
}

privKey = chef_vault_item("master", "scala-jenkins-keypair")['private_key']

# TODO: different keypairs to sandbox different workers better, just in case?
credentialsMap.each do |userName, uniqId|
  jenkins_private_key_credentials userName.dup do # dup is workaround for jenkins cookbook doing a gsub! in convert_to_groovy
    id uniqId
    private_key privKey
  end
end

masterEnvLambda = node["master"]["env"]

search(:node, 'name:jenkins-worker*').each do |worker|
  worker["jenkinsHomes"].each do |jenkinsHome, workerConfig|
    workerEnvLambda = workerConfig["env"]

    jenkins_ssh_slave workerConfig["workerName"] do
      host        worker.ipaddress
      credentials credentialsMap[workerConfig["jenkinsUser"]]  # must use id (groovy script fails otherwise)

      # TODO: make retrying more robust
      max_num_retries  10  # how often to retry when the SSH connection is refused during initial connect
      retry_wait_time  60  # seconds between retries

      remote_fs   jenkinsHome.dup
      jvm_options workerConfig["jvm_options"]

      java_path   workerConfig["java_path"] # only used on windows

      labels      workerConfig["labels"]
      executors   workerConfig["executors"]

      usage_mode  workerConfig["usage_mode"]

      # The availability of the node is managed by Jenkins,
      # the ec2-start-stop plugin will take the corresponding ec2 node [on|off]-line.
      availability    'demand'
      in_demand_delay workerConfig["in_demand_delay"]
      idle_delay      workerConfig["idle_delay"]

      # puts "Env for #{worker.name}:"
      # puts "masterEnvLambda: #{masterEnvLambda}"
      # puts "workerEnvLambda: #{workerEnvLambda}"
      masterEnv = (eval masterEnvLambda).call(worker)
      # puts "masterEnv: #{masterEnv}"
      workerEnv = (eval workerEnvLambda).call(worker)
      # puts "workerEnv: #{workerEnv}"

      environment(masterEnv.merge(workerEnv))

      action [:create] # we don't need to :connect, :online since the ec2 start/stop plugin will do that. Also, if connect fails, it may be that chef-client hasn't yet run on the client to initialize jenkins home with .ssh/authorized_keys
    end
  end
end


text:
#ifndef GAME_SIR_H
#define GAME_SIR_H

#include <stdint.h>
#include <stdbool.h>

//#define HOME_BTN_MASK 					0x8
//#define LEFT_STICK_LR_MASK 				0xFF
//#define LEFT_STICK_UD_MASK
//#define RIGHT_STICK_LR_MASK
//#define RIGHT_STICK_UD_MASK
//#define LEFT_TRIGGER_MASK
//#define RIGHT_TRIGGER_MASK
//#define ABXY_BUMPERS_MASK
//#define SELECT_START_STICKS_MASK
//#define DPAD_MASK

// Representation of location in message package of a particular btn
enum MessageFormat
{
	// Home message package
	kHomeBtnByte,
	kHomeBtnEmpty0,
	kHomeBtnEmpty1,
	kHomeBtnMsgPkgSize,

	// Standard message
	kLeftStickLRByte = 0,
	kLeftStickUDByte,
	kRightStickLRByte,
	kRightStickUDByte,
	kLeftTriggerByte,
	kRightTriggerByte,
	kABXYBumpersByte,
	kSelectStartSticksByte, 		// This byte also contains information about if the left and right triggers are greater than some value but we don't care about that
	kDPadByte,
	kStdMsgEmpty0,
	kStdMsgPkgSize
};

// Representation of index of a particular btn in the gamepad struct
enum ControllerIndices
{
	kHomeBtnIndex,				// Home button must be first as the code takes advantage of this fact
	kLeftStickLRIndex,
	kLeftStickUDIndex,
	kRightStickLRIndex,
	kRightStickUDIndex,
	kLeftTriggerIndex,
	kRightTriggerIndex,
	kAIndex,
	kBIndex,
	kXIndex,
	kYIndex,
	kLeftBumperIndex,
	kRightBumperIndex,
	kSelectIndex,
	kStartIndex,
	kLeftStickIndex,
	kRightStickIndex,
	kDPadIndex,

	kNumBtns
};

// Representation of a single button
typedef struct
{
	const uint8_t byte_position;		// Position of byte in message data
	//const uint8_t toogle;
	const uint8_t mask;					// Button mask for buttons that share a byte
	uint8_t value;						// Current value of the button
} Button;

// All the buttons on the game sir remote
static Button remote[kNumBtns] =
{
	{/*kHomeBtnIndex,*/ 				kHomeBtnByte,				/*true,*/ 	0x08,		0	},
	{/*kLeftStickLRIndex,*/ 			kLeftStickLRByte,			/*false,*/ 	0xFF,		128	},
	{/*kLeftStickUDIndex,*/ 			kLeftStickUDByte,			/*false,*/ 	0xFF,		128	},
	{/*kRightStickLRIndex,*/ 			kRightStickLRByte,			/*false,*/ 	0xFF,		128	},
	{/*kRightStickUDIndex,*/ 			kRightStickUDByte,			/*false,*/ 	0xFF,		128	},
	{/*kLeftTriggerIndex,*/ 			kLeftTriggerByte,			/*false,*/ 	0xFF,		0	},
	{/*kRightTriggerIndex,*/ 			kRightTriggerByte,			/*false,*/ 	0xFF,		0	},
	{/*kAIndex,*/			 			kABXYBumpersByte,			/*true,*/ 	0x01,		0	},
	{/*kBIndex,*/			 			kABXYBumpersByte,			/*true,*/ 	0x02,		0	},
	{/*kXIndex,*/			 			kABXYBumpersByte,			/*true,*/ 	0x08,		0	},
	{/*kYIndex,*/			 			kABXYBumpersByte,			/*true,*/ 	0x10,		0	},
	{/*kLeftBumperIndex,*/	 			kABXYBumpersByte,			/*true,*/ 	0x40,		0	},
	{/*kRightBumperIndex,*/ 			kABXYBumpersByte,			/*true,*/ 	0x80,		0	},
	{/*kSelectIndex,*/				 	kSelectStartSticksByte,		/*true,*/ 	0x04,		0	},
	{/*kStartIndex,*/				 	kSelectStartSticksByte,		/*true,*/ 	0x08,		0	},
	{/*kLeftStickIndex,*/			 	kSelectStartSticksByte,		/*true,*/ 	0x20,		0	},
	{/*kRightStickIndex,*/			 	kSelectStartSticksByte,		/*true,*/ 	0x40,		0	},
	{/*kDPadIndex,*/ 					kDPadByte,					/*false,*/ 	0x0F,		0	}
};

// State indicator for message package decoding
enum MessageDecodeState
{
	kIdle,
	kDeterminePkgType,
	kStdPkg,
	kHomeBtnPkg
};

// Current state
static enum MessageDecodeState current_msg_decode_state = kIdle;
static uint8_t current_byte = 0;

// Function to handle new incoming data
void GameSirNewData(uint8_t new_data);

// Function to get a button value
uint8_t game_sir_get_btn_value(enum ControllerIndices button_index);

#endif


text:
package io.coala.time;

import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.TreeMap;

import io.coala.json.Wrapper;
import io.reactivex.Observable;

/**
 * {@link TimingMap} provides some utility methods for (navigable or sorted)
 * discrete time mappings of a value, scheduled to change at specific discrete
 * {@link Instant}s using {@link #observeOn(Scheduler)}.
 * <p>
 * See also {@link Timing} for simple calendar-based schedules using
 * {@link org.quartz.CronExpression CRON expressions} or
 * {@link com.google.ical.compat.jodatime.DateTimeIteratorFactory iCal RRULEs
 * and RDATEs}
 *
 * @param <T> the type of value being timed
 * @version $Id: e4549ddea004fbe7e39640cac8e443a908783d31 $
 * @author Rick van Krevelen
 * @see Timing
 */
//@JsonSerialize( using = TimingMap.JsonSerializer.class )
//@JsonDeserialize(using=Object.class)
public interface TimingMap<T> extends Wrapper<NavigableMap<Instant, T>>
{

	class Simple<T> extends Wrapper.Simple<NavigableMap<Instant, T>>
		implements TimingMap<T>
	{
		public static <T> TimingMap<T> of( final Map<Instant, T> schedule )
		{
			return of( new TreeMap<>( schedule ) ); // jackson default: TreeMap
		}

		public static <T> TimingMap<T>
			of( final NavigableMap<Instant, T> schedule )
		{
			return Util.of( schedule, new TimingMap.Simple<T>() );
		}
	}

	/**
	 * @param t the {@link Instant} to check in this {@link TimingMap}
	 * @return the value occurring at specified {@link Instant}
	 */
	default T current( final Instant t )
	{
		final Entry<Instant, T> result = unwrap().floorEntry( t );
		return result == null ? null : result.getValue();
	}

	/**
	 * @param scheduler the {@link Scheduler} performing the calls
	 * @see Observable#observeOn(io.reactivex.Scheduler)
	 */
	default Observable<T> observeOn( final Scheduler scheduler )
	{
		return scheduler.atEach( unwrap().keySet() ).map( this::current );
	}

//	@SuppressWarnings( { "rawtypes", "serial" } )
//	class JsonSerializer extends StdSerializer<TimingMap>
//	{
//		protected JsonSerializer()
//		{
//			super( TimingMap.class );
//		}
//
//		@Override
//		public void serialize( final TimingMap value, final JsonGenerator gen,
//			final SerializerProvider serializers ) throws IOException
//		{
//
//			serializers.findValueSerializer( value.unwrap().getClass() )
//					.serialize( value.unwrap(), gen, serializers );
//		}
//	}
}


text:
require 'spec_helper'

describe 'School API:' do

  before(:each) do
    @location_code = '123'
    @alpha_code = 'GVC'
  end

  describe "GET /v1/school/:location_code/alpha_code" do
    it "returns a school's Alpha Code as a string" do
      get("/v1/school/#{@location_code}/alpha_code").should == 'GVC'
    end
  end

  describe "GET /v1/school/:alpha_code/location_code" do
    it "returns a school's numerical Location Code as a string" do
      get("/v1/school/#{@alpha_code}/location_code").should == '123'
    end
  end

  describe "GET /v1/school/:alpha_code/type_code" do
    it "returns a school's Type Code as a string" do
      get("/v1/school/#{@alpha_code}/type_code").should == 'School'
    end
  end

  describe "GET /v1/school/:alpha_code/mident" do
    it "returns a school's mident as a string" do
     pending("Unused. Uncertain if this should be public.")
    end
  end

  describe "GET /v1/school/:alpha_code/full_name" do
    it "returns a school's Full Name as a string" do
      get("/v1/school/#{@alpha_code}/full_name").should == 'Grand View Public School (Cambridge)'
    end
  end

  describe "GET /v1/school/:alpha_code/abbreviated_name" do
    it "returns a school's Abbreviated Name as a string" do
      get("/v1/school/#{@alpha_code}/abbreviated_name").should == 'Grand View (C)'
    end
  end

  describe "GET /v1/school/:alpha_code/panel" do
    it "returns a school's Panel (Elementary or Secondary) as a string" do
      get("/v1/school/#{@alpha_code}/panel").should == 'Elementary'
    end
  end

  describe "GET /v1/school/:alpha_code/type" do
    it "returns a school's School Type as a string" do
      get("/v1/school/#{@alpha_code}/type").should == 'Junior School (JK-6)'
    end
  end

  describe "GET /v1/school/:alpha_code/grades" do
    it "returns a school's Grades as a string" do
      get("/v1/school/#{@alpha_code}/grades").should == ''
    end
  end

  describe "GET /v1/school/:alpha_code/french" do
    it "returns a school's French as a string" do
      get("/v1/school/#{@alpha_code}/french").should == 'true'
    end
  end

  describe "GET /v1/school/:alpha_code/municipality" do
    it "returns a school's Municipality as a string" do
      get("/v1/school/#{@alpha_code}/municipality").should == 'City of Cambridge'
    end
  end

  describe "GET /v1/school/:alpha_code/street_address" do
    it "returns a school's Street Address as a string" do
      get("/v1/school/#{@alpha_code}/street_address").should == '1144 Hamilton St.'
    end
  end

  describe "GET /v1/school/:alpha_code/city" do
    it "returns a school's City as a string" do
      get("/v1/school/#{@alpha_code}/city").should == 'Cambridge'
    end
  end

  describe "GET /v1/school/:alpha_code/province" do
    it "returns a school's Province as a string" do
      get("/v1/school/#{@alpha_code}/province").should == 'Ontario'
    end
  end

  describe "GET /v1/school/:alpha_code/postal_code" do
    it "returns a school's Postal Code as a string" do
      get("/v1/school/#{@alpha_code}/postal_code").should == 'N3H 3G2'
    end
  end

  describe "GET /v1/school/:alpha_code/phone" do
    it "returns a school's Phone as a string" do
      get("/v1/school/#{@alpha_code}/phone").should == '519-653-3611'
    end
  end

  describe "GET /v1/school/:alpha_code/fax" do
    it "returns a school's Fax as a string" do
      get("/v1/school/#{@alpha_code}/fax").should == '519-653-1057'
    end
  end

  describe "GET /v1/school/:alpha_code/attendance_line" do
    it "returns a school's Attendance Phone as a string" do
      get("/v1/school/#{@alpha_code}/attendance_line").should == '519-570-8084 Ext. 3342'
    end
  end

  describe "GET /v1/school/:alpha_code/website" do
    it "returns a school's Website as a string" do
      get("/v1/school/#{@alpha_code}/website").should == 'http://gvc.wrdsb.on.ca'
    end
  end

  describe "GET /v1/school/:alpha_code/hours" do
    it "returns a school's School Hours as a string" do
      get("/v1/school/#{@alpha_code}/hours").should == '8:50am-3:10pm'
    end
  end

  describe "GET /v1/school/:alpha_code/office_hours" do
    it "returns a school's Office Hours as a string" do
      get("/v1/school/#{@alpha_code}/office_hours").should == '8:30am-3:45pm'
    end
  end

  describe "GET /v1/school/:alpha_code/break_times" do
    it "returns a school's Break Times as a string" do
      get("/v1/school/#{@alpha_code}/break_times").should == ''
    end
  end

  describe "GET /v1/school/:alpha_code/principal" do
    it "returns a school's Principal as a string" do
      get("/v1/school/#{@alpha_code}/principal").should == ''
    end
  end

  describe "GET /v1/school/:alpha_code/vice_principals" do
    it "returns a school's Vice Principals as a string" do
      get("/v1/school/#{@alpha_code}/vice_principals").should == ''
    end
  end

  describe "GET /v1/school/:alpha_code/office_supervisor" do
    it "returns a school's Office Supervisor as a string" do
      get("/v1/school/#{@alpha_code}/office_supervisor").should == ''
    end
  end

  describe "GET /v1/school/:alpha_code/superintendant" do
    it "returns a school's Superintendant as a string" do
      get("/v1/school/#{@alpha_code}/superintendant").should == ''
    end
  end

  describe "GET /v1/school/:alpha_code/superintendant_assistant" do
    it "returns a school's Superintendant's Assistant as a string" do
      get("/v1/school/#{@alpha_code}/superintendant_assistant").should == ''
    end
  end

  describe "GET /v1/school/:alpha_code/speed_dial_no" do
    it "returns a school's Speed Dial Number as a string" do
      get("/v1/school/#{@alpha_code}/speed_dial_no").should == ''
    end
  end

  describe "GET /v1/school/:alpha_code/courier" do
    it "returns a school's Courier as a string" do
      get("/v1/school/#{@alpha_code}/courier").should == ''
    end
  end

end


text:
//
//  RGCLoginRegisterViewController.m
//  BSBDQJ
//
//  Created by rgc on 16/4/4.
//  Copyright © 2016年 RGC. All rights reserved.
//

#import "RGCLoginRegisterViewController.h"
#import "RGCTopWindow.h"

@interface RGCLoginRegisterViewController ()
@property (weak, nonatomic) IBOutlet UITextField *phoneField;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
/** 登录框距离控制器view左边的间距 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *loginViewLeftMargin;

@end

@implementation RGCLoginRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 文字属性
//    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
//    attrs[NSForegroundColorAttributeName] = [UIColor lightGrayColor];
//    NSAttributedString *placeHolder = [[NSAttributedString alloc] initWithString:@"手机号" attributes:attrs];

//    NSMutableAttributedString *placeHolder = [[NSMutableAttributedString alloc] initWithString:@"手机号"];
//    [placeHolder setAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} range:NSMakeRange(0, 1)];
//    [placeHolder setAttributes:@{
//                                 NSForegroundColorAttributeName : [UIColor redColor],
//                                 NSFontAttributeName : [UIFont systemFontOfSize:30]} range:NSMakeRange(1, 1)];

//    self.phoneField.attributedPlaceholder = placeHolder;

    [RGCTopWindow hide];
}

- (IBAction)showLoginOrRegister:(UIButton *)button {

    // 退出键盘
    [self.view endEditing:YES];

    if (self.loginViewLeftMargin.constant == 0) {
        self.loginViewLeftMargin.constant -= self.view.width;
        button.selected = YES;
//        [button setTitle:@"已有账号" forState:UIControlStateNormal];
    } else {
        self.loginViewLeftMargin.constant = 0;
        button.selected = NO;
//        [button setTitle:@"注册账号" forState:UIControlStateNormal];
    }

    [UIView animateWithDuration:0.25 animations:^{
        // 马上更新布局
        [self.view layoutIfNeeded];
    }];

}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (IBAction)close:(id)sender {
    [RGCTopWindow show];
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
package org.apache.camel.component.reactive.streams.engine;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.component.reactive.streams.ReactiveStreamsBackpressureStrategy;
import org.apache.camel.component.reactive.streams.ReactiveStreamsComponent;
import org.apache.camel.component.reactive.streams.ReactiveStreamsEndpoint;
import org.apache.camel.component.reactive.streams.ReactiveStreamsProducer;
import org.apache.camel.component.reactive.streams.api.DispatchCallback;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Camel publisher. It forwards Camel exchanges to external reactive-streams subscribers.
 */
public class CamelPublisher implements Publisher<StreamPayload<Exchange>>, AutoCloseable {

    private static final Logger LOG = LoggerFactory.getLogger(CamelPublisher.class);

    private ExecutorService workerPool;

    private String name;

    private ReactiveStreamsBackpressureStrategy backpressureStrategy;

    private List<CamelSubscription> subscriptions = new CopyOnWriteArrayList<>();

    private ReactiveStreamsProducer producer;

    public CamelPublisher(ExecutorService workerPool, CamelContext context, String name) {
        this.workerPool = workerPool;
        this.backpressureStrategy = ((ReactiveStreamsComponent) context.getComponent("reactive-streams")).getBackpressureStrategy();
        this.name = name;
    }

    @Override
    public void subscribe(Subscriber<? super StreamPayload<Exchange>> subscriber) {
        Objects.requireNonNull(subscriber, "subscriber must not be null");
        CamelSubscription sub = new CamelSubscription(workerPool, this, name, this.backpressureStrategy, subscriber);
        this.subscriptions.add(sub);
        subscriber.onSubscribe(sub);
    }

    public void unsubscribe(CamelSubscription subscription) {
        subscriptions.remove(subscription);
    }

    public void publish(StreamPayload<Exchange> data) {
        // freeze the subscriptions
        List<CamelSubscription> subs = new LinkedList<>(subscriptions);

        DispatchCallback<Exchange> originalCallback = data.getCallback();
        if (originalCallback != null && subs.size() > 0) {
            // When multiple subscribers have an active subscription,
            // we acknowledge the exchange once it has been delivered to every
            // subscriber (or their subscription is cancelled)
            AtomicInteger counter = new AtomicInteger(subs.size());
            // Use just the first exception in the callback when multiple exceptions are thrown
            AtomicReference<Throwable> thrown = new AtomicReference<>(null);
            data = new StreamPayload<>(data.getItem(), (ex, error) -> {
                thrown.compareAndSet(null, error);
                if (counter.decrementAndGet() == 0) {
                    originalCallback.processed(ex, thrown.get());
                }
            });
        }

        if (subs.size() > 0) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Exchange published to {} subscriptions for the stream {}: {}", subs.size(), name, data.getItem());
            }
            // at least one subscriber
            for (CamelSubscription sub : subs) {
                sub.publish(data);
            }
        } else {
            data.getCallback().processed(data.getItem(), new IllegalStateException("The stream has no active subscriptions"));
        }
    }

    public void attachProducer(ReactiveStreamsProducer producer) {
        Objects.requireNonNull(producer, "producer cannot be null, use the detach method");
        if (this.producer != null) {
            throw new IllegalStateException("A producer is already attached to the stream '" + name + "'");
        }
        this.producer = producer;

        // Apply endpoint options if available
        ReactiveStreamsEndpoint endpoint = producer.getEndpoint();
        if (endpoint.getBackpressureStrategy() != null) {
            this.backpressureStrategy = endpoint.getBackpressureStrategy();
            for (CamelSubscription sub : this.subscriptions) {
                sub.setBackpressureStrategy(endpoint.getBackpressureStrategy());
            }
        }
    }

    public void detachProducer() {
        this.producer = null;
    }

    @Override
    public void close() throws Exception {
        for (CamelSubscription sub : subscriptions) {
            sub.signalCompletion();
        }
        subscriptions.clear();
    }

    public int getSubscriptionSize() {
        return subscriptions.size();
    }
}


text:
type: module
title: surge-teardown-branches
gh:
  - lukekarrys/surge-teardown-branches
npm:
  - surge-teardown-branches
blog: "/2016/08/18/deploying-greenkeeper-pr-branches-with-surge-and-codeship"
---

Run this as part of your continuous deployment workflow when using [Surge](https://surge.sh) to [teardown merged branches](https://github.com/lukekarrys/surge-teardown-branches). Works great if you deploy to feature branches, but don't want your Surge account littered with the ghosts of features past.


text:
var config = {
    width: 960,
    height: 600,
    params: {
        enableDebugging: "0"
    }
};
config.params["disableContextMenu"] = true;
var u = new UnityObject2(config);

jQuery(function() {

    var $missingScreen = jQuery("#unityPlayer").find(".missing");
    var $brokenScreen = jQuery("#unityPlayer").find(".broken");
    $missingScreen.hide();
    $brokenScreen.hide();

    u.observeProgress(function(progress) {
        switch (progress.pluginStatus) {
            case "broken":
                $brokenScreen.find("a").click(function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                    u.installPlugin();
                    return false;
                });
                $brokenScreen.show();
                break;
            case "missing":
                $missingScreen.find("a").click(function(e) {
                    e.stopPropagation();
                    e.preventDefault();
                    u.installPlugin();
                    return false;
                });
                $missingScreen.show();
                break;
            case "installed":
                $missingScreen.remove();
                break;
            case "first":
                break;
        }
    });
    // u.initPlugin(jQuery("#unityPlayer")[0], "lib/unity3d/aog1.unity3d"); // https://s3-us-west-2.amazonaws.com/teamrpc.aott/aog1.unity3d
    u.initPlugin(jQuery("#unityPlayer")[0], "https://s3-us-west-2.amazonaws.com/teamrpc.aott/aog1_01042015.unity3d");
});


text:
module Garlicjs
  module Rails
    VERSION = "1.3.0"
  end
end


text:
import models.Integration;
import play.db.ebean.Model.Finder;

import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;

public class GuiceModel extends AbstractModule {

    @Override
    protected void configure() {
	bind(new TypeLiteral<Finder<Integer, Integration>>(){}).toInstance(new Finder<>(Integer.class, Integration.class));
    }

//    @Provides
//    @Singleton
//    public Finder<Integer, Integration> provideIntegrationFinder() {
//	return new Finder<>(Integer.class, Integration.class);
//    }
//
//    @Provides
//    public PersistenceService<Integer, Integration> provideIntegrationService() {
//	return new IntegrationPersistenceService();
//    }
}


text:
package election_test

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"testing"
	"time"

	"github.com/google/trillian/util/clock"
	"github.com/google/trillian/util/election"
	to "github.com/google/trillian/util/election2/testonly"
)

func TestConfigResignDelay(t *testing.T) {
	const checks = 1000
	for _, tc := range []struct {
		hold    time.Duration
		jitter  time.Duration
		wantMax time.Duration
	}{
		{hold: 12 * time.Second, jitter: -1 * time.Second, wantMax: 12 * time.Second},
		{hold: 12 * time.Second, jitter: 0, wantMax: 12 * time.Second},
		{hold: 12 * time.Second, jitter: 5 * time.Second, wantMax: 17 * time.Second},
		{hold: 0, jitter: 0, wantMax: 0},
		{hold: 0, jitter: 500 * time.Millisecond, wantMax: 500 * time.Millisecond},
		{hold: 1 * time.Hour, jitter: 10 * time.Minute, wantMax: 70 * time.Minute},
	} {
		t.Run(fmt.Sprintf("%v:%v", tc.hold, tc.jitter), func(t *testing.T) {
			cfg := election.RunnerConfig{
				MasterHoldInterval: tc.hold,
				MasterHoldJitter:   tc.jitter,
			}
			for i := 0; i < checks; i++ {
				d := cfg.ResignDelay()
				if min, max := tc.hold, tc.wantMax; d < min || d > max {
					t.Fatalf("ResignDelay(): %v, want between %v and %v", d, min, max)
				}
			}
		})
	}
}

// TODO(pavelkalinnikov): Reduce flakiness risk in this test by making fewer
// time assumptions.
func TestElectionRunnerRun(t *testing.T) {
	const logID = "6962"
	checkMaster := func(t *testing.T, held []string, wantMaster bool) {
		t.Helper()
		if got := (len(held) > 0 && held[0] == logID); got != wantMaster {
			t.Errorf("holding: %v: master=%v, want %v", held, got, wantMaster)
		}
	}

	for _, tc := range []struct {
		desc       string
		errs       to.Errs
		isMaster   bool
		wantMaster bool
		loseMaster bool
		resign     bool
	}{
		// Basic cases.
		{desc: "not-master"},
		{desc: "is-master", isMaster: true, wantMaster: true},
		{desc: "lose-master", isMaster: true, wantMaster: true, loseMaster: true},
		{desc: "resign", isMaster: true, wantMaster: true, resign: true},
		// Error cases.
		{desc: "err-await", errs: to.Errs{Await: errors.New("ErrAwait")}},
		{desc: "err-mctx", errs: to.Errs{WithMastership: errors.New("ErrMastership")}},
		{
			desc:     "err-mctx-after-master",
			isMaster: true,
			errs:     to.Errs{WithMastership: errors.New("ErrMastership")},
		},
		{desc: "err-resign", errs: to.Errs{Resign: errors.New("ErrResign")}},
		{
			desc:       "err-resign-after-master",
			isMaster:   true,
			wantMaster: true,
			errs:       to.Errs{Resign: errors.New("ErrResign")},
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()

			e := to.NewElection()
			d := to.NewDecorator(e)
			d.Update(tc.errs)
			d.BlockAwait(!tc.isMaster)

			start := time.Now()
			ts := clock.NewFake(start)
			tracker := election.NewMasterTracker([]string{logID}, nil)
			cfg := election.RunnerConfig{TimeSource: ts}
			er := election.NewRunner(logID, &cfg, tracker, nil, d)
			resignations := make(chan election.Resignation, 100)

			var wg sync.WaitGroup
			wg.Add(1)
			go func() {
				defer wg.Done()
				er.Run(ctx, resignations)
			}()

			// TODO(pavelkalinnikov): This Sleep is necessary to let Run create a
			// Timer *before* we modify the time. To reduce risk of flakes,
			// FakeTimeSource should expose timer creation to this test.
			time.Sleep(100 * time.Millisecond)
			checkMaster(t, tracker.Held(), false)

			ts.Set(start.Add(election.MinPreElectionPause))
			time.Sleep(100 * time.Millisecond) // Now it *can* become the master.
			checkMaster(t, tracker.Held(), tc.wantMaster)

			if tc.loseMaster {
				d.BlockAwait(true)
				if err := e.Resign(ctx); err != nil {
					t.Errorf("Lose mastership: %v", err)
				}
				wg.Wait() // Runner exits on unexpected mastership loss.
				checkMaster(t, tracker.Held(), false)
			}

			if tc.resign {
				d.BlockAwait(true)
				// Advance fake time so that resignation triggers too, if still master.
				ts.Set(start.Add(24 * 60 * time.Hour))
				time.Sleep(100 * time.Millisecond)
				for len(resignations) > 0 {
					r := <-resignations
					r.Execute(ctx)
				}
				time.Sleep(100 * time.Millisecond)
			}

			checkMaster(t, tracker.Held(), tc.wantMaster && !tc.loseMaster && !tc.resign)
			cancel()  // If Runner is still running, it should stop now.
			wg.Wait() // Wait until it stops.
			checkMaster(t, tracker.Held(), false)
		})
	}
}


text:
<?php

// No direct access
defined('_HZEXEC_') or die();

$this->css()
     ->js();

$txt  = '';
$mode = strtolower(Request::getWord('mode', ''));

if ($mode != 'preview')
{
	switch ($this->model->published)
	{
		case 1:
			$txt .= '';
			break; // published
		case 2:
			$txt .= '[' . Lang::txt('COM_RESOURCES_DRAFT_EXTERNAL') . '] ';
			break;  // external draft
		case 3:
			$txt .= '[' . Lang::txt('COM_RESOURCES_PENDING') . '] ';
			break;  // pending
		case 4:
			$txt .= '[' . Lang::txt('COM_RESOURCES_DELETED') . '] ';
			break;  // deleted
		case 5:
			$txt .= '[' . Lang::txt('COM_RESOURCES_DRAFT_INTERNAL') . '] ';
			break;  // internal draft
		case 0:
			$txt .= '[' . Lang::txt('COM_RESOURCES_UNPUBLISHED') . '] ';
			break;  // unpublished
	}
}

$tconfig  = $this->tconfig;
$thistool = $this->thistool;
$curtool  = $this->curtool;
$revision = $this->revision;
?>

							<?php echo $txt . $this->escape(stripslashes($this->model->title)); ?>

						<input type="hidden" name="rid" id="rid" value="<?php echo $this->model->id; ?>" />

					<?php if ($this->model->params->get('show_authors', 1)) { ?>

							<?php
							$this->view('_contributors')
								->set('option', $this->option)
								->set('contributors', $this->model->contributors('tool'))
								->display();
							?>

					<?php } ?>

						<?php
						if (!$this->model->introtext)
						{
							$this->model->introtext = $this->model->fulltxt;
						}
						echo \Hubzero\Utility\Str::truncate(stripslashes($this->model->introtext), 255);
						?>

					<?php if ($this->model->params->get('access-edit-resource')) { ?>
						<a class="icon-edit edit btn" href="<?php echo Route::url('index.php?option=com_tools&task=resource&step=1&app=' . $this->model->alias); ?>"><?php echo Lang::txt('COM_RESOURCES_EDIT'); ?>
					<?php } ?>

					<?php
					// Private/Public resource access check
					if (!$this->model->access('view-all'))
					{
						$ghtml = array();
						foreach ($this->model->groups as $allowedgroup)
						{
							$ghtml[] = '' . $allowedgroup . '';
						}
						?>

							<?php echo Lang::txt('COM_RESOURCES_ERROR_MUST_BE_PART_OF_GROUP') . ' ' . implode(', ', $ghtml); ?>

						<?php
					}
					else
					{
						// get launch button
						$children = $this->model->children()
							->whereEquals('published', \Components\Resources\Models\Entry::STATE_PUBLISHED)
							->whereEquals('standalone', 0)
							->ordered()
							->rows();

						$firstChild = $children->first();

						echo \Components\Resources\Helpers\Html::primary_child($this->option, $this->model, $firstChild, '');

						$html = '';

						// Display version info
						$versiontext = '';
						if ($revision && $thistool)
						{
							$versiontext .= $thistool->version.'';
							if ($this->model->revision!='dev')
							{
								$versiontext .=  '
 '.ucfirst(Lang::txt('COM_RESOURCES_PUBLISHED_ON')).' ';
								$versiontext .= ($thistool->released && $thistool->released != '0000-00-00 00:00:00') ? Date::of($thistool->released)->toLocal(Lang::txt('DATE_FORMAT_HZ1')): Date::of($this->model->publish_up)->toLocal(Lang::txt('DATE_FORMAT_HZ1'));
								$versiontext .= ($thistool->unpublished && $thistool->unpublished != '0000-00-00 00:00:00') ? ', '.Lang::txt('COM_RESOURCES_UNPUBLISHED_ON').' '.Date::of($thistool->unpublished)->toLocal(Lang::txt('DATE_FORMAT_HZ1')): '';
							}
							else
							{
								$versiontext .= ' ('.Lang::txt('COM_RESOURCES_IN_DEVELOPMENT').')';
							}
						}
						elseif ($curtool)
						{
							$versiontext .= $curtool->version.' - '.Lang::txt('COM_RESOURCES_PUBLISHED_ON').' ';
							$versiontext .= ($curtool->released && $curtool->released != '0000-00-00 00:00:00') ? Date::of($curtool->released)->toLocal(Lang::txt('DATE_FORMAT_HZ1')): Date::of($this->model->publish_up)->toLocal(Lang::txt('DATE_FORMAT_HZ1'));
						}

						if (!$thistool)
						{
							$html .= "\t\t\t\t".'
'.Lang::txt('COM_RESOURCES_VERSION').' '.$versiontext.'
'."\n";
						}
						elseif ($revision == 'dev')
						{
							$html .= "\t\t\t\t".'
'.Lang::txt('COM_RESOURCES_VERSION').' '.$versiontext;
							$html .= $this->model->toolpublished ? ' '.Lang::txt('View').' model->link() . '&active=versions').'">'.Lang::txt('other versions').'' : '';
							$html .='
'."\n";
						}
						else
						{
							// Show archive message
							$msg = ''.Lang::txt('COM_RESOURCES_ARCHIVE').' '.Lang::txt('COM_RESOURCES_VERSION').' '.$versiontext;
							if ($this->model->curversion)
							{
								$msg .= '
'.Lang::txt('COM_RESOURCES_LATEST_VERSION').': model->link() . '&rev='.$curtool->revision).'">'.$this->model->curversion.'.';
							}
							$msg .= ' model->link() . '&active=versions').'">'.Lang::txt('COM_RESOURCES_TOOL_ALL_VERSIONS').'';
							$html .= '
' . $msg . '
' . "\n";
						}

						// doi message
						if ($revision != 'dev' && ($this->model->doi || $this->model->doi_label))
						{
							if ($this->model->doi && $tconfig->get('doi_shoulder'))
							{
								$doi = 'doi:' . ($this->model->doi_shoulder ? $this->model->doi_shoulder : $tconfig->get('doi_shoulder')) . '/' . strtoupper($this->model->doi);
							}
							else
							{
								$doi = 'doi:10254/' . $tconfig->get('doi_prefix') . $this->model->id . '.' . $this->model->doi_label;
							}

							$html .= "\t\t".'
'.$doi.' model->link() . '&active=about').'#citethis">'.Lang::txt('cite this').'
'."\n";
						}

						// Open/closed source
						if ($this->model->toolsource && $this->model->tool)
						{ // open source
							$html .= '
'.Lang::txt('Open source').': option.'&task=license&tool='.$this->model->tool.'&tmpl=component') . '">license ';
							$html .= ($this->model->taravailable) ? ' |  option.'&task=sourcecode&tool='.$this->model->tool).'">'.Lang::txt('download').' '."\n" : ' | '.Lang::txt('code unavailable').''."\n";
							$html .= '
'."\n";
						}
						elseif (!$this->model->toolsource)
						{ // closed source, archive page
							$html .= '
'.Lang::txt('COM_RESOURCES_TOOL_IS_CLOSED_SOURCE').'
'."\n";
						}
						// do we have a first-time user guide?
						if (!$thistool)
						{
							$guide = 0;
							foreach ($children as $child)
							{
								$title = ($child->logicaltitle)
										? $child->logicaltitle
										: stripslashes($child->title);
								if ($child->access == 0 || ($child->access == 1 && !User::isGuest()))
								{
									if (strtolower($title) !=  preg_replace('/user guide/', '', strtolower($title)))
									{
										$guide = $child;
									}
								}
							}
							$url = $guide ? \Components\Resources\Helpers\Html::processPath($this->option, $guide, $this->model->id) : '';
							$html .= "\t\t".'
'."\n";
							if ($url)
							{
								$html .= "\t\t\t".''.Lang::txt('COM_RESOURCES_TOOL_FIRT_TIME_USER_GUIDE').''."\n";
							}
							$html .= "\t\t\t".'model->link() . '&active=supportingdocs').'">'.Lang::txt('COM_RESOURCES_TOOL_VIEW_ALL_SUPPORTING_DOCS').''."\n";
							$html .= "\t\t".'
'."\n";
						}

						echo $html;
					} // --- end else (if group check passed)
					?>

			<?php
			// Display canonical
			$this->view('_canonical')
				->set('option', $this->option)
				->set('model', $this->model)
				->display();
			?>

			<?php
			// Show resource ratings
			if (!$thistool)
			{
				if ($this->model->params->get('show_metadata', 1))
				{
					$this->view('_metadata')
						->set('option', $this->option)
						->set('sections', $this->sections)
						->set('model', $this->model)
						->display();
				}
			}
			elseif ($revision == 'dev' or !$this->model->toolpublished)
			{
				?>

						<?php echo ($revision=='dev')
								? Lang::txt('This section will be filled when this tool version gets published.')
								: Lang::txt('This section is unavailable in an archive version of a tool.');

						if ($this->model->curversion)
						{
							echo ' '.Lang::txt('Consult the latest published version').' model->link() . '&rev='.$curtool->revision).'">'.$this->model->curversion.' '.Lang::txt('for most current information.');
						}
						?>

				<?php
			}
			?>

<?php if ($this->model->access('view-all')) { ?>

			<?php
			$this->view('_tabs')
				->set('option', $this->option)
				->set('cats', $this->cats)
				->set('resource', $this->model)
				->set('active', $this->tab)
				->display();

			$this->view('_sections')
				->set('option', $this->option)
				->set('sections', $this->sections)
				->set('resource', $this->model)
				->set('active', $this->tab)
				->display();
			?>

			<?php
			// Show related content
			$out = Event::trigger('resources.onResourcesSub', array($this->model, $this->option, 1));
			if (count($out) > 0)
			{
				foreach ($out as $ou)
				{
					if (isset($ou['html']))
					{
						echo $ou['html'];
					}
				}
			}

			// Show what's popular
			if ($this->tab == 'about')
			{
				echo \Hubzero\Module\Helper::renderModules('extracontent');
			}
			?>

<?php }


text:
'''A container for timeline-based events and traces and can handle importing
raw event data from different sources. This model closely resembles that in the
trace_viewer project:
https://code.google.com/p/trace-viewer/
'''

from operator import attrgetter

from telemetry.timeline import async_slice as async_slice_module
from telemetry.timeline import bounds
from telemetry.timeline import event_container
from telemetry.timeline import inspector_importer
from telemetry.timeline import slice as slice_module
from telemetry.timeline import process as process_module
from telemetry.timeline import surface_flinger_importer
from telemetry.timeline import tab_id_importer
from telemetry.timeline import trace_data as trace_data_module
from telemetry.timeline import trace_event_importer

# Register importers for data

_IMPORTERS = [
    inspector_importer.InspectorTimelineImporter,
    tab_id_importer.TabIdImporter,
    trace_event_importer.TraceEventTimelineImporter,
    surface_flinger_importer.SurfaceFlingerTimelineImporter
]

class MarkerMismatchError(Exception):
  def __init__(self):
    super(MarkerMismatchError, self).__init__(
        'Number or order of timeline markers does not match provided labels')

class MarkerOverlapError(Exception):
  def __init__(self):
    super(MarkerOverlapError, self).__init__(
        'Overlapping timeline markers found')

def IsSliceOrAsyncSlice(t):
  if t == async_slice_module.AsyncSlice:
    return True
  return t == slice_module.Slice

class TimelineModel(event_container.TimelineEventContainer):
  def __init__(self, trace_data=None, shift_world_to_zero=True):
    """ Initializes a TimelineModel.

    Args:
        trace_data: trace_data.TraceData containing events to import
        shift_world_to_zero: If true, the events will be shifted such that the
            first event starts at time 0.
    """
    super(TimelineModel, self).__init__(name='TimelineModel', parent=None)
    self._bounds = bounds.Bounds()
    self._thread_time_bounds = {}
    self._processes = {}
    self._browser_process = None
    self._gpu_process = None
    self._surface_flinger_process = None
    self._frozen = False
    self._tab_ids_to_renderer_threads_map = {}
    self.import_errors = []
    self.metadata = []
    self.flow_events = []
    if trace_data is not None:
      self.ImportTraces(trace_data, shift_world_to_zero=shift_world_to_zero)

  def IterChildContainers(self):
    for process in self._processes.itervalues():
      yield process

  def GetAllProcesses(self):
    return self._processes.values()

  def GetAllThreads(self):
    threads = []
    for process in self._processes.values():
      threads.extend(process.threads.values())
    return threads

  @property
  def bounds(self):
    return self._bounds

  @property
  def processes(self):
    return self._processes

  @property
  #pylint: disable=E0202
  def browser_process(self):
    return self._browser_process

  @browser_process.setter
  #pylint: disable=E0202
  def browser_process(self, browser_process):
    self._browser_process = browser_process

  @property
  #pylint: disable=E0202
  def gpu_process(self):
    return self._gpu_process

  @gpu_process.setter
  #pylint: disable=E0202
  def gpu_process(self, gpu_process):
    self._gpu_process = gpu_process

  @property
  #pylint: disable=E0202
  def surface_flinger_process(self):
    return self._surface_flinger_process

  @surface_flinger_process.setter
  #pylint: disable=E0202
  def surface_flinger_process(self, surface_flinger_process):
    self._surface_flinger_process = surface_flinger_process

  def AddMappingFromTabIdToRendererThread(self, tab_id, renderer_thread):
    if self._frozen:
      raise Exception('Cannot add mapping from tab id to renderer thread once '
                      'trace is imported')
    self._tab_ids_to_renderer_threads_map[tab_id] = renderer_thread

  def ImportTraces(self, trace_data, shift_world_to_zero=True):
    """Populates the model with the provided trace data.

    trace_data must be an instance of TraceData.

    Passing shift_world_to_zero=True causes the events to be shifted such that
    the first event starts at time 0.
    """
    if self._frozen:
      raise Exception("Cannot add events once trace is imported")
    assert isinstance(trace_data, trace_data_module.TraceData)

    importers = self._CreateImporters(trace_data)

    for importer in importers:
      # TODO: catch exceptions here and add it to error list
      importer.ImportEvents()
    for record in trace_data.metadata_records:
      self.metadata.append(record)
    self.FinalizeImport(shift_world_to_zero, importers)

  def FinalizeImport(self, shift_world_to_zero=False, importers=None):
    if importers == None:
      importers = []
    self.UpdateBounds()
    if not self.bounds.is_empty:
      for process in self._processes.itervalues():
        process.AutoCloseOpenSlices(self.bounds.max,
                                    self._thread_time_bounds)

    for importer in importers:
      importer.FinalizeImport()

    for process in self.processes.itervalues():
      process.FinalizeImport()

    if shift_world_to_zero:
      self.ShiftWorldToZero()
    self.UpdateBounds()

    # Because of FinalizeImport, it would probably be a good idea
    # to prevent the timeline from from being modified.
    self._frozen = True

  def ShiftWorldToZero(self):
    self.UpdateBounds()
    if self._bounds.is_empty:
      return
    shift_amount = self._bounds.min
    for event in self.IterAllEvents():
      event.start -= shift_amount

  def UpdateBounds(self):
    self._bounds.Reset()
    for event in self.IterAllEvents():
      self._bounds.AddValue(event.start)
      self._bounds.AddValue(event.end)

    self._thread_time_bounds = {}
    for thread in self.GetAllThreads():
      self._thread_time_bounds[thread] = bounds.Bounds()
      for event in thread.IterEventsInThisContainer(
          event_type_predicate=lambda t: True,
          event_predicate=lambda e: True):
        if event.thread_start != None:
          self._thread_time_bounds[thread].AddValue(event.thread_start)
        if event.thread_end != None:
          self._thread_time_bounds[thread].AddValue(event.thread_end)

  def GetOrCreateProcess(self, pid):
    if pid not in self._processes:
      assert not self._frozen
      self._processes[pid] = process_module.Process(self, pid)
    return self._processes[pid]

  def FindTimelineMarkers(self, timeline_marker_names):
    """Find the timeline events with the given names.

    If the number and order of events found does not match the names,
    raise an error.
    """
    # Make sure names are in a list and remove all None names
    if not isinstance(timeline_marker_names, list):
      timeline_marker_names = [timeline_marker_names]
    names = [x for x in timeline_marker_names if x is not None]

    # Gather all events that match the names and sort them.
    events = []
    name_set = set()
    for name in names:
      name_set.add(name)

    def IsEventNeeded(event):
      if event.parent_slice != None:
        return
      return event.name in name_set

    events = list(self.IterAllEvents(
      recursive=True,
      event_type_predicate=IsSliceOrAsyncSlice,
      event_predicate=IsEventNeeded))
    events.sort(key=attrgetter('start'))

    # Check if the number and order of events matches the provided names,
    # and that the events don't overlap.
    if len(events) != len(names):
      raise MarkerMismatchError()
    for (i, event) in enumerate(events):
      if event.name != names[i]:
        raise MarkerMismatchError()
    for i in xrange(0, len(events)):
      for j in xrange(i+1, len(events)):
        if events[j].start < events[i].start + events[i].duration:
          raise MarkerOverlapError()

    return events

  def GetRendererProcessFromTabId(self, tab_id):
    renderer_thread = self.GetRendererThreadFromTabId(tab_id)
    if renderer_thread:
      return renderer_thread.parent
    return None

  def GetRendererThreadFromTabId(self, tab_id):
    return self._tab_ids_to_renderer_threads_map.get(tab_id, None)

  def _CreateImporters(self, trace_data):
    def FindImporterClassForPart(part):
      for importer_class in _IMPORTERS:
        if importer_class.GetSupportedPart() == part:
          return importer_class

    importers = []
    for part in trace_data.active_parts:
      importer_class = FindImporterClassForPart(part)
      if not importer_class:
        raise Exception('No importer found for %s' % repr(part))
      importers.append(importer_class(self, trace_data))

      importers.sort(key=lambda k: k.import_order)

    return importers


text:
<html>
  <head>
    <title>Foot</title>
    <link rel="stylesheet" type="text/css" href="./style.css">
  </head>
  <body>
    <canvas id="simulator"></canvas>
    <script src="./dist/bundle.js" type="text/javascript"></script>
  </body>
</html>


text:
package slogo.view;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;
import slogo.model.Memory;

/**
 * The methods table that shows saved methods.
 *
 * @author Aditya Srinivasan, Arjun Desai
 *
 */
public class Methods extends TableView<Method> {
    @SuppressWarnings("unused")
	private Memory memory;
    private EventHandler<ActionEvent> event;

    private static final String CALLBACK = "Callback";
    private static final String NAME_COLUMN = "Name";
    private static final String ACTION_COLUMN = "Action";
    private static final String NAME_KEY = "name";
    private static final String VALUE_KEY = "value";

    public Methods(double paneWidth, double paneHeight, EventHandler<ActionEvent> event) {

        // set dimensions for window
        this.setWidth(paneWidth);
        this.setHeight(paneHeight);

        this.event = event;

        // Initialize instances
        memory = Memory.getMemoryInstance();

        initializeTable();
    }

    /**
     * Initializes the table.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void initializeTable() {
        this.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        TableColumn<Method, String> nameColumn = new TableColumn<Method, String>(NAME_COLUMN);
        TableColumn valueColumn = new TableColumn<Method, Button>(ACTION_COLUMN);

        // set where to read values from
        nameColumn.setCellValueFactory(new PropertyValueFactory<Method, String>(NAME_KEY));
        valueColumn.setCellValueFactory(new PropertyValueFactory<>(VALUE_KEY));

        valueColumn.setCellFactory(generateCallback());

        this.getColumns().addAll(nameColumn, valueColumn);
    }

    /**
     * Generates the callback to be used by the buttons.
     * @return
     */
    @SuppressWarnings("rawtypes")
	private Callback generateCallback() {
    	return new Callback<TableColumn<Method, String>, TableCell<Method, String>>() {
			@Override
            public TableCell call(TableColumn<Method, String> parameter) {
                final TableCell<Method, String> cell = new TableCell<Method, String>() {
                    final Button button = new Button(CALLBACK);
                    @Override
                    public void updateItem(String item, boolean empty) {
                    	super.updateItem(item, empty);
                        if(empty) {
                        	setGraphic(null);
                        	setText(null);
                        } else  {
                        	Method method = getTableView().getItems().get(getIndex());
                        	button.setId(CALLBACK + " " + method.getValue());
                        	button.setOnAction(event);
                        	setGraphic(button);
                        	setText(null);
                        }
                    }
                };
                return cell;
            }
        };
    }

    /**
     * Adds a method specified to the table.
     *
     * @param name
     * @param value
     */
    void addMethodToTable (String name, String value) {
        this.getItems().add(new Method(name, value));
    }

}


text:
require 'rubygems'
require 'test/unit'
require 'shoulda'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'bincache'

class Test::Unit::TestCase
end


text:
@interface GooglePlusSignInApplication : UIApplication

@end


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
const core_1 = require('@angular/core');
const router_1 = require('@angular/router');
const app_module_1 = require('./releves_module/app.module');
const app_module_2 = require('./compteur_module/app.module');
const app_module_3 = require('./Graph_module/app.module');
const crisis_center_module_1 = require('./crisis-center/crisis-center.module');
const main_menu_component_1 = require('./main/main.menu.component');
let AppRoutingModule = class AppRoutingModule {
};
AppRoutingModule = __decorate([
    core_1.NgModule({
        imports: [
            app_module_1.RelevesModule,
            app_module_2.CompteurModule,
            app_module_3.GraphModule,
            crisis_center_module_1.CrisisCenterModule,
            router_1.RouterModule.forRoot([{
                    path: '',
                    component: main_menu_component_1.MainMenuComponent
                }])
        ],
        exports: [
            router_1.RouterModule
        ]
    }),
    __metadata('design:paramtypes', [])
], AppRoutingModule);
exports.AppRoutingModule = AppRoutingModule;
//# sourceMappingURL=app.routes.js.map


text:
package validators_test

import (
	"testing"
	"time"

	"github.com/markbates/going/validate"
	. "github.com/markbates/going/validate/validators"
	"github.com/stretchr/testify/assert"
)

func Test_TimeIsPresent(t *testing.T) {
	a := assert.New(t)
	v := TimeIsPresent{"Created At", time.Now()}
	es := validate.NewErrors()
	v.IsValid(es)
	a.Equal(0, es.Count())

	v = TimeIsPresent{"Created At", time.Time{}}
	v.IsValid(es)
	a.Equal(1, es.Count())
	a.Equal(es.Get("created_at"), []string{"Created At can not be blank."})
}


text:
//
//  JKPhotoPickerViewController.h
//  JKPhotoPicker
//
//  Created by albert on 2016/12/21.
//  Copyright © 2016年 安永博. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "JKPhotoUtility.h"

@class JKPhotoItem, PHAsset, JKPhotoConfiguration;

@interface JKPhotoPickerViewController : UIViewController

+ (void)showWithConfiguration:(void(^)(JKPhotoConfiguration *configuration))configuration
              completeHandler:(void(^)(NSArray <JKPhotoItem *> *photoItems, NSArray<PHAsset *> *selectedAssetArray))completeHandler;

/**
 * 使用UIImagePicker
 * presentVc : 由哪个控制器present出来,传nil则由根控制器弹出
 * dataType : 要选择的数据类型 仅支持JKPhotoPickerMediaDataTypeStaticImage和JKPhotoPickerMediaDataTypeVideo
 * allowsEditing : 是否允许编辑
 * completeHandler : 选择完成的回调
 */
//+ (void)showUIImagePickerWithPresentVc:(UIViewController *)presentVc dataType:(JKPhotoPickerMediaDataType)dataType allowsEditing:(BOOL)allowsEditing completeHandler:(void(^)(UIImage *image))completeHandler;
@end


text:
class CartCoinsController {
    constructor(CoinsService, $log, CartService) {
        this.$log = $log;
        this.CartService = CartService;
        this.totalCoins = 0;
        this.totalDollars = 0;
    }

    ifEmpty(value) {
        switch (value !== '' && value !== undefined) {
            case true:
                return 'active';
        }
    }

    outputCurrency(){
        if( this.totalCurrency >= 0 ) {
            this.onSayHello({
                $event: this.totalCurrency
            });
        }
    }

    toAddNumberCoins() {
        this.totalCoins = 0;
        let dimeT = parseInt(this.currency.coins.dime) * 0.10;
        let quarterT = parseInt(this.currency.coins.quarter) * 0.20;
        let halfEuroT = parseInt(this.currency.coins.halfEuro) * 0.50;
        let oneEuroT = parseInt(this.currency.coins.oneEuro);
        let twoEuroT = parseInt(this.currency.coins.twoEuro) * 2;

        let totalCoins = dimeT + quarterT + halfEuroT + oneEuroT + twoEuroT;
        if( totalCoins > 0) this.totalCoins = totalCoins;

        this.totalCurrency = totalCoins + this.totalDollars;

        this.outputCurrency();
    }

    toAddNumberDollars() {
        let fiveT = parseInt(this.currency.dollars.five) * 5;
        let tenT = parseInt(this.currency.dollars.ten) * 10;
        let twentyT = parseInt(this.currency.dollars.twenty) * 20;
        let fiftyT = parseInt(this.currency.dollars.fifty) * 50;
        let hundredT = parseInt(this.currency.dollars.hundred) * 100;

        let totalDollars = fiveT + tenT + twentyT + fiftyT + hundredT;
        if( totalDollars > 0) this.totalDollars = totalDollars;

        this.totalCurrency = this.totalCoins + totalDollars;

        this.outputCurrency();
    }

}

export default CartCoinsController


text:
namespace game {

class RaceTracker {
 public:
  RaceTracker(game::CarTracker& car_tracker,
              const game::Race& race, const std::string& color);

  // Detects if issuing the given command is safe based on cars
  // in front of us. If false, also returns command that is safe in safe_command.
  //
  // It only checks cars that are ahead of us (or will be ahead of us), and
  // makes sure that if we bump them, we will not crash.
  //
  // Use cases that we need to consider.
  // - someone is (or will be) in front of us and we will hit him
  // - someone respawns on top of us - this is hard, because we want to consider it
  //   only if we will not be able to pass him if we go optimally (it doesn't
  //   make sense to slow down if going fast is safe).
  // - one tick after the switch piece -
  //
  // Assumptions:
  // - for a given
  //
  // What is not working:
  // - if someone is much slower, and will take a switch just before us and
  //   we bump into him.
  // - if we ride on switch (or someone is on switch)
  bool IsSafeAhead(const CarState& current_state, const Command& command, Command* safe_command);

  bool IsSafeAttack(const CarState& current_state, const Command& command, Command* safe_command);

  bool IsSafeBehind(const CarState& current_state,
                    const vector<double>& schedule,
                    const Command& command,
                    Command* safe_command);

  // Recording methods

  void Record(const std::map<std::string, game::Position>& positions, int game_tick);
  void RecordCrash(const std::string& color);
  void RecordLapTime(const std::string& color, int time);
  void FinishedRace(const std::string& color);
  void TurboForEveryone(const game::Turbo& turbo);
  void CarSpawned(const std::string& color);
  void TurboStarted(const std::string& color);
  void DNF(const std::string& color);
  void ResurrectCars();

  // Lane scores based on who is there
  std::map<Switch, int> ScoreLanes(const CarState& state, const utils::Deadline& deadline);

  // TODO
  // Move to enemy?
  bool WorthBumping(const std::string& color);
  bool ShouldOvertake(const std::string& color, int from, int to);

  bool IsCompetitive(const std::string& color) { return false; }

  // Getters
  const std::vector<EnemyTracker>& enemies() const { return enemies_; }
  const std::string& my_color() const { return color_; }
  EnemyTracker& enemy(const std::string& color) { return enemies_[indexes_[color]]; }

  // Returns true if there was bump between those two cars in last tick
  bool BumpOccured(const std::string& color, const std::string& color2);

  BumpDetector& bump_detector() { return bump_detector_; }
  void ResetBumpDetector() { bump_detector_.Reset(); }

  bool HasSomeoneMaybeBumpedMe(const map<string, Position>& positions, double* bump_velocity);
  bool HasBumped(
      const Position& position1,
      const Position& position2);

 private:
  // TODO(tomek) deprecated version of IsSafeAhead() method.
  bool IsSafeInFront(const CarState& current_state, const Command& command, Command* safe_command);

  bool IsSafe(const CarState& state, const Command& command,
              Command* safe_command, const Command& our_command);

  void DetectBumps(const std::map<std::string, Position>& positions);

  bool IsBumpInevitable(
      const CarState& my_state_before,
      const CarState& my_state_after,
      const CarState& enemy_state,
      int ticks_after);

  // void RecordEnemy(int index, const game::Position& position);
  // void UpdateSpeedStats(int index, const game::Position& position);

  std::vector<EnemyTracker> enemies_;
  // Maps color to index
  std::map<std::string, int> indexes_;

  const Race& race_;
  CarTracker& car_tracker_;
  std::string color_;

  BumpDetector bump_detector_;
  LaneScorer lane_scorer_;
};

}  // namespace game

#endif  // CPP_GAME_RACE_TRACKER_H_


text:
/**
 * @module ol/LayerType
 */

/**
 * A layer type used when creating layer renderers.
 * @enum {string}
 */
export default {
  IMAGE: 'IMAGE',
  TILE: 'TILE',
  VECTOR_TILE: 'VECTOR_TILE',
  VECTOR: 'VECTOR'
};

//# sourceMappingURL=LayerType.js.map


text:
"""oocgcm.nemo.io
Define tools that help dealing with the creation of xarray objects from
NEMO netcdf files and creating NEMO-like netcdf files from xarray objects.

"""

from ...core.io import return_xarray_dataset as _return_xarray_dataset
from ...core.io import return_xarray_mfdataset as _return_xarray_mfdataset
from ...core.io import return_xarray_dataarray as _return_xarray_dataarray

def return_xarray_dataset(*args,**kwargs):
    """Wrapper for core.io.return_xarray_dataset.

    Parameters
    ----------
    *args : arguments
    **kwargs : keyword arguments

    Returns
    ------
    ds : xarray.Dataset

    Methods
    ------
    change the name of dimension 'time_counter' in 't'
    """
    _ds = _return_xarray_dataset(*args,**kwargs)
    if 'time_counter' in _ds.keys():
        ds = _ds.rename({'time_counter':'t'})
    else:
        ds = _ds
    return ds

def return_xarray_mfdataset(*args,**kwargs):
    """Wrapper for core.io.return_xarray_mfdataset.

    Parameters
    ----------
    *args : arguments
    **kwargs : keyword arguments

    Returns
    ------
    ds : xarray.Dataset

    Methods
    ------
    change the name of dimension 'time_counter' in 't'
    """
    _ds = _return_xarray_mfdataset(*args,**kwargs)
    if 'time_counter' in _ds.keys():
        ds = _ds.rename({'time_counter':'t'})
    else:
        ds = _ds
    return ds

def return_xarray_dataarray(*args,**kwargs):
    """Wrapper for core.io.return_xarray_dataarray.

    Parameters
    ----------
    *args : arguments
    **kwargs : keyword arguments

    Returns
    -------
    da : xarray.DataArray

    Methods
    -------
    change the name of dimension 'time_counter' in 't'
    """
    _da = _return_xarray_dataarray(*args,**kwargs)
    if 'time_counter' in _da.coords.keys():
       da = _da.rename({'time_counter':'t'})
    else:
       da = _da
    return da


text:
#ifndef SVGTransformListPropertyTearOff_h
#define SVGTransformListPropertyTearOff_h

#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/svg/SVGTransformList.h"
#include "core/svg/properties/SVGListPropertyTearOff.h"

namespace WebCore {

// SVGTransformList contains two additional methods, that can be exposed to the bindings.
class SVGTransformListPropertyTearOff : public SVGListPropertyTearOff<SVGTransformList> {
public:
    typedef SVGAnimatedListPropertyTearOff<SVGTransformList> AnimatedListPropertyTearOff;
    typedef SVGAnimatedListPropertyTearOff<SVGTransformList>::ListWrapperCache ListWrapperCache;

    static PassRefPtr<SVGListPropertyTearOff<SVGTransformList> > create(AnimatedListPropertyTearOff* animatedProperty, SVGPropertyRole role, SVGTransformList& values, ListWrapperCache& wrappers)
    {
        ASSERT(animatedProperty);
        return adoptRef(new SVGTransformListPropertyTearOff(animatedProperty, role, values, wrappers));
    }

    PassRefPtr<SVGPropertyTearOff<SVGTransform> > createSVGTransformFromMatrix(SVGPropertyTearOff<SVGMatrix>* matrix, ExceptionState& exceptionState)
    {
        ASSERT(m_values);
        if (!matrix) {
            exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
            return 0;
        }
        return SVGPropertyTearOff<SVGTransform>::create(m_values->createSVGTransformFromMatrix(matrix->propertyReference()));
    }

    PassRefPtr<SVGPropertyTearOff<SVGTransform> > consolidate(ExceptionState& exceptionState)
    {
        ASSERT(m_values);
        ASSERT(m_wrappers);
        if (!canAlterList(exceptionState))
            return 0;

        ASSERT(m_values->size() == m_wrappers->size());

        // Spec: If the list was empty, then a value of null is returned.
        if (m_values->isEmpty())
            return 0;

        detachListWrappers(0);
        RefPtr<SVGPropertyTearOff<SVGTransform> > wrapper = SVGPropertyTearOff<SVGTransform>::create(m_values->consolidate());
        m_wrappers->append(wrapper);

        ASSERT(m_values->size() == m_wrappers->size());
        return wrapper.release();
    }

private:
    SVGTransformListPropertyTearOff(AnimatedListPropertyTearOff* animatedProperty, SVGPropertyRole role, SVGTransformList& values, ListWrapperCache& wrappers)
        : SVGListPropertyTearOff<SVGTransformList>(animatedProperty, role, values, wrappers)
    {
    }
};

}

#endif // SVGListPropertyTearOff_h


text:
using PrecizeSoft.GetPdfOnline.Data;
using PrecizeSoft.GetPdfOnline.Domain.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrecizeSoft.GetPdfOnline.Domain.Handlers
{
    public class GetConvertedFilesInfo
    {
        protected ICacheRepository cacheRepository;

        public GetConvertedFilesInfo(ICacheRepository cacheRepository)
        {
            this.cacheRepository = cacheRepository;
        }

        public IEnumerable<ConvertedFileInfo> Execute(Guid sessionId)
        {
            return
                from P in this.cacheRepository.GetJobsBySession(sessionId, true)
                orderby P.OutputFile.CreateDateUtc descending
                where P.OutputFile != null
                select new ConvertedFileInfo
                {
                    FileId = P.OutputFileId.Value,
                    SessionId = P.SessionId,
                    FileName = P.OutputFile.FileName,
                    FileSize = P.OutputFile.FileSize,
                    CreateDateUtc = P.OutputFile.CreateDateUtc.UtcDateTime,
                    ExpireDateUtc = P.ExpireDateUtc?.UtcDateTime,
                    Rating = P.Rating
                };
        }
    }
}


text:
package br.usp.exoma.service;

import br.usp.exoma.dao.UsuarioDao;
import br.usp.exoma.dao.tx.Transacional;
import br.usp.exoma.model.Usuario;
import br.usp.exoma.util.ServiceException;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;

/**
 *
 * @author marcelo
 */
@RequestScoped
public class UsuarioService {
    @Inject
    private UsuarioDao usuarioDao;

    public UsuarioService() {
    }

    @Transacional
    public Usuario create(Usuario usuario, String confirmaSenha) throws ServiceException {
        try {
            if(this.podeSerSalvo(usuario, confirmaSenha)){
                usuario = usuarioDao.adiciona(usuario);
            }
        } catch (ServiceException ex) {
            throw ex;
        }
        return usuario;
    }

    public Usuario buscarPorUsernamePassword(String username, String password) {
        return usuarioDao.buscarPorUsernamePassword(username, password);
    }

    private boolean podeSerSalvo(Usuario usuario, String confirmaSenha) throws ServiceException{
        ServiceException serviceException = new ServiceException();
        if(!usuario.getPassword().equals(confirmaSenha)){
            serviceException.addMessage("A senha e a confirmação não são iguais");
        }

        if(serviceException.hasMessages()){
            throw serviceException;
        }
        return true;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Diatrype ribis Barthelet

### Remarks
null


text:
<?xml version='1.0' encoding='utf-8'?>
<Project ToolsVersion='Current' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>

  <!-- Test-specific data -->
  TEST_SPECIFIC_XML

  <!-- Boilerplate -->
  <PropertyGroup>
    <ImportByWildcardBeforeMicrosoftCommonTargets>false</ImportByWildcardBeforeMicrosoftCommonTargets>
    <ImportByWildcardAfterMicrosoftCommonTargets>false</ImportByWildcardAfterMicrosoftCommonTargets>
    <ImportUserLocationsByWildcardBeforeMicrosoftCommonTargets>false</ImportUserLocationsByWildcardBeforeMicrosoftCommonTargets>
    <ImportUserLocationsByWildcardAfterMicrosoftCommonTargets>false</ImportUserLocationsByWildcardAfterMicrosoftCommonTargets>
    <OutputPath>bin\</OutputPath>
    <Language>C#</Language>
    <OutputType>library</OutputType>
    <ProjectGuid>ffdb93c0-2880-44c7-89a6-bbd4ddab034a</ProjectGuid>
  </PropertyGroup>

  <!-- Standard boilerplate closing imports -->
  <Import Project='SQ_IMPORTS_BEFORE' />
  <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' />
</Project>


text:
        <form ng-submit="login()">

                Имя пользователя

                    <input type="text" class="form-control" id="username" ng-model="model.username" placeholder="Имя пользователя" required autofocus>

                Пароль

                    <input type="password" class="form-control" id="password" ng-model="model.password" placeholder="Пароль" required>

                        <input type="checkbox" id="rememberMe" value="remember-me" ng-model="model.rememberMe"> Запомнить меня

                <button type="submit" class="btn btn-large btn-primary btn-block">Войти</button>

        </form>


text:
package com.formulasearchengine.mathosphere.mlp.text;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Lists;

import com.formulasearchengine.mathosphere.mlp.cli.FlinkMlpCommandConfig;

import org.junit.Assert;
import org.junit.Test;

/**
 * Created by Moritz on 12.12.2015.
 */
public class TexInfoTest {

  @Test
  public void testGetIdentifiers() throws Exception {
    FlinkMlpCommandConfig cfg = FlinkMlpCommandConfig.test();
    final HashMultiset<String> expected = HashMultiset.create();
    expected.addAll(Lists.newArrayList("E", "m", "c"));
    Assert.assertEquals(expected, TexInfo.getIdentifiers("E=mc^2", cfg.getTexvcinfoUrl()));
  }
}


text:
package org.gradle.api.internal.tasks.properties.annotations;

import org.gradle.api.internal.tasks.DeclaredTaskOutputFileProperty;
import org.gradle.api.internal.tasks.PropertySpecFactory;
import org.gradle.api.internal.tasks.properties.BeanPropertyContext;
import org.gradle.api.internal.tasks.properties.PropertyValue;
import org.gradle.api.internal.tasks.properties.PropertyVisitor;

public abstract class AbstractOutputPropertyAnnotationHandler implements PropertyAnnotationHandler {

    protected abstract DeclaredTaskOutputFileProperty createFileSpec(PropertyValue propertyValue, PropertySpecFactory specFactory);

    @Override
    public boolean shouldVisit(PropertyVisitor visitor) {
        return true;
    }

    @Override
    public void visitPropertyValue(PropertyValue propertyValue, PropertyVisitor visitor, PropertySpecFactory specFactory, BeanPropertyContext context) {
        DeclaredTaskOutputFileProperty fileSpec = createFileSpec(propertyValue, specFactory);
        fileSpec
            .withPropertyName(propertyValue.getPropertyName())
            .optional(propertyValue.isOptional());
        visitor.visitOutputFileProperty(fileSpec);
    }
}


text:
package gov.hhs.fha.nhinc.filetransfer;

import gov.hhs.fha.nhinc.properties.PropertyAccessException;
import gov.hhs.fha.nhinc.properties.PropertyAccessor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author dunnek
 *
 *         Notes:http://forums.java.net/jive/thread.jspa?messageID=265679 Glassfish does not currently send notification
 *         that undeploy has occurred. thread will continue to run.
 */
public class CDCTimer extends Thread {

    private static Log log = LogFactory.getLog(CDCTimer.class);
    private static CDCTimer m_oTheOneAndOnlyTimer = null;
    private static boolean m_bRunnable = false;
    // private static final String GATEWAY_PROPERTY_FILE = "gateway";
    private static final String ADAPTER_PROPERTY_FILE = "adapter";
    private static final String CDC_REFRESH_DURATION_PROPERTY = "CDCRefreshDuration";
    private static final int CDC_REFRESH_DURATION_DEFAULT = 1800; // (30 minutes)
    // private Timer m_oTimer = new Timer(true); // Timer thread - set up as a daemon.
    private int m_iDurationSeconds = CDC_REFRESH_DURATION_DEFAULT;
    private String monitorDir = "";

    /**
     * This method is used to crete an instance of the UDDITimer. There should only be exactly one instance of this
     * running at any time. If it exists, it simply returns the one that exists. If it does not exist, then it will
     * create it, start the timer, and return a handle to it.
     *
     * @throws UDDIAccessorException
     */
    public static void startTimer() throws CDCTimerException {
        m_bRunnable = true;

        if (m_oTheOneAndOnlyTimer == null) {
            m_oTheOneAndOnlyTimer = new CDCTimer();
            try {
                m_oTheOneAndOnlyTimer.initialize();
                m_oTheOneAndOnlyTimer.setDaemon(true);
                m_oTheOneAndOnlyTimer.start();
            } catch (Exception e) {
                m_oTheOneAndOnlyTimer = null;
                String sErrorMessage = "Failed to start the CDC  timer.  Error: " + e.getMessage();
                log.error(sErrorMessage, e);
                throw new CDCTimerException(sErrorMessage, e);
            }

            log.info("UDDIUpdateManager timer has just been started now.");
        }
    }

    /**
     *
     */
    public static void stopTimer() {
        m_bRunnable = false;
        m_oTheOneAndOnlyTimer.interrupt();
    }

    /**
     *
     * @throws gov.hhs.fha.nhinc.cdc.CDCTimerException
     * @throws gov.hhs.fha.nhinc.properties.PropertyAccessException
     */
    private void initialize() throws CDCTimerException, PropertyAccessException {
        String refreshDuration = PropertyAccessor.getInstance().getProperty(ADAPTER_PROPERTY_FILE, CDC_REFRESH_DURATION_PROPERTY);
        if (refreshDuration != null && !refreshDuration.equals("")) {
            m_iDurationSeconds = Integer.parseInt(refreshDuration);
        } else {
            m_iDurationSeconds = 1;
        }
    }

    @Override
    public void run() {
        CDCTimerTask task = new CDCTimerTask();
        task.setMonitorDirectory(this.getMonitorDirectory());

        while (m_bRunnable) {
            task.run();
            try {
                Thread.sleep(m_iDurationSeconds * 1000);
            } catch (InterruptedException ex) {
                log.error("Failed to sleep.", ex);
            }
        }
    }

    /**
     *
     * @return String
     */
    protected String getMonitorDirectory() {
        String dir = "";
        try {
            dir = PropertyAccessor.getInstance().getProperty(ADAPTER_PROPERTY_FILE, "CDCMonitorDir");
        } catch (Exception ex) {
        }

        return dir;
    }
}


text:
using System.ComponentModel;
using System.Text;

namespace Meziantou.Framework.Html;

public sealed class HtmlDocumentParseEventArgs : CancelEventArgs
{
    public HtmlDocumentParseEventArgs(HtmlReader reader)
    {
        Reader = reader ?? throw new ArgumentNullException(nameof(reader));
    }

    public HtmlReader Reader { get; }
    public Encoding DetectedEncoding { get; set; }
    public HtmlNode CurrentNode { get; set; }
    public HtmlAttribute CurrentAttribute { get; set; }
    public bool Continue { get; set; }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1.02">

    <FrameLayout
        android:id="@+id/checkcontainer"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen0"
        android:layout_weight="0.90">

    </FrameLayout>

    <FrameLayout
        android:id="@+id/paycontainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.02">

    </FrameLayout>

    <TextView
        android:id="@+id/displayid"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen0"
        android:layout_weight="0.1"
        android:background="#FFDAB9"
        android:textColor="@android:color/black"
        android:textSize="@dimen/textsize28" />
</LinearLayout>


text:
package org.destinationsol.game;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;
import org.destinationsol.common.SolMath;
import org.destinationsol.game.projectile.Projectile;

public class SolContactListener implements ContactListener {
  private final SolGame myGame;

  public SolContactListener(SolGame game) {
    myGame = game;
  }

  @Override
  public void beginContact(Contact contact) {
    SolObject oA = (SolObject) contact.getFixtureA().getBody().getUserData();
    SolObject oB = (SolObject) contact.getFixtureB().getBody().getUserData();

    boolean aIsProj = oA instanceof Projectile;
    if (!aIsProj && !(oB instanceof Projectile)) return;

    Projectile proj = (Projectile)(aIsProj ? oA : oB);
    SolObject o = aIsProj ? oB : oA;
    proj.setObstacle(o, myGame);
  }

  @Override
  public void endContact(Contact contact) {
  }

  @Override
  public void preSolve(Contact contact, Manifold oldManifold) {
  }

  @Override
  public void postSolve(Contact contact, ContactImpulse impulse) {
    SolObject soa = (SolObject) contact.getFixtureA().getBody().getUserData();
    SolObject sob = (SolObject) contact.getFixtureB().getBody().getUserData();
    if (soa instanceof Projectile && ((Projectile) soa).getConfig().density <= 0) return;
    if (sob instanceof Projectile && ((Projectile) sob).getConfig().density <= 0) return;

    float absImpulse = calcAbsImpulse(impulse);
    Vector2 collPos = contact.getWorldManifold().getPoints()[0];
    soa.handleContact(sob, impulse, true, absImpulse, myGame, collPos);
    sob.handleContact(soa, impulse, false, absImpulse, myGame, collPos);
    myGame.getSpecialSounds().playColl(myGame, absImpulse, soa, collPos);
    myGame.getSpecialSounds().playColl(myGame, absImpulse, sob, collPos);
  }

  private float calcAbsImpulse(ContactImpulse impulse) {
    float absImpulse = 0;
    int pointCount = impulse.getCount();
    float[] normImpulses = impulse.getNormalImpulses();
    for (int i = 0; i < pointCount; i++) {
      float normImpulse = normImpulses[i];
      normImpulse = SolMath.abs(normImpulse);
      if (absImpulse < normImpulse) absImpulse = normImpulse;
    }
    return absImpulse;
  }
}


text:
<?php

namespace Propel\Tests\Runtime;

use Propel\Tests\Helpers\BaseTestCase;

use Propel\Runtime\Propel;
use Propel\Runtime\ServiceContainer\StandardServiceContainer;

class PropelTest extends BaseTestCase
{
    public function testGetServiceContainerReturnsAServiceContainer()
    {
        $this->assertInstanceOf('\Propel\Runtime\ServiceContainer\ServiceContainerInterface', Propel::getServiceContainer());
    }

    public function testGetServiceContainerAlwaysReturnsTheSameInstance()
    {
        $sc1 = Propel::getServiceContainer();
        $sc1->foo = 'bar';
        $sc2 = Propel::getServiceContainer();
        $this->assertSame($sc1, $sc2);
    }

    public function testSetServiceContainerOverridesTheExistingServiceContainer()
    {
        $oldSC = Propel::getServiceContainer();
        $newSC = new StandardServiceContainer();
        Propel::setServiceContainer($newSC);
        $this->assertSame($newSC, Propel::getServiceContainer());
        Propel::setServiceContainer($oldSC);
    }
}