text:
#include <znc/znc.h>
#include <znc/User.h>
#include <znc/FileUtils.h>

using std::set;

class CDCCMod;

class CDCCSock : public CSocket {
public:
	CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, const CString& sLocalFile, unsigned long uFileSize = 0, CFile* pFile = NULL);
	CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, const CString& sRemoteIP, unsigned short uRemotePort, const CString& sLocalFile, unsigned long uFileSize);
	virtual ~CDCCSock();

	virtual void ReadData(const char* data, size_t len);
	virtual void ConnectionRefused();
	virtual void SockError(int iErrno, const CString& sDescription);
	virtual void Timeout();
	virtual void Connected();
	virtual void Disconnected();
	void SendPacket();
	virtual Csock* GetSockObj(const CString& sHost, unsigned short uPort);
	CFile* OpenFile(bool bWrite = true);
	bool Seek(unsigned long int uPos);

	// Setters
	void SetRemoteIP(const CString& s) { m_sRemoteIP = s; }
	void SetRemoteNick(const CString& s) { m_sRemoteNick = s; }
	void SetFileName(const CString& s) { m_sFileName = s; }
	void SetFileOffset(unsigned long u) { m_uBytesSoFar = u; }
	// !Setters

	// Getters
	unsigned short GetUserPort() const { return m_uRemotePort; }
	const CString& GetRemoteNick() const { return m_sRemoteNick; }
	const CString& GetFileName() const { return m_sFileName; }
	const CString& GetLocalFile() const { return m_sLocalFile; }
	CFile* GetFile() { return m_pFile; }
	double GetProgress() const { return ((m_uFileSize) && (m_uBytesSoFar)) ? (double) (((double) m_uBytesSoFar / (double) m_uFileSize) *100.0) : 0; }
	bool IsSend() const { return m_bSend; }
	//const CString& GetRemoteIP() const { return m_sRemoteIP; }
	// !Getters
private:
protected:
	CString         m_sRemoteNick;
	CString         m_sRemoteIP;
	CString         m_sFileName;
	CString         m_sLocalFile;
	CString         m_sSendBuf;
	unsigned short  m_uRemotePort;
	unsigned long long  m_uFileSize;
	unsigned long long  m_uBytesSoFar;
	bool            m_bSend;
	bool            m_bNoDelFile;
	CFile*          m_pFile;
	CDCCMod*        m_pModule;
};

class CDCCMod : public CModule {
public:
	MODCONSTRUCTOR(CDCCMod) {
		AddHelpCommand();
		AddCommand("Send",          static_cast<CModCommand::ModCmdFunc>(&CDCCMod::SendCommand),
			"<nick> <file>");
		AddCommand("Get",           static_cast<CModCommand::ModCmdFunc>(&CDCCMod::GetCommand),
			"<file>");
		AddCommand("ListTransfers", static_cast<CModCommand::ModCmdFunc>(&CDCCMod::ListTransfersCommand));
	}

	virtual ~CDCCMod() {}

#ifndef MOD_DCC_ALLOW_EVERYONE
	virtual bool OnLoad(const CString& sArgs, CString& sMessage) {
		if (!m_pUser->IsAdmin()) {
			sMessage = "You must be admin to use the DCC module";
			return false;
		}

		return true;
	}
#endif

	bool SendFile(const CString& sRemoteNick, const CString& sFileName) {
		CString sFullPath = CDir::ChangeDir(GetSavePath(), sFileName, CZNC::Get().GetHomePath());
		CDCCSock* pSock = new CDCCSock(this, sRemoteNick, sFullPath);

		CFile* pFile = pSock->OpenFile(false);

		if (!pFile) {
			delete pSock;
			return false;
		}

		unsigned short uPort = CZNC::Get().GetManager().ListenRand("DCC::LISTEN::" + sRemoteNick, m_pUser->GetLocalDCCIP(), false, SOMAXCONN, pSock, 120);

		if (m_pUser->GetNick().Equals(sRemoteNick)) {
			PutUser(":*dcc!znc@znc.in PRIVMSG " + sRemoteNick + " :\001DCC SEND " + pFile->GetShortName() + " " + CString(CUtils::GetLongIP(m_pUser->GetLocalDCCIP())) + " "
				+ CString(uPort) + " " + CString(pFile->GetSize()) + "\001");
		} else {
			PutIRC("PRIVMSG " + sRemoteNick + " :\001DCC SEND " + pFile->GetShortName() + " " + CString(CUtils::GetLongIP(m_pUser->GetLocalDCCIP())) + " "
			    + CString(uPort) + " " + CString(pFile->GetSize()) + "\001");
		}

		PutModule("DCC -> [" + sRemoteNick + "][" + pFile->GetShortName() + "] - Attempting Send.");
		return true;
	}

	bool GetFile(const CString& sRemoteNick, const CString& sRemoteIP, unsigned short uRemotePort, const CString& sFileName, unsigned long uFileSize) {
		if (CFile::Exists(sFileName)) {
			PutModule("DCC <- [" + sRemoteNick + "][" + sFileName + "] - File already exists.");
			return false;
		}

		CDCCSock* pSock = new CDCCSock(this, sRemoteNick, sRemoteIP, uRemotePort, sFileName, uFileSize);

		if (!pSock->OpenFile()) {
			delete pSock;
			return false;
		}

		CZNC::Get().GetManager().Connect(sRemoteIP, uRemotePort, "DCC::GET::" + sRemoteNick, 60, false, m_pUser->GetLocalDCCIP(), pSock);

		PutModule("DCC <- [" + sRemoteNick + "][" + sFileName + "] - Attempting to connect to [" + sRemoteIP + "]");
		return true;
	}

	void SendCommand(const CString& sLine) {
		CString sToNick = sLine.Token(1);
		CString sFile = sLine.Token(2);
		CString sAllowedPath = GetSavePath();
		CString sAbsolutePath;

		if ((sToNick.empty()) || (sFile.empty())) {
			PutModule("Usage: Send <nick> <file>");
			return;
		}

		sAbsolutePath = CDir::CheckPathPrefix(sAllowedPath, sFile);

		if (sAbsolutePath.empty()) {
			PutStatus("Illegal path.");
			return;
		}

		SendFile(sToNick, sFile);
	}

	void GetCommand(const CString& sLine) {
		CString sFile = sLine.Token(1);
		CString sAllowedPath = GetSavePath();
		CString sAbsolutePath;

		if (sFile.empty()) {
			PutModule("Usage: Get <file>");
			return;
		}

		sAbsolutePath = CDir::CheckPathPrefix(sAllowedPath, sFile);

		if (sAbsolutePath.empty()) {
			PutModule("Illegal path.");
			return;
		}

		SendFile(m_pUser->GetNick(), sFile);
	}

	void ListTransfersCommand(const CString& sLine) {
		CTable Table;
		Table.AddColumn("Type");
		Table.AddColumn("State");
		Table.AddColumn("Speed");
		Table.AddColumn("Nick");
		Table.AddColumn("IP");
		Table.AddColumn("File");

		set<CSocket*>::const_iterator it;
		for (it = BeginSockets(); it != EndSockets(); ++it) {
			CDCCSock* pSock = (CDCCSock*) *it;

			Table.AddRow();
			Table.SetCell("Nick", pSock->GetRemoteNick());
			Table.SetCell("IP", pSock->GetRemoteIP());
			Table.SetCell("File", pSock->GetFileName());

			if (pSock->IsSend()) {
				Table.SetCell("Type", "Sending");
			} else {
				Table.SetCell("Type", "Getting");
			}

			if (pSock->GetType() == Csock::LISTENER) {
				Table.SetCell("State", "Waiting");
			} else {
				Table.SetCell("State", CString::ToPercent(pSock->GetProgress()));
				Table.SetCell("Speed", CString((int)(pSock->GetAvgRead() / 1024.0)) + " KiB/s");
			}
		}

		if (PutModule(Table) == 0) {
			PutModule("You have no active DCC transfers.");
		}
	}

	virtual void OnModCTCP(const CString& sMessage) {
		if (sMessage.Equals("DCC RESUME ", false, 11)) {
			CString sFile = sMessage.Token(2);
			unsigned short uResumePort = sMessage.Token(3).ToUShort();
			unsigned long uResumeSize = sMessage.Token(4).ToULong();

			set<CSocket*>::const_iterator it;
			for (it = BeginSockets(); it != EndSockets(); ++it) {
				CDCCSock* pSock = (CDCCSock*) *it;

				if (pSock->GetLocalPort() == uResumePort) {
					if (pSock->Seek(uResumeSize)) {
						PutModule("DCC -> [" + pSock->GetRemoteNick() + "][" + pSock->GetFileName() + "] - Attempting to resume from file position [" + CString(uResumeSize) + "]");
						PutUser(":*dcc!znc@znc.in PRIVMSG " + m_pUser->GetNick() + " :\001DCC ACCEPT " + sFile + " " + CString(uResumePort) + " " + CString(uResumeSize) + "\001");
					} else {
						PutModule("DCC -> [" + m_pUser->GetNick() + "][" + sFile + "] Unable to find send to initiate resume.");
					}
				}

			}
		} else if (sMessage.Equals("DCC SEND ", false, 9)) {
			CString sLocalFile = CDir::CheckPathPrefix(GetSavePath(), sMessage.Token(2));
			if (sLocalFile.empty()) {
				PutModule("Bad DCC file: " + sMessage.Token(2));
			}
			unsigned long uLongIP = sMessage.Token(3).ToULong();
			unsigned short uPort = sMessage.Token(4).ToUShort();
			unsigned long uFileSize = sMessage.Token(5).ToULong();
			GetFile(m_pClient->GetNick(), CUtils::GetIP(uLongIP), uPort, sLocalFile, uFileSize);
		}
	}
};

CDCCSock::CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, const CString& sLocalFile,
		unsigned long uFileSize, CFile* pFile) : CSocket(pMod) {
	m_sRemoteNick = sRemoteNick;
	m_uFileSize = uFileSize;
	m_uRemotePort = 0;
	m_uBytesSoFar = 0;
	m_pModule = pMod;
	m_pFile = pFile;
	m_sLocalFile = sLocalFile;
	m_bSend = true;
	m_bNoDelFile = false;
	SetMaxBufferThreshold(0);
}

CDCCSock::CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, const CString& sRemoteIP, unsigned short uRemotePort,
		const CString& sLocalFile, unsigned long uFileSize) : CSocket(pMod) {
	m_sRemoteNick = sRemoteNick;
	m_sRemoteIP = sRemoteIP;
	m_uRemotePort = uRemotePort;
	m_uFileSize = uFileSize;
	m_uBytesSoFar = 0;
	m_pModule = pMod;
	m_pFile = NULL;
	m_sLocalFile = sLocalFile;
	m_bSend = false;
	m_bNoDelFile = false;
	SetMaxBufferThreshold(0);
}

CDCCSock::~CDCCSock() {
	if ((m_pFile) && (!m_bNoDelFile)) {
		m_pFile->Close();
		delete m_pFile;
	}
}

void CDCCSock::ReadData(const char* data, size_t len) {
	if (!m_pFile) {
		DEBUG("File not open! closing get.");
		m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File not open!");
		Close();
	}

	// DCC specs says the receiving end sends the number of bytes it
	// received so far as a 4 byte integer in network byte order, so we need
	// uint32_t to do the job portably. This also means that the maximum
	// file that we can transfer is 4 GiB big (see OpenFile()).
	if (m_bSend) {
		m_sSendBuf.append(data, len);

		while (m_sSendBuf.size() >= 4) {
			uint32_t iRemoteSoFar;
			memcpy(&iRemoteSoFar, m_sSendBuf.data(), sizeof(iRemoteSoFar));
			iRemoteSoFar = ntohl(iRemoteSoFar);

			if ((iRemoteSoFar + 65536) >= m_uBytesSoFar) {
				SendPacket();
			}

			m_sSendBuf.erase(0, 4);
		}
	} else {
		m_pFile->Write(data, len);
		m_uBytesSoFar += len;
		uint32_t uSoFar = htonl((uint32_t)m_uBytesSoFar);
		Write((char*) &uSoFar, sizeof(uSoFar));

		if (m_uBytesSoFar >= m_uFileSize) {
			Close();
		}
	}
}

void CDCCSock::ConnectionRefused() {
	DEBUG(GetSockName() << " == ConnectionRefused()");
	m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Connection Refused.");
}

void CDCCSock::Timeout() {
	DEBUG(GetSockName() << " == Timeout()");
	m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Timed Out.");
}

void CDCCSock::SockError(int iErrno, const CString& sDescription) {
	DEBUG(GetSockName() << " == SockError(" << iErrno << ", " << sDescription << ")");
	m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Socket Error [" + sDescription + "]");
}

void CDCCSock::Connected() {
	DEBUG(GetSockName() << " == Connected(" << GetRemoteIP() << ")");
	m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Transfer Started.");

	if (m_bSend) {
		SendPacket();
	}

	SetTimeout(120);
}

void CDCCSock::Disconnected() {
	const CString sStart = ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - ";

	DEBUG(GetSockName() << " == Disconnected()");

	if (m_uBytesSoFar > m_uFileSize) {
		m_pModule->PutModule(sStart + "TooMuchData!");
	} else if (m_uBytesSoFar == m_uFileSize) {
		if (m_bSend) {
			m_pModule->PutModule(sStart + "Completed! - Sent [" + m_sLocalFile +
					"] at [" + CString((int) (GetAvgWrite() / 1024.0)) + " KiB/s ]");
		} else {
			m_pModule->PutModule(sStart + "Completed! - Saved to [" + m_sLocalFile +
					"] at [" + CString((int) (GetAvgRead() / 1024.0)) + " KiB/s ]");
		}
	} else {
		m_pModule->PutModule(sStart + "Incomplete!");
	}
}

void CDCCSock::SendPacket() {
	if (!m_pFile) {
		m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File closed prematurely.");
		Close();
		return;
	}

	if (GetInternalWriteBuffer().size() > 1024 * 1024) {
		// There is still enough data to be written, don't add more
		// stuff to that buffer.
		DEBUG("SendPacket(): Skipping send, buffer still full enough [" << GetInternalWriteBuffer().size() << "]["
				<< m_sRemoteNick << "][" << m_sFileName << "]");
		return;
	}

	char szBuf[4096];
	ssize_t iLen = m_pFile->Read(szBuf, 4096);

	if (iLen < 0) {
		m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Error reading from file.");
		Close();
		return;
	}

	if (iLen > 0) {
		Write(szBuf, iLen);
		m_uBytesSoFar += iLen;
	}
}

Csock* CDCCSock::GetSockObj(const CString& sHost, unsigned short uPort) {
	Close();

	CDCCSock* pSock = new CDCCSock(m_pModule, m_sRemoteNick, m_sLocalFile, m_uFileSize, m_pFile);
	pSock->SetSockName("DCC::SEND::" + m_sRemoteNick);
	pSock->SetTimeout(120);
	pSock->SetFileName(m_sFileName);
	pSock->SetFileOffset(m_uBytesSoFar);
	m_bNoDelFile = true;

	return pSock;
}

CFile* CDCCSock::OpenFile(bool bWrite) {
	if ((m_pFile) || (m_sLocalFile.empty())) {
		m_pModule->PutModule(((bWrite) ? "DCC <- [" : "DCC -> [") + m_sRemoteNick + "][" + m_sLocalFile + "] - Unable to open file.");
		return NULL;
	}

	m_pFile = new CFile(m_sLocalFile);

	if (bWrite) {
		if (m_pFile->Exists()) {
			delete m_pFile;
			m_pFile = NULL;
			m_pModule->PutModule("DCC <- [" + m_sRemoteNick + "] - File already exists [" + m_sLocalFile + "]");
			return NULL;
		}

		if (!m_pFile->Open(O_WRONLY | O_TRUNC | O_CREAT)) {
			delete m_pFile;
			m_pFile = NULL;
			m_pModule->PutModule("DCC <- [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]");
			return NULL;
		}
	} else {
		if (!m_pFile->IsReg()) {
			delete m_pFile;
			m_pFile = NULL;
			m_pModule->PutModule("DCC -> [" + m_sRemoteNick + "] - Not a file [" + m_sLocalFile + "]");
			return NULL;
		}

		if (!m_pFile->Open()) {
			delete m_pFile;
			m_pFile = NULL;
			m_pModule->PutModule("DCC -> [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]");
			return NULL;
		}

		// The DCC specs only allow file transfers with files smaller
		// than 4GiB (see ReadData()).
		unsigned long long uFileSize = m_pFile->GetSize();
		if (uFileSize > (unsigned long long) 0xffffffffULL) {
			delete m_pFile;
			m_pFile = NULL;
			m_pModule->PutModule("DCC -> [" + m_sRemoteNick + "] - File too large (>4 GiB) [" + m_sLocalFile + "]");
			return NULL;
		}

		m_uFileSize = uFileSize;
	}

	m_sFileName = m_pFile->GetShortName();

	return m_pFile;
}

bool CDCCSock::Seek(unsigned long int uPos) {
	if (m_pFile) {
		if (m_pFile->Seek(uPos)) {
			m_uBytesSoFar = uPos;
			return true;
		}
	}

	return false;
}

template<> void TModInfo<CDCCMod>(CModInfo& Info) {
	Info.SetWikiPage("dcc");
}

USERMODULEDEFS(CDCCMod, "This module allows you to transfer files to and from ZNC")


text: Scrapes Results from the CBSE Website and stores them in an excel file.

redpajama_set_name: RedPajamaGithub


text:
/**
 *  Represents a GraphIT Access Token.
 *
 *  Access is always a promise, as we may have to renew it.
 *
 *  both `onInvalidate()` and `getToken()` can return promises.
 *  `getMeta` should return synchronously.
 */

// note: this error is for "CANNOT" get a token, not "FAILED" to get a token.
// i.e. we look up in a database and it's not there. no amount of retries will
// succeed.
export const cannotGetToken = (reason) => {
    return Object.assign(new Error(reason), { cannotGetToken: true });
};

export default class Token {
    constructor({ onInvalidate = () => {}, getMeta = () => {}, getToken }) {
        this._onInvalidate = onInvalidate;
        this._getMeta = getMeta;
        this._getToken = getToken;
    }

    updateToken({ getToken }) {
        this._getToken = getToken;
        this._tokenPromise = null;
    }

    get() {
        if (!this._tokenPromise) {
            this._tokenPromise = Promise.resolve(this._getToken())
                .catch((err) => {
                    // flatten this, so another attempt can be made
                    this._tokenPromise = null;

                    // check if this is a permanent error
                    if (err.cannotGetToken) {
                        // we should throw. otherwise the user will end up in an infinite loop
                        throw err;
                    }

                    // otherwise return a bogus token
                    // returning a bogus token ("", falsy), should hopefully trigger this again,
                    // waiting subscribers will receive it, fail, and try again.
                    console.error('ERROR GETTING TOKEN!', err);

                    return '';
                })
                .then((token) => {
                    this._invalidated = false; // this resolved one way or another...

                    return token;
                });
        }

        return this._tokenPromise;
    }

    invalidate() {
        if (this._invalidated) {
            return;
        }

        this._tokenPromise = false;
        this._invalidated = true;

        return Promise.resolve(this._onInvalidate()).catch(() => {});
    }

    //returns nothing by default, but you may want to synchronously return the
    //last valid token, the time is was acquired, it's expiry, a refresh token, etc...
    meta() {
        return this._getMeta();
    }
}

export const fixedToken = (tokenString) =>
    new Token({ getToken: () => tokenString });


text:
package com.yahoo.pulsar.client.api;

import java.io.Serializable;

/**
 * A listener that will be called in order for every message received.
 *
 *
 */
public interface MessageListener extends Serializable {
    /**
     * This method is called whenever a new message is received.
     *
     * Messages are guaranteed to be delivered in order and from the same thread for a single consumer
     *
     * This method will only be called once for each message, unless either application or broker crashes.
     *
     * Application is responsible of handling any exception that could be thrown while processing the message.
     *
     * @param consumer
     *            the consumer that received the message
     * @param msg
     *            the message object
     */
    void received(Consumer consumer, Message msg);
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>se.mah.elis.external.control</groupId>
  <version>1.0.0</version>
  <packaging>bundle</packaging>

  <properties>
    <site.basedir>${project.parent.basedir}</site.basedir>
  </properties>

  <dependencies>
  	<dependency>
  		<groupId>org.osgi</groupId>
  		<artifactId>org.osgi.core</artifactId>
  		<version>4.3.1</version>
  	</dependency>
  	<dependency>
  		<groupId>org.osgi</groupId>
  		<artifactId>org.osgi.compendium</artifactId>
  		<version>4.3.1</version>
  	</dependency>
  	<dependency>
  		<groupId>javax.ws.rs</groupId>
  		<artifactId>javax.ws.rs-api</artifactId>
  		<version>2.0</version>
  	</dependency>
  	<dependency>
  		<groupId>org.apache.felix</groupId>
  		<artifactId>org.apache.felix.scr.annotations</artifactId>
  		<version>1.9.6</version>
  	</dependency>
  	<dependency>
  		<groupId>se.mah.elis.services.users</groupId>
  		<artifactId>user-service</artifactId>
  		<version>2.0.0</version>
  		<type>bundle</type>
  	</dependency>
  	<dependency>
  		<groupId>se.mah.elis.adaptor.device.api</groupId>
  		<artifactId>device-api</artifactId>
  		<version>2.2.0</version>
  		<type>bundle</type>
  	</dependency>
  	<dependency>
  		<groupId>com.google.code.gson</groupId>
  		<artifactId>gson</artifactId>
  		<version>2.2.4</version>
  	</dependency>
  	<dependency>
  		<groupId>org.mockito</groupId>
  		<artifactId>mockito-all</artifactId>
  		<version>1.9.5</version>
  		<scope>test</scope>
  	</dependency>
  	<dependency>
  		<groupId>
  			org.glassfish.jersey.test-framework.providers
  		</groupId>
  		<artifactId>
  			jersey-test-framework-provider-inmemory
  		</artifactId>
  		<version>2.6</version>
  		<scope>test</scope>
  	</dependency>
  	<dependency>
  		<groupId>se.mah.elis.services.storage</groupId>
  		<artifactId>storage-api</artifactId>
  		<version>2.1.0</version>
  		<type>bundle</type>
  	</dependency>
  	<dependency>
  		<groupId>se.mah.elis.impl.services.users-and-storage</groupId>
  		<artifactId>user-and-storage-service-impl</artifactId>
  		<version>2.1.0</version>
  		<type>bundle</type>
  		<scope>test</scope>
  	</dependency>
  	<dependency>
  		<groupId>com.fasterxml.jackson.jaxrs</groupId>
  		<artifactId>jackson-jaxrs-base</artifactId>
  		<version>2.4.1</version>
  		<type>bundle</type>
  		<scope>test</scope>
  	</dependency>
  	<dependency>
  		<groupId>com.fasterxml.jackson.jaxrs</groupId>
  		<artifactId>jackson-jaxrs-providers</artifactId>
  		<version>2.4.1</version>
  		<type>pom</type>
  		<scope>test</scope>
  	</dependency>
  	<dependency>
  		<groupId>com.fasterxml.jackson.jaxrs</groupId>
  		<artifactId>jackson-jaxrs-json-provider</artifactId>
  		<version>2.4.1</version>
  		<type>bundle</type>
  		<scope>test</scope>
  	</dependency>
  	<dependency>
  		<groupId>se.mah.elis.external.beans</groupId>
  		<artifactId>elis-service-beans</artifactId>
  		<version>1.1.0</version>
  		<type>bundle</type>
  	</dependency>
  	<dependency>
  		<groupId>javax.validation</groupId>
  		<artifactId>validation-api</artifactId>
  		<version>1.1.0.Final</version>
  	</dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>    <!-- (2) START -->
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>2.4.0</version>
        <extensions>true</extensions>
        <configuration>
          <instructions>
          	<Bundle-ActivationPolicy>lazy</Bundle-ActivationPolicy>
          	<Private-Package>${project.groupId}</Private-Package>
            <Export-Package>${project.groupId}.*</Export-Package>
          </instructions>
        </configuration>
      </plugin>    <!-- (2) END -->
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-scr-plugin</artifactId>
        <version>1.14.0</version>
        <executions>
          <execution>
            <id>generate-scr-scrdescriptor</id>
            <goals>
              <goal>scr</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  <name>The Elis Basic Control bundle</name>
  <artifactId>elis-basic-control</artifactId>
  <parent>
  	<groupId>se.mah.elis</groupId>
  	<artifactId>super-pom</artifactId>
  	<version>1.0.0</version>
  	<relativePath>../super</relativePath>
  </parent>
  <description>Provides some REST HTTP API endpoints that enable basic device control.</description>
</project>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Xenosphaeria sphyridiana J. Lahm

### Remarks
null


text:
<?php

namespace ndj\DAdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class AventurierType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('idmembre','entity',array(
            		'class'=>'ndjUserBundle:User',
					'property' => 'username',))
            ->add('idcreature','entity',array(
            		'class'=>'ndjDGameBundle:Creature',
					'property' => 'nom',))
            ->add('nom')
            ->add('acrobatie')
            ->add('bagarre')
            ->add('charme')
            ->add('acuite')
            ->add('age')
            ->add('experience')
            ->add('renommee')
            ->add('renommeeMax')
            ->add('pvie')
            ->add('pvieMax')
            ->add('argent')
            ->add('mana')
            ->add('manaMax')
            ->add('pact')
            ->add('pdep')
            ->add('position')
            ->add('pouvoirs')
            ->add('talents')
            ->add('envoutement')
            ->add('points')
            ->add('etat')
            ->add('idorganisation')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'ndj\DGameBundle\Entity\Aventurier'
        ));
    }

    public function getName()
    {
        return 'ndj_dgamebundle_aventuriertype';
    }
}


text:
namespace BlogEngine.Core
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;

    /// <summary>
    /// The role class.
    /// </summary>
    public class Role
    {
        #region Constants and Fields

        private readonly object synclock = new object();

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Role"/> class.
        /// </summary>
        /// <param name="name">
        /// A name of the role.
        /// </param>
        public Role(string name) : this(name, new List<string>())
        {
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref = "Role" /> class.
        /// </summary>
        public Role() : this(null, new List<string>())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Role"/> class.
        /// </summary>
        /// <param name="name">
        /// A name of the role.
        /// </param>
        /// <param name="userNames">
        /// A list of users in role.
        /// </param>
        public Role(string name, List<string> userNames)
        {
            if (userNames == null)
            {
                throw new System.ArgumentNullException("userNames");
            }
            else
            {
                this.Name = name;
                this.Users = userNames;
            }
        }

        #endregion

        #region Properties

        /// <summary>
        ///     Gets or sets the name.
        /// </summary>
        /// <value>The name of the role.</value>
        public string Name { get; set; }

        /// <summary>
        ///     Gets the users.
        /// </summary>
        /// <value>The users.</value>
        public List<string> Users { get; private set; }

        #endregion

    }
}


text:
#define NIX 1
#define WIN 2

#ifdef __linux__
#include <unistd.h>
#define PLATFORM NIX
#elif __APPLE__
#include <unistd.h>
#define PLATFORM NIX
#elif _WIN32
#include <windows.h>
#define PLATFORM WIN
#endif

#include <iostream>
#include <thread>
#include <chrono>
#include <vector>
#include <iomanip>

#include "data.hpp"
#include "gamemech.hpp"
#include "generator.hpp"

using namespace std;

const short numberOfCards = 5;
const short maxRandom = 52;
const short precPoint = 5;

void play();
void displayResult();

bool done = false;

Score myScore;
Generator generator;
GameMech game;

vector<Card> resultCards;

thread displayThread;

void crossClear() {
#if PLATFORM == NIX
	system("clear");
#elif PLATFORM == WIN
	system("CLS");
#endif
}

int main() {
	generator.createDeck();

	displayThread = thread(displayResult);
	displayThread.detach();

	cout << "[^] Started with " << numberOfCards << " cards!" << endl;

	play();

	return 0;
}

void displayResult() {
	while (true) {

		crossClear();

		auto tmpScore = myScore;

		auto nothingPrc = tmpScore.nothing / static_cast<float>(tmpScore.getTotal()) * 100;
		auto pairsPrc = tmpScore.pair / static_cast<float>(tmpScore.getTotal()) * 100;
		auto twoPairPrc = tmpScore.twopair / static_cast<float>(tmpScore.getTotal()) * 100;
		auto threePrc = tmpScore.three / static_cast<float>(tmpScore.getTotal()) * 100;
		auto straightPrc = tmpScore.straight / static_cast<float>(tmpScore.getTotal()) * 100;
		auto flushPrc = tmpScore.flush / static_cast<float>(tmpScore.getTotal()) * 100;
		auto fullPrc = tmpScore.full / static_cast<float>(tmpScore.getTotal()) * 100;
		auto fourKindsPrc = tmpScore.four / static_cast<float>(tmpScore.getTotal()) * 100;
		auto straightFlushPrc = tmpScore.straightflush / static_cast<float>(tmpScore.getTotal()) * 100;
		auto royalFlushPrc = tmpScore.royal / static_cast<float>(tmpScore.getTotal()) * 100;

		auto total = nothingPrc + pairsPrc + twoPairPrc + threePrc + straightPrc + flushPrc + fullPrc + fourKindsPrc + straightFlushPrc + royalFlushPrc;

		cout << "[?] Game #" << tmpScore.getTotal() << " Done ->" << setiosflags(ios::fixed) << setprecision(0) << total << "%" << endl;
		cout << "[?] Nothing ->" << tmpScore.nothing << " ->" << setiosflags(ios::fixed) << setprecision(precPoint) << nothingPrc << "%" << endl;
		cout << "[?] Pairs ->" << tmpScore.pair << " ->" << pairsPrc << "%" << endl;
		cout << "[?] TwoPairs ->" << tmpScore.twopair << " ->" << twoPairPrc << "%" << endl;
		cout << "[?] ThreeKinds ->" << tmpScore.three << " ->" << threePrc << "%" << endl;
		cout << "[?] Straights ->" << tmpScore.straight << " ->" << straightPrc << "%" << endl;
		cout << "[?] Flushes ->" << tmpScore.flush << " ->" << flushPrc << "%" << endl;
		cout << "[?] Fulls ->" << tmpScore.full << " ->" << fullPrc << "%" << endl;
		cout << "[?] FourKinds ->" << tmpScore.four << " ->" << fourKindsPrc << "%" << endl;
		cout << "[?] StraightFlushes ->" << tmpScore.straightflush << " ->" << straightFlushPrc << "%" << endl;
		cout << "[?] RoyalFlushes ->" << tmpScore.royal << " ->" << royalFlushPrc << "%" << endl;

		this_thread::sleep_for(chrono::milliseconds(1000));

	}
}

void play() {
	while (true) {

		resultCards.clear();

		resultCards = generator.rollTable(maxRandom, numberOfCards);

		game.verifyResult(resultCards, myScore);
	}
}


text:
<?php

namespace humhub\modules\space\models\forms;

use Yii;
use yii\base\Model;
use humhub\modules\user\models\User;
use humhub\modules\space\models\Membership;

/**
 * @author Luke
 * @package humhub.modules_core.space.forms
 * @since 0.5
 */
class InviteForm extends Model
{

    /**
     * Field for Invite GUIDs
     *
     * @var type
     */
    public $invite;

    /**
     * Field for external e-mails to invite
     *
     * @var type
     */
    public $inviteExternal;

    /**
     * Current Space
     *
     * @var type
     */
    public $space;

    /**
     * Parsed Invites with User Objects
     *
     * @var type
     */
    public $invites = array();

    /**
     * Parsed list of E-Mails of field inviteExternal
     */
    public $invitesExternal = array();

    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
    public function rules()
    {
        return array(
            array('invite', 'checkInvite'),
            array('inviteExternal', 'checkInviteExternal'),
        );
    }

    /**
     * Declares attribute labels.
     */
    public function attributeLabels()
    {
        return array(
            'invite' => Yii::t('SpaceModule.forms_SpaceInviteForm', 'Invites'),
            'inviteExternal' => Yii::t('SpaceModule.forms_SpaceInviteForm', 'New user by e-mail (comma separated)'),
        );
    }

    /**
     * Form Validator which checks the invite field
     *
     * @param type $attribute
     * @param type $params
     */
    public function checkInvite($attribute, $params)
    {

        // Check if email field is not empty
        if ($this->$attribute != "") {

            $invites = explode(",", $this->$attribute);

            foreach ($invites as $userGuid) {
                $userGuid = preg_replace("/[^A-Za-z0-9\-]/", '', $userGuid);

                if ($userGuid == "")
                    continue;

                // Try load user
                $user = User::findOne(['guid' => $userGuid]);
                if ($user != null) {
                    $membership = Membership::findOne(['space_id' => $this->space->id, 'user_id' => $user->id]);

                    if ($membership != null && $membership->status == Membership::STATUS_MEMBER) {
                        $this->addError($attribute, Yii::t('SpaceModule.forms_SpaceInviteForm', "User '{username}' is already a member of this space!", ['username' => $user->getDisplayName()]));
                        continue;
                    } else if($membership != null && $membership->status == Membership::STATUS_APPLICANT) {
                        $this->addError($attribute, Yii::t('SpaceModule.forms_SpaceInviteForm', "User '{username}' is already an applicant of this space!", ['username' => $user->getDisplayName()]));
                        continue;
                    }
                    $this->invites[] = $user;
                } else {
                    $this->addError($attribute, Yii::t('SpaceModule.forms_SpaceInviteForm', "User not found!"));
                    continue;
                }
            }
        }
    }

    /**
     * Checks a comma separated list of e-mails which should invited to space.
     * E-Mails needs to be valid and not already registered.
     *
     * @param type $attribute
     * @param type $params
     */
    public function checkInviteExternal($attribute, $params)
    {

        // Check if email field is not empty
        if ($this->$attribute != "") {
            $emails = explode(",", $this->$attribute);

            // Loop over each given e-mail
            foreach ($emails as $email) {
                $email = trim($email);

                $validator = new \yii\validators\EmailValidator();
                if (!$validator->validate($email)) {
                    $this->addError($attribute, Yii::t('SpaceModule.forms_SpaceInviteForm', "{email} is not valid!", array("{email}" => $email)));
                    continue;
                }

                $user = User::findOne(['email' => $email]);
                if ($user != null) {
                    $this->addError($attribute, Yii::t('SpaceModule.forms_SpaceInviteForm', "{email} is already registered!", array("{email}" => $email)));
                    continue;
                }

                $this->invitesExternal[] = $email;
            }
        }
    }

    /**
     * Returns an Array with selected recipients
     */
    public function getInvites()
    {
        return $this->invites;
    }

    /**
     * Returns an Array with selected recipients
     */
    public function getInvitesExternal()
    {
        return $this->invitesExternal;
    }

     /**
     * E-Mails entered in form
     *
     * @return array the emails
     */
    public function getEmails()
    {
        $emails = [];
        foreach (explode(',', $this->inviteExternal) as $email) {
            $emails[] = trim($email);
        }
        return $emails;
    }

}


text:
require 'simplecov'
SimpleCov.start

require 'test/unit'
require 'fileutils'
require 'mocha/setup'

require 'i18n-docs'

Rails = Struct.new(:dummy)

module TestHelper
  def fixture_path
    File.join(File.expand_path(File.dirname(__FILE__)), 'fixtures')
  end

  def tmp_dir
    File.join(fixture_path, 'tmp')
  end

  def create_tmp_dir
    FileUtils.mkdir(tmp_dir) unless File.exist?(tmp_dir)
  end

  def remove_tmp_dir
    FileUtils.rmtree(tmp_dir)
  end
end


text:
<?php

/* SonataAdminBundle:CRUD:acl.html.twig */
class __TwigTemplate_19d4c7bb80e3cc8add8391aeb5e3d2fff54daf962491763222c8273e58b2cdbe extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 12
        try {
            $this->parent = $this->env->loadTemplate("SonataAdminBundle:CRUD:base_acl.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(12);

            throw $e;
        }

        $this->blocks = array(
        );
    }

    protected function doGetParent(array $context)
    {
        return "SonataAdminBundle:CRUD:base_acl.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    public function getTemplateName()
    {
        return "SonataAdminBundle:CRUD:acl.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  11 => 12,);
    }
}


text:
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using Newtonsoft.Json;

namespace Hanabi.Server.Controllers.Helper
{
    public class JsonNetModelBinder : IModelBinder
    {
        public bool BindModel( HttpActionContext actionContext, ModelBindingContext bindingContext )
        {
            string data = actionContext.Request.Content.ReadAsStringAsync().Result;
            if ( data == null )
            {
                bindingContext.ModelState.AddModelError( bindingContext.ModelName, "Null data" );
                return false;
            }

            MethodInfo method = typeof( JsonConvert ).GetMethods().Where( m => m.Name == "DeserializeObject" && m.IsGenericMethod && m.GetParameters().Length == 1 ).First();
            if ( method == null )
            {
                bindingContext.ModelState.AddModelError( bindingContext.ModelName, "Cannot DeserializeObject" );
                return false;
            }

            method = method.MakeGenericMethod( bindingContext.ModelType );
            bindingContext.Model = method.Invoke( null, new[] { data } );

            return true;
        }
    }
}


text:
rm -rf /usr/local/lib/libytsvrlib.so
cp -rf libytsvrlib.so /usr/local/lib/libytsvrlib.so
rm -rf /usr/lib/libytsvrlib.so
ln /usr/local/lib/libytsvrlib.so /usr/lib/
mkdir -p /usr/include/ytsvrlib
cp -rfuv ../*.h ../../Header/
cp -rfuv ../../Header/* /usr/include/ytsvrlib/


text:
namespace LeinCottage.Web.LocalData
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Newtonsoft.Json;
    using Models;
    using Data;

    public class JsonPhotoRepository<T> : IRepository<T> where T : Photo
    {
        private static volatile JsonPhotoRepository<T> instance;
        private static object syncRoot = new object();
        public static JsonPhotoRepository<T> Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new JsonPhotoRepository<T>();
                    }
                }

                return instance;
            }
        }

        private static int idGenerator = 0;
        private const string LocalStorageFileName = "LocalJsonStorage.json";
        private readonly string filePath =
            System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/" + LocalStorageFileName);

        public JsonPhotoRepository()
        {
            if (!File.Exists(filePath))
            {
                File.Create(filePath);
                this.AllObjects = new List<T>();
            }
            else
            {
                string alltext = string.Empty;
                using (StreamReader sr = new StreamReader(filePath))
                {
                    alltext = sr.ReadToEnd();
                }

                this.AllObjects = JsonConvert.DeserializeObject<List<T>>(alltext);
                if (this.AllObjects == null)
                {
                    this.AllObjects = new List<T>();
                }
            }
        }

        private List<T> AllObjects { get; set; }

        public void Add(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("Can not add null to the json");
            }

            entity.Id = IdGenerator();

            this.AllObjects.Add(entity);
        }

        public IQueryable<T> All()
        {
            return this.AllObjects.AsQueryable<T>();
        }

        public T Attach(T entity)
        {
            throw new NotImplementedException();
        }

        public void Delete(object id)
        {
            this.AllObjects.Remove(this.AllObjects.FirstOrDefault(p => p.Id == (int)id));
        }

        public void Delete(T entity)
        {
            this.AllObjects.Remove(entity);
        }

        public void Detach(T entity)
        {
            throw new NotImplementedException();
        }

        public T GetById(object id)
        {
            return this.AllObjects.FirstOrDefault(p => p.Id == (int)id);
        }

        public int SaveChanges()
        {
            File.WriteAllText(filePath, JsonConvert.SerializeObject(this.AllObjects));
            return 0;
        }

        public void Update(T entity)
        {
            throw new NotImplementedException();
        }

        private static int IdGenerator()
        {
            return idGenerator += 1;
        }
    }
}


text:
package ru.mipt.acsl.device.modeling.flying;

import com.google.common.collect.Lists;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * @author Artem Shein
 */
public class Route
{
    private int name;
    @NotNull
    private SimplifiedRouteKind kind;
    private boolean isRing;
    private int crc16;
    private int maxLength;
    @NotNull
    private String info;
    @NotNull
    private List<RoutePoint> points;

    public Route(int name, @NotNull SimplifiedRouteKind kind, boolean isRing, int crc16, int maxLength, @NotNull String info,
                 @NotNull RoutePoint... points)
    {
        this(name, kind, isRing, crc16, maxLength, info, Lists.newArrayList(points));
    }

    public Route(int name, @NotNull SimplifiedRouteKind kind, boolean isRing, int crc16, int maxLength, @NotNull String info,
                 @NotNull List<RoutePoint> points)
    {
        this.name = name;
        this.kind = kind;
        this.isRing = isRing;
        this.crc16 = crc16;
        this.maxLength = maxLength;
        this.info = info;
        this.points = points;
    }

    @NotNull
    public RoutePoint getPoint(int i)
    {
        return points.get(i);
    }

    public int size()
    {
        return points.size();
    }

    public boolean isRing()
    {
        return isRing;
    }
}


text:
using UwpNetworkingEssentials.ChatSample.ViewModels;
using Windows.System;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;

namespace UwpNetworkingEssentials.ChatSample
{
    public sealed partial class ClientPage : Page
    {
        public ClientViewModel ViewModel { get; private set; }

        public ClientPage()
        {
            InitializeComponent();
            DataContext = this;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ViewModel = e.Parameter as ClientViewModel;
        }

        private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key == VirtualKey.Enter && e.KeyStatus.RepeatCount == 0)
            {
                ViewModel.SendMessage(messageTextBox.Text);
                messageTextBox.Text = "";
            }
        }
    }
}


text:
/*
 * UDP client
 *
 * Author: BANSAL, Pranshu
 *         pban1993@gmail.com
 *
 */

#include <arpa/inet.h>
#include <errno.h>

#include <netinet/in.h>
#include <net/if.h>
#include <netdb.h>

#include <stdio.h>
#include <stdlib.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>

#include <string.h>
#include <time.h>
#include <unistd.h>

#define BUFSIZE 1024

double AVERAGE_HEART_RATE = 70.0;

double generate_random_number(double lower, double upper)
{
    double random = ( (double)rand() / (double)RAND_MAX );
    double diff = upper - lower;
    double r = random * diff;
    return lower + r;
}

char * get_ip_addr()
{
	FILE *fp;
	char *line = NULL;
	char *rv = malloc(256*sizeof(char));
	int len, i;
	system("configure_edison --showWiFiIP > ip_addr.txt");

	fp = NULL;
	fp = fopen("ip_addr.txt", "r");
	if (fp == NULL) {
		fprintf(stderr, "failed to open output file. exiting.\n");
		exit(1);
	}

	if (getline(&line, &len, fp) > 0) {
		strcpy(rv, line);
		for (i=0; i < strlen(rv); i++) {
			if (rv[i] == '\n') rv[i]='\0';
		}
	} else {
		fprintf(stderr, "No IP address detected. Exiting.\n");
		exit(1);
	}

	fclose(fp);
	system("rm ip_addr.txt");
	return rv;
}

int main(int argc, char **argv)
{
    FILE *fp;
    char *line = NULL;
    char ip_addr[BUFSIZE];
    char *my_ip_addr;
    char buf[BUFSIZE];
    int port, range, rate;
    int line_length, message_size;
    int sockfd;
    int pid;
    double heart_rate;
    struct sockaddr_in server_addr;
    struct hostent *server;

    my_ip_addr = get_ip_addr();
    printf("My ip addr is: %s\n", my_ip_addr);

    /* READ INPUT FILE */
    fp = fopen("config_file", "r");
    if (fp == NULL){
		fprintf(stderr, "Error opening config file with name 'config_file'. Exiting.\n");
		exit(1);
    }

    printf("Reading input file...\n");
    while (getline(&line, &line_length, fp) > 0) {
		if (strstr(line, "host_ip") != NULL){
	    	sscanf(line, "host_ip: %s\n", ip_addr);
		} else if (strstr(line, "port") != NULL) {
	    	sscanf(line, "port: %d\n", &port);
		} else if (strstr(line, "range") != NULL) {
	    	sscanf(line, "range: %d\n", &range);
		} else if (strstr(line, "rate") != NULL) {
	    	sscanf(line, "rate: %d\n", &rate);
		} else {
	    	fprintf(stderr, "Unrecognized line found: %s. Ignoring.\n", line);
		}
    }
    fclose(fp);
    /* FINISH READING INPUT FILE */

    printf("Connecting to: %s:%d with rate %d and range %d\n", ip_addr, port, rate, range);

    /* SETUP SOCKET COMMUNICATIONS */
    server = gethostbyname(ip_addr);
    socklen_t len = sizeof(server_addr);

    //Set up datagram socket communication with ARPA Internet protocol
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    bzero((char *)&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(ip_addr);
    server_addr.sin_port = htons(port);
    /* FINISH SETUP SOCKET COMMUNICATIONS */

    /* SEND HEART RATE TO SERVER */
    while (1) {
		printf("Current settings: rate: %d, range: %d\n", rate, range);
		heart_rate = generate_random_number(AVERAGE_HEART_RATE-(double)range,
					AVERAGE_HEART_RATE+(double)range);
		memset(buf,0,sizeof(buf)); //clear out the buffer

		//populate the buffer with information about the ip address of the client and the heart rate
		sprintf(buf, "Heart rate of patient %s is %4.2f", my_ip_addr, heart_rate);
		printf("Sending message '%s' to server...\n", buf);

		if (sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&server_addr, len) < 0) {
		    fprintf(stderr, "Failed to send.\n");
		    exit (1);
		}

		/* FINISH HEART RATE TO SERVER */
		memset(buf,0,sizeof(buf));
		if (recvfrom(sockfd, buf, BUFSIZE, 0, (struct sockaddr *)&server_addr, &len) < 0) {
		    fprintf(stderr, "Failed to receive.\n");
		    exit (0);
		}

		if (strstr(buf, "new_rate: ") != NULL) {
		    sscanf(buf, "Heart rate of patient %*s is %*f new_rate: %d", &rate);
		    rate = rate;
		    printf("New rate %d received from server.\n", rate);
		}

		printf("Received message '%s' from server.\n\n", buf);
		sleep(rate);
    }

    close(sockfd);
    return 0;
}


text:
<!-- Samsung Galaxy Trend Plus (GT-S7580) -->
<deviceProfile>

	<recordingHint>
    STILL_ONLY
	</recordingHint>

</deviceProfile><!-- From: file:/home/mmurphy/stuff/CommonsWare/projects/CWAC/Camera/camera/res/xml/cwac_camera_profile_samsung_kyleproxx.xml -->


text:
A simple TODO-list managing web-app powered by Express.js

### howto

1. `npm install`
1. `npm run build`
1. `npm run start`


text:
<?php

include_once __DIR__ . '/../_common.php';

bad_request_if(empty($_POST['id']) || empty($_POST['properties']));

no_access_if_not(is_allowed_to('vis/factory/edit'), has_access_to_factory($_POST['id']));

$factory = fetch_one('SELECT v.factory FROM factories f LEFT JOIN vis_factories v ON v.factory=f.id WHERE f.id=?', array(1 => $_POST['id']));

bad_request_if(empty($factory));

if ($factory->factory === null)
{
  exec_stmt('INSERT INTO vis_factories SET factory=?', array(1 => $_POST['id']));
}

$availProps = array(
  'width', 'height', 'fg_color', 'bg_color', 'bg_image', 'bg_position', 'bg_repeat',
);

$match = array();

if (isset($_POST['properties']['bg_image'])
&& preg_match('/^[0-9]+_new\.(.*?)$/', $_POST['properties']['bg_image'], $match)
&& file_exists($file = dirname(dirname(__FILE__)) . ENVIS_UPLOADS_DIR . '/vis-factory-bg/' . $_POST['properties']['bg_image']))
{
  $_POST['properties']['bg_image'] = (int)$_POST['id'] . '.' . $match[1];

  rename($file, dirname(dirname(__FILE__)) . ENVIS_UPLOADS_DIR . '/vis-factory-bg/' . $_POST['properties']['bg_image']);

  echo 'url(' . url_for(ENVIS_UPLOADS_DIR . '/vis-factory-bg/' . $_POST['properties']['bg_image']) . '?u=' . mt_rand() . ')';
}
elseif (isset($_POST['properties']['bg_image']))
{
  unset($_POST['properties']['bg_image']);
}

$bindings = array(':factory' => (int)$_POST['id']);

$sql = 'UPDATE vis_factories SET ';

foreach ((array)$_POST['properties'] as $name => $value)
{
  if (!in_array($name, $availProps)) continue;

  $sql .= $name . '=:' . $name . ', ';

  $bindings[':' . $name] = $value;
}

$sql = substr($sql, 0, -2) . ' WHERE factory=:factory';

exec_stmt($sql, $bindings);


text:
package fr.adrienbrault.idea.symfony2plugin.routing.inspection;

import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.indexing.FileBasedIndex;
import com.jetbrains.php.lang.PhpFileType;
import fr.adrienbrault.idea.symfony2plugin.routing.Route;
import fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper;
import fr.adrienbrault.idea.symfony2plugin.stubs.indexes.AnnotationRoutesStubIndex;
import fr.adrienbrault.idea.symfony2plugin.stubs.indexes.RoutesStubIndex;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.YAMLFileType;

import java.util.Collection;
import java.util.Map;

public class PhpRouteWeakInspection extends AbstractPhpRouteInspection {

    protected void annotateRouteName(PsiElement target, @NotNull ProblemsHolder holder, final String routeName) {

        Map<String, Route> routes = RouteHelper.getCompiledRoutes(target.getProject());
        if(routes.containsKey(routeName))  {
            return;
        }

        Collection fileCollection = FileBasedIndex.getInstance().getContainingFiles(RoutesStubIndex.KEY, routeName,  GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(target.getProject()), YAMLFileType.YML, XmlFileType.INSTANCE));
        if(fileCollection.size() > 0) {
            holder.registerProblem(target, "Weak Route", ProblemHighlightType.WEAK_WARNING);
            return;
        }

        fileCollection = FileBasedIndex.getInstance().getContainingFiles(AnnotationRoutesStubIndex.KEY, routeName, GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(target.getProject()), PhpFileType.INSTANCE));
        if(fileCollection.size() > 0) {
            holder.registerProblem(target, "Weak Route", ProblemHighlightType.WEAK_WARNING);
            return;
        }

    }

}


text:
'use strict';

/**
 * Module dependencies.
 */
var express = require('express'),
    http = require('http'),
    fs = require('fs');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Load configurations
// Set the node enviornment variable if not set before
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
global.__base = __dirname + '/';

// Initializing system variables
var config = require('./config/config');

var app = express();

// Express settings
require('./config/express')(app);

// Bootstrap routes
var routes_path = __dirname + '/app/routes';
var walk = function(path) {
    fs.readdirSync(path).forEach(function(file) {
        var newPath = path + '/' + file;
        var stat = fs.statSync(newPath);
        if (stat.isFile()) {
            if (/(.*)\.(js$)/.test(file)) {
                require(newPath)(app);
            }
        // We skip the app/routes/middlewares directory as it is meant to be
        // used and shared by routes as further middlewares and is not a
        // route by itself
        } else if (stat.isDirectory() && file !== 'middlewares') {
            walk(newPath);
        }
    });
};
walk(routes_path);

var server = http.createServer(app);

// Start the app by listening on <port>
var port = process.env.PORT || config.port;
server.listen(port);
console.log('Express app started on port ' + port);

// Expose app
exports = module.exports = app;


text:
<?php
namespace Noticias\NotaBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\ORM;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Noticias\NotaBundle\Entity\Fuente;
use Noticias\UsuarioBundle\Entity\Usuario;
use Noticias\PlazaBundle\Util\Util;

class Usuarios_Fuentes extends AbstractFixture implements OrderedFixtureInterface
{

    public function getOrder()
    {
        return 110;
    }
    public function load (ObjectManager $manager)
    {
        $usuarios=$manager->getRepository('UsuarioBundle:Usuario')->findAll();
        $fuentes=$manager->getRepository('NotaBundle:Fuente')->findAll();
        for($i=0;$i<count($usuarios);$i++)
        {
            $usuario = new Usuario();
            $fuente = new Fuente();
            $fuente =$fuentes[rand(0, count($fuentes)-1)];
            $usuario=$usuarios[$i];
            $usuario->getFuentes()->add($fuentes[rand(0, count($fuentes)-1)]);
            $fuente->getUsuarios()->add($usuario);
            $manager->persist($fuente);
            $manager->persist($usuario);
        }
        $manager->flush();
    }
}


text:
def separate_comma(number)
    reversed_number = number.to_s.reverse
    comma = reversed_number.scan(/\d{1,3}/).join(",").reverse
    return comma
 end

# 2. Refactored Solution
def separate_coma(number)
	return number.to_s.reverse.scan(/\d{1,3}/).join(",").reverse
end

# 3. Reflection
# What was your process for breaking the problem down? What different approaches did you consider?
# I broke it into smaller pictures, then thought about smaller pictures, but not forgetting about the bigger picture.
# Since I knew, I couldnt join commas from the front, I reversed it and added a comma every three positions
# And reversed back

# Was your pseudocode effective in helping you build a successful initial solution?
# Yes, it did actually made me think about going reverse and reversing it back again later.

# What new Ruby method(s) did you use when refactoring your solution? Describe your experience of using the Ruby documentation to implement it/them (any difficulties, etc.). Did it/they significantly change the way your code works? If so, how?
# I used scan, reverse, to_s, and join.  Scan was to scan the string individually, reverse is used to reversethe
# string.  To_s changes the number into a string and join joins every split items into one

# How did you initially iterate through the data structure?
# I first did split method after changing the number to a string, then I was stuck, so I read about scan method

# Do you feel your refactored solution is more readable than your initial solution? Why?
# Due to all the dots before the method, it clearly shows the step by step of my approach toward this problem.


text:
@implementation OADTraceRequestSender

- (void)sendDTraceForRequest:(NSURLRequest*)request {
  if ([self isTraceingEnabled]) {
    [self sendStringTrace:[self dtraceStringForRequest:request]];
  }
}

- (BOOL)isTraceingEnabled {
  return OADPROBE_REQUEST_ENABLED();
}

- (void)sendStringTrace:(NSString*)traceString {
  OADPROBE_REQUEST(traceString.UTF8String);
}

- (NSString*)dtraceStringForRequest:(NSURLRequest*)request {
  NSMutableDictionary *dic = [@{} mutableCopy];

  dic[@"method"] = [request HTTPMethod];

  if ([request URL]) {
    dic[@"url"] = [[request URL] absoluteString];
  }

  id cookies = [self cookieDictionaryForRequest:request];
  if (cookies) {
    dic[@"cookies"] = cookies;
  }

  id headers = [request allHTTPHeaderFields];
  if (headers) {
    dic[@"headers"] = headers;
  }

  id body = [self bodyStringForRequest:request];
  if (body) {
    dic[@"body"] = body;
  }

  NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
  NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  return string;
}

- (NSMutableDictionary*)cookieDictionaryForRequest:(NSURLRequest*)request {
  if (![request URL]) { return nil; }

  NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[request URL]];
  if (cookies.count == 0) { return nil; }

  NSMutableDictionary *dic = [@{} mutableCopy];
  for (NSHTTPCookie *cookie in cookies) {
    [dic setValue:[cookie value] forKey:[cookie name]];
  }

  return dic;
}

- (NSString*)bodyStringForRequest:(NSURLRequest*)request {
  if ([[request HTTPBody] length] == 0) { return nil; }

  NSMutableString *HTTPBodyString = [[NSMutableString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding];
  return HTTPBodyString;
}

@end


text:
package org.oscm.test.ejb;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;

import javax.ejb.EJBException;
import javax.ejb.ScheduleExpression;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

public class TestTimerService implements TimerService {

    @Override
    public Timer createCalendarTimer(ScheduleExpression arg0)
            throws IllegalArgumentException, IllegalStateException,
            EJBException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Timer createCalendarTimer(ScheduleExpression arg0, TimerConfig arg1)
            throws IllegalArgumentException, IllegalStateException,
            EJBException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Timer createIntervalTimer(long arg0, long arg1, TimerConfig arg2)
            throws IllegalArgumentException, IllegalStateException,
            EJBException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Timer createIntervalTimer(Date arg0, long arg1, TimerConfig arg2)
            throws IllegalArgumentException, IllegalStateException,
            EJBException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Timer createSingleActionTimer(long arg0, TimerConfig arg1)
            throws IllegalArgumentException, IllegalStateException,
            EJBException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Timer createSingleActionTimer(Date arg0, TimerConfig arg1)
            throws IllegalArgumentException, IllegalStateException,
            EJBException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Timer createTimer(long arg0, Serializable arg1)
            throws IllegalArgumentException, IllegalStateException,
            EJBException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Timer createTimer(Date arg0, Serializable arg1)
            throws IllegalArgumentException, IllegalStateException,
            EJBException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Timer createTimer(long arg0, long arg1, Serializable arg2)
            throws IllegalArgumentException, IllegalStateException,
            EJBException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Timer createTimer(Date arg0, long arg1, Serializable arg2)
            throws IllegalArgumentException, IllegalStateException,
            EJBException {
        return null;
    }

    @Override
    public Collection<Timer> getTimers() throws IllegalStateException,
            EJBException {
        return Collections.emptyList();
    }

    @Override
    public Collection<Timer> getAllTimers() throws IllegalStateException, EJBException {
        return null;
    }

}


text: <link rel="stylesheet" href="%%GLOBAL_CdnStorePath%%/content/BxSlider/jquery.bxslider.css" type="text/css" />


text:
<form name="empForm" novalidate="true" ng-submit="vm.save(empForm)">
        <md-content   layout-padding class="md-whiteframe-z2" style="background-color=rgb(250, 250, 250)">

                DateTime picker, week start date is Monday , Disabled Year selection with attribute   disable-year-selection="true"

                    <sm-date-time-picker
                        fname="field"
                        label="Date of Birth"
                        data-ng-model="vm.dateOfBirth"
                        flex="100"
                        flex-sm="100"
                        disable-year-selection="true"
                        flex-xs="100"
                        on-focus
                        is-required="true"
                        format="MM-DD-YYYY HH:mm"
                        mode="date-time"
                        ng-change="vm.dateChanged(vm.dateOfBirth)"
                        week-start-day="Monday"
                        on-date-selected-call="vm.dateSelected(date)">
                    </sm-date-time-picker>

                <md-button class="md-button" ng-click="vm.changeModelValue()">Chanage Model two way binding</md-button>
                <md-button class="md-button" ng-click="vm.clearInput()">clear</md-button>
                Call back value {{vm.callBackValue }}
                ng Change {{vm.dateOnNgChange}}

                Date picker, Close on date select only works with   Date Picker   mode with attribute   close-on-select="true"   without floating label

                    <sm-date-time-picker
                        fname="exitDate"
                        label="Date of Exit"
                        ng-model="vm.employee.exitDate"
                        flex="50"
                        flex-sm="100"
                        no-floating-label="true"
                        flex-xs="100"
                        close-on-select="true"
                        format="MM-DD-YYYY"
                        week-start-day="Monday">
                    </sm-date-time-picker>

                Min date set to {{vm.minDate}}: min-date="{{vm.minDate}}"

                    <sm-date-time-picker
                        fname="Date of Pay"
                        label="Date of Pay"
                        min-date="{{vm.minDate}}"
                        ng-model="vm.employee.dateOfPay"
                        flex="50"
                        is-required="{{true}}"
                        format="MM-DD-YYYY"
                        week-start-day="Sunday">
                    </sm-date-time-picker>
                {{vm.employee.dateOfPay}}

                Date picker:  disable="true"

                    <sm-date-time-picker
                        fname="exitDate"
                        label="Date of Exit"
                        ng-model="vm.employee.exitDate"
                        flex="50"
                        flex-sm="100"
                        flex-xs="100"
                        close-on-select="true"
                        is-required="{{true}}"
                        disable="true"
                        format="MM-DD-YYYY"
                        week-start-day="Monday">
                    </sm-date-time-picker>

                Date picker, Max date   max-date="{{vm.maxDate}}"  and  week-start-day="Sunday"

                    <sm-date-time-picker
                        fname="joiningDate"
                        label="Date of Joining"
                        ng-model="vm.employee.joiningDate"
                        data-start-date="10-15-2015"
                        flex="50"
                        flex-sm="100"
                        flex-xs="100"
                        max-date="{{vm.maxDate}}"
                        is-required="{{true}}"
                        format="MM-DD-YYYY"
                        week-start-day="Sunday">
                    </sm-date-time-picker>

                Min date set to {{vm.minDate}}: min-date="{{vm.minDate}}" and max date   max-date="{{vm.maxDate}}"

                    <sm-date-time-picker
                        fname="Date of Pay"
                        label="Date of Pay"
                        ng-model="vm.employee.dateOfPay"
                        flex="50"
                        is-required="{{true}}"
                        max-date="11-10-2017"
                        min-date="10-10-2015"
                        format="MM-DD-YYYY"
                        week-start-day="Sunday">
                    </sm-date-time-picker>

                Date picker as service, click on calender icon

                calender inline  selected date: {{vm.dateOfBirth}}

                    <sm-calender
                        ng-model="vm.dateOfBirth"
                        data-mode="{{mode}}"
                        data-min-date="minDate"
                        data-max-date="maxDate"
                        close-on-select="{{closeOnSelect}}"
                        data-format="{{format}}"
                        data-week-start-day="{{weekStartDay}}">
                    </sm-calender>

                <md-button class="md-button" ng-click="vm.changeModelValue()">Chanage Model</md-button>  {{vm.dateOfBirth}} Call back value {{vm.callBackValue }}

       <md-button type="submit" class="md-primary md-raised">save</md-button>
       </md-content>
    </form>